Custom Placeholder Module

Question: I have created a custom module to create a few placeholders in form fields.  Unfortunately, I am having a little trouble with getting two of them to work.  The code I have in the module is as follows:
function solid_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#attributes']['placeholder'] = t('enter search terms');
  }
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    $form['name']['#attributes']['placeholder'] = t( 'Username or Email' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );
  }
  if ($form_id == 'user_account_form') {
    $form['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['mail']['#attributes']['placeholder'] = t( 'Email Address' );
    $form['pass[pass1]']['#attributes']['placeholder'] = t( 'Password' );
    $form['pass[pass2]']['#attributes']['placeholder'] = t( 'Confirm Password' );
  }
  if($form_id == "views_exposed_form"){
    $form['title']['#attributes'] = array('placeholder' => array(t('Search by Title')));
    $form['sku']['#attributes'] = array('placeholder' => array(t('Search by SKU')));
    $form['commerce_price_amount[min]']['#attributes'] = array('placeholder' => array(t('Min Price')));
    $form['commerce_price_amount[max]']['#attributes'] = array('placeholder' => array(t('Max Price')));
  }
}

(In order) The search block placeholder texts works perfectly.  The login placeholders also work perfectly.  The register (user_account_form) placeholders are not working at all, and I can not figure out why.  And the views_exposed_form works for the title and sku, but not for the min and max price range?
I need helping figuring out what I did wrong on the register form, and the min/max view filter price range fields.
EDIT:  I have gotten everything to work except the registration passwords.  When I uncomment the line for the password fields, they are no longer displayed on the page.
    function solid_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#attributes']['placeholder'] = t('enter search terms');
  }
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    $form['name']['#attributes']['placeholder'] = t( 'Username or Email' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );
  }
  if($form_id == "views_exposed_form"){
    $form['title']['#attributes'] = array('placeholder' => array(t('Search by Title')));
    $form['sku']['#attributes'] = array('placeholder' => array(t('Search by SKU')));
    $form['commerce_price_amount']['#process'][] = 'placeholders_process_commerce_price_amount';
  }
  if ($form_id == 'user_register_form') {
    $form['account']['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['account']['mail']['#attributes']['placeholder'] = t( 'Email Address' );
    //$form['account']['pass']['#process'][] = 'placeholders_process_password_confirm';
  }
}
function placeholders_process_password_confirm($element) {
  $element['pass1']['#attributes']['placeholder'] = t( 'Password' );
  $element['pass2']['#attributes']['placeholder'] = t( 'Confirm Password' );
  return $element;
}
function placeholders_process_commerce_price_amount($element) {
  $element['min']['#attributes']['placeholder'] = t( 'Min price' );
  $element['max']['#attributes']['placeholder'] = t( 'Max price' );
  return $element;
}

Answer: The user account form stuff is one level up in the account container. For the name and email you can use:
$form['account']['name']['#attributes']['placeholder'] = t( 'Username' );
$form['account']['mail']['#attributes']['placeholder'] = t( 'Email Address' );

The password is slightly more complicated, as the 2 inputs are created in a process function. You'll need something like:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  ...
  if ($form_id == 'user_account_form') {
    ...
    $form['account']['pass']['#process'][] = 'MYMODULE_process_password_confirm';
  }
  ...
}

function MYMODULE_process_password_confirm($element) {
  $element['pass1']['#attributes']['placeholder'] = t( 'Password' );
  $element['pass2']['#attributes']['placeholder'] = t( 'Confirm Password' );
  return $element;
}

See form_process_password_confirm() if you're wondering where 'pass1' and 'pass2' come from (it's one of the default process functions for a password_confirm element as set in system_element_info()).
It'll be the same sort of thing for the slider, but without knowing where that slider comes from (module, custom code, etc) it's difficult to say what the code should be. At a guess based on the input name's you're trying to target:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  ...
  if ($form_id == 'views_exposed_form') {
    ...
    $form['commerce_price_amount']['#process'][] = 'MYMODULE_process_commerce_price_amount';
  }
  ...
}

function MYMODULE_process_commerce_price_amount($element) {
  $element['min']['#attributes']['placeholder'] = t( 'Min price' );
  $element['max']['#attributes']['placeholder'] = t( 'Max price' );
  return $element;
}

Comment: Thank you for the reply.  That is some great information, unfortunately I have not gotten them to work just yet.  I was going to paste what I changed it to in here, but it is a little too long.
Comment: altered code added to the original post.
Comment: Sorry I wasn't clear enough, you still need to alter the form elements inside your form alter hook. The updated code should help
Comment: Thank you.  I am making progress now.  One other mistake that I made was the ID for the register form.  It was `user_register_form` not `user_account_form`
Comment: One last Question!  I have gotten everything to work with the exception of the registration passwords.  I have put my current code in the original post once again.  When I uncomment the line for the process in the first function, both fields are removed from the registration page.

Custom Placeholder Module


Calculating DATETIME difference in Mysql

Question: I am calculating time difference between the cleartime and firstoccurrence time which should result in hh:mm:ss format .how can i get the Datetime DURATION in mysql  in format hh:mm:ss
enter image description here
Answer: Use TIMEDIFF, such as
SELECT TIMEDIFF("2018-01-25 13:10:11", "2018-01-24 11:10:10");

will output 26:00:01
Further information on TIMEDIFF, please refer to the document

TIMEDIFF(expr1,expr2) returns expr1 − expr2 expressed as a time value. expr1 and
  expr2 are time or date-and-time expressions, but both must be of the
  same type.

For your case, if you want to set the time duration into the column of DURATION, you can try a UPDATE query for all records. It would be simpler if you have an ID column, which is not shown in your screenshot.


Sonata admin datagrid filter can't get ChoiceType to work

Question: I'm removing my hairs over this one. On sonata admin 3.x I had this filter in the list view, providing a select box with the options described.

protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
{
    ->add('state', 'doctrine_orm_choice',
                array('label' => 'State'),
                ChoiceType::class, array(
                    'choices' => array(
                        'new' => 'new',
                        'open' => 'open',
                        'closed' => 'closed' ),
                        'required' => false

                    )
            )
}

But on the upgrade to 4.x I got the following error :
No attached service to type named 'doctrine_orm_choice'
I tried everything between the ChoiceType, to the ChoiceFilter but I can't find any snippet on the docs or any relevant cue on how this is supposed to work now.
Thanks a lot !
Answer: And the correct syntax is :
use Sonata\DoctrineORMAdminBundle\Filter\ChoiceFilter;

protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
{
     ->add('state',   ChoiceFilter::class, ['label' => 'State',
                    'field_type' => ChoiceType::class,
                    'field_options' => [
                        'choices' => [
                            'new' => 'new',
                            'open' => 'open',
                            'closed' => 'closed'],
                        'required' => false

                    ]
                ]
            )
}


How to easily see the time integral of a Brownian motion is normally distributed?

Question: It's well known that $X_t:=\int_0^tB_\tau d\tau$ where $\{B_\tau\}$ is a 1D standard Brownian motion is distributed as $N(0, t^3/3)$. Is there any "immediate" way to see this fact?
The easiest one I can get: discretise $X_t$ into Riemannian sum, and break each $B_{\tau_i}$ into independent increments over tiny intervals, then we see the sum is just a linear sum of independent normal distributions, then take the limit and use convergence in distribution to conclude.
I wouldn't say this is hard, but this is in no way trivial or immediate either. Can we somehow see this fact without any effort or whatsoever? Thanks.
Comment: Writing the integral as limit of Riemann sums is ths natural easiest way to prove this.
Comment: @Vim Well, the expectation as well as the variance can be calculated using Fubini's theorem... that's not really a problem. From my point of view, the key point is to show that $X_t$ is Gaussian. By the way, I don't think that it possible to get rid of the discretisation - simply because the integral is defined as the limit of the discretisations. Obviously, you can apply some "big" result and hide the discretisation there... but that doesn't make the proof "easier", in my oppinion.
Comment: @KaviRamaMurthy Ok, but I'm still expecting something easier, like a "continuous" argument (cleverly determine its characterisitc function, so to speak). Discretisation looks non-tidy, albeit natural.
Comment: Why do you have to breat $B_{\tau_i}$ into tiny intervals...? The random vector $(B_{t_1},\ldots,B_{t_n})$ is Gaussian for any choice of $t_i$ (as $B$ is a Gaussian process), and hence $$\sum_{i=1}^n c_i B_{t_i}$$ is Gaussian for any choice of constants $c_i$.
Comment: @saz you're definitely correct. It's just that estimating the variance of independent sums is easier.
Comment: @saz thanks. If you don't mind, would you care to elaborate a bit on how to apply Fubini to work out the expectation and variance?
Answer: There are three things which need to be done:

Check that $X_t$ is Gaussian.
Compute its expectation.
Compute its variance.

1. $X_t$ is Gaussian: It seems to me that the most natural (and also direct) way to prove this is an approximation by Riemann sums. Noting that
$$X_t^{(n)} := \sum_{j=1}^n \frac{1}{n} B_{t j/n} \tag{1}$$
is Gaussian for each $t>0$ (because $(B_t)_{t \geq 0}$ is a Gaussian process), we find that $$X_t = \lim_{n \to \infty} X_t^{(n)}$$ is Gaussian as pointwise limit of Gaussian random variables. For an alternative reasoning see the very end of my answer.
2. Compute $\mathbb{E}(X_t)$: Since $\mathbb{E}(B_s)=0$ for all $s \geq 0$, it follows that each $X_t^{(n)}$ (defined in $(1)$) has expectation zero, and hence its limit $X_t = \lim_n X_t^{(n)}$ has expectation zero. Alternatively, we can apply Fubini's theorem:
$$\mathbb{E}(X_t) = \mathbb{E} \left( \int_0^t B_s \, ds \right) = \int_0^t \underbrace{\mathbb{E}(B_s)}_{=0} \, ds =0.$$
3. Compute $\text{var}(X_t)$: Since we already know that $\mathbb{E}(X_t)=0$, we clearly have $\text{var}(X_t) = \mathbb{E}(X_t^2)$. As
$$X_t^2 = \int_0^t \int_0^t B_s B_r \, ds \, dr$$
it follows from Fubini's theorem that
$$\mathbb{E}(X_t^2) = \int_0^t \int_0^t \mathbb{E}(B_s B_r) \, ds \, dr. \tag{2}$$
By symmetry, we thus get
$$\mathbb{E}(X_t^2) = 2 \int_0^t \int_0^r \underbrace{\mathbb{E}(B_s B_r)}_{\min\{s,r\}=s} \, ds \, dr = 2 \int_0^t \int_0^r s \, ds = \frac{t^3}{3}$$
If you don't like symmetrization, then note that (2) implies
$$\mathbb{E}(X_t^2) = \int_0^t \int_0^s \underbrace{\mathbb{E}(B_s B_r)}_{\min\{s,r\}=s} \, ds \, dr + \int_0^t \int_s^t \underbrace{\mathbb{E}(B_s B_r)}_{\min\{s,r\}=r} \, ds \, dr$$
and each of the integrals can be calculated explicitly using standard calculus.

Let me close this answer with a result which combines all the three steps into one.

Proposition: Let $(L_t)_{t \geq 0}$ be a Lévy process with characteristic exponent $\psi$, i.e. $$\mathbb{E}\exp(i \xi L_t) = \exp(-t \psi(\xi)), \qquad t \geq 0, \xi \in \mathbb{R}. \tag{3}$$ Then the characteristic function of $$X_t := \int_0^t L_s \, ds$$ equals $$\phi(\xi) = \exp \left(- \int_0^t \psi(\xi s) \, ds \right), \qquad \xi \in \mathbb{R}.$$

If you are not familar with Lévy processes (that it, stochastic processes with independent and stationary increments), then you can just think of a Brownian motion; in this case $\psi$ is given by $\psi(\xi) = \xi^2/2$. Applying the proposition, we thus find that the characteristic function of $X_t = \int_0^t B_s \, ds$ equals $$\exp \left(- \frac{t^3}{3} \frac{\xi^2}{2} \right)$$ which is the characteristic function of $N(0,t^3/3)$, and so $X_t \sim N(0,t^3/3)$.
Proof of the proposition: For fixed $n \in \mathbb{N}$  and $t>0$ set $t_j := t j/n$ for $j=1,\ldots,n$, and set
$$\phi_n(\xi) := \mathbb{E} \exp \left( i \xi \frac{1}{n} \sum_{j=1}^n L_{t_j} \right).$$
Denote by $\mathcal{F}_t := \sigma(L_s; s \leq t)$ the canonical filtration of $(L_t)_{t \geq 0}$. Using the tower property of the conditional expectation, we find
$$\begin{align*} \phi_n(\xi) &= \mathbb{E} \bigg\{ \mathbb{E} \bigg[ \exp \left( i \xi \frac{1}{n} \sum_{j=1}^n L_{t_j} \right) \mid \mathcal{F}_{t_{n-1}} \bigg] \bigg\} \\ &=  \mathbb{E} \bigg\{ \exp \left( i \xi \frac{1}{n} \sum_{j=1}^{n-1} L_{t_j} \right) \mathbb{E} \bigg[ \exp \left( i \xi \frac{1}{n} L_{t_n} \right) \mid \mathcal{F}_{t_{n-1}} \bigg] \bigg\} \tag{4} \end{align*}$$
Since $(L_t)_{t \geq 0}$ has independent increments, we have
$$\begin{align*} \mathbb{E} \bigg[ \exp \left( i \xi \frac{1}{n} L_{t_n} \right) \mid \mathcal{F}_{t_{n-1}} \bigg] &=\exp(i \xi/n L_{t_{n-1}}) \mathbb{E} \bigg[ \exp \left( i \xi \frac{1}{n} (L_{t_n}-L_{t_{n-1}}) \right) \mid \mathcal{F}_{t_{n-1}} \bigg] \\ &= \exp(i \xi/n L_{t_{n-1}}) \mathbb{E}\exp\left( i \xi \frac{1}{n} (L_{t_n}-L_{t_{n-1}}) \right). \end{align*}$$
Using that $(L_t)_{t \geq 0}$ has stationary increments, i.e. $L_{t_n}-L_{t_{n-1}} \sim L_{t_n-t_{n-1}}=L_{1/n}$, and using $(3)$ we thus get
$$ \mathbb{E} \bigg[ \exp \left( i \xi \frac{1}{n} L_{t_n} \right) \mid \mathcal{F}_{t_{n-1}} \bigg] = \exp(i \xi/n L_{t_{n-1}}) \exp \left(- \frac{1}{n} \psi \left( \frac{\xi}{n} \right) \right).$$
Plugging this into $(4)$, we obtain that
$$\phi_n(\xi) = \mathbb{E} \bigg\{ \exp \left( i \xi \frac{1}{n} \sum_{j=1}^{n-2} L_{t_j} + i \xi \frac{2}{n} L_{t_{n-1}} \right) \exp \left(- \frac{1}{n} \psi \left( \frac{\xi}{n} \right) \right) .$$
Iterating this reasoning (i.e. next conditioning on $\mathcal{F}_{t_{n-2}}$, then on $\mathcal{F}_{t_{n-3}}$, ...) we conclude that
$$\phi_n(\xi) = \exp \left( - \frac{1}{n} \sum_{j=1}^n \psi \left( \frac{j}{n} \xi \right) \right).\tag{5}$$
Finally, we note that
$$X_t \stackrel{\text{def}}{=} \int_0^t L_s \, ds = \lim_{n \to \infty} \frac{1}{n} \sum_{j=1}^n L_{tj/n},$$
and thus, by letting $n \to \infty$ in (5), we get
$$\mathbb{E}\exp(i \xi X_t) = \exp \left(- \int_0^t \psi(s \xi) \, ds \right).$$
Comment: Thanks for such a detailed answer!
Comment: @Vim You're welcome.


Android custom Array adapter and database connection

Question: I couldn't find any solid information regarding this so here it goes;
I am using information from SQLite db in my array adapter to show/hide a view. Array list data comes from file system and depending on user's choice a view in the row displayed or hidden. So, on getView of my adapter I open connection, query db for that array item and if it is in the db I display a view then close db connection.
Is this the right way to do it? It feels like a lot of opening and closing especially if there are many items in the array list. I can open connection on adapter's public constructor but then where would I close it?
Any advice?
Answer: To avoid opening and closing the DB so much, you should store the objects retrieved from the DB query in memory, then attach that collection of objects to your adapter.  Then instead of querying the DB everytime getView is called, you should just check your list of query results.
So to sum up, query your DB objects all at once, store them in a collection in memory (as a java ArrayList or something), then refer to the ArrayList when in getView.


drupal_set_message() shows a message twice when called from hook_init()

Question: Basically the issue is that drupal_set_message() shows a message twice on some pages, when it is called from hook_init().
How can I avoid it happens?
Answer: It's likely that the first message you see is the left-over result of a previous AJAX call, and the second message is the one you're intending to see.
To test that, open a different browser and browse to the page in question. First time round you should see the message once; when you refresh the page, and on subsequent requests, you should see it twice.
It happens because hook_init() is also invoked for AJAX requests, but the messages added to the session are never printed-then-cleared - so there's an extra copy of the same message in the next normal page load.
For most (all?) modern browser/server combinations you can use something like this to detect whether or not the request is from an AJAX source, and react accordingly:
function is_ajax_request() {
  return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

Comment: hi Clive, thanks for the answer! So according to you if  I add this in the check in hook_init - it must work, but I just checked and it is not working so here is what I wrote in hook_init:                 `if (user_is_logged_in() && !_is_ajax_request() && !have_profile()) { drupal_set_message(...) }`
Comment: Is `have_profile()` returning the expected value?
Comment: yes I was just editing my comment ... exactly
Comment: yes ... everything is working - just it is showing twice sometimes, and when I checked further - I realized that the hook_init is executing twice, because I added a dpm there
Comment: Hmmm...you can check that it's the definitely happening twice in the same request using a static: `static $foo = FALSE; if (!$foo) { $foo = TRUE; drupal_set_message('..); }`. If you only get one message from now on, then `hook_init()` is indeed being invoked twice. If not, it's that the message is being added to the session as part of another page request somehow (and usually that's AJAX)
Comment: I added static $foo = FALSE; outside hook_init and in hook init checked both for !_is_ajax_request() and !$foo ... it is invoked several times (hook_init),  but the workaround with the static variable is not working
Comment: The static var needs to go inside `hook_init()`
Comment: with the static variable it is showing far less frequently, but sometimes it is showing twice ... maybe it is in the session somehow
Comment: even inside hook_init - the message is showing twice sometimes
Comment: You could add a `watchdog('MYMODULE', 'hook_init called from path @path', array('@path' => $_GET['q']));`, then check the db log - that'll tell you what URLs are invoking `hook_init()`, should help narrow things down
Comment: when I checked this way - it is executing many many times - it is adding records that it is executed from while cropping images, js files, and maybe in some of those requests it is adding the message more than once
Comment: Sounds very likely. You can narrow it down still further by combining the watchdog and static methods. `static $foo = FALSE; if ($foo) { watchdog(...); } $foo = TRUE;`. Theoretically you should only get watchdog entries when `hook_init()` has fired at least once before in the same page build
Comment: do you know of some other hook that is executed only once per page load ? if can't find a way to fix it maybe I will just add an empty block and will add this functionality there
Answer: The easiest way to avoid the messages are repeated is setting the drupal_set_message() $repeat parameter to FALSE.
 drupal_set_message(t('You must validate your email address for this account before logging in via OpenID.'), 'status', FALSE);


Trying to set the class path in linux

Question: I found the location of my JRE it is
/usr/local/jdk1.7.0_03/jre

but where are all the class files stored? What should I set the class path to, this?
Also does Java with an empty class path still look in the default directories used during install?
Can jars when launched contain meta data that specifies the class path ahead of time?
Comment: Should I just delete the question? I still want to know if there are any default location searched for the class path
Comment: *"what could be causing this?"*  The code and class-path.  Voting to close.
Comment: I was just trying to give my reasoning for asking it, that's not my full question
Comment: If your application starts with no errors, at least the standard libraries and the jar itself must be on the classpath. Maybe the java program needs additional resources like property files on the classpath. Does the jar runs under windows with a double click?
Comment: I'm running it on linux, but when I've used net beans (on windows) in the past it does
Comment: I had to do some workarounds to get it to open with java in general for linux
Comment: *"that's not my full question"*  I count 3 '?' on this question at the moment.  Better to limit it to 1.  ;)
Comment: I meant to type actual not full, it's very early where I am not and I should be asleep :-)
Answer: Java traces the several directories to find the classes required for a program.This is the sequence of searching:
1) <JDK/JRE>/lib
2) <JDK/JRE>/lib/ext
3) Current directory
4) Additional jars or classes with -cp argument while compiling or executing.

If it doesn't find any of those directories, then it would simply through ClassNotFoundException
Can jars when launched contain meta data that specifies the
class path ahead of time?

Ans:Yes. When compiling or building a jar, one could pass several arguments to mark the main class if it's a executable jar and also the META-INF of the environment etc.
Please go through the link on META-INF information for a jar management.META-INF Info in Java
Comment: Yes, as a java or javac executable it knows those two paths a head of time.

Trying to set the class path in linux


Is Cohen's $d$ a better measure of effect-size than a simple mean difference for a meta-analysis?

Question: Cohen's $d$ measures the difference between the mean for the experimental group and the control group divided by standard deviation. The Cohen's $d$ statistic produces something that does not add any value to the observed effect-size i.e. the difference between the mean for the experimental group and the mean of  control group.Should we use  Cohen's $d$ or simple difference produced by a controlled experiment for a meta-analysis?
Comment: "d statistic" is what?  Cohen's, Durbin-Watson, Tajima, Kolmogorov-Smirnov, Hoeffding's, Cook's, Somers, something else?
Comment: Cohen's d-statistics is the difference between two means scaled by the standard deviation. The idea is to have a measure of effect size not dependent on the magnitude of the variable.
Comment: Does S.D. stand for 'standard deviation' or 'simple difference'? Ordinarily I'd assume the first, but since you are talking about 'simple difference' several times, it has become ambiguous.
Comment: The effect size measure Cohen's *d*?
Comment: Thank you for the clarification. If you would like your question answered, though, it will be necessary to edit it accordingly: most readers will not take the time or effort to read through these comments in order to figure out what you might be asking.
Comment: Could you please edit it ?
Comment: I think that it Cohen's d simply misleads. It does not add anything to the correct interpretation of effect-size. Dividing by S.D. should generate a value that can not be explained in meaningful words. The S. D. is average distance from the mean. It simply changes the locus.
Answer: It is common to use simple (unscaled) mean differences to understand and communicate experimental results.  Furthermore, it is permissible to use them in meta-analyses.
In meta-analyses, however, mean differences are rarely used.  The reason is that studies often measure effects using different (incommensurate) scales.  If one study were conducted using degrees Fahrenheit and another using degrees Celsius, this would not be a problem, because there is a known conversion between these measures.  Often, however, there is not a known conversion.  Thus, standardizing the mean difference by dividing by the standard deviation eliminates the original units and denotes the effect in units of standard deviation instead.  This makes the measure more universal, and makes disparate studies comparable.
As a result of these facts, Cohen's $d$ is often used to communicate experimental results as well (that is, Cohen's $d$ is often used outside of meta-analyses).  It can be easier for people to understand.  This is especially true if people are likely to be unfamiliar with the scale used in the study.  Of course, if people would be very familiar with the measurements used, it may be better to retain the original scale for communicative purposes.
Note that dividing by the standard deviation is just a type of rescaling.  Rescaling does not change the nature of the information; the result cannot be more or less correct.
Answer: Cohen's d is a measure of effect size.  Standard deviation is a measure of spread.
The standard deviation is used in calculating Cohen's d, but other than that there is very little relation - they measure different things, they require different input and they answer different questions.


Leitura arquivo em C

Question: Ttenho a seguinte estrutura para leitura de cada linha de um arquivo:
fclose(arq); // fecha o arquivo para em seguida abri-lo em modo leitura apenas
arq = fopen(url, "r");
if(arq == NULL) {
    printf("Erro, nao foi possivel abrir o arquivo\n");
} else {
    system("cls");
    printf("\n **************************************** NOME DA EMPRESA - LISTA DE CLIENTES ****************************************\n\n");
    fflush(stdin);
    while (fgets(linha, TAM_BUFFER, arq)) { // lê cada linha do arquivo por vez, cada linha está na variável buffer
        printf("Cliente %d:\n", idx);
        idx++;
        fflush(stdin);
        // para cada linha capturada, atribui um valor a variável, para em seguida fazer a impressão
        fscanf(arq, "%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,]\n", cpf, nome, cnh, endereco, contato, passaporte, idoneo);

Problemas:

a primeira linha não é impressa (acredito que o programa está lendo
um ENTER e passa para a segunda linha, só não vejo onde);
após a impressão da primeira linha (que na verdade é a segunda), o
CPF do terceiro cliente é impresso isoladamente;
os dados do terceiro cliente não são impressos, daí pula para o
quarto cliente, como, assim como o segundo cliente, os dados são
impressos corretamente.

Essa sequência de problemas é o padrão da resposta.

Cada campo no arquivo está separado por vírgula, como pode ser notado no código acima.
Alguém pode me confirmar o famigerado ENTER que está sendo lido em algum ponto que não consigo detectar? Ou vê algum outro erro?
Comment: Tem como postar a saída como texto? Não consigo ver daqui do meu celular
Comment: Você deve ter percebido que não está lendo todos os clientes ímpares, correto? Isso acontece porque você está consumindo o arquivo em dois pontos distintos
Comment: Você quer dizer no fgets e no fscanf?
Comment: Sim. Estou escrevendo uma resposta detalhando isso
Answer: Para começar, como você não está tocando na stdin, você não precisa dar um fflush nela.
Outra coisa: usar fgets fará com que o ponteiro de leitura do arquivo seja movido para frente. Usar fscanf logo em seguida não conseguirá usar esse dados, pois eles já foram consumidos!
Como resolver isso? Tem algumas maneiras...

Como a entrada não está disponível, não posso tentar rodar e verificar se realmente faz sentido o código; fiz o que pude com os dados fornecidos

Retorno do fscanf
A função scanf e suas irmãs retornam um inteiro. O que esse inteiro quer dizer? Simples, quantos argumentos foram lidos. Essa função retorna a quantidade de caracteres consumidos pela leitura, ou negativo caso não consiga ler nada. Você pode encontrar a documentação aqui.

eu não tenho certeza em relação a argumentos do tipo %*

Isso quer dizer que a função pode ser o parâmetro do while. De modo geral, assumindo que seu fscanf está correto:
while (fscanf(arq, "%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,]\n", cpf, nome, cnh, endereco, contato, passaporte, idoneo) > 0) { // tenta ler, se possível é um cliente válido
        printf("Cliente %d:\n", idx);
        idx++;
        // para cada linha capturada, atribui um valor a variável, para em seguida fazer a impressão
        // resto do seu código

sscanf, leitura de uma string
Outra alternativa é manter o fgets e alterar a fonte de leitura. Uma das funções da família scanf é o sscanf:

scanf faz leitura da entrada padrão
fscanf faz leitura de um arquivo dado
sscanf faz leitura de uma string

O resto do código continua idêntico, só troque o fscanf por isso:
sscanf(linha, "%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,]\n", cpf, nome, cnh, endereco, contato, passaporte, idoneo);

Comment: Muito obrigado!!!
Comment: @Ângelo por nada! As informações que eu obtive através de seu texto eram parciais, mas espero que tenham sido suficiente para dar uma luz no seu problema

Leitura arquivo em C


How to handle variable number of process variables in Camunda

Question: I'm new to Camunda and didn't find any tutorial or reference explaining how to achieve the following:
When starting a process I want the user to add as many items as he likes to an invoice. On the next user task all those items and their quantity should be printed to somebody approving the data.
I don't understand yet how to get this 1:n relationship between a process and its variables working. Do I need to start subprocesses for each item? Or do I have to use a custom Java object? If so, how can I map form elements to such an object from within the Tasklist?
Comment: Perhaps these resources allow you to formulate an answer: https://groups.google.com/d/msg/camunda-bpm-users/KrZKWcUCSz0/80gAwGUCXz8J and https://github.com/camunda/camunda-bpm-examples/tree/master/usertask/task-form-embedded-serialized-java-object
Comment: And a question: Do you need the list as a Java List variable or do you intend to use it in task forms only (where a JSON string could do)?
Comment: Will have a look, thanks. An yes JSON is just fine, but it sounds like I have to write some JS inside the forms to serialize/deserialize this JSON manually.
Comment: This blog post may also be helpful: http://blog.camunda.org/2015/02/json-everywhere-how-to-use-json-in.html
Comment: @thorben Thanks, got most of it working, see remaining issues in my answer below. But these are different questions and don't need to get answered here.
Answer: I got it working with the help of the links provided by Thorben.
The trick is to use JSON process variables to store more complex data structures. I initialize such lists in my "Start Event". This can be done either in a form or in my case in a Listener:
execution.setVariable("items", Variables.objectValue(Arrays.asList(dummyItem)).serializationDataFormat("application/json").create());

Note that I added a dummyItem, as an empty list would lose its type information during serialization.
Next in my custom form I load this list and can add/remove items. Using the camForm callbacks one can persist the list.
<form role="form" name="form">

Name	Count	Price

                <input type="text" ng-model="i.name"/>
                <input type="number" ng-model="i.count"/>
                <input type="number" ng-model="i.price"/>

                    <button class="btn btn-default" ng-click="removeItem($index)">

                    </button>

                    <button class="btn btn-default" ng-click="addItem()">

                    </button>

</form>

Two things aren't working yet:

Field validation, e.g. for number fields
The dirty flag used on the "save" button doesn't get updated, when adding/removing rows


O que é code golf?

Question: Olhando as tags do site, me deparo com a tag code-golf, li a breve explicação:

code-golf
  Utilize esta tag quando somente quando a pergunta tem uma relação
  irrefutável à competição de código Code Golf. Tome muito cuidado ao
  utilizar esta tag, pois este é um tema fácil de ter perguntas de
  baixíssima qualidade. Code Golf é uma competição recreacional de
  programação com o intuito de resolver um problema específico no menor
  número de bytes, caracteres ou com algum tipo de restrição de código
  fonte.
Fonte: https://pt.stackoverflow.com/tags/code-golf/info

E gostaria de saber:

O que é essa competição?
Como seria um problema de uma competição Code Golf?
Exemplo de uma resolução de um problema Code Golf?
Comment: Estou na dúvida se é melhor a pergunta ficar aqui ou no meta
Comment: [Codewar](https://www.codewars.com/) é isso.
Answer: Definição de code-golf
Code Golf é uma competição para resolver um problema específico no menor número, de bytes ou linhas de código.

O termo code golf é derivado da semelhança de seu objetivo com o do golfe convencional, onde os participantes procuram alcançar a menor pontuação possível... Enquanto os jogadores de golfe convencional estão tentando minimizar a quantidade de golpes necessários para completar a partida, os code golfers estão se esforçando para reduzir o número de bytes de seus algoritmos.1

Puzzles (problemas) de programação precisam ser resolvidos (geralmente) com alguma restrição ou condição especial. Nessa competição pode se usar qualquer ferramenta disponível, desde que não vá contra as regras ditas no post.

Exemplos
Construir um relógio digital no Conway's Game of Life
Veja um prelúdio do post:

Sua tarefa é construir uma simulação Game of Life que represente um relógio digital:
Objetivos

O relógio exibe as horas e os minutos em decimal (12:00, 3:59, 7:24)
O padrão é periódico, e o estado é acompanhado sem qualquer interação externa.
A atualização de minutos é em intervalos regulares
Os dígitos são visíveis e claramente distinguíveis.
A atualização dos dígitos é no lugar e devem aparecer  próximos uns dos outros

Pontuação
Seu programa será pontuado nas seguintes coisas, em ordem (com critérios mais baixos atuando como desempatadores para critérios mais altos):

Tamanho da caixa de encadernação
Execução mais rápida
Contagem inicial de células vivas
Primeiro a postar

Resultado final:

Via browser para você ver funcionando também.

Era somente um bug
Outro code golf, um pouco diferente, o objetivo era conseguir desenvolver um algoritmo que printasse na tela, exatamente igual o texto abaixo:
1        2        3        4        5        6        7        8        9        0
1       2       3       4       5       6       7       8       9       0
1      2      3      4      5      6      7      8      9      0
1     2     3     4     5     6     7     8     9     0
1    2    3    4    5    6    7    8    9    0
1   2   3   4   5   6   7   8   9   0
1  2  3  4  5  6  7  8  9  0
1 2 3 4 5 6 7 8 9 0
1234567890
1 2 3 4 5 6 7 8 9 0
1  2  3  4  5  6  7  8  9  0
1   2   3   4   5   6   7   8   9   0
1    2    3    4    5    6    7    8    9    0
1     2     3     4     5     6     7     8     9     0
1      2      3      4      5      6      7      8      9      0
1       2       3       4       5       6       7       8       9       0
1        2        3        4        5        6        7        8        9        0

A resposta aceita foi dada  utilizando uma linguagem específica para code golf stack-based. Foi essa abaixo, utilizando somente 13 bytes:
17F9ÝÀN8αð×ý,

Simples e em pouquíssimas linhas foi resolvido. Você pode ver como fica o resultado aqui.
Explicação abaixo:
17F            # para N em [0 ... 16] faça
   9Ý          # empurre de [0 ... 9]
     À         # virar esquerda
      N8α      # computa diferença absoluta entre N e 8
         ð×    # empurre esse tanto de espaços
           ý   # mescla a lista de dígitos com a seqüência de espaço como separador
            ,  # print

Todos esses e vários outros code golf podem ser encontrados na comunidade específica da SE em
Programming Puzzles & Code Golf.
Answer: Segué a resposta:

"Code golf é um tipo de competição recreacional de programação de computadores em que os participantes se esforçam para alcançar o código fonte mais curto possível que implemente um determinado algoritmo. Código de golfe não deve ser confundido com sizecoding, um concurso para alcançar o menor código binário executável. O código de reprodução de golfe é conhecido como "scripting de golfe". Os torneios de golfe de código também podem ser nomeados com a linguagem de programação usada (por exemplo, Perl golf)"

Fonte: wikipedia
Exemplo: www.code-golf.com/
Comment: Esse link pode ser uma boa sugestão, mas sua resposta não terá validade se um dia o link deixar de funcionar. Além disso, é importante para a comunidade ter conteúdo aqui no site mesmo. Seria melhor incluir mais detalhes na sua resposta. Um resumo do conteúdo do link já ajudaria bastante! Saiba mais sobre o assunto neste item do nosso FAQ da Comunidade: [Queremos respostas que contenham somente links?](http://meta.pt.stackoverflow.com/q/42/74)

O que é code golf?


Special characters in special places

Question: In some European languages we use accents like à or special letters like ç. So in the html I use à  ç
But what about places like the title of the page, description tag, the alt of an img or the title of a link. I think I can write special characters in that places but what is the most correct way to write this type of code? I mean should I use à or à ?
Comment: This question appears to be off-topic because it is about SEO, not programming.
Comment: Sorry, it is not only seo. My question is what is the correct way to write that type of html code. Not to get visitors, just to do good code
Comment: `` and you're good to go even with šđčćž just make sure to encode `&` using `&` ;) or just be careful with it's use in HTML5
Comment: possible duplicate of [Do I need to use HTML entities for special characters if I'm using the UTF-8 charset?](http://stackoverflow.com/questions/7405007/do-i-need-to-use-html-entities-for-special-characters-if-im-using-the-utf-8-cha)
Comment: I do not understand why this is not the right place to ask that. It is just a question about how to write good code. Can someone explain ?
Answer: It does not matter, because entity references like à are resolved by HTML parsers, in browser, search engines, and other relevant software. Provided that the character encoding is properly declared, as it should be anyway, the difference is only in writing HTML documents.
If you think that it is easier, in some authoring environment, to create and edit HTML documents containing à rather than à, consider whether this justifies reduced readability of HTML source (to human eyes).
There is of course size difference between, say, à (normally 7 bytes) and à (usually 1 or 2 bytes depending on encoding), and the size affects data transfer times, but these days such issues are seldom important. (Text content tends to be a minor part of the total size of a page in bytes.)
Whether people use accents in searches is irrelevant here. The entity à stands for the very same character as à, with the accent.

Special characters in special places


Solving for $x$ in $x(t) = \frac{-2}{3}\cos(10t) + \frac{1}{2}\sin(10t)$

Question: A physics problem is asking me a to find when a weight on a spring crosses the equilibrium point.
The equation of motion given is $$x(t) = \frac{-2}{3}\cos(10t) + \frac{1}{2}\sin(10t)$$
Basically, I need to solve for $t$ when $x(t) = 0$. How do I solve for $t$ in such an equation?
Comment: **Hint** Divide by $\cos(10t)$, as long as $\cos(10t)\neq 0$.
Comment: if you have $a \cos(\omega t)+b \sin(\omega t)=0$ then you take one term to the right hand side and divide both sides by say $\cos$  to get an equation in terms of tangent. Then you solve that equation.
Answer: So, $\frac 2 3 \cos 10t=\frac 12 \sin 10t$
So, $$\frac{\cos 10t}{3} =\frac{\sin 10t}4$$
So, $\tan 10t=\frac 4 3\implies 10t=n\pi+\arctan \frac 4 3$ where $n$ is any integer.
So,$t=\frac{n\pi+\arctan \frac 4 3}{10}$
For $n=0,t=\frac{\arctan \frac 4 3}{10}$
Also,  $$\frac{\cos 10t}{3} =\frac{\sin 10t}4=\pm\frac{\sqrt{\cos^2 10t+\sin^2 10t}}{\sqrt{3^2+4^2}}=\pm\frac 1 5$$
$\implies \cos 10t=\pm \frac 3 5,\sin 10t=\pm \frac 4 5$
$\cos 10t\cdot \sin 10t=\cos^210t\tan 10t=\cos^210t\cdot\frac 4 3>0$
So, the sign of $\cos 10t, \sin 10t$ will be same.
Comment: @Imray, please find the edited answer.
Comment: @Imray, $x(t)=0\implies  \frac{-2}{3}\cos(10t) + \frac{1}{2}\sin(10t)\implies \frac{2}{3}\cos(10t)=\frac{1}{2}\sin(10t)$, then divide either sides by $2$
Comment: Put $10t=\arctan \frac 4 3\implies \cos 10t=\pm \frac 3 5,\sin 10t=\pm \frac 4 5$
Comment: @Imray, sorry for the confusion.Please find the rectified answer.
Comment: So what's the first value of $t$ where $x(t)$ is zero?
Comment: So when $t$ is $\approx .0927$, the equation should be equal to zero?  But when I plug it the value it's still pretty far from zero.
Comment: Why am I not getting zero when I set $t = arctan \frac{4}{3}$
Comment: ok Thanks it works now!
Comment: It's not clear how you went from $\pm \frac{1}{5}$ to the next step... Where did the $tan(10t)$ come from?


How do I set a block title to the title of a referenced node?

Question: In Views 3, I have a block that is showing content from a particular Node ID. I'd like to have the title of that block set dynamically to what the referenced page's title is. I know this would be accomplished using Contextual Filters and that my display's title would be an argument, like %1 but I'm uncertain what the Contextual Filter settings should be. I'd rather not use PHP code if avoidable simply because I don't have the 'PHP Filter' module enabled on most sites I create.
Which settings should I use to make a block title the same as the title of a referenced node?
Answer: In Views, with a block output & Content Entity Relationship set up, in 'Contextual Filters':
WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED
- Override title (tick this & I used %1 with some text)
which offers "Override the view and other argument titles. Use "%1" for the first argument, "%2" for the second, etc."
Answer: You can't set the block title from within the view using contextual filters the way you are thinking, only the title of the view itself. On this page there is a similar goal and a few suggestions:
Dynamic block titles
Answer: I know this is old, but maybe it can help someone. Just put on the view title <code>[title]</code>, and add the field title to field list in view; then, select Exclude from display. Done!
Comment: This is not dynamic. You have set it to be based from one particular node which is unchangeable. The idea is for the title to change based on the node that is being viewed. Thanks anyhow.
Comment: @Pierre.Vriens Where do you see a new question? There aren't questions at all.


Local Link Multicast Name Resolution replaces NetBIOS, yet textbook says otherwise

Question: I am studying from Configuring Windows Server 2008 Network Infrastructure (our environment still has significant Windows 2008 R2 servers), and one question asks

You are working on a Windows Server 2008 R2 computer named WS08A. You
  cannot connect to computers running Windows XP on the local network by
  specifying them by name in a UNC path such as \computer1.
What can you do to enable your computer to connect to these computers
  by specifying them in a UNC?

The choices are

Enable IPv6 on WS08A.
Enable NetBIOS on WS08A.
Enable Local Link Multicast Name Resolution (LLMNR) on WS08A.
Disable IPv6 on WS08A.

I believe the correct choice is Enable Local Link Multicast Name Resolution (LLMNR) on WS08A. because it replaces NetBIOS. However, the textbook says Enable NetBIOS on WS08A is the answer.
When I researched this, I read somewhere that using LLMRN to connect to a 32bit machine will take longer than if you use NetBIOS, but this connection is still possible.
http://www.schoolleader.com/Documentation/Disabling_LLMNR_Causing_Slow_Networks.pdf
If this is the case, why can't they re-write the question to ask,

"Which is the faster way to connect to Windows XP by specifying them
  in a UNC?"

Or is there something else I am missing?
Answer: You can't use LLMNR in that scenario because it was introduced with Windows Vista/Server 2008. Windows XP does not support it.
Since Windows XP is end of life, and nobody should be using it anymore, (though some are) you can use LLMNR once you have completely eliminated XP from your environment.


Why does my bass not provide enough gain for my audio interface?

Question: I bought a used bass some time ago to teach myself some basics and have fun. I don't have a dedicated bass amp so I play it over my audio interface (Behringer U-Phoria UMC22), DAW (Reaper) and PC speakers.
Problem is, even when maxing out both the gain on the bass itself and the interface instrument input and also plucking the strings pretty hard, I'm still not even close to maxing out the meter in Reaper. I can scale up the signal digitally, of course, but this results in a LOT of unpleasant noise. The 9V block battery the bass contains is freshly replaced, so it probably can't be the issue.
I'm just starting into the whole electric music category, so I don't know a whole lot about it. Is a bass even meant to be plugged directly into the instrument input of an audio interface? Or do people normally put their bass amp (which I don't own) in between the bass and the interface to ramp up the gain? Could be anything wrong with the bass itself (other than the gain issue, it sounds fine and looks fine on both the outside and inside, as far as I can tell)? Or is it just normal equipment behaviour and I need to put up with it?
Comment: Which input are you using? The mic/line one or the inst2 one? If there is a battery in the bass, it is not a passive bass right?
Comment: @Tom 2nd one (6.3mm jack). As far as I'm aware this is the dedicated instrument input. The 1st one (XLR) is for microphones only, I think.
Comment: Nope, you can put a jack in there too. As your bass is pre-amplified, the impedance matching will probably be better there.
Comment: Hard to say, obviously when you max out you lose some quality. But it does say that you have some room decrease the gain of this input and likely get a better sound as less gain means less noise (and max out is extremely noisy).
Answer: From the information you provide, it seems that your bass is already fitted with a pre-amplifier. It is thus giving a line signal.
On your sound card, the Mic/line input (which is a combo input that can accommodate XLR or Jack) is low impedance input and thus will have a better impedance matching with the pre-amp of the bass and might give you more juice than the second input which is meant to receive signals from passive (high impedance) instruments such as normal electric guitars.
You can try on the Line input to see if you get more signal, it should be more coherent to plug it there (beware not to have phantom power activated).
Another point is, if your signal is strong enough compared to the background level, this should not bother you for recording as you can very likely push a bit the gain inside Reaper while keeping a good sound quality!
Comment: Would a device like this https://www.thomann.de/gb/behringer_vtone_bass_bdi21_analog_modeling_preamp.htm enable me to plug the bass in the 2nd input without the current issues? I'd really like to reserve the 1st input for my microphone, as I want to use both simultanously.
Comment: @MaxD as this is also acting like a DI unfortunately you will likely get the same problem…
Comment: Is there a similar device that would create the desired effect?
Comment: @MaxD Arf, recommendations are a bit offtopic here, but basically anything with more than one line level input! Could be a sound card, or a small mixing table (that you feed after to your card) for instance.
Comment: Active basses generally give out _higher_ signal levels than passive ones, so they can drive hi-Z instrument inputs just as well as low-Z line inputs. Impedance matching is not really necessary for audio. That this doesn't work for the OP indicates theres something wrong with either the bass, or the input, or both.
Comment: @leftaroundabout I agree but the signal to noise ratio will be better will matched impedance. Also, as these two inputs are of different types, maybe their amplifiers are not exactly the same...
Answer: I finally found the problem. In Windows Settings -> Sound -> Device Properties (at "Input") for some reason the volume was set to 76%. I turned it up all the way to 100% and have had more than enough gain ever since.
Comment: anything above about 12-14ms starts to be (generally) perceived as late/echo/unique event. the shared mode WASAPI starts at 20ms due to fixed buffers
Comment: Are you using the ASIO drivers?
Comment: @topoReinstateMonica I'm using FlexASIO, but only because the UMC22 doesn't have its own driver. Why you asking?
Comment: I was just interested whether that setting you mentioned has any effect with ASIO drivers. Sounds like it does! Strange that there's no driver, I thought I recalled installing one for my UMC404.
Comment: @topoReinstateMonica Yep as far as I know the UMC22 is the only Behringer interface without a dedicated driver. Not sure what you mean with the first part.
Comment: re: "the first part," The windows control panel sound settings are usually for the WDM or DirectX driver. ASIO is a different, hardware-level driver that usually communicates with the hardware separately.
Comment: @Yorik I'm using the WASAPI backend of FlexASIO in shared mode (so I can listen to youtube tutorials and play at the same time). Haven't tested it with other modes but in THIS mode the setting certainly makes a difference.
Comment: Yeah quick check of the docs indicates that shared mode goes through the whole windows pipeline. That would probably explain it. ( https://github.com/dechamps/FlexASIO/blob/master/BACKENDS.md ) Super high latency though. I use a mixer and two sound devices for "shared mode"
Comment: @Yorik Dunno what latency you would consider "super high", but if I don't notice it at all it's certainly good enough for me.


How to split a string correctly by array of double curly brackets in js regex?

Question: I have a regex that matches the words with double curly brackets:
    let str = 'This is a {{test}} string with {{multiple}} matches.';
    let regex = /\{\{(.+?)\}\}/g;
    let matches = str.match(regex);
    console.log(matches); // ['{{test}}', '{{multiple}}']

Now I want to split str into chunks by matches array:
 let regex2 = new RegExp(`\\b${matches.join('|')}\\b`, 'gi');
 let substrings = str.split(regex2);
 console.log(substrings);

But the output of substrings is "This is a {{test}} string with {{multiple}} matches.".
What I was expected is: ["This is a ", "{{test}}", " string with ", "{{multiple}}", "matches."]
But I know my regex is correct because if I do it without using those double curly brackets, it works. but I must need to use them to get what I want.
So why regex doesn't split them as I was expecting? how can I change the code so that it will work as expected?
Comment: `let regex2 = new RegExp(\`(${matches.join('|')})\`, 'i');` should suffice.
Answer: You can achieve that by using the paranthesis () outside the whole group. Doing so, will include the separator in the result.
Try this regex - /({{.+?}})/g

const str = "This is a {{test}} string with {{multiple}} braces"
console.log(str.split(/({{.+?}})/g))

Basically, If separator is a regular expression that contains capturing parentheses ( ), matched results are included in the array.


Cold Fusion 9 - Remove JSON string from text

Question: I am generating a preview of certain length out of a text string. The text was made out of a HTML string where the HTML code has been removed. Because of certain reasons there are some JSON block within the text. These JSON blocks are placeholders to retrieve information from a database and replace the json string with it on page load.
For the preview the JSON must not be in the string. Therefore I have to clean the string and remove the JSON blocks.
Here is an example of how the string may look:
Pellentesque et vulputate felis. {"bla":"blabla", "blubb":"blubablub"} Maecenas tortor ex, commodo eu massa a, vehicula cursus erat. Nam rhoncus, nunc ut lobortis pretium, libero lorem {"blurb":"blarblar", "blabb":"blabablurb", "test":"testatest"} facilisis urna, et gravida tellus turpis ut nisi. Nulla in ullamcorper metus. Sed sed blandit magna. Integer fermentum.

How do I get these two JSON blocks using regex and remove it?
{"bla":"blabla", "blubb":"blubablub"}
{"blurb":"blarblar", "blabb":"blabablurb", "test":"testatest"}

It works with Rematch() and a following cfloop over the array of JSON blocks. But is it possible with ReReplace()?
Just found the solution
ReReplace(mystring, "\{([^}]*)\}", "", "ALL")

Sry for bothering.
Comment: Simply write the solution as an answer below, instead of an edit in your question (yes, you can answer your own questions here). Note that your approach does not work for JSON with nested objects.
Answer: Just found the solution
ReReplace(mystring, "\{([^}]*)\}", "", "ALL")

This solution doesn't work for JSON with nested objects but in my case it's enough.


Why is my localStorage clear on redirect (URL change)?

Question: I am trying to persist data between pages, a variable that I collect in my URL. So my user will enter a URL like: https://my-solution/event/:identifier
I want to keep that identifier but I need to go through authentication first. I store my identifier in the local storage or Session storage before the redirection and when I redirect to https://my-solution/auth, this entry disappear from local storage.
Once the auth succeed and I store my user jwt token in this very same local storage, it persists ! My identifier is been deleted but my token persist (and every variable stored after that btw); After my token is being stored I can redirect all I want, and my data persist. I don't understand what's happening...
It is a create-react-app solution. Working with react-router and redux.
Is this linked to the way I redirect ? I use <Redirect> from react-router but also windows.location.href sometimes (inside useEffect callbacks).
I did tried to store a non-dynamic variable like a basic string :
localStorage.setItem("test", "mytestValue")

And this entry does persists. Is this behavior related to dynamic values ?
I do have a complicated workaround : passing the data through location.search in every url and trying in every component to store it until the data persists in the local storage... But I want to know if I am doing something wrong here.
Thank you !
Here is my architecture flow :
Index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';

import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import reducer from './reducers';
import thunk from 'redux-thunk';
import { signalRMiddleware } from './middlewares/signalRMiddleware';

import 'bootstrap/dist/css/bootstrap.css';
import 'primereact/resources/themes/nova/theme.css';
import 'primereact/resources/primereact.min.css';
import 'primeicons/primeicons.css';

const store = process.env.REACT_APP_WITHOUT_SIGNALR == "true" ? createStore(reducer, applyMiddleware(thunk)) : createStore(reducer, applyMiddleware(thunk, signalRMiddleware()))
ReactDOM.render(
    <Provider store={store}>
        <BrowserRouter basename={process.env.PUBLIC_URL}>
            <App />
        </BrowserRouter>
    </Provider>,
    document.getElementById('root')
);

App.tsx
import React from 'react';
import './App.css';
import Router from './components/Router';
import moment from 'moment';
import 'moment/locale/fr';
moment().locale('fr');

function App() {
  return (
      <Router />
  );
}

export default App;

Router.index
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import ProtectedRoute from './ProtectedRoute';
import UtilsService from '../../services/utils.service';

function Router() {
    const AuthRouters = UtilsService.getRoute('/auth').component;
    const BackofficeRouters = UtilsService.getRoute('/backoffice').component;
    const EventLayout = UtilsService.getRoute('/').component;
    const MultiEventLayout = UtilsService.getRoute('/multiEvents').component;
    const ChatLayout = UtilsService.getRoute('/chat').component;
    const ChatOtoLayout = UtilsService.getRoute('/chat_oto').component;
    const QuestionsLayout = UtilsService.getRoute('/questions').component;
    const PlanningLayout = UtilsService.getRoute('/planning').component;
    const AccueilMobileLayout = UtilsService.getRoute('/accueil_mobile').component;

    return (
        <Switch>
            <Route path="/auth" render={(props: any) => <AuthRouters {...props} />} />
            <ProtectedRoute path="/backoffice" isBackoffice={true} render={(props: any) => <BackofficeRouters {...props} exact />} />
            <ProtectedRoute path="/multiEvents" isBackoffice={false} render={(props: any) => <MultiEventLayout {...props} />} />
            <ProtectedRoute path="/room/:id" isBackoffice={false} render={(props: any) => <EventLayout {...props} />} />
            <ProtectedRoute path="/event/:identifier" isBackoffice={false} render={(props: any) => <EventLayout {...props} />} />
            <ProtectedRoute path="/questions/:idButton" isBackoffice={false} render={(props: any) => <QuestionsLayout {...props} />} />
            <ProtectedRoute path="/chat_oto" isBackoffice={false} render={(props: any) => <ChatOtoLayout {...props} />} />
            <ProtectedRoute path="/chat/:id" isBackoffice={false} render={(props: any) => <ChatLayout {...props} />} />
            <ProtectedRoute path="/planning/:idEvent" isBackoffice={false} render={(props: any) => <PlanningLayout {...props} />} />
            <ProtectedRoute path="/accueil_mobile/:idEvent" isBackoffice={false} render={(props: any) => <AccueilMobileLayout {...props} />} />
            <ProtectedRoute path="/" isBackoffice={false} render={(props: any) => <EventLayout {...props} />} />
        </Switch>
    );
}

export default Router;

ProtectedRoute.tsx
return (
        <Route
            {...rest}
            render={props => {
                let eventUrlIdentifier = "";
                if(props.match.path === "/event/:identifier"){
                    let url = props.match.url;
                    let s = url.split("/");
                    eventUrlIdentifier = s[2];
                }
                if (!fetchAllConfLoading && isClientSettingsLoaded) {
                    //process auth anonymous
                    if (user == null) {
                        if (clientSettings.monoEventId != undefined && clientSettings.allowAnonymous != undefined) {
                            if (!clientSettings.allowAnonymous) {
                                // Redirection vers /Auth si la connexion anonyme n'est pas autorisé pour un mono-event
                                return (
                                    <Redirect to={{ pathname: '/Auth', state: { from: props.location }, search: eventUrlIdentifier }} />
                                );
                            }
                            else {
                                return (
                                    <Redirect to={{ pathname: '/auth/anonyme', state: { from: props.location }, search: eventUrlIdentifier }} />
                                );
                            }
                        }

Answer: session storage and local storage will remain only for the same domain. If domain changes then, the values stored in either one of them will be gone. Work around for this to use cookies to store data between two pages of different domains.


C++ map custom comparator using multiple object properties

Question: Let's say I have a map of students with ID as the key and Student object as the value. Here's the illustration:
struct Student{
  int id;
  int score;
  string name;
}

map<int, Student> students;

I want to sort the map in the following order: Sort the students based on their test score, the student with lower ID comes first if they got the same score
Is it possible to make a custom comparator using multiple object attributes? How can I do that?
I'm using the map because I also need the random access, is there any better approach instead of using map for this case?
UPDATE
I've changed the key with a new Object Mapkey with ID and score as the properties. And then I sort the map by comparing those properties.
But the problem is: it's kinda tricky to get the student value from the map since the score changes over time and I have to update the key. I'm wondering if there's a better and simpler solution.
Here's my implementation:

struct Mapkey {
    int id;
    int score;
};

struct cmp {
    bool operator()(const Mapkey &p1, const Mapkey &p2) const {

        if (p1.score == p2.score) {
            return p1.id < p2.id;
        }

        return p1.score > p2.score;

    }
};
map<Mapkey, Student*, cmp> sectionMap;

Comment: Absolutely! What is your attempt? map provides O(logN) access. map can only order on key. So may you want std::set.
Comment: I want to store the students where I can get students with the highest and the lowest score. But I also want to have the fastest way to get the student data by their ID, is it achievable if I use std::set? @CaptainGiraffe
Comment: Also, the score will be updated over time, so I need the fastest way to pop, reinsert, and sort the data again
Comment: It is understood what you want, but can you show your attempt at implementing this comparator, and explain, ***specifically*** what your question is, what problem are you having with your comparator? Do you know how to implement a custom map comparator?
Comment: I just posted my implementation @SamVarshavchik
Comment: Since the score changes over time, including it in the key is a very bad idea. If you need to update a score, you cant avoid popping the old score key and then inserting the new score key
Comment: @Sigmalalalala Please check out my edited answer using a vector of structures.
Comment: The comparator looks fine to me. However, map keys are always `const`, and once in the map they cannot be modified in place. It doesn't matter how the comparator works, this is always the case. To change a key, the key and its value get removed from the map and a new key and the same value get added. There are no other alternative. C++ just doesn't work any other way. If somewhere in the program the key gets modified how could a map know that it must magically re-sort itself, it can't.
Answer: If I understood you correctly, then you want to sort your Student objects based on their test scores first. In case they have the same score, then their ID is used as a secondary key instead.
I would recommend using a class for this. You can use the comparison operator to achieve what you want the following way:
bool operator< (const Student& left, const Student& right)
{
    if (left.score == right.score)
        return left.id < right.id;
    else
        return left.score < right.score;
}

You can place your objects in an array or a vector, it is really up to you.
Edit: an alternative solution by Remy:
bool operator< (const Student& left, const Student& right)
{
    return std::tie(left.score, left.id) < std::tie(right.score, right.id);
}

Edit2: Here is the complete implementation using a vector of structures. If this is not what you were looking for, then I give up.
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

struct Student
{
    int id;
    int score;
    std::string name;

    // Constructor
    Student(int a, int b, std::string s) : id(a), score(b), name(s) {}

    // Operator overloading
    bool operator < (const Student& obj) const
    {
        if (score == obj.score)
            return id < obj.id;
        else
            return score < obj.score;
    }

    // Printing
    void print()
    {
        std::cout << "id: " << id << ", score: " << score << ", name: " << name << '\n';
    }
};

int main()
{
    std::vector<Student> students;

    students.push_back(Student(1, 55, "A"));
    students.push_back(Student(4, 78, "D"));
    students.push_back(Student(3, 55, "C"));
    students.push_back(Student(2, 55, "B"));
    students.push_back(Student(5, 65, "E"));

    std::sort(students.begin(), students.end(), std::less<Student>());
    //std::sort(students.begin(), students.end()); // You can use this too
    std::cout << "Sorted vector:" << '\n';

    for (auto it = students.begin(); it != students.end(); ++it)
        it->print();

    std::cout << '\n';
    return 0;
}

Output of the code above:
Sorted vector:
id: 1, score: 55, name: A
id: 2, score: 55, name: B
id: 3, score: 55, name: C
id: 5, score: 65, name: E
id: 4, score: 78, name: D

Comment: This can be greatly simplified using `std::tie()`, eg: `bool operator< (const Student& left, const Student& right){ return std::tie(left.score, left.id) < std::tie(right.score, right.id); }`


Sql Date query for birthday

Question: I have table like this:
+----------+------------+
| name     | birthday   |
+----------+------------+
| jean     | 1988-08-09 |
| andrew   | 1990-09-20 |
| jennifer | 1980-09-05 |
| Harry    | 1985-10-25 |
| Chris    | 1987-09-22 |
+----------+------------+

I want to show result from birthday table where birthday just at September and date between 4 and 21 like this:
+----------+------------+
| name     | birthday   |
+----------+------------+
| andrew   | 1990-09-20 |
| jennifer | 1980-09-05 |
+----------+------------+

Can anybody help me, please?
Answer: SELECT name,
       birthday
FROM T
WHERE MONTH(birthday) = 9
AND DAY(birthday) > 4
AND DAY(birthday) < 21;

Comment: can i add more condition to that like date between 4 and 21 so i can just get andrew and jennifer??
Comment: Absolutely. Add `AND DAY(birthday) >= 4 AND DAY(birthday) <= 21` to the end of that query. If you'll update your question to include that, I'll add it to my answer.
Comment: done edit it.. :)
thank you so much...
Answer: SELECT NAME,BIRTHDAY
FROM YOURTABLE
WHERE MONTH(BIRTHDAY)=9 AND DAY(BIRTHDAY) BETWEEN 4 AND 21

Sql Date query for birthday


Can a fielder get a run-out by removing bails or stumps with their upper arm or shoulder?

Question: During a run-out attempt, removing the bails using the hands holding the ball is a valid run-out.
But when a fielder removes the bails or stumps using his elbow or shoulder, is it still a valid dismissal?
Answer: Yes, this is explicitly allowed by the Laws of Cricket; quoting from Law 29 "The Wicket is Down":

29.1.1 The wicket is put down if a bail is completely removed from the top of the stumps, or a stump is struck out of the ground,
[...]
188.8.131.52 by a fielder with his/her hand or arm, providing that the ball is held in the hand or hands so used, or in the hand of the arm so used.

(my emphasis).
Comment: The latest update to lords.org has made it very hard to find/link to the specific Laws. I'll update this answer if I find a way to do it, or anyone else feel free to propose an edit...
Comment: I think it's perfectly adequate to cite the law (and exact section(s) as appropriate) and allow users to make their own way to Lords.org if they want to check. It's not like the new interface is confusing or difficult.


Implicit declaration of function - C99

Question: I am currently using Xcode 4, and in my .pch file I have this macro:
#define localize(s) NSLocalizedString((s), nil).
When I try to use this macro in some .m file, I receive this warning: Implicit declaration of function 'localize' is invalid in C99.
This code compiles without a problem, but how can I fix this so I don't get a warning?
Comment: I wasn't able to reproduce the issue, it compiles and runs just fine, no warnings.
Comment: It seems it was a bug in XCode... 4.0.2 I think. 4.2 betas work fine.
Answer: I had this problem when I did a global replace of NSLog with DLog.  I foolishly included the
#define DLog(...) NSLog(...

statements, so I ended up with
#define DLog(...) DLog(...

which caused the warnings, and a linker error.
Answer: Implicit function declarations are those that the compiler sees the first time used as a function call (as opposed to those where a prototype or the function definition is seen first).
Apparently your code used localize(foo) but the macro definition was not visible. Possible reasons: you forgot to #include the file containing the localize macro or the precompilation of headers went south an did not include the localize macro so it was left unexpanded.
Comment: But that would indicate a bug in Xcode, if the macro was defined in the project's prefix header, because that header should be precompiled and available to all compilation units (e.g. every .m file in the project). FWIW I still see this bug occasionally in Xcode 4.4.1, but quitting and relaunching Xcode fixes it.
Comment: That could probably be filed under 'precompilation of headers went south'. With bugs in tools, anything can happen.
Comment: I've seen this happen in Xcode 5. The safest way to get rid of the warning message is to simply include the relevant header file inside the file showing the error.
Answer: Another "foolish" mistake I ran into was the fact that my DLog was defined in the prefix header of the iOS target, so I had to copy it over to the prefix of the OSX target, as well...
Answer: I had this problem because I accidentally imported CocoaLumberjack like this:
#import <CocoaLumberjack/DDLog.h>

Apparently the CocoaLumberjack team modularized the code some more; and macros like DDLogError are now defined separately in their own header file.
I replaced the import statement with this and the error went away:
#import <CocoaLumberjack/CocoaLumberjack.h>

Answer: In my case only one file was giving this error. Turned out that I added it to the project's tests target membership (in the File Inspector on the right).

Implicit declaration of function - C99


JMeter - Response code: Non HTTP response code: java.net.SocketException Response message

Question: Recorded Blazemeter scripts are not working in JMeter, getting following error message.
Response code: Non HTTP response code: java.net.SocketException
Response message: Non HTTP response message: Software caused connection abort: recv failed
Answer: The error indicates that JMeter fails to receive the response most probably due to network error (connection has been terminated or timed out)
In order to get more information you should increase JMeter Logging verbosity for Apache HttpComponents by adding the next line to log4j2.xml file
<Logger name="org.apache.http" level="debug" />

it would also be a good idea to enable network debugging on Java level, it can be done by adding the next line to system.properties file:
javax.net.debug=all

and you should get way more information in jmeter.log file and STDOUT, this way you will get the error reason and would be able to handle it.
It worth also checking:

that your application is not overloaded as it might be the case the application cannot handle the load delivered by JMeter hence fails to respond properly
if you're absolutely sure that the application works normally and the problem is at JMeter end you can follow workarounds from JMeterSocketClosed wiki page


What is the exact size of UIModalPresentationFormSheet in iPad

Question: I am using following code for displaying a Screen/View Controller.
SearchParams *nxt=[[SearchParams alloc] initWithNibName:@"SearchParams" bundle:nil];

UINavigationController *nvc=[[UINavigationController alloc] initWithRootViewController:nxt];

nvc.modalPresentationStyle=UIModalPresentationFormSheet;

[self.preLCtr.preCinescape_iPadViewController presentModalViewController:nvc animated:YES];

I am not sure about the size of PesentationSheet. I tried to take screenshots & take dimentions/size. But its not the exact solution.
Question : What is the exact size of Present-Modal-Sheet in iPad ?
Comment: According to the screen-shot taken, it is 545 × 625 pixels. Is it the correct one ?
Comment: http://stackoverflow.com/questions/30491951/what-exactly-is-the-height-of-modalpresentationstyle-formsheet-on-ipad You can find it here.
Answer: This is what I found for the current (iPad 3) iO6 dimensions:
BOUNDS: 540.000000, 620.000000 - Portrait-no-keyboard.
But you shouldn't use this for any code. Follow the correct answer.
Comment: It does seem bad to do this, but I wanted to recreate the form sheet size with a custom presentation controller and... it does seem to be a fixed 540x620. I tested a few different iPads and orientations and it never changes.
Answer: According to Apple's documentation the size could change depending on the available screen size:

The width and height of the presented view are smaller than those of the screen and the view is centered on the screen. If the device is in a landscape orientation and the keyboard is visible, the position of the view is adjusted upward so that the view remains visible. All uncovered areas are dimmed to prevent the user from interacting with them.

Maybe in the viewcontroller that is loaded to the FormSheet you can determine the view size at runtime by using: self.view.bounds;
If you need to resize the FormSheet i saw some answers on stackoverflow
Answer: If you're adjusting a freeform view controller so that you can get the aspect right for a modal transition with form sheet presentation style, note that there is a Form Sheet option under the Size dropdown in the Size Inspector. I didn't notice this at first.
Comment: How do you choose a custom form sheet size - no matter what I try - I get a standard form sheet?
Answer: I checked different orientation and also in multi window mode, the default size is
width: 540, height: 620.
And below is the screenshot from Reveal.
Comment: Shout out to Reveal!


Where is template_preprocess() located

Question: where is the template_preprocess() function located? It seems that my markaspot theme (mas) call this function but I can not find this funktion in a file.
Thanks for your help.
Answer: It's in
includes/theme.inc.

Docs are here.
Next time just put the name of the function in Google...the docs on Drupal.org will tell you what file any function is in.
Comment: You beat me and clicked "post" faster. Again. :D And for search, if someone knows the exact name of a function, search box located on the right of https://api.drupal.org may be faster and more accurate than Google, in my experience.
Comment: Yep good point about the search on d.o, that's a better idea than google :)

Where is template_preprocess() located


How to calculate percent deviance explained on square-root-transformed dependent variable?

Question: I have a multiple linear regression model with a square-root transformed dependent variable.
I want to report % deviance explained for each parameter. I assume I need to back-transform in some way, but I am not sure how. Or is it okay to report % deviance explained on the original (non-transformed) model?
I am using R to calculate model deviance, if it matters.  I appreciate any insight on this issue.
Comment: You mention deviance. It sounds like you're fitting a GLM. Why transform?
Answer: The % deviance explained is calculated by comparing the predictions (fit$fitted.values in R)  for Y to  actual values of Y. It does not take into account any transformations on the explanatory variables. You might need to take into account the fact that you tested a raft of transformations when doing inference. With each transformation you are implicitly increasing the number of degrees of freedom for your numerator. R will report an adjusted R^2 but to be true to your modeling process you might need to recalculate it.


Convergence with respect to $d_1(x,y)=\sum^\infty_{i=1}\frac{1}{2^i}\frac{|x_i-y_i|}{1+|x_i-y_i|}$ is equivalent to pointwise convergence?

Question: This was part of an exercise given to the students in my class last week which I wasn't sure how to do. The question starts by studying the metric $d_1$ defined on $\mathbb{R}^\infty=\{x=(x_i)\mid i\in\mathbb{N}\}$ given by
$$d_1(x,y)=\sum^\infty_{i=1}\frac{1}{2^i}\frac{|x_i-y_i|}{1+|x_i-y_i|},\qquad x,y\in\mathbb{R}^\infty.$$
The students are asked to show that this is indeed a metric and compare it with another metric defined on the same space, none of which is difficult. Finally the question asks to show that if $(x^{(n)})_{n\in\mathbb{N}}\subseteq\mathbb{R}^\infty$ is a sequence, then its convergence to a point $x\in\mathbb{R}^\infty$ with respect to $d_1$ is equivalent to its pointwise convergence to the same point.
As I understand it, pointwise convergence should mean that for each $i\in\mathbb{N}$, and each real $\epsilon>0$ there exists $N=N(\epsilon,i)\in\mathbb{N}$ such that $|x^{(n)}_i-x_i|<\epsilon$ whenever $n>N$.

Now one direction is clear to me, but proving that pointwise convergence implies $d_1$-convergence is not. Can anyone help me out with this direction?

What I need to show is that given any real $\delta>0$ there exists $M=M(\delta)\in\mathbb{N}$ such that
$$d_1(x^{(n)},x)=\sum^\infty_{i=1}\frac{1}{2^i}\frac{|x^{(n)}_i-x_i|}{1+|x^{(n)}_i-x_i|}<\delta$$
whenever $n>M$, using the assumption of pointwise convergence which I believe to have interpreted correctly just above. The problem seems to be that whilst a suitable $M=M(\epsilon,i)$ exists for each $i$, it is by no means clear to me that this collection of $M$s is bounded above.
Any help would be greatly appreciated.
Comment: Is it okay that $d_1$ can be infinite? For example, define $x^{(n)}$ to be a sequence starting with $n$ zeros and then all ones. Its point-wise limit is a sequence consisting only of zeros. But the $d_1$-distance from any $x^{(n)}$ to the limit is infinite
Comment: The crucial point to observe is that the $n$-th term in the series is always bounded above by $2^{-n}$, so you can make the tail of this series as small as you want, say smaller than $\epsilon/2$...
Comment: Usually the "mimic metric" for pointwise convergence is taken to be $$d(x,y)=\sum_{n=1}^{\infty}2^{-n}\frac{|x_n-y_n|}{1+|x_n-y_n|}.$$
Comment: @SashaKozachinskiy, sorry about that, and thank you for pointing out the error. I have fixed the correct definition of the metric. Sorry for the confusion. metamorphy, I have corrected the mistake. Than you for pointing it out.
Comment: (Now you don't need the "boundedness" of $M$'s...)
Comment: @LukasGeyer, if you want to shape those comments into an answer I can understand I will be happy to accept it.
Answer: So this is the answer I ended up giving my students. I'll use the notation introduced in the question itself.
We assume that $(x^{(n)})_{n\in\mathbb{n}}$ is a sequence converging pointwise to a point $x\in\mathbb{R}^\infty$. We also assume given a real $\delta>0$. Now, since for any $n$, the value $d_1(x^{(n)},x)$ is bounded above by the absolutely convergent series $\sum^\infty_{n=1}\frac{1}{2^n}=1$ we can find for the given sequence $(x^{(n)})_{n\in\mathbb{n}}$ an integer $K$ such that the inequality
$$\sup_{n\in\mathbb{N}}\left\{\sum^\infty_{i=K+1}\frac{1}{2^i}\frac{|x_i^{(n)}-x_i|}{1+|x_i^{(n)}-x_i|}\right\}<\frac{\delta}{2}$$
is satisfied. Notably $K$ is independent of $n$.
Now for each $i=1,\dots,K$ we use the assumption of pointwise convergence to get integers $N_i$, $i=1,\dots,K$, such that
$$|x_i^{(n)}-x_i|<\frac{\delta}{\frac{2K}{2^i}-\delta}.$$
Note that if necessary we are free to replace $K$ be any larger (but finite) integer so as to guarantee that $\frac{2K}{2^i}-\delta\neq 0$ for each $i$.
After a little rearranging we get from this that
$$\sum^K_{i=1}\frac{1}{2^i}\frac{|x_i^{(n)}-x_i|}{1+|x_i^{(n)}-x_i|}<\sum^K_{i=1}\frac{\delta}{2K}=K\cdot \frac{\delta}{2K}=\frac{\delta}{2}$$
whenever $n>N:=\max_{i}n_i$, and we use this to get
$$d_1(x^{(n)},x)=\sum^\infty_{i=1}\frac{1}{2^i}\frac{|x_i^{(n)}-x_i|}{1+|x_i^{(n)}-x_i|}=\sum^K_{i=1}\frac{1}{2^i}\frac{|x_i^{(n)}-x_i|}{1+|x_i^{(n)}-x_i|}+\sum^\infty_{i=K+1}\frac{1}{2^i}\frac{|x_i^{(n)}-x_i|}{1+|x_i^{(n)}-x_i|}<\frac{\delta}{2}+\frac{\delta}{2}=\delta$$
which is enough to conclude that the sequence $(x^{(n)})_{n\in\mathbb{N}}$ converges to $x$ with respect to the metric $d_1$. This is exactly what we needed to show, so we are done.


How to resize the inserted picture from excel to outlook using VBA?

Question: this is the code I am trying, I wanna resize the inserted picture in outlook. I tried differet methods but its not working. Could anyone tell which picture object/function or method I can use to adjust the width and height of the picture?
Sub SendOutlookMail()
Dim outlookApplication As Outlook.Application
Dim mail As Outlook.MailItem
Dim insp As Outlook.Inspector
Dim doc As Word.Document
Dim msgText As String
Dim sp As Double

Set outlookApplication = New Outlook.Application

Set mail = outlookApplication.CreateItem(olMailItem)
    With mail
        .BodyFormat = olFormatRichText
        .Display
        .To = ""
        .CC = ""
        .Subject = "Report " & Date
        Set insp = .GetInspector
        Set doc = insp.WordEditor
        msgText = "Hallo " & vbNewLine
        doc.Range.InsertBefore msgText

        Tabelle2.Range("A1:I32").Copy
        doc.Range(Len(msgText), Len(msgText)).PasteAndFormat wdChartPicture

    End With

End Sub
Answer: Below is a code found on the internet which resize the images, but it applies to the entire document, you can get the pasted image and replace the  For Each oShp In ActiveDocument.Shapes part in the code:
Sub AllPictSize()
    Dim targetHeight As Integer
    Dim oShp As shape
    Dim oILShp As InlineShape
    targetHeight = 9
    For Each oShp In ActiveDocument.Shapes
      With oShp
        .Width = AspectHt(.Height, .Width, _
         CentimetersToPoints(9))
        .Height = CentimetersToPoints(9)
      End With
    Next

    For Each oILShp In ActiveDocument.InlineShapes
      With oILShp
          .Width = AspectHt(.Height, .Width, _
          CentimetersToPoints(9))
          .Height = CentimetersToPoints(9)
      End With
    Next

End Sub

Private Function AspectHt(ByVal origWd As Long, ByVal origHt As Long, ByVal newWd As Long) As Long
    If origWd <> 0 Then
        AspectHt = (CSng(origHt) / CSng(origWd)) * newWd
    Else
        AspectHt = 0
    End If
End Function


Number of ways of adding k positive numbers to obtain a fixed number $M$

Question: This problem is close to a standard problem: the number of ways of adding up non-negative integers to form a given fixed number $M$.
However in this case there are two constraints:
1) each of the summands has to be strictly greater than 0, and
2) the total number of summands is fixed at length $k$.

for $k=1$ the answer is easy, 1
for $k=2$ the answer is 2(sum from 1 to floor(M/2)).

So obviously that's enough to create a recursive algorithm that would allow one to calculate the answer to the question for any specific values of M and k, but I'm wondering if there is any closed form solution for arbitrary $M$ and $k$?
Another way to express this is the number of partitions of a non-empty set of finite cardinality $M$ where the number of parts (or blocks) in each partition is a fixed value $k$.
Comment: What does '2(sum from 1 to floor(M/2))' mean? And should order matter so that $1+2+3=6$ and $1+3+2=6$ constitute two distinct solutions to $M=6,k=3$?
Answer: It appears from your second example that the order of summation matters (1+2 and 2+1 are distinct). In that case, consider the summands as k bins that you have to fill with M objects. It is clearly a combinations-with-repetition problem. Remember to reduce M by k, denoting how you took care not to leave any bins empty.
Answer: This is precisely the stars and bars algorithm.  You have $M$ stars and $M-1$ places to put bars between them.  Each of your integers is the number of stars between neighboring bars.  You need to place $k-1$ bars to get $k$ blocks of stars, so there are $$M-1 \choose k-1$$ ways to do it.
Comment: Thanks!  I realized after I posted the question how to figure it out, but I still appreciate the answer.  I did a bunch of searching before posting, but didn't find the right way of asking the question apparently, because today I found the right answer easily.  Thanks again!
Comment: There are a number of problems that have classic solutions but with names that are not obviously related.  If you know the name it is easy to search, but if you don't it can be impossible.  This is one.


Importando arquivos sem nomenclatura com NodeJS

Question: Estou criando uma estrutura de arquivos em uma aplicação onde cada diretório contém um arquivo "index". Esse arquivo index leva o nome do meu diretório para melhorar a legibilidade. Ex:
foo
|--foo.js    // <- index
|--bin.html
|--bar
|  |--bar.js // <- index
   |--bin.html

Com isso, a estrutura que será utilizada para um require() ao fazer a importação de qualquer arquivo sempre será algo do tipo
const foo = require('./foo/foo');
const bar = require('./foo/bar/bar');

Eu procuro alguma maneira de criar um arquivo sem a nomenclatura, e que o NodeJS entenda para a importação, seria algo do tipo:
foo
|--.js // <- sem nome = arquivo da pasta
|--bin.html

Assim eu poderia trabalhar com arquivos semelhante a namespace's...
Existe alguma forma de fazer isso com NodeJS?
Comment: No caso de `|--.js // <- sem nome = arquivo da pasta` como queres fazer o `require`?
Answer: Você pode usar foo/index.js e require('./foo') (isso é mais prudente e bem comum). Ou você pode adicionar um package.json no diretório foo e dar qualquer nome para o main.
eg.
foo/package.json
{"main": "qualquer-coisa.js"}

main.js
require('./foo') // vai dar require em './foo/qualquer-coisa.js'

O algoritmo completo está em: https://nodejs.org/api/modules.html#modules_folders_as_modules
Mas não faz isso, não vai muito com as convenções.
Melhor só fazer
foo
|--index.js
|--bin.html

require('./foo')


CSS Style not applied in HTML

Question: I have the following HTML Code which style I want to include in a CSS in a different file

                Lorem Ipsum Text oder Claim
gerne auch mehrzeilig

Which looks like this:

Now if I try to insert the style in a separate CSS, like this:
    #leftPanel {
   background-color:grey;
   margin-left:7px;
   margin-top:7px;
   float:left;
}

And in the HTML:
<link rel="stylesheet" href="css/style.css"/>

Then the position is changed, getting this result:
Comment: You may have better luck using the image as a background-image. Add some padding to put the text to the side of the image.
Comment: Yes! I don't know why is not working, no matter if I put it as a class (.) or as an id (#)
Comment: http://jsfiddle.net/zfdUw/1/  what browse is this in? Looks fine to me, mozilla and Chrome.
Comment: its in Safari.@leigero
Comment: check with the parent container width once. maybe width is exceeding
Answer: leftPanel is an id, not a class, in your final html. In the css it should be #leftPanel not .leftPanel.
Comment: Sorry about the missunderstanding, I was just trying with both at the same time. But now I have left them both as id and as #leftPanel in the CSS and the error still persists. I would appreciate any help.
Comment: Is the css file loading at all? Change the background-color to red to test this.
Answer: Your first piece of HTML has class="leftPanel" where your second piece of code has id="leftPanel".
If you have changed it from a class to an id you need to reference it in your CSS as #leftPanel.
Comment: Sorry about the missunderstanding. Check my comment above, the error still persists.
Answer: Your CSS matches based on class .leftPanel but your div has id="leftPanel" instead of class="leftPanel". Is this a typo?
Answer: This looks fine to me. Sounds like an issue with your CSS file not being loaded properly. Check to make sure the CSS file is saved in the right location and contains the right ID styles.
http://jsfiddle.net/zfdUw/1/  (does this work for you in Safari?)
HTML:
<link rel="stylesheet" href="css/style.css"/>

                Lorem Ipsum Text oder Claim
gerne auch mehrzeilig

CSS:
#leftPanel {
    background-color:gray;
    margin-left:7px;
    margin-top:7px;
    float:left;
}

CSS Style not applied in HTML


No result from an SQL query

Question: I have a view with a custom PHP field containing the following code.
$storeArray = array();
$result = db_query("SELECT nid FROM node WHERE type ='emp'");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $storeArray[] =  $row[nid];
}

if ($storeArray) {
  echo 'not empty';
}

The query doesn't return anything. Why?
Answer: You're mixing a couple of different things there :)
The resource returned from db_query() can be iterated over directly, there's no need for an intermediary function. The resource isn't the same as one that would be returned from mysql_query(), as the Drupal database layer wraps around PDO.
This is the standard way to iterate over db_query() results:
$result = db_query("SELECT nid FROM node WHERE type ='emp'");

$storeArray = array();
foreach ($result as $row) { // An object is returned by default
  $storeArray[] = $row->nid;
}

However, the db layer also has a handy shortcut method called fetchCol() that will fetch the results of the query's first column into an array. So you can simplify your code to a single line:
$storeArray = db_query("SELECT nid FROM node WHERE type ='emp'")->fetchCol();

No result from an SQL query


using pf for packet filtering and ipfw's dummynet for bandwidth limiting at the same time

Question: I would like to ask if it's fine to use pf for all packet filtering (including using altq for traffic shaping) and ipfw's dummynet for bandwidth limiting certain IPs or subnets at the same time.
I am using FreeBSD 10 and I couldn't find a definitive answer to this. Googling returns such results as:

It works
It doesn't work
Might work but it's not stable and not recommended
It can work as long as you load the kernel modules in the right order
It used to work but with recent FreeBSD versions it doesn't
You can make it work provided you use a patch from pfsense

Then there's a mention that this patch might had been merged back to FreeBSD, but I can't find it.
One certain thing is that pfsense uses both firewalls simultaneously so the question is, is it possible with stock FreeBSD 10 (and where to obtain the patch if it's still necessary).
For reference here's a sample of what I have for now and how I load things
/etc/rc.conf
ifconfig_vtnet0="inet 22.214.171.124 netmask 255.255.255.0 -rxcsum -txcsum"
ifconfig_vtnet1="inet 10.20.20.1 netmask 255.255.255.0 -rxcsum -txcsum"
defaultrouter="18.104.22.168"
gateway_enable="YES"
firewall_enable="YES"
firewall_script="/etc/ipfw.rules"
pf_enable="YES"
pf_rules="/etc/pf.conf"

/etc/pf.conf
WAN1="vtnet0"
LAN1="vtnet1"

set skip on lo0
set block-policy return

scrub on $WAN1 all fragment reassemble
scrub on $LAN1 all fragment reassemble

altq on $WAN1 hfsc bandwidth 30Mb queue { q_ssh, q_default }
queue q_ssh bandwidth 10% priority 2 hfsc (upperlimit 99%)
queue q_default bandwidth 90% priority 1 hfsc (default upperlimit 99%)

nat on $WAN1 from $LAN1:network to any -> ($WAN1)

block in all
block out all

antispoof quick for $WAN1
antispoof quick for $LAN1

pass in on $WAN1 inet proto icmp from any to $WAN1 keep state
pass in on $WAN1 proto tcp from any to $WAN1 port www
pass in on $WAN1 proto tcp from any to $WAN1 port ssh

pass out quick on $WAN1 proto tcp from $WAN1 to any port ssh queue q_ssh keep state
pass out on $WAN1 keep state

pass in on $LAN1 from $LAN1:network to any keep state

/etc/ipfw.rules
ipfw -q -f flush
ipfw -q add 65534 allow all from any to any
ipfw -q pipe 1 config bw 2048KBit/s
ipfw -q pipe 2 config bw 2048KBit/s
ipfw -q add pipe 1 ip from 10.20.20.4 to any via vtnet1 in
ipfw -q add pipe 2 ip from any to 10.20.20.4 via vtnet1 out

Answer: Officially you can't mix them. Unofficially various incantations and sacrifices might lead to a working, though precarious, configuration. In any case it's simply not recommended.
Also, why not just use one or the other? I assume you're wanting dummynet to do some per-endpoint bandwidth limiting, if not PF might be all you need. Similarly, IPFW can do almost everything PF can do, with a few notably different scheduling algorithms and less dynamic rule space.