How do I format the initialization string for an extremely old date (around year 0 CE) in JavaScript?

Question: I want to represent the year 0 in JavaScript, not 1970 which as we know is the actual year zero. I want to know how to correctly format this or any date string with an unusually small number of years. I tried initializing it with new Date('0000-00-00T00:00:00') and also with new Date('0-00-00T00:00:00'), but both times the toString method said 'Invalid Date'.
I just realized I can get around this by using the year 1970 and offsetting it, so it's not really mission critical, but supposedly JavaScript can do really small and really big years, over plus or minus 200,000. I find it odd and dumb that implementations of it don't seem to support initializing dates in one of the standard ways for all of the years in its range. I find a lot of things in JavaScript odd, dumb, and inconsistent, honestly, some of it due to individual implementations no doubt, but my opinion remains unchanged.
Ok now that I've insulted the language, you may proceed to enlighten me if there's some way to do this.
Comment: The [ECMAScript Date range](https://tc39.es/ecma262/#sec-time-values-and-time-range) is fixed to exactly ±100,000,000 days from 1970-01-01, which is about ±285,426 years. :-)
Answer: K I figured it out. I was being inconsistent and dumb! And so was JavaScript. It's not blameless.
Years, hours, minutes and seconds can be zero, but the months and days start at 1. I simply have to make my default month and day 01 and not 00.
Comment: If 0000-00-00 date existed that would mean that a month starts with day 0 instead of day 1 and year starts with month 0. This means June 5 2020 has to be written as `2020-05-04`. I would not be happy with that...
Comment: @Gherman yeah, I noticed that. I was thinking in terms of 0 indexing for everything haha!
Answer: Maybe this?

var date = new Date();
date.setFullYear(0);
var year = date.getFullYear();
alert(year);
Comment: Thank you! Yes that would definitely work, I hadn't thought of that. I seem to have found another way to do it though. I was thinking about the days and months wrong, forgot that humans start days at 1. Glad I'm not one of them.
Comment: A pleasure, im glad this is usefull for you
Comment: if you want you can give me that thumbs up and i would glad, thanks


Rails Active Record - Calling Distict Rows

Question: I have the following models
influencers (id, name, ..)
influencer_authorizations (id, influencer_id, ... )
influencer_metrics (id, influencer_authorization_id, date, count)

The relationships are as follows
influencers has_many influencer_authorizations
influencer_authorizations has_many influencer_metrics

I want to fetch the count of all the influencer_authorizations in the influencer_metrics with the latest DATE and sum to show the total followers of the influencer
What am trying
Finding all the Authorizations IDs
influencer_authorizations = InfluencerAuthorization.where(influencer_id: influencer.id).pluck(:id)

Now i am trying to find the latest Date's rows all the influencer_authorizations technically for each influencer_authorizations it should give back one row whose sum i want to calculate.
total_followers = InfluencerMetric.where(influencer_authorization_id: influencer_authorizations).order('metrics_date DESC').first

But it returns all the rows right now. The date is tricky as i each influencer_authorizations last fetched date can be different at times. So we need the lastest metrics records for each influencer_authorizations
Answer: Could this possibly be what you're looking for?
Influencer.
  joins(influencer_authorizations: :influencer_metrics).
  select("SUM(influencer_metrics.count) as followers, COUNT(influencer_metrics.id)").
  where(id: influencer.id).
  group("influencer_authorizations.id").
  order("influencer_metrics.metrics_date DESC").
  limit(1)

I'm not quite clear on the query that you described, as some of the wording seemed inverted from the schema relationships.  It may be a starting point.
If it happens to not work as expected, try to remove the .limit(1) portion and see what's returned.  We can go from there if you're game.
Comment: Basically i want the total followers of the Influencer. Based on the lastest Crawled data for various authorizations like `facebook` `twitter` etc


Como fazer baralhar este array dentro dele mesmo?

Question: $img = array
  (
  array("1.jpg","Logo","Tigre"),
  array("2.jpg","Logo","Cão"),
  array("3.jpg","Logo","Montanha"),
  array("4.jpg","banner","Design Grafico"),
  array("5.jpg","Logo","Dentista"),
  array("6.jpg","Logo","Basketball")
  );

Queria que por exemplo o array ficasse assim
$img = array
  (
  array("5.jpg","Logo","Dentista"),
  array("1.jpg","Logo","Tigre"),
  array("4.jpg","banner","Design Grafico"),
  array("3.jpg","Logo","Montanha"),
  array("2.jpg","Logo","Cão"),
  array("6.jpg","Logo","Basketball")
  );

Tentei isto:
   function shuffle_assoc($list) {
      if (!is_array($list)) return $list;

      $keys = array_keys($list);
      shuffle($keys);
      $random = array();
      foreach ($keys as $key) {
        $random[$key] = $list[$key];
      }
      return $random;
    }

    $img = array
      (
      array("1.jpg","Logo","Tigre"),
      array("2.jpg","Logo","Cão"),
      array("3.jpg","Logo","Montanha"),
      array("4.jpg","banner","Design Grafico"),
      array("5.jpg","Logo","Dentista"),
      array("6.jpg","Logo","Basketball")
      );
   $img = shuffle_assoc($img);
    print_r($img);

Comment: `$imagens[] = shuffle($img[0])` não faz o que você precisa?
Comment: Obrigado pelo -1 mas eu continuo a precisar de ajuda xD
Comment: não esta a funcionar
Comment: Queria baralhar a posição dos arrays mas mantendo a ordem de cada "linha"
Answer: Pelo que notei não existe padrão algum, então usar apenas shuffle(...) deve resolver:
<?php

$img = array(
    array("1.jpg","Logo","Tigre"),
    array("2.jpg","Logo","Cão"),
    array("3.jpg","Logo","Montanha"),
    array("4.jpg","banner","Design Grafico"),
    array("5.jpg","Logo","Dentista"),
    array("6.jpg","Logo","Basketball")
);

echo 'Antes:', PHP_EOL;

var_dump($img);

shuffle($img);

echo 'Depois:', PHP_EOL;

var_dump($img);

Veja o resultado no ideone
Comment: +1 ... [There is no shuffle.](https://www.youtube.com/watch?v=ECQxrFYYk2g)


How should we react whenever we encounter ideas that we disagree with?

Question: I am not trying to start an argument with this.  I am also not trying to prove anyone wrong.  I just want everyone to be on the same page.
In the comments following this question, there are some remarks that are at least somewhat offensive toward religious academic institutions, beliefs held by certain religious groups, and the author of the article referenced in the original question.  (I am not making a value judgment on the comments themselves; rather, I am judging the way the comments were made.)
I understand that there will be a lot of disagreement in the areas of economics and religion and we shouldn't expect everyone to agree.  So, that being said, how should we react whenever we encounter ideas that we disagree with?
Edit
The more offensive post (the one with a derivation of the "s" word) against religious academic institutions and the author of the linked article has been removed.  But the other issues remain in the remaining comments.
Comment: As far as economics vs religion (or ideology, or any other non-substantiated thought) is concerned: this is an economics site. We should respect the beliefs as others, but those beliefs have no place polluting the scientific discussion on this site. Reason and evidence should be welcome here, superstition should not.
Comment: I'm curious to know what others think about the particular situation in the link you provide. This will be helpful in setting a precedent for how to deal with issues like this.
Comment: I think the use of crude language (in the comment now deleted) is not appropriate for the site. But I have no qualms with the general sentiment expressed in that comment. I think it is fair enough to question whether ideas or statements are supported by evidence or make logical sense. I think it is also fair to call for special scrutiny of ideas that come from sources that have shown themselves to be unreliable in the past.
Comment: The comments are way off topic and should be deleted.  The question is also way off topic and should be deleted.  I can imagine ways to make this question interesting, e.g. "In calculating the cost of a riot --- or a hurricane --- how should we include changes in land values in neighboring areas?".  But no interesting form of the question will mention Ferguson specifically,  because all of the interesting questions are far more general than that.
Answer: Keep it away. If you "believe" in something - keep it to your self - it has nothing to do on this site. Be that political or religious views.
As Ubiquitous puts it very elegantly in a comment

"Reason and evidence should be welcome here, superstition should not."


how to perform rolling mean using if condition in group by operation

Question: I am trying to add a code wherein, if the difference between current date and the minimum date of the id column is more than 3 months, the rolling mean should be for a 21 days window, else it should be for a 7 days window.
Sample data:
import pandas as pd
import numpy as np
np.random.seed(0)
dt = pd.DataFrame({'id' : [1,1,2,2,1],
                  'date' : ['2023-09-01', '2023-09-10', '2023-01-01', '2023-01-13', '2023-09-11'],
                  'rev' : np.random.randint(100, 150, 5)})
dt
    id  date        rev
0   1   2023-09-01  144
1   1   2023-09-10  147
2   2   2023-01-01  100
3   2   2023-01-13  103
4   1   2023-09-11  103

Code I am trying to get the rolling mean is:
dt.groupby('id').transform(lambda x : x['rev'].rolling(window = '21D', min_periods = 1).mean() if pd.to_datetime('today') - x['date'].min() >= 90 else x['rev'].rolling(window = '7D', min_periods = 1).mean())

But I am getting KeyError: 'date' error.
Could someone please help on how to get the rolling means.
Answer: Create DatetimeIndex and compare days by Timedelta.days:
dt['date'] = pd.to_datetime(dt['date'])

out = (dt.set_index('date')
         .groupby('id')['rev']
         .apply(lambda x : x.rolling(window = '21D', min_periods = 1).mean()
                          if (pd.to_datetime('today') - x.index.min()).days >= 90
                          else x.rolling(window = '7D', min_periods = 1).mean()))

print (out)
id  date
1   2023-09-01    144.0
    2023-09-10    147.0
    2023-09-11    125.0
2   2023-01-01    100.0
    2023-01-13    101.5
Name: rev, dtype: float64

With transform:
dt['date'] = pd.to_datetime(dt['date'])

out = (dt.set_index('date')
         .groupby('id')['rev']
         .transform(lambda x : x.rolling(window = '21D', min_periods = 1).mean()
                           if (pd.to_datetime('today') - x.index.min()).days >= 90
                           else x.rolling(window = '7D', min_periods = 1).mean()))

print (out)
date
2023-09-01    144.0
2023-09-10    147.0
2023-01-01    100.0
2023-01-13    101.5
2023-09-11    125.0
Name: rev, dtype: float64

Answer: You can use the on keyword in groupby.apply:
dt['rev'] = (dt.groupby('id', group_keys=False)
               .apply(lambda x : x.rolling(window='21D', on='date', min_periods = 1)['rev'].mean()
                      if pd.to_datetime('today') - x['date'].min() >= pd.Timedelta('90D')
                      else x.rolling(window = '7D', on='date', min_periods = 1)['rev'].mean()
                     )
            )

Output:
   id       date    rev
0   1 2023-09-01  144.0
1   1 2023-09-10  147.0
2   2 2023-01-01  100.0
3   2 2023-01-13  101.5
4   1 2023-09-11  125.0

Comment: @KarthikS because `transform` doesn't allow access to other columns, it operates separately on each column while `apply` passes the full DataFrame to the function.
Comment: @KarthikS hard to answer without a clear example, I'd encourage you to open a new question with all details. In general you should avoid for loops in pandas.
Comment: could you please let me know why `apply` works and `transform` doesn't work
Comment: I have a generic query, the `for` loop runs fine with I run it as it is, but while building a function, the same `for` loop takes lot of time when it's inside the function block, is it normal for Python/Pandas to work that way?


$\ln |f|$ is harmonic where $f$ is holomorphic

Question: In a book, there is a proposition states that : Let $U$ be an open set of $\mathbb{C}$ and $f$ be a holomorphic function on $U$ does not take value $0$. Then $\ln |f|$ is harmonic.
In the proof, it's written $\frac{\partial}{\partial z} \ln|f| = \frac{\overline{f}f'}{2\overline{f}f}$. But I don't know how this calculation be down. Can somone detail this? Thanks.
My attempts is as follows : $\frac{\partial}{\partial z} \ln|f| = \frac{1}{4}(\frac{\partial \ln f\overline{f}}{\partial x} + i\frac{\partial \ln f\overline{f}}{\partial y}) = \frac{1}{4f\overline{f}} (f\frac{\partial\overline{f}}{\partial x} + \overline{f}\frac{\partial f}{\partial x} + if\frac{\partial\overline{f}}{\partial y} + i\overline{f}\frac{\partial f}{\partial y})$
Answer: Notice that
$\ln \left|f\right|=\frac{1}{2}\ln f\overline{f}$ and $\frac{\partial \overline{f}}{\partial \overline{z}}=0$ since $f$ is holomorphic and thus locally we have the expansion
$$f\left(z\right)=\sum_{n=0}^{\infty} \frac{f^{n}\left(z_0\right)}{n!}\left(z-z_0\right)^n$$
so $\overline{f}\left(z\right)$ would not have any term that entails $z$.
Hence, we can see
$$\frac{\partial \ln \left|f\right|}{\partial z}=\frac{1}{2}\frac{\partial \ln f\overline{f}}{\partial z}=\frac{1}{2f\overline{f}}\frac{\partial f\overline{f}}{\partial z}=\frac{\overline{f}f'}{2f\overline{f}}=\frac{f'}{2f}.$$
Now, if we do $\frac{\partial}{\partial \overline{z}}$, we have
$$\frac{\partial^2 \ln \left|f\right|}{\partial \overline{z}\partial z}=\frac{\partial}{\partial \overline{z}} \frac{f'}{2f}=0$$
since $f,f'$ are both holomorphic.
Hence, $\ln \left|f\right|$ is harmonic by the identity
$$ \Delta=4\frac{\partial^2 }{\partial \overline{z}\partial z}.$$
Back to your attempt, it seems like it is pretty close to the desired form and you can get it if you realize $\frac{\partial \overline{f}}{\partial z}=0$ as mentioned above.


Determining the best correlated time series

Question: Before asking, I read similar questions, but none of them lead to satisfying answers for my specific interest.
I want to homogenize a climate time series of precipitation of the Dominican Republic over 64 years (1940-2003). For that, it is really important to select a reference series among a group of candidates.
Let's say sjo is the base series, for which I want to find a good reference series; bani, plc and ra are reference candidates, because they are close to sjo. In the following map, the red point is the base station, and the green ones are the reference candidates:

I performed three correlation analyses (done in R, function cor()), considering these monthly variables: raw precipitation value, normalized difference, and transformed values with Box-Cox. Those variables correspond, respectively, to fields that begin with p, dian and pnorm.
Normalized difference comes from the first difference series method (FDM), which was proposed by Peterson, consisting of:
$[Pm_t - Pm_{t-1}] / [Pm_t + Pm_{t-1}]$,
where $Pm_t$ is the precipitation value for the month $m$, and $Pm_{t-1}$ is the precipitation for the same month 1 year before. I followed Peterson and colleagues' (1998) remark, which says that FDM applied to precipitation might work better using normalized difference.
As can be seen in page 1 of this PDF file, correlation was calculated for the whole time series (1940-2003). For raw precipitation and Box-Cox transformed values, bani is the best correlated with sjo (yellow background cells shows the maximum correlation index). Notice that for raw precipitation, bani is significantly more correlated than others. For normalized difference, ra is only a bit more correlated than the rest. However, each candidate station has a statistically significant correlation index with sjo at the $\alpha=.05$ significance level, suggesting ANY of them could be used as a reference series.
This is a bit confusing, so I was unsatisfied and decided to make a more detailed analysis, splitting the series in 5-year period intervals, and evaluating correlation between series for the same 3 variables: raw precipitation, normalized difference and Box-Cox transformed.
Tables from page 2 to 8 in the PDF show the results of these partial correlations; the last page summarizes the times each station has had the maximum correlation value for each variable. As can be seen, bani is the most frequently correlated value for the 3 variables analyzed (in all cases, more than 7 times of the twelve 5-year periods analyzed).
With these results, I think that bani is the best candidate as a reference series of sjo, but I'm not sure about it. Is the five-year period analysis OK? Should I perform some other analysis?
Comment: Thanks @Nick for corrections, I learned a lot from them. Sorry, English is not my mother tongue.
Comment: Glad to be of help :) Your work was already clearer than that of many native speakers! My changes were only cosmetic and technical, not essential. Welcome to CV BTW!
Comment: the correlations are significant, but are the differences between these correlations different? if not, then you can't pick one reference station over another based on correlations
Comment: Thanks @Aksakal for your comment. For the whole period analyzed, and exclusively for raw precipitation, 'sjo' (the base series) has this correlations indexes with reference candidates: 0.650 with 'bani', 0.536 with 'plc', and 0.557 with 'ra'. Is the largest index significantly greater than the next more correlated? Regarding to the other variables, normalized difference and Box-Cox transformed, difference are not large. Should I apply another analysis? What would you suggest me?
Comment: @JoseRamon, I can't answer these questions, you have the data. You can run the statistical tests to see whether the difference is significant
Comment: Thanks @Aksakal for your comment, which motivated me to apply some new tests. After verifying the normality assumption, I applied a `oneway.test` to correlation indexes between variables `pbani`, `pplc` and `pra`; differences were not statistically significant, and a `pairwise.t.test` with Bonferroni adjustment, confirmed it. I also applied a `t.test` to pairs of variables, but differences were only significant between `pbani` and `pra`. I suppose that choosing either `pbani` or `pplc` as reference series would lead to equivalent results. Am I right? Any other suggestions?
Comment: @JoseRamon, if the differences between correlation coefficients are not statistically significant, then you can't use the correlations to make decisions solely _based on statistics_. this doesn't make that you can't make decisions at all. you may use other metrics, such as different forms of variables, maybe differences, 2nd diffs etc., depending on your domain. you can also make decisions based on non-statistical argument, e.g. by looking at the map it looks to me that bani is a better choice: it's closer to the coast as the base station
Comment: Thanks @Aksakal. I'll try your suggestions, and appreciate your help. I like geographic criteria for `bani` choice, not only for the proximity to the coast, but also for its relative position respect mountain range and tradewinds, which is basically the same for `sjo`
Comment: @JoseRamon, ideally you want your statistical tests to agree with other considerations. That's why I'd be looking closer at criteria used to identify the reference stations. Maybe there's a better way than FDM. Also, you tried to address the time-variability of correlations by 5-year segments. You could also try to estimate VAR (vector autoregression) like process, and look at the correlation matrix of errors?
Comment: Thanks @Aksakal. I'll try your suggestions and give you feedback.
Comment: Why do you need to choose one of them rather than using all three or using some kind of aggregate score?
Comment: Thanks @Tim. Something like a weighted mean using the three of them?
Comment: @JoseRamon yes, foe example, weighted by inverted distance to rour target destination.
Answer: how about you try a Two-Way Anova AND a pairwise test whether with your yearly data and/or the 5 year-period-intervals. You may also do this with the raw, normalized data or Box-Cox data.
Idea is, that you can look for any non-significant (for the reference station) difference between the distributions of precipitation per station.
I found this link to be helpful to start your own Two-Way-Anova via R r-tutorial-series-two-way-anova
Sebastian
Comment: Hello again @tester1234. I'm trying to perfomr the Two-Way Anova test for my data. Based on the link you suggested me: which should be my two factors? May I say: which variables should I put inside the 'lm()' function? I have precipitation from 3 stations (pbani, pplc, pra), and I want to know which one is best correlated with a fourth one (psjo). I have monthly data that is grouped in 5 years period intervals (data can be downloaded from this [link](http://www.geografiafisica.org/wp-content/uploads/2014/03/sjo_bani_ra_plc_5yr.csv)). Thanks in advance
Comment: Thanks Sebastian for your answer. I'll try this suggestions, which seems very helpful. I've used it in another research, and is very powerful.


How can I fit the parametres of t-distribution if I know the number of degrees of freedom in R?

Question: I have some data. Does anybody know a function which can fit the parameters of a t-distribution of this data when I know the numbers of degrees of freedom?
Thanks!
Comment: You might also want to mention which parameters you're interested in.  Are we talking about some sort of shifted t-distribution?  Do you want to estimate a non-centrality parameter?  What are you trying to estimate?
Comment: See the `fitdistr` function in the `MASS` package -- especially the second example in `?fitdistr` ...
Comment: I want to estimate mean = mu and variance = sigma like the function fit.st of the QRM-packages does it, but this function also estimate the number of degrees of freedom but I just know this number.
Answer: Expanding @Ben Bolker's comment:
You may use the fitdistr function in R MASS package.
See the second example in ?fitdistr function help. Also in this pdf, page 50.
library(MASS)

#generate a random sample with t distribution, where the degrees of freedom = 9.
set.seed(123)
x2 <- rt(250, df = 9)

#find the parameters for the t distribution
fitdistr(x2, "t", df = 9)

the output is:
       m             s
  -0.01069496    1.04410551
 ( 0.07222623) ( 0.05434369)

where the second line represents the parameter estimates, and the numbers inside brackets are their standard deviations.
fitdistr uses the Maximum Likelihood Estimation (MLE) method to adjust the parameters of a given distribution.
For a theoretical insight about MLE, you might find @Glen_b's answer helpful.
Reference.
Venables, W. N., & Ripley, B. D. (2002). Modern Applied Statistics with S (4a ed., p. 495).


Is there a way with drush or console to delete all active config with a certain prefix?

Question: I'm currently trying to migrate a site with drush migrate-upgrade --configure-only ... and copying the export migrate_plus.migration_*.yml into a custom module for tweaking. Now I want to enable that module but I get PreExistingConfigException.php and ... provided by MYMODULE already exist in active configuration.
I'd like to delete all config but it looks like the latest drush has removed drush config-delete and drupal config:delete is gone too. How do I achieve this?
Comment: FWIW I'm having the same issue.  Currently scouring the d.o comments for a solution.  Will report back if I find something.
Comment: Btw, doing `drush pm-uninstall migrate_upgrade migrate_plus migrate_tools` does NOT clean up these config entities either.
Answer: This isn't the greatest solution, but it does work, and also allows you to not have to execute a dozen steps/commands to register your migrations.
In my custom module where I'm creating migration sources/plugins, I added a .install file and implemented hook_uninstall().  In there I delete the configurations remaining manually.
<?php

/**
 * @file
 * Contains my_module_migrate.install.
 */

/**
 * Implements hook_uninstall().
 *
 * Removes stale migration configs during uninstall.
 */
function my_module_migrate_uninstall() {
  $query = db_select('config', 'c')
    ->fields('c', array('name'))
    ->condition('name', db_like('migrate_plus.') . '%', 'LIKE')
    ->execute();

  $config_names = $query->fetchAll();

  // Delete each config using configFactory.
  foreach ($config_names as $config_name) {
    \Drupal::configFactory()->getEditable($config_name->name)->delete();
  }
}

Note: You may need to clear cache after uninstalling for the changes to show before re-enabling the module.
If you want to remove them before you uninstall you can either run each line from hook_uninstall() implementation in devel/php, or you can run them via drush:
drush ev "\Drupal:;configFactory()->getEditable('migrate_plus.migration.xxxxxx')->delete();"
You will probably have to clear cache after removing all of them manually via drush as well.
If you'd like to just run a couple of drush commands to re-register your migrations, you can add this drush plugin file my_module.drush.inc to your modules' root directory, clear cache, and run drush mpc -y && drush mcr my_module.  You may need to also run drush cache-clear drush for the commands to be come available.
Here's the code for the my_module.drush.inc file:
<?php
/**
 * @file
 * Contains my_module_migrate.drush.inc
 */

/**
 * Implements hook_drush_command().
 *
 * Defines drush commands.
 */
function my_module_migrate_drush_command() {
  // Company update Dynamically
  $items['migrate-prune-configs'] = array(
    'description' => dt('Prune migrate configs.'),
    'aliases' => array('mpc'),
    'examples' => array(
      'drush migrate-prune-configs' => 'Removes migrate configuations.',
    ),
    'callback' => 'my_module_migrate_migrate_prune_configs',
  );

  $items['module-config-reset'] = array(
    'description' => dt('Resets default config for a given module.'),
    'arguments' => [
      'module_name' => dt('Module name'),
    ],
    'aliases' => ['mcr'],
    'required-arguments' => 1,
    'callback' => 'my_module_migrate_config_reset',
  );

  return $items;
}

/**
 * Callback for drush command migrate-prune-configs to prune migratin configs.
 */
function my_module_migrate_migrate_prune_configs() {
  //Confirmation will be Y/N when use type "y" the condition will be executed if not it will not
  if (drush_confirm(dt("Are you sure you want to remove migrate configs?"))) {
    drush_print("Removing.....");
    // Get all of the migration config names.
    $query = db_select('config', 'c')
      ->fields('c', array('name'))
      ->condition('name', db_like('migrate_plus.') . '%', 'LIKE')
      ->execute();

    $config_names = $query->fetchAll();

    // Delete each config using configFactory.
    foreach ($config_names as $config_name) {
      drush_print("..." . $config_name->name);
      \Drupal::configFactory()->getEditable($config_name->name)->delete();
    }

    drush_print("Removed succesfully");

    return TRUE;
  }
}

/**
 * Reinstall default module's config files
 */
function my_module_migrate_config_reset($module_name) {
  if (!in_array($module_name, array_keys(\Drupal::moduleHandler()->getModuleList()))) {
    return drush_set_error(dt('Module @module_name not found.', ['@module_name' => $module_name]));
  }
  // Initiate config installer for given module.
  \Drupal::service('config.installer')->installDefaultConfig('module', $module_name);

  drush_print('Configuration was successfully reset.');

  return TRUE;
}

The code for resetting the module's configs was found in this issue on d.o.  I found that it doesn't work unless the configs are already removed, hence the first command to remove them.
Comment: Tomorrow I will try to write a drush plugin that will remove migrate configs.
Comment: Change `my_module_migrate_drush_command()` to the `my_module_drush_command()` according to the example.
Answer: config:delete is in core drush 8 and drush9. it is not removed. make sure your site is bootstrapping properly for drush requests.


Confused about directional derivatives

Question: I have the following question:

Calculate the directional derivative of the function at the point and in direction indicated.
$f(x, y) = \arctan(xy)$ at $(1, 2)$ along the line $y = 2x$ in the direction of increasing $x$.

When I looked at the solution, I was confused about the way they solved it:

I understand that we need a gradient vector at (1,2) and some unit vector to give the direction.
I also understand that since it is in the direction of increasing x, x will be positive.
However, how did they get that it is going to be along the line (1,2).
Did they set x = t and then got parametric equations where x = t, and y = 2t?
If so, are the coefficient before t our vector that gives us the direction?
Also, I'm so confused about the use of parametric equations with directional derivatives. Could someone explain relationship between parametric equations and directional derivatives?
Comment: $$\pmatrix{x \\ y} = \pmatrix{t \\ 2t} = t\pmatrix{1 \\ 2}$$  So the direction of the line $y=2x$ is $\langle 1,2\rangle$.
Answer: If you are going along the line $y = 2x$ then you find it's directional vector by looking at $\vec{OP}$ where $O = (0,0)$ and $P$ is a point on the line. Take $P = (1,2)$ then the directional vector is $\vec{OP} = \langle1,2 \rangle$.
Comment: @Jack You should use the parametrized equations or *two* points on the line.  It just so happens that one of the points on this line was the origin so for any point $P(x,y)$ on the line, $\vec{OP}=\langle x,y\rangle$ will be parallel to the line.  In general you want $P(x_1,y_1)$ and $Q(x_2,y_2)$ and then the direction parallel to your line will be $\vec{PQ} = \langle x_2-x_1,y_2-y_1\rangle$.
Comment: But could we try another point? Not (1,2), but something else? Would the answer be different?
Comment: @Jack Try a different point on the line.  What happens if you choose, say, the point $(-3,-6)$ (verify that this is on the line $y=2x$)?
Comment: @Bye_World Since in (-3, -6), x = -3 (it's negative). But we need the direction in increasing x. So, if I try something like (3,6), it would have the same results as (1,2) vector, right?
Comment: @Jack Ah.  You're right.  It asks for $D_vf$ for along $y=2x$ for increasing $x$.  Then yes try $(3,6)$ instead.  You will get the same answer (but try it yourself anyway to see why).
Comment: @Bye_World Thank you! That makes so much sense right now. So, just to clarify, we can either construct parametric equations and then pick the coefficient before "t" to be our direction vector, or we can choose any point that lies on our line?
Comment: @Bye_World Thank your for the answers! But sometimes they give you set of parametric equations but not any points. And when they do, I'm having a hard time getting the direction vector for our directional derivative.
Comment: @Jack Well it's hard to give definitive strategies for every type of problem.  But when you get stuck on one, you can always ask here.
Comment: @Bye_World THank you so much, you clarified confusion I had about directional derivatives and parametric equations! Now, should I accept the answer above or you would post your comments as a separate answer and then I would accept it ?

Confused about directional derivatives


Send an image through socket: ByteArrayOutputStream.size() return negative value (sometimes )

Question: I am making server-client program, the server is Java on the computer and the client is android app (android studio) and I try to send image from the server to the client, and to show this image on the client's screen by ImageView. The problem is that sometimes its work and sometimes it doesn't work. Looks like there are times that ByteArrayOutputStream.size() return negative value in the client side in the variable len (that keep the length). When the return value is positive it works. Why am I getting negative values (sometimes)?
Server code:
    public class Server extends JFrame {
    BufferedImage bi,inputImage;
    JButton btn;
    ServerSocket serverSocket;
    Socket socket;
    private Scanner in;
    private PrintWriter out;
    public Server(){
        File imageFile = new File("ssss.PNG");
        try {
             bi = ImageIO.read(imageFile);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        this.add(btn = new JButton("Send"), BorderLayout.NORTH);
        this.add(new JLabel(new ImageIcon(bi)), BorderLayout.CENTER);
        this.setSize(200, 180);
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        try{
             serverSocket = new ServerSocket(8000);
             socket = serverSocket.accept();
             in = new Scanner(socket.getInputStream());
             out = new PrintWriter(socket.getOutputStream(), true);
        }
        catch(IOException ex){
            System.err.println(ex);
        }
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                out.println("IMAGE");
               sendImage(new File("ssss.PNG"));
               // try {
                   // ImageIO.write(bi, "PNG", socket.getOutputStream());
                //} catch (IOException e) {
                    // TODO Auto-generated catch block
                 //   e.printStackTrace();
              // }
            }
        });
    }
    public static void main(String[] args) {
                new Server();
    }
    public void sendImage(File file){
        try {
            DataOutputStream out = new DataOutputStream(
                    socket.getOutputStream());
            DataInputStream dis = new DataInputStream(new FileInputStream(file));
            ByteArrayOutputStream ao = new ByteArrayOutputStream();
            int read = 0;
            byte[] buf = new byte[dis.available()];
            while ((read = dis.read(buf)) > -1) {
                ao.write(buf, 0, read);
            }
            System.out.println("ao.size(): "+ao.size());
            out.writeInt(ao.size());
            out.write(ao.toByteArray());
            out.flush();
           // out.close();
           // dis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client code(android):
    public class MainActivity extends AppCompatActivity {
    public Socket socket;
    public PrintWriter out;
    public Scanner in;
    public TextView textView;
    public DataOutputStream dos=null;
    public DataInputStream dis=null;
    public ImageView imageView;
    public Bitmap bitmap;
    private static final int SERVERPORT = 8000;
    private static final String SERVER_IP = "192.168.5.59";
    public static final String TAG="TAG";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView=(TextView)findViewById(R.id.text);
        imageView=(ImageView)findViewById(R.id.imageView);
        imageView.setImageResource(R.drawable.ic_launcher_background);
        new Thread(new ClientThread()).start();
    }
    class ClientThread implements Runnable {
        @Override
        public void run() {
            try {
                Log.d(TAG, "try to connect...");
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                socket = new Socket(serverAddr, SERVERPORT);
                in = new Scanner(socket.getInputStream());
                out = new PrintWriter(socket.getOutputStream(), true);
                Log.d(TAG, "connected1234");
                while (in.hasNextLine()) {
                    String response = in.nextLine();
                    if (response.startsWith("IMAGE")) {
                        InputStream in = socket.getInputStream();
                        Log.d(TAG, "in: "+in);
                        DataInputStream input = new DataInputStream(in);
                        Log.d(TAG, "input: "+input);
                        byte[] data;
                        int len= input.readInt();
                        Log.d(TAG, "len: "+len);
                        data = new byte[len];
                        Log.d(TAG, "data: "+data);
                        if (len > 0) {
                            input.readFully(data,0,data.length);
                        }
                        final Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
                        Log.d(TAG, "Bitmap: "+bitmap);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                imageView.setImageBitmap(bitmap);
                            }
                        });
                    }
                }
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}

The error:
len: -298696669
E/AndroidRuntime: FATAL EXCEPTION: Thread-5
Process: com.example.sendimageexample, PID: 17224
java.lang.NegativeArraySizeException: -298696669
    at com.example.sendimageexample.MainActivity$ClientThread.run(MainActivity.java:80)
    at java.lang.Thread.run(Thread.java:784)`

Answer: I solved it!
client code:
     public class MainActivity extends AppCompatActivity {
public Socket socket;
public ImageView imageView;
private static final int SERVERPORT = 8000;
private static final String SERVER_IP = "192.168.5.59";
public static final String TAG="TAG";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView=(ImageView)findViewById(R.id.imageView);
    imageView.setImageResource(R.drawable.ic_launcher_background);
    new Thread(new ClientThread()).start();
}
class ClientThread implements Runnable {
    @Override
   public void run() {
        try {
            Log.d(TAG, "try to connect...");
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
            Log.d(TAG, "Adder: "+serverAddr);
            socket = new Socket(serverAddr, SERVERPORT);
            InputStream in = socket.getInputStream();
            Log.d(TAG, "in: "+in);
            DataInputStream input = new DataInputStream(in);
            Log.d(TAG, "input: "+input);
            Log.d(TAG, "connected1234");
                    byte[] data;
                    int len= input.readInt();//-298696669//17976
                    Log.d(TAG, "len: "+len);
                    data = new byte[len];
                    Log.d(TAG, "data: "+data);
                    if (len > 0) {
                        input.readFully(data,0,data.length);
                    }
                    final Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data
                    .length);
                    Log.d(TAG, "Bitmap: "+bitmap);
                    runOnUiThread(new Runnable() {
                        @Override
                     public void run() {
                            imageView.setImageBitmap(bitmap);
                        }
                    });
                    ByteArrayOutputStream bos =new ByteArrayOutputStream();

             Bitmap bitmap1=BitmapFactory.decodeResource(getResources(),R.drawable.image22);
            Log.d(TAG, "bitmap1: "+bitmap1);
            bitmap1.compress(Bitmap.CompressFormat.PNG,0,bos);
            byte []array=bos.toByteArray();
            OutputStream outputStream=socket.getOutputStream();
            DataOutputStream dos=new DataOutputStream(outputStream);
            dos.writeInt(bos.size());
            dos.write(array,0,array.length);
            Log.d(TAG, "bos.size: "+bos.size());
            Log.d(TAG, "bos.array: "+bos.toByteArray());
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

server code:
public class Server extends JFrame {
BufferedImage bi,inputImage;
JButton btn;
ServerSocket serverSocket;
Socket socket;
private Scanner in;
private PrintWriter out;
Server jframe=this;
public Server(){
    File imageFile = new File("ssss.PNG");
    try {
         bi = ImageIO.read(imageFile);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    this.add(btn = new JButton("Send"), BorderLayout.NORTH);
    //this.add(new JLabel(new ImageIcon(bi)), BorderLayout.CENTER);
    this.setSize(200, 180);
    this.setVisible(true);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    try{
         serverSocket = new ServerSocket(8000);
         socket = serverSocket.accept();
         in = new Scanner(socket.getInputStream());
         out = new PrintWriter(socket.getOutputStream(), true);
    }
    catch(IOException ex){
        System.err.println(ex);
    }
    btn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
           sendImage(new File("ssss.PNG"));
           InputStream inputStream;
        try {
            inputStream = socket.getInputStream();
            DataInputStream dis=new DataInputStream(inputStream);
           int size = dis.readInt();
           System.out.println("size: "+size);
           byte[] imageAr = new byte[size];
           dis.readFully(imageAr);
           System.out.println("imageAr: "+imageAr);
           System.out.println("dis: "+dis);
           BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));
           jframe.add(new JLabel(new ImageIcon(image)), BorderLayout.CENTER);
           revalidate();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
           // try {
               // ImageIO.write(bi, "PNG", socket.getOutputStream());
            //} catch (IOException e) {
                // TODO Auto-generated catch block
             //   e.printStackTrace();
          // }
        }
    });
}
public static void main(String[] args) {
            new Server();
}
public void sendImage(File file){
    try {
        DataOutputStream out = new DataOutputStream(
                socket.getOutputStream());
        DataInputStream dis = new DataInputStream(new FileInputStream(file));
        ByteArrayOutputStream ao = new ByteArrayOutputStream();
        int read = 0;
        byte[] buf = new byte[dis.available()];
        while ((read = dis.read(buf)) > -1) {
            ao.write(buf, 0, read);
            System.out.println("read: "+read);
            System.out.println("buf: "+buf);
        }
        System.out.println("ao.size(): "+ao.size());
        out.writeInt(ao.size());
        System.out.println("ao.toByteArray(): "+ao.toByteArray());
        out.write(ao.toByteArray());
        out.flush();
       // out.close();
       // dis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}


Dice rolling statistics

Question: Say I roll a 20-sided dice 4 times. The probability of the first roll hitting 1 is $1/20$ (5%). However, what is the chance of one of the 4 dice coming up with a 1 (and 2 dice coming up with a 1, and 3 dice coming up with a 1)?
I know the probability of rolling 4 ones in a row would be $1/20^4$ (.0000625%) but not sure how to figure the rest of it out.
Answer: The probability of rolling just one 1 is the probability of rolling a 1 with one die times the probability of rolling a non-1 three times.  $\frac{1}{20}\times \frac{19}{20}\times \frac{19}{20}\times \frac{19}{20}$
But that's just the probability of the first die to be a one.  So we have to multiply that by 4 to get the total probability of rolling one 1.  $(\frac{1}{20})^1\times(\frac{19}{20})^3\times4$
The probability of rolling two 1's is similarly done. $(\frac{1}{20})^2(\frac{19}{20})^2\times(number\space ways\space the\space 1s\space can\space be\space arranged)=(\frac{1}{20})^2(\frac{19}{20})^2\times{4\choose 2}$
Finally rolling three 1's is done the same way as rolling one 1. $(\frac{1}{20})^3\times(\frac{19}{20})\times4$

Dice rolling statistics


Fix toggle comment functionality for batch files in Sublime Text

Question: I must be having a bad search day, but I can't find any information about how to customize Sublime Text 2 so that toggle comment works correctly for windows batch files (i.e. adding either a REM or :: to the beginning of a line). Any help?
Answer: You can create a plugin or a macro to do it. Perhaps a snippet already exists but i have not found it.
I will try to explain the "create macro" alternative.
Create a macro with this code (save it in Packages/User, with name what-you-want.sublime-macro):
[
    {"command": "split_selection_into_lines"},
    {"command": "move_to", "args": {"to": "hardbol", "extend": false}},
    {"command": "insert", "args": {"characters": "REM "}}
]

Now you can use it. Select the lines to comment and execute the macro.
You can also bind the macro to a key. Add in "Key Bindings - User" this key binding:
{ "keys": ["alt+."], "command": "run_macro_file",
  "args": {"file": "Packages/User/what-you-want.sublime-macro"}, "context":
    [
        { "key": "selector", "operator": "equal", "operand": "source.dosbatch" }
    ]
}

The "selector" key in the "context" ensures that this key is only mapped when in batch files ("source.dosbatch").
References:

Banish Repetitive Tasks with Sublime Text 2 Macros
Key binding context to only react on e.g. Python code
Comment: Hi @Pat. You can set the key shortcut to specific sources (http://sublimetext.userecho.com/topic/21146-key-binding-context-to-only-react-on-eg-python-code/). Anyway, a better option is create a plugin to manage the toggle func.
Comment: Thanks @aanton, that's a great start! However, I'd like to be able to *toggle* the comment (and only in source.dosbatch files). And if I set the key shortcut to Ctrl+/, it overrides the default commenting behavior. So close...


Please check proof of convergence in $L^2(0,T;L^2)$ of a composition (uses Nemytskii operator)

Question: Suppose we have a continuous function $g:\mathbb{R} \to \mathbb{R}$ that satisfies $|g(x)| \leq C|x|$. Let $u_{n} \to u$ in $L^2(0,T;L^2)$. I want to show that $g(u_{n'}) \to g(u)$ in $L^2(0,T;L^2)$. for a subsequence $n'$.
I was thinking since we only care about a subsequence, we can extract $u_{n'} \to u$ pointwise a.e. But the Dominated Convergence Theorem does not apply because we can't find a uniform bound (there is a bound because $g$ is bounded linearly but obviously it is not uniform).
However we can use this theorem from here

where $N_f(u)(z) = f(z,u(z))$.
Define $f\colon [0,T] \times L^2(\Omega) \to L^2(\Omega)$ by $f(t, u) = g(u)$. $f$ is Caratheodory since $g$ is continuous. Define $N_f(u)(t) = f(t,u(t)) = g(u(t))$. If $u \in L^2(0,T;L^2)$ then
$$|N_f(u)(t)|^2 = |g(u(t))|^2 \leq C|u(t)|^2$$
which is in $L^2(\Omega)$. So $N_f(u) \in L^2(0,T;L^2)$. Therefore the theorem applies and $N_f$ is continuous. So if $u_n \to u$ in $L^2(0,T;L^2)$ then $g(u_n) \to g(u)$ in $L^2(0,T;L^2)$.
Question:

Is this a correct proof?
I feel weird about this because this removes the need for the dominated convergence theorem when we don't have a uniform bound. Surely this must be more well-known if what I wrote is correct.
Answer: Yes, applying the textbook theorem about the continuity of a more general Nemytskii operator solves the problem stated in the first paragraph.
That said, the proof of continuity in 3.4.4. is much like the proof you could give directly for your problem. The idea of picking a subsequence that converges a.e. is good. And you are right: we don't have a dominating function for the Dominated Convergence Theorem. So, use the Generalized DCT instead.
To simplify writing, I assume   $u_n$ already converges a.e. Since $\int u_n^2 \to\int u^2$ and $C^2u_n^2$ dominates $g(u_n)^2$, it follows that $\int g(u_n)^2 \to\int g(u)^2$. That is, $$\|g(u_n)\|_2\to \|g(u)\|_2 \tag1$$ Since $g(u_n)$ is a bounded sequence in $L^2$, it contains a weakly convergent subsequence $g(u_{n_k})$. Recall that when   weak limit and a.e. limit both exists, they are equal. Therefore, the weak limit is $g(u)$.  The relation (1) upgrades the  weak limit to strong (with respect to the $L^2$ norm).
Let's recap: every subsequence of $g(u_n)$ contains a subsubsequence that converges to $g(u)$ in the norm. By a general topological fact, $g(u_n)\to g(u)$ in the norm.


Skewness and correlation

Question: I have a data set on which I want to run a machine learning algorithm. Some of the columns are skewed.
If I apply a transformation (let's say log) to those columns and I want to display the matrix of correlations, should I do it before or after transforming the skewed columns, or should I not do it all?
Does it become meaningless after this transformation?
(original:)

J'ai un jeu de données avec des colonnes "skewed" sur lequel j'applique de l'apprentissage automatique , après une transformation log sur ces colonnes , si je veux la matrice de corrélation dois-je la faire avant ou après la transformation ou ne pas le faire du tout ? perd-elle tout sens après cette transformation?
Comment: From the network FAQ: [Do posts have to be in English on Stack Exchange?](https://meta.stackexchange.com/questions/13676/do-posts-have-to-be-in-english-on-stack-exchange)
Comment: @william3031 Thanks, however, this is the older post; normally the repost should close in favor of this one.
Answer: It would be worth displaying the matrix both before and after the transformation.
Correlation is a measure of strength of the linear relationship between two variables.
Lets say If after the log transformation the correlation is higher in magnitude than before, it tells you that there is a stronger relationship between log(x) and y than just x and y

Skewness and correlation


diretiva para colocar campos input em maiúsculo com angularJS

Question: Criei a seguinte diretiva, para quando um usuário digitar no input ser convertido para maiúsculo, porém, quando preciso editar esse campo para inserir uma palavra no meio do que já tinha digitado ele joga o cursor do mouse no final da palavra do input.
Ex:  Teste0 Teste2
Quando vou inserir uma outra palavra Teste0 Teste1 Teste2 ele joga o curso para o final de Teste2 ficando Teste0 Teste2Teste1.
return {
         require: 'ngModel',
         link: function(scope, element, attrs, modelCtrl) {
            var capitalize = function(inputValue) {
               if(inputValue === undefined) inputValue = '';
               var capitalized = inputValue.toUpperCase();
               if(capitalized !== inputValue) {
                   modelCtrl.$setViewValue(capitalized);
                   modelCtrl.$render();
                }
                return capitalized;
             };
             modelCtrl.$parsers.push(capitalize);
             capitalize(scope[attrs.ngModel]);  // capitalize initial value
        }
       };

Answer: Se o único objetivo da diretiva é transformar o texto em uppercase, você pode usar um css:
.uppercase {
    text-transform: uppercase;
}

CSS é mais leve que o AngularJs e o resultado será o mesmo.
Answer: @Felipe j.lemos,
HTML

    <input type="text" ng-model="name" capitalizado/>

JavaScript
angular.module('componente', [])
   .directive('capitalizado', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, modelCtrl) {
            element.css("text-transform","capitalize");
        }
    };
});

angular.module('meuApp', ['componente']);

JSFIDDLE
Comment: Funcionou, mas eu tive que colocar isso: element.css("text-transform","uppercase");
Comment: `Capitalize` deixa apenas a primeira letra maiúscula.


ASP.NET Reverse Loop

Question: I have some code and I'm trying to do my For loop in reverse and it doesn't seem to work
Session("mysession") = "1234-5678-"

Dim delimiters As Char() = New Char() {"-"C}

Dim mystring As String() = Trim(Session("mysession")).Split(delimiters, StringSplitOptions.RemoveEmptyEntries)

For x = 0 to mystring.Length - 1

    'Do Something

Next

That works but shows it in the wrong order I'm trying to reverse it by simply doing this
For mystring.Length - 1 to x = 0

But I'm getting an error
Expression is a value and therefore cannot be the target of an assignment.

Any ideas?
Thanks
Answer: The syntax of your reversed loop is incorrect. It should be:
For x = mystring.Length - 1 To 0 Step -1

Comment: Or [`Array.Reverse(mystring)`](http://msdn.microsoft.com/en-us/library/d3877932.aspx) if you're mentally lazy/before coffee sets in.

ASP.NET Reverse Loop


custom accumulator class in spark

Question: I'd like to define an accumulator in pyspark which is of type List and accumulate string values for worker nodes. Here is the code I have :
class ListParam(AccumulatorParam):
 def zero(self, v):
    return []
 def addInPlace(self, acc1, acc2):
    acc1.extend(acc2)
    return acc1

I then define an accumulator of this type as below
accu = sc.accumulator([], ListParam())

and then add different values to it in the executors as follows
accu.add("abc")

I'd like the value abc to appear as just one value in the accumulator but the accumulator adds three different values (one pr character) and when I look at the accu value in the driver it looks like ['a','b','c']. How can I change it such that it doesn't add each character as a separate entry in the accumulator?
--------------edit----------------
I defined another custom class for my accumulator as follows
class VectorAccumulatorParam(AccumulatorParam):
 def zero(self, value):
    return [0.0] * len(value)
 def addInPlace(self, val1, val2):
    for i in range(len(val1)):
        val1[i] += val2[i]
    return val1

and within the worker I have the following code
global accu
accu += [accuracy]

but when I print the accu in the driver, it is empty. Anything wrong?
Answer: I had the same problem as you, saw this question and worked with your code. The following code runs on a HDP 2.5 Cluster with (Py)Spark 2 and worked for me.
I took your class and changed it to append a string.
from pyspark.accumulators import AccumulatorParam
class ListParam(AccumulatorParam):
    def zero(self, v):
        return []
    def addInPlace(self, variable, value):
        variable.append(value)
        return variable

Then i created a accumulator variable and a test dataframe:
accu = sc.accumulator([], ListParam())
rdd = sc.parallelize([(0,1), (0,1), (0,2), (1,2), (1,10), (1,20), (3,18), (3,18), (3,18)])
df=rdd.toDF(['id','score'])

For the program i am working on, i have to repartition my dataframe to an individual size. So i tried this as well:
df.repartition(2)

After that i created a worker function, which will append a string to the accumulator list:
def worker(row):
    global accu
    accu.add("Moin")

Now i can call the foreach loop of the datafame (each partition is a task):
df.foreach(worker)

Every task append an item to the list with his own string list:
>>> accu
Accumulator<id=66, value=[['Moin', 'Moin', 'Moin', 'Moin'], ['Moin', 'Moin', 'Moin', 'Moin', 'Moin']]>

So i have to add every sub-list into a result-list
res = []
for i in range(0, len(accu.value)):
    res += accu.value[i]

Result:
>>> res
['Moin', 'Moin', 'Moin', 'Moin', 'Moin', 'Moin', 'Moin', 'Moin', 'Moin']

Comment: Brilliant. Good job, mate
Answer: Have you tried to explicitly tell spark to perform your operations that deal with the accumulator? As you should know, spark's operations are lazy, and many times you need to call rdd.collect() to actually perform your mappings

custom accumulator class in spark


Distance between varying skew lines

Question: Let $s \equiv$ $x=t, y=\left(\frac{t}{3}\right)+2$ and $z=\left(\frac{bt}{3}\right)+1$ $$$$
$r \equiv x=2bu-4b+1, y=u, z=2u-4$
Question: determine if there exists any value(s) of $b$ s.t. $r$ and $s$ are skew. If such value(s) exist then find the distance between $r$ and $s$.
Attempt:
I did the first part and found that $r$ and $s$ are only co-planar if $b=1$ which means they are skewed when $b\neq 1$ $$$$
The direction vectors of $r$ & $s$ are
$$d_s=(1,\left(\frac{1}{3}\right),\left(\frac{b}{3}\right))$$ and $$d_r=(2b,1,2)$$ respectively. So I worked out the normal vector and got
$$n=(\left(\frac{2-b}{3}\right),\left(\frac{2b^2-6}{3}\right),\left(\frac{3-2b}{3}\right))$$ with magnitude
$\mid n \mid=\left(\frac{\sqrt{4b^4-19b^2-16b+49}}{3}\right)$
Since the shortest distance is the perpendicular distance than the line with $n$ as a directional vector will cross both $r$ & $s$ at some points and the length of that point will be the shortest distance.
Thi is where I keep getting stuck. If I use the general points $P_s=(t,\left(\frac{t}{3}\right)+2,\left(\frac{bt}{3}\right)+1)$ and $P_r=(2bu-4b+1,u,2u-4)$ then things get very messy with $u$ and $t$.
$\dot{\vec{P_sP_r}}=(2bu-4b-1-t,u-\left(\frac{t}{3}\right)-2,2u-4-\left(\frac{bt}{3}\right)-1)$
Do I just multiply $\dot{\vec{P_sP_r}}$ by $\left(\frac{n}{\mid n \mid}\right)$ even though I'll still have $u$ and $t$ everywhere or is there a simplification that I am missing?
$$$$Note: I know that this is similar to two other questions here but none have the case where there is variable so this is not a duplicate.
Answer: You don't need to use general points, as the distance is the same for every couple of $P_r$ and $P_s$. Just set, for instance, $P_r=(1,2,0)$ and $P_s=(0,2,1)$.

Distance between varying skew lines


@Transactional timeout default value

Question: In Spring documentation, it is given that Spring JpaTransactionManager default time out is -1. So if we are not manually specifying any @Transactional timeout, it is expected to take default timeout value(-1). What does it mean? Exactly after how many seconds will the transaction timeout?
Answer: It won't timeout at all. If the connection to DB freezes, you will get transactions lasting hours.
See, for ex., org.springframework.jdbc.datasource.DataSourceTransactionManager
int timeout = determineTimeout(definition);
if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
    txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
}

protected int determineTimeout(TransactionDefinition definition) {
    if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
        return definition.getTimeout();
    }
    return this.defaultTimeout;
}

where TransactionDefinition.TIMEOUT_DEFAULT is -1

@Transactional timeout default value


How to increment multiple variables in a loop?`

Question: I am trying to execute a while loop but missing some syntax I guess.
I have a column with years ranging 1871 to 2010. I am trying to assign these years in a ranged value.. Like all years between 1871 to 18765 as '1' then 1876 to 1880 as '2' and s on.
I am unable to execute the loop correctly. please shed some light.
SQL Server Code: ( guess something is wrong when trying to increment @i,@year..)
DECLARE @i int = 0,
@year int = 1875,
@yearstart int = 1870

WHILE (@i < 30)
BEGIN
   UPDATE [train]
   SET [YearBuilt] = @i
   WHERE [YearBuilt]  between  @yearstart and  @year

    SET @i = @i + 1
    SET @year = @year + 5
    SET @yearstart = @year + 6
END

Comment: What error you have?
Answer: Add ;  and why @year + 6 instead of + 5 ?
DECLARE

@i int = 0,
@year int = 1875,
@yearstart int = 1870

WHILE (@i < 30)
BEGIN
   update train
   set YearBuilt =@i
   where YearBuilt  between  @yearstart and  @year;
   SET   @i = @i + 1;
   SET   @year = @year + 5;
   SET   @yearstart = @year + 5;
END

Comment: hi! Juan. Your suggested edit did not solve my problem. I am still not able to normalize all my years in yearsbuilt column. Why is that? is the loop not executing well?
Comment: be more specific, what is the problem?
Comment: I got the answer. I just did a logical error. i forgot to add 'start' while making increment in $yearstart.(see my post) apart much thanks to correct my syntax for SET attribute @juan


How can I write dynamic query?

Question: Can anybody suggest to me how I can write a dynamic query in Drupal for the below MySQL query.
Any suggestion will be appreciated.
<code>select * from cap_pas where pas_uid not in
  (select pas_uid from cap_boat_to_pas)
</code>
Comment: For documentation relating to this see https://www.drupal.org/dynamic-queries and https://www.drupal.org/node/310086
Comment: Are you familiar with the [Forena](https://www.drupal.org/project/forena) module?
Answer: There are many similar questions on Drupal Answers.
<code>$subquery = db_select('cap_boat_to_pas', 'cp')
  ->fields('cp', array('pas_uid'));

$query = db_select('cap_pas', 'cp')
  ->fields('cp')
  ->condition('cp.pas_uid', $subquery, 'NOT IN');

results = $query->execute()->fetchAll();
</code>
Note: to write this in a single query (by using joins), take a look at leftJoin().
Comment: Thanks for your suggestion. Is there any possibility of writing this in a single query by using joins??
Comment: Yes. you can. I didn't try it. You can take a look on [leftJoin()](https://api.drupal.org/api/drupal/includes!database!select.inc/function/SelectQuery%3A%3AleftJoin/7.x)

How can I write dynamic query?


Mule - Start a Stopped default flow

Question: I have a two mule flows, one of them is stopped by default.
I want to start that flow when I want although the application is started.
I've been looking this post: Starting a mule flow programmatically using groovy
But how can I execute in Windows Server that command? I don't understand it..
Answer: That "command" is really a component of Mule: Groovy.
You can learn more in
https://docs.mulesoft.com/mule-user-guide/v/3.7/groovy-component-reference
Comment: But.. How can I call to that compand with Groovy in Windows?
Comment: It's not a command. It is a Mule Component. Regardless of S.O, it will run in the same way

Mule - Start a Stopped default flow


Facebook Login not working in PWA app if app is in stand alone state

Question: I am building a PWA webiste. I am using Angular JS and I used javascript facebook login in my website. But if I view my app in browser, facebook login is working. But when I add shortcut to homescreen and launch the app from the homescreen, FB login is not working. Facebook page is loading. But after entering credentials it shows blank page. Can anyone help ?
Here is my FB login code

var doBrowserLogin = function(){
  var deferred = $q.defer();
  FB.login(
    function(response){
      if (response.authResponse) {
              deferred.resolve(response);
            }else{
              deferred.reject(response);
            }
          },
          {scope:'email,public_profile'}
       );
  return deferred.promise;
}

It is opening the facebook login screen and after entering the credentials, it is showing blank. Not coming back to app.

In my manifest.json file, the display property is set to standalone.
Please help.
Comment: did you debug it with remote debugging?
Comment: When I debug, there are two windows opened. One is my app and another is facebook. No error in both console.
Comment: Trivago's developers have mercy on us...please help
Answer: Don't use facebook javascript plugin, write your own flow:
1) Create a static html that will receive fb login response (ex: /fb-login-receiver.html)
It will send back login result to the application with postMessage.
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>

    Facebook login completed.

2) In your application write a function that will open fb login page in a popup window
this typescript example returns a promise for the access token and check if the user has allowed email access:
async loginFacebook(): Promise<string> {
    let popup = window.open("https://www.facebook.com/v3.1/dialog/oauth?client_id=**<YOUR_CLIENT_ID>**&display=popup&scope=email&response_type=token,granted_scopes&auth_type=rerequest&redirect_uri=" + window.location.origin + "/fb-login-receiver.html", 'Facebook Login', 'width=500,height=500');
    var promise = new Promise<string>((resolve, reject) => {
      let finished = false;
      let listener = (e: MessageEvent) => {
        finished = true;
        let url = new URL(e.data);
        let hash = url.hash.substring(1);
        let splitted = hash.split('&');
        let dct: { [key: string]: string } = {};
        for (let s of splitted) {
          var spltd = s.split('=');
          dct[spltd[0]] = spltd[1];
        }

        if (dct['granted_scopes'].indexOf('email') < 0) {
          reject("Email required");
          return;
        }
        resolve(dct['access_token']);
      };
      addEventListener('message', listener);

      let intervalChecker = setInterval(() => {
        if (popup.closed) {
          clearInterval(intervalChecker);
          removeEventListener('message', listener);
          if (!finished) {
            reject('Login canceled');
          }
        }
      }, 10);
    });
    return promise;
}

Answer: This is correct behaviour because Facebook API to login user open new tab with login form. Facebook implement OAuth2 solution and for authenticate user using their API activate OAuth2 Implicit Flow. For login in the same window you must use Authorization Code, but for client side applications isn't secure beacause you will need a secret code not available for users.
Instead of open new tab you can create iframe with facebook login form and when user logged in close it and redirect.
Comment: No solution?? I found a pwa doing it... www.trivago.it... how they Archive it???? I m going crazy
Comment: Still am facing the issue. No solutions yet.
Comment: I forgot that PWA doesn't allow to open other side in the same window.
Comment: Yes. That is the issue. I am not able to open other tabs and after finish the login procedure and come back to the app, which is not working
Comment: @SANGEETHKUMARSG have you found any solution yet ??
Comment: @PardeepJain, Couldn't find any solution
Comment: Did anyone find a solution?


the norm a functional that maps a convergent sequence to its limit

Question: Given the linear space $\vec{E}$ of real convergent sequences, dotated with the norm
\begin{equation*}
\begin{aligned}
\| \cdot \| : \vec{E}&\to \mathbb{R} \\
x=(x_n)_{n\in\mathbb{N}} &\mapsto \|x\|=\sup_{n\in\mathbb{N}} |x_n|
\end{aligned}
\end{equation*}
and the function
\begin{equation*}
\begin{aligned}
l : \vec{E}&\to \mathbb{R} \\
x=(x_n)_{n\in\mathbb{N}} &\mapsto l(x)=\lim_{n\to\infty} x_n
\end{aligned}
\end{equation*}
prove that $l$ is a continuous linear function and calculate its norm on $\mathcal{L}(\vec{E},\mathbb{R})$.
I think that the norm is 1 but i would appreciate if someone could help me with it.
PS: this is not homework, i just saw this and needed to know the answer hahah
Comment: Where you wrote "dotated," I would guess that you are thinking of Spanish "dotado," so the English word you want is "endowed."
Comment: thanks! i didn't know which word to use :)
Answer: The norm is indeed $1$. First, you want to show $|l(x)|\le\|x\|$ for all $x\in\vec E$ (which implies $\|l\|\le1$). That is, you want to show that if $x_n\to x$,
$$|x|\le\sup_{n\in\mathbb N}|x_n|.$$
To show $\|l\|\ge1$, it suffices to find a sequence $(x_n)$ such the above inequality is an equality. Are you able to find such a sequence?


Transformar imagem em Base 64

Question: Estou transformando uma imagem que envio pela camera em base64 porem a imagem fica toda preta, não sei o que esta errado, segue abaixo o meu código
app.encodeImageUri(mediaFiles[i].fullPath); //Aqui envio o caminho da minha imagem da seguinte maneira 'file:/storage/emulated/0/DCIM/Camera/140014212.jpg'

encodeImageUri: function (imageUri)
{
    var c=document.createElement('canvas');
    var ctx=c.getContext("2d");
    var img=new Image();
    img.onload = function(){
       c.width=this.width;
       c.height=this.height;
       ctx.drawImage(img, 0,0);
    };
    img.src=imageUri;
    var dataURL = c.toDataURL("image/jpeg");
    alert(dataURL);

    var tb1 = '';
    document.getElementById("imgBase64").innerHTML = tb1;

    return dataURL;
},

Comment: @ErlonCharles arrumei o meu comentario, veja se agora está mais clato
Comment: Vinicius da uma olhada nesse post http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript
Comment: Existe algo que não está funcionando? O retorno não está dentro do esperado? Qual a dúvida?
Comment: veja esse link: http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript
Answer: Acredito que fazendo isso, resolva o problema da imagem preta:
dataURL.replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
var tb1 = '';
document.getElementById("imgBase64").innerHTML = tb1;

Mas se não rolar, aqui tem um exemplo funcional:
http://jsfiddle.net/handtrix/yvq5y/
Answer: Consegui resolver com o seguinte código:
convertImgToBase64URL: function (url, nome,callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'), dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null;
    };
    img.src = url;
},

A chamada da função ficou assim:
app.convertImgToBase64URL(anexo[aux], ext, function(base64Img){
           /* Aqui Voce coloca a ação que deseja */
        });

Comment: Porem gostaria de saber se seria possível adaptar o código para enviar vídeos e áudios?

Transformar imagem em Base 64


CANCELED - TimeUnit.MINUTES.convert() method functionality

Question: Well I'm trying to get diference between times and I'm using TimeUnit.XXX.convert().
Here's my piece of test code:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");

        Date d1 = new Date();

        Date d2 = new Date();

try {
            d1 = sdf.parse("08/11/2015 10:00:00");
            d2 = sdf.parse("08/11/2015 14:30:00");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Duration in minutes: "  + TimeUnit.MINUTES.convert(d2.getTime()-d1.getTime(), TimeUnit.MILLISECONDS));
        System.out.println("Duration in hours: "    + TimeUnit.HOURS.convert(d2.getTime()-d1.getTime(), TimeUnit.MILLISECONDS));

The results were: 'Duration in minutes: 270' and 'Duration in hours: 4'.

But in fact the difference beteween 10:00:00 and 14:30:00 is 4,5 hours (decimal).
Is that a bug or am I doing something wrong?
Comment: How can you represent 4.5 hours with _units_ of hours?
Comment: @Tunaki Yes Tunaki, I didn't paid attention on return of the function. My bad!
Answer: 270 minutes if presented as hours are truncated to 4 hours.
Remember that the method convert  returns a long, not a decimal value.
From javadoc

Convert the given time duration in the given unit to this unit.
  Conversions from finer to coarser granularities truncate, so lose
  precision. For example converting 999 milliseconds to seconds results
  in 0.
Comment: I'm pretty sure it's truncated... not rounded
Comment: @Lance... right truncated, I edit my answer and added the reference to the documentation highlighting it. Thanks


build.gradle error set targetCompatibility t 1.7

Question: i got this error message saying
Error:Error converting bytecode to dex:Cause: Dex cannot parse version 52 byte code. This is caused by library dependencies that have been compiled using Java 8 or above. If you are using the 'java' gradle plugin in a library submodule add targetCompatibility = '1.7' sourceCompatibility = '1.7' to that submodule's build.gradle file.
i tried to add targetCompatibility = '1.7'and sourceCompatibility = '1.7' inside the dependencies but it still gave me the same error,, how do i solve this?
(i just added mysql connector to my library and it automatically generated that dependency)
<code> apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.example.boneyflesh.connectnapls"
    minSdkVersion 17
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',   {
    exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    testCompile 'junit:junit:4.12'
    compile files('libs/mysql-connector-java-5.1.38-bin.jar')

   }
</code>
Comment: solved it with some dexOptions and defaultConfig
Answer: Solved this by adding this to app.gradle
<code>defaultConfig {
    jackOptions {
        enabled true
    }
}
dexOptions {

}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
</code>


Mongoose instance .save() not working when embedded array object changed

Question: I am using Mongoose npm module to manage mongodb.
This is schema of mongodb collection what I am going to update.
var UserSchema = new Schema({
    username: {
        type: String,
        unique: true,
        required: true
    },
    email: {
        type: String,
        unique: true,
        required: true
    },
    cards: []
});
module.exports = mongoose.model('User', UserSchema);

inside post request, here req is request object of post request.
 and res is response object.
User.findById(userID).exec(function (err, doc) {
        let cardInfo = req.cardInfo
        let cardIndex = req.cardIndex
        doc["cards"][0] = cardInfo;
        console.log(doc)
/*  here I got right doc object as I requested
{
        "_id": "59f3bdd488f912234fcf06ab",
        "email": "firstname.lastname@example.com",
        "username": "test",
        "__v": 2,
        "cards": [
            {
                "testNo": "42424242424242"
            }
        ]
    }
*/
        doc.save(function (err) {
          if (err) {
            return res.json({
              success: false,
              msg: 'Card add error'
            });
          }
          res.json({
            success: true,
            msg: 'Successful updated card.'
          });
        });
})

I got message 'Successful updated card.', but actually, It doesn't save.
How to solve it. Thanks.
Comment: Where is `cardIndex` being used?
Comment: It was used for index of array cards. but I abbreviated to simplicity.
It's not problem, it doesn't work when I post request with param cardIndex = 0
Answer: The problem is that mongoose don't knwo your array is modified.
You can use 2 solutions :
markModified
This function will mark the embedded element as modified and force a resave of it.
It will tell mongoose to resave this element.
User.findById(userID).exec(function (err, doc) {
        let cardInfo = req.cardInfo
        let cardIndex = req.cardIndex
        doc["cards"][0] = cardInfo;
        console.log(doc)
/*  here I got right doc object as I requested
{
        "_id": "59f3bdd488f912234fcf06ab",
        "email": "firstname.lastname@example.com",
        "username": "test",
        "__v": 2,
        "cards": [
            {
                "testNo": "42424242424242"
            }
        ]
    }
*/
        doc.markModified('cards');
        doc.save(function (err) {
          if (err) {
            return res.json({
              success: false,
              msg: 'Card add error'
            });
          }
          res.json({
            success: true,
            msg: 'Successful updated card.'
          });
        });
})

Use a full schema.
To avoid the markModified trick, you should describe the content of cards in your schema. This way mongoose will be able to determine if it needs to save the field or not.
Here is the way to declare your schema properly :
const CardSchema = new Schema({
  testNo: String,
});

var UserSchema = new Schema({
    username: {
        type: String,
        unique: true,
        required: true
    },
    email: {
        type: String,
        unique: true,
        required: true
    },
    cards: [CardSchema]
});
module.exports = mongoose.model('User', UserSchema);

This way, mongoose will be able to detect if a value inside cards changed and save only the modified item.
If you can do it (static schema), this is clearly the good way to do it.
Answer: Thanks for all answers.
I find this solution in addition.
doc["cards"].set(cardIndex, cardInfo)

Cheers!
Answer: If you just want to update cards based on cardIndex:
User.update({_id: userID}, {'$set': {
    'cards.cardIndex': cardInfo
}}, function(err) {
   //code
}

Comment: Thanks but I have to update existing cards.
so I passed index of card.


Como formatar os números diretamente pelo SQL

Question: Senhores, meus números estão saindo sem formatação quando realizo o select diretamente no banco, estão saindo da seguinte forma:
REALIZADO             META
61274436,2090003    80000000,00

Como posso fazer com que eles saiam legíveis para quem for interpreta-los?
Comment: Defina legíveis para quem for interpretá-los
Comment: imagino que seja `sql-server` por conta da função `datepart` correto? O que seria legíveis pra vc? Arredondar?
Comment: @LeandroAngelo nesse caso, gostaria de inserir as pontuações em suas posições corretas.
Comment: É o Sql-server mesmo @RicardoPontual, não quero arredonda-los, apenas inserir as pontuações em seus devidos lugares.
Comment: Isso deveria ser feito em sua aplicação através de máscaras, caso contrário você não terá mais valores númericos, apenas textos. Onde você exibe essas informações e o que mais faz com elas após a consulta?
Comment: Assim: "61.274.436,2090003"? Mas o usuário/você vão ler o resultado direto do `sql` ou em uma aplicação (formulário, página web, etc)? Porque a responsabilidade da formatação é da apresentação, mas se não tiver isso, só o resultado do banco é possível de formatar
Comment: Se você usa `SQL Server 2012` ou mais atual, tem a função **format**: `select FORMAT(61274436.2090003,'#,0.0000', 'pt-BR')`, veja se é isso que precisa que eu coloca numa resposta detalhando melhor
Comment: É isso mesmo que preciso @RicardoPontual.
Answer: Usando a partir do SQL SERVER 2012, você pode usar a função FORMAT  :
SELECT FORMAT(A.REALIZADO,'#,0.0000', 'pt-BR') ...

Usando só o padrão '#0.0000' irá formatar a exibição usando pontuação, mas será exibido de acordo com a configuração SQL Server, que se estiver configurado em inglês por exemplo, vai exibir "61,274,436.2090". Para exibir no format correto, usar o último parâmetro, que é a "cultura", no exemplo, usei "pt-BR" para exibir pontos nos milhares e vírgula nos decimais.
Pode ser usado com tipos tanto numéricos como data, verificar a tabela no link acima com a documentação.
Comment: Ricardo, essa query será inserida em meu JavaScript, tentei inserir mas ele não reconheceu, eu já estava utilizando a query, mas só implementar essa nova funcionalidade que o meu JavaScript não reconheceu, sabe se tem alguma outra maneira para poder utiliza-lo dentro do meu código?
Comment: No `javascript`? Geralmente colocamos isso no código lado servidor (`c#`, `php`, `Java`, etc), ou você está usando `node-js`?
Comment: Essa é a query que já utilizo hoje dentro da minha JSP e funciona.
    SELECT
    A.REALIZADO,
    A.META,
    FLOOR((A.REALIZADO/A.META)*100) AS ACUMULADO

    FROM (

    SELECT
    ((SELECT ISNULL(SUM((ITE1.QTDNEG*ITE1.VLRUNIT)-ITE1.VLRDESC-ITE1.VLRREPRED),0)....     Após implementar essa configuração que vc me informou ela não reconhece mais, só funciona no banco...
Comment: estranho porque deveria apenas passar a query para o banco, e se funciona no banco deve funcionar também no código. Só repare que, se antes o resultado era um valor numérico, do tipo `decimal` ou `float`, não sei bem o tipo da campo da sua tabela, usando `format` ele será agora `nvarchar`, verifique se o seu código está tratando os campos que estão usando `format` como `nvarchar`, senão vai dar erro no retorno da query


How to use a views contextual filter OR?

Question: After browsing the net and SE for a while it appears to me there is no good solution to combine 2 contextual filters with OR (rather than the default AND).
This post mentions a PHP hack and this post has some links to an issue stating a recent change in views 7.x-3.1.
It also mentiones using hook_views_query_alter(&$view, &$query) to modify the view.
Does anyone have a working example or a better solution?
Comment: I don't think there is a better solution as of now. As said in the threads you pointed, it's an ongoing issue apparently. I stumbled on the same problem this week, and had to find a workaround with attachments. But then, it doesn't give a mixed list but two connected ones, which doesn't fit all needs.
Answer: The comment thread starting here describes an effective workaround. MotoTribe linked to the same thread, but at the time of his question, there was no working example on that page. Now there is, as follows:
In your module, implement hook_views_api():
function MODULENAME_views_api() {
  return array(
    'api' => 3,
  );
}

Then add a new file to your module called MODULENAME.views.inc, and implement hook_views_query_alter():
function MODULENAME_views_query_alter(&$view, &$query) {
  if ($view->name == 'whatever_your_view_is_called') {
    $query->where[0]['type'] = 'OR';
  }
}

Also be aware of this caveat:
Apparently, the "Content: Published (Yes)" filter that comes with every View is considered to be a part of the same filter group as the contextual filters (group 0). So in order to make my view display only published nodes which belong to any of the groups specified by contextual filters (published AND (arg1 OR arg2 OR ...)), I had to move the "Content: Published (Yes)" into a new filter group (using the "And/Or, Rearrange" dialog). Note that the UI didn't display the "Content: Published (Yes)" filter any differently after I moved it into a new group (there weren't any other groups), but in the query object that gets passed into hook_views_query_alter() it did move it from group 0 into group 1, causing the code in the above functions to no longer affect it.
Comment: It is better to at least paraphrase the relevance of the references to the OP's question. Link only answers are discouraged because links may not persist.
Comment: @Triskelion: Ah, you're absolutely right. I've edited my response to fix that.
Answer: Try the patch in this issue : Pull filter value from an argument
It allows you to pass the value from the contextual filter to the "normal filter". There you can do your advanced conditions.
Answer: There is a module which changes handlers of Views to make contextual filters to be used with OR instead of AND:
Views Contextual Filters OR
Comment: I want to create a view with content from "current user" + "Content from flagged users (the current user has flagged using follow flag[user])"
Answer: The situation with Contextual Filters and Filter Groups is indeed bleak. Here is thread on D.o about this toppic, which has the same solution as stated by @CoreDumpError.
https://drupal.org/node/1451218
Also, here is a module that can help resolve conflicting contextual and exposed filters...
Views Filter Harmonizer


Create OpenFileDialog when RichTextBox selected?

Question: In my application, a list of fields is read from a database, and then rendered in a TabControlPage. Each field has a Control of a specific type, one of which is a RichTextBox.
What I need, is when the user selects the RichTextBox, an OpenFileDialog should appear, allowing the user to select a file. The RichTextBox should then display the full path + filename(eg. C:/files/excel/thing.xlsx) in the form of a hyperlink.
Currently, you can type in the path+filename into the RichTextBox and it will automatically be made into a hyperlink.
Any suggestions, or perhaps reference material you can give me?
Answer: You can attach something like this to the Enter event on your RichTextBox:
<code>Dim dialog As New OpenFileDialog()
Dim result As DialogResult = dialog.ShowDialog()
If result = Windows.Forms.DialogResult.OK Then
    RichTextBox1.Text = dialog.FileName
End If
</code>
This is not turning it into a hyperlink for me, but it sounds like you have that part handled?
edited as per Lars' comment.
Comment: ShowDialog returns a DialogResult, not a Boolean.
Comment: That's not what it says here: http://msdn.microsoft.com/en-GB/library/system.windows.window.showdialog.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

And it's working fine for me.
Comment: That's for WPF.  Post was tagged WinForms.  See [DialogResult Enumeration](http://msdn.microsoft.com/en-us/library/system.windows.forms.dialogresult(v=vs.110).aspx)
Comment: Haha, fair point. Strangely though the code still seems to be compiling and working for me in a Winforms app.
Comment: Pressing the Cancel button on the dialog will also return "true" in your original version, since Cancel's value is > 0, or "not false".  :-)
Comment: Ok I got it to work, using something similar to what you have.  This seems to break my hyperlinks, but I wrote a module to just navigate to the address of the text, using either iexplore or explorer.  Thanks for your help!


Select não retorna nada quando tenho NULL na chave estrangeira

Question: Tabela COMPROVANTE: codigo, subprojetocodigo
Tabela SUBPROJETO: codigo, nome
meu select:
select a.codigo, q.nome as nomesubprojeto, a.subprojeto from comprovante a, subprojeto q where a.subprojeto = q.codigo and a.codigo = 3

funciona normalmente quando no campo subprojetocodigo eu tenho algo cadastrado
mas alguns desses campos são NULL
quando eu dou aquele select e a chave estrangeira é null, não retorna nada
como eu faria para retornar mas dizendo que nomesuprojeto é null?
Comment: Por que não usar INNER JOIN ou LEFT JOIN?
Comment: Você quer fazer um `LEFT OUTTER JOIN` mas está fazendo um `INNER JOIN` implicito. Existe uma notação p/ fazer isso implicitamente mas é muito melhor vc já ir se acostumando a escrever SQL em notação explícita
Answer: Da maneira como montou seu SELECT você está fazendo um INNER JOIN.
Substitua por um LEFT OUTER JOIN:
SELECT a.codigo, q.nome as nomesubprojeto, a.subprojeto
FROM comprovante a LEFT OUTER JOIN subprojeto q ON a.subprojeto = q.codigo
WHERE a.codigo = 3;

Answer: Utiliza algo assim:
SELECT a.codigo,
    ISNULL(q.nome, '') AS nomesubprojeto,
    a.subprojeto
FROM comprovante a
    LEFT JOIN subprojeto q ON a.subprojeto = q.codigo
WHERE a.codigo = 3

Answer: Não tem segredo nenhum - a linguagem SQL foi feita para parecer inglês e só seguindo a lógica do seu "where" fica fácil entender que não vai ter nenhum registro para o qual o "a.subprojeto" seja NULL e que tenha um equivalente "NULL" em q.código. Esta query deve funcionar:
select a.codigo, q.nome as nomesubprojeto, a.subprojeto from
     comprovante a, subprojeto q
where (a.subprojeto = q.codigo OR a.subprojeto IS NULL) AND a.codigo = 3

Uma forma mais específica, e que vai ser bem mais famíliar para quem já está acostumado com SQL é usar a clausula intermediária de "join" para indicar a junção de tabelas antes da cláusula "where". No caso, como você quer resultados da tabela da esquerda mesmo quando não houver um registro correspondente, o correto é o LEFT JOIN:
SELECT a.codigo, q.nome as nomesubprojeto, a.subprojeto
     FROM comprovante as a
     LEFT JOIN subprojeto as q
     ON a.subprojeto = q.codigo
where a.codigo = 3

Comment: eu preciso de algo assim pq na verdade minha query é gigante, coloquei só um pedacinho.
preciso só de uma linha, como esse exemplo: where (a.subprojeto = q.codigo OR a.subprojeto IS NULL)

só que nesse exemplo, ele me retornou todos os subprojetos, daí na hora de exibir o nomesuprojeto, ao invés de retornar null ele exibe o primeiro da lista
Comment: com o LEFT JOIN, o nomesubprojeto deve ser simplesmente "NULL".


How to disable autodesk-forge mouseHover on panel

Question: I'm trying to add some CSS on a forge panel.
Whenever I put my mouse hover a forge panel the colour of the background become darker.
Is it possible to disable this behaviour?
Edited:
Here picture of my problem
My mouse was hover the panel titled 2.
I want the background to stay like the panel 1.
Comment: Could you consider providing a reproducible case demonstrating how you create these two panels? I tried to reproduce the situation you mentioned, but unfortunately I couldn't. All panels I created are all transparent like your panel 2.
Comment: I might have found the problem. We're using the third version of the forge viewer on the 6th version the problem doesn't appear. We are going to upgrade the viewer thx for your help
Comment: Sure thing, thank you for confirming. :)
Answer: I supposed that you want to change the background color of the tree nodes of the model structure panel or property panel while mouse hovering. Please place this CSS snippet after viewer's stylesheet:
<code>// Change background color to red color in dark-theme
.adsk-viewing-viewer.dark-theme .treeview .group>lmvheader:hover,
.adsk-viewing-viewer.dark-theme .treeview .leaf>lmvheader:hover,
.adsk-viewing-viewer.dark-theme .treeview group>lmvheader:hover,
.adsk-viewing-viewer.dark-theme .treeview leaf>lmvheader:hover {
    background: rgba(255,0,0,.4)!important;
}

// Change background color to red color in light-theme
.adsk-viewing-viewer.light-theme .treeview .group>lmvheader:hover,
.adsk-viewing-viewer.light-theme .treeview .leaf>lmvheader:hover,
.adsk-viewing-viewer.light-theme .treeview group>lmvheader:hover,
.adsk-viewing-viewer.light-theme .treeview leaf>lmvheader:hover {
    background: rgba(255,0,0,.4)!important;
}
</code>
And here you go!
Comment: sorry I have poorly explained my problem. I edited my question and an image. To show my problem
Answer: This problem doesn't appear in the last version of the forge viewer. I'm gooing to upgrade my viewer


Como agrupar vários registros em uma única linha

Question: Tenho uma consulta onde preciso que os valores de outras tabelas relacionadas venham agrupadas em uma única coluna. Para isso utilizo um for, entretanto, as linhas vem duplicadas.

Eu precisaria que o resultado trouxesse apenas a linha completa, no exemplo a linha 6. Alguém tem alguma ideia de como poderia fazer isso?
Abaixo segue o select que utilizo.
Select
  MAS_INDIVIDUO.INDIVIDUO_ID AS INDIVIDUO_ID
  ,Upper(Stuff((Select ', ' + Cast(t3.BFA_DESCRICAO As varchar(100)) From MAS_BUSCA_DE_FALTOSOS t3 Where t3.BUSCA_DE_FALTOSOS_ID In (Select MAS_VISITA_BUSCA_FALTOSOS.BUSCA_DE_FALTOSOS_ID From MAS_VISITA_BUSCA_FALTOSOS Where MAS_VISITA_BUSCA_FALTOSOS.VISITA_ID = MAS_VISITA.VISITA_ID) For Xml Path('')), 1, 1, '')) BUSCA_ATIVA
  ,Upper(Stuff((Select ', ' + Cast(t2.ACO_DESCRICAO As varchar(100)) From MAS_ACOMPANHAMENTO t2 Where t2.ACOMPANHAMENTO_ID In (Select MAS_VISITA_ACOMPANHAMENTO.ACOMPANHAMENTO_ID From MAS_VISITA_ACOMPANHAMENTO Where MAS_VISITA_ACOMPANHAMENTO.VISITA_ID = MAS_VISITA.VISITA_ID) For Xml Path('')), 1, 1, '')) ACOMPANHAMENTO
  ,Upper(Stuff((Select ', ' + Cast(t4.MVI_DESCRICAO As varchar(100)) From MAS_MOTIVO_VISITA t4 Where t4.MOTIVO_VISITA_ID In (Select MAS_VISITA_MOTIVO_VISITA.MOTIVO_VISITA_ID From MAS_VISITA_MOTIVO_VISITA Where MAS_VISITA_MOTIVO_VISITA.VISITA_ID = MAS_VISITA.VISITA_ID) For Xml Path('')), 1, 1, '')) OUTROS
  ,Upper(Stuff((Select ', ' + Cast(t5.AOU_DESCRICAO As varchar(100)) From MAS_ACOMPANHAMENTO_OUTROS t5 Where t5.ACOMPANHAMENTO_OUTROS_ID In (Select MAS_VISITA_ACOMPANHAMENTO_OUTROS.ACOMPANHAMENTO_OUTROS_ID From MAS_VISITA_ACOMPANHAMENTO_OUTROS Where MAS_VISITA_ACOMPANHAMENTO_OUTROS.VISITA_ID = MAS_VISITA.VISITA_ID) For Xml Path('')), 1, 1, '')) ENDEMIA
From
  MAS_VISITA
  Inner Join
  MAS_INDIVIDUO On MAS_INDIVIDUO.INDIVIDUO_ID = MAS_VISITA.INDIVIDUO_ID
  LEFT Join
  MAS_AGENTE On MAS_AGENTE.AGENTE_ID = MAS_VISITA.AGENTE_ID
  Left Join
  MAS_SEXO On MAS_SEXO.SEXO_ID = MAS_INDIVIDUO.SEXO_ID
  left Join
  MAS_VISITA_ACOMPANHAMENTO ON MAS_VISITA.VISITA_ID = MAS_VISITA_ACOMPANHAMENTO.VISITA_ID
  Left Join
  MAS_VISITA_MOTIVO_VISITA On MAS_VISITA.VISITA_ID = MAS_VISITA_MOTIVO_VISITA.VISITA_ID
  Left Join
  MAS_VISITA_BUSCA_FALTOSOS On MAS_VISITA.VISITA_ID = MAS_VISITA_BUSCA_FALTOSOS.VISITA_ID
  Left Join
  MAS_VISITA_ACOMPANHAMENTO_OUTROS On MAS_VISITA.VISITA_ID = MAS_VISITA_ACOMPANHAMENTO_OUTROS.VISITA_ID
WHERE
  MAS_INDIVIDUO.INDIVIDUO_ID = 2822
GROUP BY
  MAS_INDIVIDUO.INDIVIDUO_ID,
  MAS_VISITA.VISITA_ID
GO

Comment: Eduardo Couto, caso tenha encontrado a resposta, não esqueça de publicar a resposta aqui na sua pergunta.
Answer: Adicione a cláusula And conferindo se os registros são nulos
Select
   MAS_INDIVIDUO.INDIVIDUO_ID AS INDIVIDUO_ID
  ,Upper(Stuff((Select ', ' + Cast(t3.BFA_DESCRICAO As varchar(100)) From MAS_BUSCA_DE_FALTOSOS t3 Where t3.BUSCA_DE_FALTOSOS_ID In (Select MAS_VISITA_BUSCA_FALTOSOS.BUSCA_DE_FALTOSOS_ID From MAS_VISITA_BUSCA_FALTOSOS              Where MAS_VISITA_BUSCA_FALTOSOS.VISITA_ID = MAS_VISITA.VISITA_ID) For Xml Path('')), 1, 1, '')) BUSCA_ATIVA
  ,Upper(Stuff((Select ', ' + Cast(t2.ACO_DESCRICAO As varchar(100)) From MAS_ACOMPANHAMENTO t2 Where t2.ACOMPANHAMENTO_ID In (Select MAS_VISITA_ACOMPANHAMENTO.ACOMPANHAMENTO_ID From MAS_VISITA_ACOMPANHAMENTO Where MAS_VISITA_ACOMPANHAMENTO.VISITA_ID = MAS_VISITA.VISITA_ID) For Xml Path('')), 1, 1, '')) ACOMPANHAMENTO
  ,Upper(Stuff((Select ', ' + Cast(t4.MVI_DESCRICAO As varchar(100)) From MAS_MOTIVO_VISITA t4 Where t4.MOTIVO_VISITA_ID In (Select MAS_VISITA_MOTIVO_VISITA.MOTIVO_VISITA_ID From MAS_VISITA_MOTIVO_VISITA Where MAS_VISITA_MOTIVO_VISITA.VISITA_ID = MAS_VISITA.VISITA_ID) For Xml Path('')), 1, 1, '')) OUTROS
  ,Upper(Stuff((Select ', ' + Cast(t5.AOU_DESCRICAO As varchar(100)) From MAS_ACOMPANHAMENTO_OUTROS t5 Where t5.ACOMPANHAMENTO_OUTROS_ID In (Select MAS_VISITA_ACOMPANHAMENTO_OUTROS.ACOMPANHAMENTO_OUTROS_ID From MAS_VISITA_ACOMPANHAMENTO_OUTROS Where MAS_VISITA_ACOMPANHAMENTO_OUTROS.VISITA_ID = MAS_VISITA.VISITA_ID) For Xml Path('')), 1, 1, '')) ENDEMIA
  From
      MAS_VISITA
  Inner Join
      MAS_INDIVIDUO On MAS_INDIVIDUO.INDIVIDUO_ID = MAS_VISITA.INDIVIDUO_ID
  LEFT Join
      MAS_AGENTE On MAS_AGENTE.AGENTE_ID = MAS_VISITA.AGENTE_ID
  Left Join
      MAS_SEXO On MAS_SEXO.SEXO_ID = MAS_INDIVIDUO.SEXO_ID
  left Join
      MAS_VISITA_ACOMPANHAMENTO ON MAS_VISITA.VISITA_ID =                  MAS_VISITA_ACOMPANHAMENTO.VISITA_ID
  Left Join
      MAS_VISITA_MOTIVO_VISITA On MAS_VISITA.VISITA_ID = MAS_VISITA_MOTIVO_VISITA.VISITA_ID
  Left Join
      MAS_VISITA_BUSCA_FALTOSOS On MAS_VISITA.VISITA_ID = MAS_VISITA_BUSCA_FALTOSOS.VISITA_ID
  Left Join
      MAS_VISITA_ACOMPANHAMENTO_OUTROS On MAS_VISITA.VISITA_ID = MAS_VISITA_ACOMPANHAMENTO_OUTROS.VISITA_ID
  WHERE
     MAS_INDIVIDUO.INDIVIDUO_ID = 2822
  and
     MAS_AGENTE.AGENTE_ID is not null /*Todas as Tabelas que não deseja que estejam nulas coloca a condição para que só traga se não for null*/
 GROUP BY
     MAS_INDIVIDUO.INDIVIDUO_ID,
     MAS_VISITA.VISITA_ID
 GO

Comment: @EduardoCouto, marque essa resposta como a solução já que ela resolveu seu problema
Comment: Infelizmente isso não resolveu.
Comment: Resolvido, obrigado!
Comment: Creio que isso não resolva de fato o problema
Answer: SELECT Id+ ': '+Name+ ', ' AS idName
FROM Table1
FOR XML PATH('')