como escrever um nome usando ponteiros

Question: Preciso de um programa que utilize memoria heap para armazenar um nome qualquer. de entrada temos o numero de caracteres do nome e, em seguida, o nome, por exemplo:
32
Josefina Penacho Reis dos Santos
A saída deve ser o nome, neste caso:
Josefina Penacho Reis dos Santos
Meu programa é o seguinte:
int main(void)
{

    char *vetor=NULL;                       //vetor é o nome da pessoa
    int tam;                                //tam é o numero de caracteres do nome (tamanho do espaço alocado)
    char *aux;                              //vetor auxiliar

    scanf("%d\n", &tam);                    //determinar o tamanho do espaço alocado

    vetor=(char*) malloc(tam*sizeof(char)); //alocar o espaço necessario
    vetor[tam]='\0';                        //final da string

    aux = vetor;

    for(;*aux != '\0';aux++)
    {
        printf("%c",*aux);                  //printar o nome
    }

    printf("\n");

    return 0;
}

Não faço ideia de onde está o erro, me ajudem pf!! Obrigado
Answer:
É confuso, mas ao contrário do printf, no scanf você não deve tentar consumir o \n da entrada. scanf é uma função cheia de sutilezas, mas uma boa regra se você não quiser pensar muito é sempre escrever " %d", " %s", etc. na especificação de formato, com um espaço logo antes do %, e nenhum no final da string.
Você só tem um scanf no seu código; você está lendo o comprimento da string mas não a string em si.
O '\0' ocupa espaço; se você vai ler um nome de quatro caracteres, você precisa de cinco bytes (e portanto você precisa ajeitar a linha com o malloc):
+---+---+---+---+----+
| j | o | s | e | \0 |
+---+---+---+---+----+

Pra ler linhas com espaços no meio, você deve usar scanf(" %[^\n]", &var); o " %s" lê uma palavra de cada vez (e mesmo a versão com os colchetes falha se a linha puder começar com um espaço em branco — nesse caso, a única alternativa é fazer fgets pra dentro de um buffer e fscanf em cima desse buffer, o que é bem mais complicado).
Comment: Obrigado pela dica! Uma parte está resolvida, o problema agora é que, mesmo havendo um sobrenome, o programa só imprime o primeiro nome :/
Comment: Eu atualizei a resposta pra tratar esse caso — você pode atualizar a pergunta pra mencionar que é possível que o nome tenha espaços no meio?
Comment: OK. O lance com o scanf(" %[^\n}", &var) resolveu o problema. Obrigado!
Comment: Em vez do `scanf()` sugiro o `fgets()` para ler linhas.

como escrever um nome usando ponteiros


Unit testing iphone app withXcode, SenTestCase and C++ dependencies

Question: I have a iphone project with a embedded (for ease of use) open source C++ project in it (meaning its folders are just a group inside the project). Following Apple's tutorial on unit testing Xcode, I could run the tests no problem, provided the only imported files are from Objective-C classes.
However, whenever I run tests that import C/C++ code, the test target fails on tons of "file not found". Any idea on how to solve this, without turning all C/C++ deps on system files?
Answer: Try using the .mm extension for your C files, if you're not using it already...
If we're talking about TONS of files, go ahead and try renaming one and see if that removes it from the "file-not-found-pile".
Answer: Actually just configuring the search path on the test target solved this. Which is kinda odd, as the project target is a dependency. However, it lead to other issues, which this SO thread took care of it.


Cisco Router - NAT in and out on the same interface

Question: Here's the situation:
I have a couple of clients connected to a switch and the switch is connected to a Cisco 2621.
The clients all have IP addresses in the range 192.168.1.0/24 and the router address is 192.168.1.254.
So, host A has the address 192.168.1.1 and host B has the address 192.168.1.2.
I would like to be able to get to each host using another address (172.16.1.1 for 192.168.1.1 for example).
So I need to be able to NAT this on the router. I have played about and used a loopback interface and assigned an address and used ip nat outside on there, though I couldn't really get it working.
Any ideas on how to do this would be great.
Thanks
Answer: This configuration is called 'NAT on a stick', as the router will forward to the same end of the stick.
Cisco has a good design technote here which explain how to use it with indeed a loopback, but also with route-maps. This could help you.
Here is the configuration they're using. With only a little ajustments you should be able to use it with your setup:
<code>interface Loopback0
 ip address 10.0.1.1 255.255.255.252
 ip nat outside

interface Ethernet0
 ip address 192.168.1.2 255.255.255.0 secondary
 ip address 10.0.0.2 255.255.255.0
 ip nat inside
 ip policy route-map Nat-loop

ip nat pool external 192.168.2.2 192.168.2.3 prefix-length 29
ip nat inside source list 10 pool external overload
ip nat inside source static 10.0.0.12 192.168.2.1

ip classless

ip route 0.0.0.0 0.0.0.0 192.168.1.1
ip route 192.168.2.0 255.255.255.0 Ethernet0

access-list 10 permit 10.0.0.0 0.0.0.255

access-list 102 permit ip any 192.168.2.0 0.0.0.255
access-list 102 permit ip 10.0.0.0 0.0.0.255 any
access-list 177 permit icmp any any

route-map Nat-loop permit 10
 match ip address 102
 set ip next-hop 10.0.1.2
</code>
Comment: Thanks. I'd seen that before and gave it a go and couldn't get it working at all. Would it essentially let me ping say 172.16.1.1 and this be translated to 192.168.1.1?
Comment: well, you have to adapt it to your configuration, but yes, this would allow it.
Comment: Just adapted that config and tried it on my router. Basically, the pings now work, but the router shows nothing when debugging NAT and the host isn't showing that it's getting the actual pings either when using tcpdump. So it's like it's pinging just the router itself.


Check assumptions in generalized linear model binomial family

Question: I have the following dataset
'data.frame':   768 obs. of  2 variables:
 $ Trattamento: Factor w/ 4 levels "CONTROLLO","LIDAR",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Risposta   : num  0 1 0 1 0 1 1 1 1 1 ...

I have four treatments (Trattamento) and a response variable (Risposta) that is binomial.
I want to check whether the treatments have an effect on my response variable.
I applied the following model and obtained the following results:
    model <- glm(Risposta ~ Trattamento,
                     data = data,
                     family = binomial(link = "logit"))
Call:
glm(formula = Risposta ~ Trattamento, family = binomial(link = "logit"),
    data = data)

Coefficients:
                    Estimate Std. Error z value Pr(>|z|)
(Intercept)           0.1252     0.1446   0.865   0.3868
TrattamentoLIDAR     -0.9136     0.2125  -4.299 1.71e-05 ***
TrattamentoRECUPERO  -1.2238     0.2207  -5.546 2.92e-08 ***
TrattamentoSTANDARD  -0.4402     0.2056  -2.141   0.0322 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 1019.18  on 767  degrees of freedom
Residual deviance:  981.31  on 764  degrees of freedom
AIC: 989.31

Number of Fisher Scoring iterations: 4

My interpretation here is that there are significant effects of treatment respect to my response variable. Thus I applied the following post-hoc test:
tukey_results <- glht(model, linfct = mcp(Trattamento = "Tukey"))

 Simultaneous Tests for General Linear Hypotheses

Multiple Comparisons of Means: Tukey Contrasts

Fit: glm(formula = Risposta ~ Trattamento, family = binomial(link = "logit"),
    data = data)

Linear Hypotheses:
                          Estimate Std. Error z value Pr(>|z|)
LIDAR - CONTROLLO == 0     -0.9136     0.2125  -4.299  < 0.001 ***
RECUPERO - CONTROLLO == 0  -1.2238     0.2207  -5.546  < 0.001 ***
STANDARD - CONTROLLO == 0  -0.4402     0.2056  -2.141  0.13992
RECUPERO - LIDAR == 0      -0.3102     0.2281  -1.360  0.52432
STANDARD - LIDAR == 0       0.4734     0.2135   2.217  0.11853
STANDARD - RECUPERO == 0    0.7835     0.2217   3.535  0.00214 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Adjusted p values reported -- single-step method)

I wanted to check that the main assumptions of the GLM are satisfied using this code:
plot(model, which = 1)
plot(residuals(model), pch = 16, main = "Residuals Plot")
qqnorm(residuals(model))
qqline(residuals(model))

Can you help me interpreting the graphs that I obtained?:
Comment: If the treatments are categorical and they are the only variables in the model, then the only real assumption is that the observations are iid. Your model is basically estimating the risk of the outcome for each treatment; no different than just computing the mean in each treatment group.
Comment: Thank you. Do you mean that I can also apply a simpler test? If yes, which one might be suitable?
Answer: Standard residual plots tend to not be very useful for logistic regressions or other forms of GLMs. I would instead run some simulated residuals and see if their output looks normal. The DHarma package is great for this and has a useful vignette for learning how to run them on a number of generalized linear and additive models.
Answer: Since the treatments are categorical, your model as it stands looks like
$$ \log \left( \dfrac{p_i}{1-p_i} \right) = \beta_0 + \sum_{i=1} \beta_i \mathbb{I}(trt_i = i)   $$
Essentially, you're estimating one mean for each treatment.  The mean for treatment $i$ on the log odds scale is then $$\beta_0 + \beta_i$$
So far as assumptions go, the only things you are assuming are:

The data are iid
The likelihood is binomial

There are no other assumptions, e.g about linearity of the conditional log odds in a specific variable, to check.  Even if there were other assumptions to check, those residual plots are not the ones to look at.
Because your model is so simple, you could get away with just comparing the risk difference between groups (i.e. doing a test of proportion between all treatments).  The two approaches would be equivalent.
Comment: @ShawnHemelstrand If the data are binomial, there is nothing to check.  The iid assumption can't be checked with data, one has to bring their domain knowledge to the problem.  The binomial likelihood is an assumption, but if the data are binary I think its safe to make this.

My point here is that OP might as well group by treatment and estimate the mean  in each group. The analysis doesn't necessitate logistic regression, and hence there are not many assumptions being made.
Comment: @GiorgioS  The chi-square should be approximately the same as the likelihood ratio test for logistic regression, so that makes sense.
Comment: *There are no other assumptions, e.g about linearity of the conditional log odds in a specific variable, to check. Even if there were other assumptions to check, those residual plots are not the ones to look at.*---What should the check then? I think that is the essence of OP's question.
Comment: If OP wants to know what kind of diagnostic plots to make, I think your answer is useful.
Comment: I can see your point now. Your logic makes sense (+1 btw).
Comment: Thank you. So as far as I understood I can make a group mean between the zeros and ones within each treatment and compare the means among treatments. Which mean comparison approach should be more appropriate with the type of data I have?
Comment: @GiorgioS both methods are equivalent
Comment: I have applied a simple chi-square test and I came up with the same significances


Confidence Band in GAMM

Question: I would like to know why, when adjusting the following model, the confidence band is wider in one of the factors than in the other, if the variability of the raw data seems to be the same in both factors.

Maybe it's because there is no significance for the smooth effect?
To graph I am using the visreg library.
I appreciate any idea.
Comment: On the other hand if I adjust with:

gam(pH ~  Impacted + s(Year, bs= "ps") + s(Year, by= Impacted)+ S(Stnumber, bs="re")+s(Year,by=Stnumber, bs="re"), data = X)

the confidence bands are tigh.
Answer: The problem I think is a lack of identifiability on the Year smooths when you have a global smooth plus factor-by smooths of the same variable. Adding is the random factor-smooth probably isn't helping.
Often one needs to change the penalty on the by smooths so that they are more easily identifiable from the data. One way to do that is to place the penalty on the integrated squared first derivative of the by smooths. This has the effect of penalising deviations from a flat line. Now the smooth effect of Year in your groups is given by
$$ \gamma_{j[i]} + f(Year_{i}) + f_j(Year_{i}) $$
where $\gamma_{j[i]}$ is the $j$th group mean for the $i$th observation, and where the $f_j$ are penalised for deviating from a flat function. When coupled with the global smoother deviation from a flat function means deviation from the global function.
To do this for your model, you would need:
gam(pH ~ Impacted + s(Year) + s(Year, by = Impacted, m = 1) +
         s(Year, Stnumber, bs = 'fs'),
    method = 'REML', data = X)

The issue doesn't crop up as often with the "fs" basis as those bases are fully penalised and include a random intercept, so the penalties help I believe to make these terms identifiable.
You may also just not have enough data to uniquely identify three different kinds of smooth effect of Year. Do you need both the global and the Impacted-level smooths? Could you just work with the Impacted level smooths as in
gam(pH ~ Impacted + s(Year, by = Impacted) + s(Year, Stnumber, bs = 'fs'),
    method = 'REML', data = X)

where we no longer need the m = 1 bit for the first derivative-based penalty?
Nothing is really lost here as you could use methods to compare the by smooths to see how similar they are.

Confidence Band in GAMM


Uploading svg file in Codeigniter

Question: I am trying to upload file with type svg in Codeigniter. But i could not do it with codeigniters built in upload library. I have tried to do it by adding this line in congig > mimes.php file
'svgz' => 'image/svg+xml',
'svg' => 'image/svg+xml',

but still no solution. I am getting this error -
The filetype you are attempting to upload is not allowed.

here is my code
                    $dir = 'uploads/svg/';
                    $this->load->library('upload');

                    $config['file_name'] = $result . '.svg';
                    $config['upload_path'] = $dir;
                    $config['allowed_types'] = 'image/svg+xml';

                    $this->load->library('upload');
                    $this->upload->initialize($config);
                    $this->upload->do_upload();

Can anyone help me please?
thanks in advance
Comment: @rafi_ccj from what I see from documentation, the `allowed_type` option should be like this `$config['allowed_types'] = 'gif|jpg|png';` Try putting `svg` there.
Comment: @rafi_ccj looking at [this answer](http://stackoverflow.com/a/12338258/1983684) to a similar question, providing that you have correctly added the SVG mime types to `mime.php` (which it appears you have done), all you need to do is pass `svg` as an allowed type, not the mime type itself.
Comment: `But i could not do it`. Why? What error?
Comment: @Bibhas -- this is the error ----- The filetype you are attempting to upload is not allowed.
Comment: Specify that in the question. Plus show the code you're using to upload.
Comment: Have you tried looking at [CodeIgniter's File Uploading Class documentation](http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html)? See the `allowed_types` preference.
Comment: @ChrisL - yes i did. but can't find anything helpful for this situation. this is my first time to upload svg type file.
Comment: @ChrisL - thanks! that was the wrong i was doing. many many thanks!
Comment: @Bibhas - thanks! i have done this and problem solved!
Comment: @rafi_ccj before running away, please accept an answer. That'll help people who face the same issues. :)
Answer: First of all, check the mime type of your image here
Then,
Open mimes.php from the config folder
then find the array element of index same as your image extension from the array,
add the mime type of your image to the array
In my case, I added 'image/svg':
'svg'   =>  array('image/svg+xml', 'application/xml', 'text/xml', 'image/svg')

Answer: $config['allowed_types'] = 'image/svg+xml';

This should be:
$config['allowed_types'] = 'svg';

Answer: You need to put a list of allowed file extensions in $config['allowed_types'], separated by |, not MIME type. Try this -
$config['allowed_types'] = 'svg';

Uploading svg file in Codeigniter


How to run code on every page request - after modules are loaded?

Question: I want to write a module that redirects visitors to another page based on the geoip module.
There is hook_boot() which runs on all page requests, but before the modules are loaded. There is also hook_init() which isn't run on cached pages. I'd need something that runs after all modules are loaded - but before cached pages are served. Did I miss another hook in the documentation?
Note: Turning off the cache is not an option for performance reasons.
Answer:
I'd need something that runs after all modules are loaded - but before cached pages are served.

You cannot, as loading all the modules is the last phase of Drupal bootstrap, while cached pages are served in the second bootstrap phase.
See the code used by drupal_bootstrap().
  switch ($current_phase) {
    case DRUPAL_BOOTSTRAP_CONFIGURATION:
      _drupal_bootstrap_configuration();
      break;

    case DRUPAL_BOOTSTRAP_PAGE_CACHE:
      _drupal_bootstrap_page_cache();
      break;

    case DRUPAL_BOOTSTRAP_DATABASE:
      _drupal_bootstrap_database();
      break;

    case DRUPAL_BOOTSTRAP_VARIABLES:
      _drupal_bootstrap_variables();
      break;

    case DRUPAL_BOOTSTRAP_SESSION:
      require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
      drupal_session_initialize();
      break;

    case DRUPAL_BOOTSTRAP_PAGE_HEADER:
      _drupal_bootstrap_page_header();
      break;

    case DRUPAL_BOOTSTRAP_LANGUAGE:
      drupal_language_initialize();
      break;

    case DRUPAL_BOOTSTRAP_FULL:
      require_once DRUPAL_ROOT . '/includes/common.inc';
      _drupal_bootstrap_full();
      break;
  }

If you look at _drupal_bootstrap_page_cache(), you will notice that hook_boot() is eventually invoked before the page is served from the cached data, while hook_exit() is eventually invoked after the page is served from the cached data. Those hooks are invoked if the value of the Drupal variable "page_cache_invoke_hooks" is TRUE.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('boot');
  }
  drupal_serve_page_from_cache($cache);
  // If the skipping of the bootstrap hooks is not enforced, call
  // hook_exit.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('exit');
  }

Notice that in Drupal 8, hook_boot()has been removed and so does hook_exit(). This means Drupal 8 will never invoke those hooks.
Comment: That's a more verbose description of my problem - thanks.
Comment: While it was not the solution to my problem it still is a comprehensive answer to my question.
Answer: I think it's best to summarize the options in a new answer:
First off: There is no hook that's executed between hook_boot() and hook_init(). That means there is no hook that has a fully initialized drupal environment and is executed regardless of the page cache. -- thanks @kiamlaluno for clearing that up.
There are still two methods to get a similar effect:

It's possible to selectively load include files or modules in hook_boot() using module_load_include() or drupal_load() respectively. This is especially useful if you only need some rather self-contained functionality which isn't spread over a lot of files.
The module dynamic_cache can be used to dynamically deactivate the cache on certain page loads by setting $GLOBALS['conf']['cache'] = FALSE in hook_boot() and then do the heavy lifting in hook_init(). - thanks to @David Meister

The two methods can also be combined to narrow down the number of requests where caching needs to be disabled: Use a minimal-bootstrap in hook_boot() to determine exactly when caching needs to be disabled.
The dynamic_cache module seems rather hackish though. So I'll stick to method 1 for now.
Answer: I know you said that turning off the cache is not an option but the Dynamic Cache module lets you turn off the cache conditionally in hook_boot which might actually be an option as the cache will only be off for users you're about to redirect - http://drupal.org/project/dynamic_cache
If you can get the logic you need out of GeoIP in hook_boot() then you can turn off the cache for that page load and just do a drupal_goto() in hook_init().
Answer: Or you could just load the modules in hook_boot(), then drupal won't have to load them later and you can do whatever you want with the modules. I understand that this is a bit irregular, but programming in Drupal seems to require several irregular ways of doing things.
Answer: You can try hook_exit which is run even on cached pages. I'm not sure if drupal_goto works inside it but if it doesn't you could do what the boost module does and use header('Location: mynewurl').
Comment: drupal_goto won't work because `drupal_serve_page_from_cache()` already started sending headers at that time.


Override specific configuration keys in settings.local.php

Question: I'm trying to learn the Drupal 8 configuration override system based on the documentation here:
https://www.drupal.org/docs/drupal-apis/configuration-api/configuration-override-system
As a simple test, I have disabled the Shield module and exported config. Here's a diff:
diff --git a/config/sync/shield.settings.yml b/config/sync/shield.settings.yml
index 3f7482f18..d9f019ca4 100644
--- a/config/sync/shield.settings.yml
+++ b/config/sync/shield.settings.yml
@@ -1,4 +1,4 @@
-shield_enable: true
+shield_enable: false
 credential_provider: shield
 credentials:
   shield:

Now, in my settings.local.php I have attempted to override this config key:
/**
 * Disable Shield (HTTP Basic Authentication).
 */
$config['shield']['shield_enable'] = FALSE;

This approach does not seem to work.
Do I need to do anything else to override the configuration?
NOTE: This is a contrived example. I could use configuration splits to disable HTTP basic auth in the production environment, even if it's enabled in the active database configuration. In fact, I am hoping this approach will allow me to use environment variables to provide environment-specific values for authentication tokens, API keys and other secrets that may change in sandbox and production environments, but details are irrelevant to the question.
Answer: The key for $config is the config name, not the module. This should work:
$config['shield.settings']['shield_enable'] = FALSE;

Comment: Instant gratification! That is indeed the correct approach. Thank you!


Thymeleaf - Appending  to input tag

Question: I'm trying to append a
 after every input line in a form, but Thymeleaf keeps giving me parsing error.
Here is the code piece that I'm having trouble with:
<form th:if="${not #lists.isEmpty(brands)}">
<input th:each="brand : ${brands}" type="checkbox" th:value="${brand.name}" th:utext="${brand.name +
}" />
</form>

If I add the
 tag outside of input tag, it doesn't add it to each line.
Thanks in advance
Comment: Shouldn't  be in quotation marks? I don't know thymeleaf, but it seems weird to me that  is not between " "
Comment: Are you saying `th:utext="${brand.name}" + ""`? If yes, this is a syntax error in Thymeleaf.
Comment: I meant th:utext="${brand.name + ''}"
Comment: That doesn't work either. Same parsing error.
Answer: I think you may be going about this in the wrong way.
th:utext would insert that within the <input> node. But, according to the HTML5 Spec, nothing goes in an <input> tag ("Content model: Empty.")
I think you want something more like this:
<form th:if="${not #lists.isEmpty(brands)}">

        Brand A
        <input type="checkbox" th:id="${#ids.seq('brand')}"
            name="brand" th:value="${brand.name}"/>

</form>

If you're using Spring MVC, you may also find this example helpful: http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#checkbox-fields
Comment: This code gives me an error at ${#ids.next('brand')}, but other than that it fixed the br issue. Thanks for the link to that example.
Comment: Oops, I think I was missing a `}` ... try the edited version.

Thymeleaf - Appending  to input tag


Java: How to start some asyncronous operations and update the ui from other thread?

Question: I have a little problem, now I have to work on a small Java project. I'm trying to run a few threads from Button event handler; then the last one of the threads must update TextArea on the UI. The threads are doing computational stuff work. The most important part is to make the UI woks fine - I don't want to freeze the UI and of course I want to update the UI's TextArea from one of the other threads at regular intervals (not the ui's one). So here is a part of my code:
Inside Button's the event handler I'm starting these 4 threads:
Thread generate = new CombinaMaker();
generate.run();

Thread forward = new TranslateForward();
forward.run();

Thread backward = new TranslateBackward();
backward.run();

Thread refresh = new Refresher();
refresh.run();

I want the threads to work simultaneously. The Refresher thread must update the UI TextArea component at regular intervals.
So, here is how I update the UI from Refresher thread:
public static void updateProgress()
{
    SwingUtilities.invokeLater(new Runnable()
    {
         public void run()
         {
             //HERE
             //I have a loop that have to be looping at every 500 ms
         }
     }
}

My qustion is: am I supposed to do that link this? I need to be simple and effective. This loop is making me sad because it must be looping as long as the application works. May be this is the reason of freezing the UI? I know that I am making big error somewhere, but at this moment I can't find it alone. May be you can suggest me some simple solution. And the last think - the first 4 threads: I want to start them 'simultaneously', without freezing my UI. Is that way (starting them like this from the event handler...) the correct one or may be there is better? Thanks a lot friends!
PS. If the refreshing the UI through my 'refresher' thread is hard work I am ready for a compromise variant - Update the UI through his owns thread (UI thread). But in this case may be I must use some 'time shooting mechanism' - avoiding the freezing of the UI. What are you thinking?
Comment: What is the problem you are having, specifically, with your code? Using other threads or TimerTasks is basically what you have to do, yes.
Comment: the loop in update progress - how to avoid freezing the UI? Timer Tasks?
Comment: This is probably terrible advice, but I've passed in references of view objects into other threads, then just have those threads append data to the view directly.  Works good enough for small programs. Not sure I'd release it in a product or anything.
Answer: The main problem is your algorithm. Instead of
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        //HERE
        //I have a loop that have to be looping at every 500 ms
    }
}

You should have
// HERE
// I have a loop that have to be looping at every 500 ms
// and when something must be updated in the GUI:
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        // update the GUI as fast as possible
    }
});

i.e.
while (true) {
    Thread.sleep(500L);
    String update = getUpdate();
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            textArea.append(update);
        }
    });
}

The runnable passed to SwingUtilities.invokeLater() is executed in the event dispatch thread. It must not execute long-running tasks. Looping endlessly is a very long running task.
Answer: You don't want to loop in the runnable you pass to invokeAndDoLater. See this for an example: http://www.javamex.com/tutorials/threads/invokelater.shtml
Comment: The link given, although it will successfully blind the OP, says nothing about loops inside of runnables. ASAIK there is nothing wrong with having a loop in a runnable, which is a just another thread as far as the system is concerned. The only issue is that it is synchronous with event dispatch, so if the loop does not exit or yield(), then it will block the event dispatch.
Comment: Many swing objects are not synchronized, and therefore it is important to not update them from other threads. The purpose of InvokeAndDoLater is to get your changes on the AWT update thread (and therefore avoid race conditions with the AWT thread). You never want to do heavy operations on that thread (such as looping) because the UI will freeze until the operation completes. So technically you are right there's nothing to stop you, but it's a very bad idea if you want a responsive UI.
Answer: The SwingUtilities.invokeLater has not been designed to invoke long running threads.
One solution to your problem could be this one.
You could also try to invert the nesting of your loop and SwingUtilities.invokeLater invocation, but the feasibility of this depends on the rest of your code
do {
    // Sleep and other stuff
    SwingUtilities.invokeLater(new Runnable() {
        public void run()  {
        // Update UI
        }
    });
} while(...);

Answer:
I don't want to freeze the UI and of course

Thumbs up for not wanting to freeze the UI. Unfortunately the

I want to update the UI's TextArea from one of the other threads at regular intervals

is not an option. Updating Swing components must be done on the UI thread (the Event Dispatch Thread). Luckily, Swing has a built-in class for updating the UI at regular intervals: the javax.swing.Timer class. The Timer runs in the background, and executes on the Event Dispatch Thread so it is perfectly suited for this task.


Stratified SRS vs. probability-proportional-to-size (PPS) sampling - what's the difference?

Question: If my understanding is correct, the key difference is that:

In stratified SRS you intentionally draw $N_h$ samples from each of your $k$ strata ($h = 1...k$, $\sum_{1}^{k}{N_h} = N$) and are therefore guaranteed to get a certain number, $N_h$, from each stratum by design.
In PPS you are modifying the probability of selection for each unit to be proportional to the size of the stratum containing that unit, $p_h = \frac{x_h}{\sum_{i=1}^{k}{x_i}}$ (where $x$ is the number of units in a stratum), but you aren't guaranteed to hit a certain number of samples per unit.

Is this correct?
What I don't understand is why you would use one of these over the other. I haven't been able to find any comparison between the two online, can anyone help? Thanks!
Comment: In PPS, strata aren't (necessarily) involved. Instead, each unit's prob is proportional to the "size" of the **unit** itself. For example, you might sample companies proportionally to the number of employees at the company, or its gross income, or something. In this example the units are the companies, not employees or dollars. Each unit (company) has **its own** sampling prob, unlike in stratified sampling.
Answer: If you're doing financial audits, there is some research that Stratified SRS does a better job hitting the nominal confidence levels you're shooting for:
http://www.asasrms.org/Proceedings/y2002/Files/JSM2002-000704.pdf
In general, SRS gives you an equal chance of hitting all transactions, low and high, which is a nice property if you think there is risk spread evenly across the population.
PPS can be a good way to make sure you get "coverage" of high dollar items, which is not a statistical consideration necessarily, but is sometimes a leadership consideration. The issue of non-equal chance of selection, especially low chances for small dollar items, could be an issue since large dollar items often received better oversight than smaller transactions, so you might be unintentionally excluding low-dollar, high-risk items.


Consistency of density estimation under marginalization

Question: Let $(x_1,y_1),\ldots,(x_n,y_n)$ be samples from some unknown distribution $p(X,Y)$ and $\hat{p}(X,Y)$, $\hat{p}(Y)$ density estimates of the joint and marginal distributions (i.e., for the estimation of $\hat{p}(Y)$ we only use the $y$-part of the samples).
Question: Under which condition is
$\int_x \hat{p}(x,y)\ \mathrm{d}x = \hat{p}(y)$?
The answer obviously depends on the estimator. Is it true only in the limit and for consistent estimators? Is it important whether the estimate is parametric or non-parametric?
Essentially, I want to understand why marginalization could be useful in a continuous and non-parametric setting, if I can just as well learn the marginal distribution from the restriction of the data to the marginal dimensions.
Comment: without details about the estimation method you use, the question is unclear as we can always define $\hat{p}(y)$ by $$\int_\mathcal{X} \hat{p}(x,y)\ \mathrm{d}x = \hat{p}(y)$$
Comment: No, you can't. As I wrote, $\hat{p}(y)$ can only use the $y$-part of the samples. I can't be more specific, because the conditions are part of the question. You can assume kernel density estimation, if you need to.
Answer: $\newcommand{\R}{\mathbb{R}} \newcommand{\ud}{\mathrm{d}}$Suppose we're using KDE, so that
$$
\hat{p}(y) = \frac{1}{n} \sum_{i=1}^n k_y(y, y_i) \\
\hat{p}(x, y) = \frac{1}{n} \sum_{i=1}^n k_{xy}\left( \begin{bmatrix}x \\ y\end{bmatrix}, \begin{bmatrix}x_i \\ y_i\end{bmatrix} \right),$$
where $k_y : \R \times \R \to \R$ and $k_{xy} : \R^2 \times \R^2 \to \R$ are our kernels.
Suppose further that
$k_{xy}\left( \begin{bmatrix}x \\ y\end{bmatrix}, \begin{bmatrix}x_i \\ y_i\end{bmatrix} \right) = k_y(y, y_i) \, k_{x \mid y}(x, x_i \mid y, y_i)$
for some function $k_{x \mid y}$ which integrates to 1 for any $y, y_i$.
If the kernel function is a probability density (i.e. is everywhere nonnegative),
then this should hold,
since $k_{x \mid y}$ is itself a marginal density;
even if not, a product kernel will still satisfy this.
Then
\begin{align*}
 \int \hat{p}(x, y) \,\ud{x}
 &= \int \frac{1}{n} \sum_{i=1}^n k_{xy}\left( \begin{bmatrix}x \\ y\end{bmatrix}, \begin{bmatrix}x_i \\ y_i\end{bmatrix} \right) \,\ud{x}
\\&= \frac{1}{n} \sum_{i=1}^n \int k_y(y, y_i) k_{x \mid y}(x, x_i \mid y, y_i) \,\ud{x}
\\&= \frac{1}{n} \sum_{i=1}^n k_y(y, y_i) \int k_{x \mid y}(x, x_i \mid y, y_i) \,\ud{x}
\\&= \frac{1}{n} \sum_{i=1}^n k_y(y, y_i)
\\&= \hat{p}(y)
.\end{align*}
Comment: Thank you, that helped me a lot. So it's not true in case of a full bandwidth matrix, right? Still, since the choice of kernel is almost irrelevant, I don't see why I would ever want to compute the integral in practice...
Comment: @ASML I think it is true for a full bandwidth matrix; see my edit. If you actually need the marginal, though, numerical integration isn't free....
Comment: But didn't you just show that I basically never need numerical integration, because I can always learn consistent marginals from data?
Comment: @ASML ...yes, I misread what you were saying. :)


Protected Access Level in Swift

Question: How can I make protected (like in ruby) variable or function in Swift? I know Swift has only 3 levels but nonetheless is it possible?
Access Levels

Swift provides three different access levels for entities within your
  code. These access levels are relative to the source file in which an
  entity is defined, and also relative to the module that source file
  belongs to.

Public access enables entities to be used within any source file from
  their defining module, and also in a source file from another module
  that imports the defining module. You typically use public access when
  specifying the public interface to a framework.
Internal access
  enables entities to be used within any source file from their defining
  module, but not in any source file outside of that module. You
  typically use internal access when defining an app's or a framework's
  internal structure.
Private access restricts the use of an entity to
  its own defining source file. Use private access to hide the
  implementation details of a specific piece of functionality.

Public
  access is the highest (least restrictive) access level and private
  access is the lowest (or most restrictive) access level

Currently I see only one solution - write parent class with private modifier and children class in single file but it's kind of painful.
Comment: There was a Swift Blog entry explaining the rationale for this. It seems not to be on Apple's website anymore, but you can still read it here: http://web.archive.org/web/20150810115840/https://developer.apple.com/swift/blog/?id=11.
Comment: @MartinR it is still on Apple Swift blogs, see my answer :)
Answer: Swift prefers to not use protected. You can read the reasons here Access Control and protected

In contrast, protected conflates access with inheritance, adding an entirely new control axis to reason about. It doesn't actually offer any real protection, since a subclass can always expose "protected" API through a new public method or property. It doesn't offer additional optimization opportunities either, since new overrides can come from anywhere. And it's unnecessarily restrictive — it allows subclasses, but not any of the subclass's helpers, to access something.
Comment: "Since a subclass can always expose "protected" API through a new public method or property." this is just a stupid rationale. Well my private method can also be exposed by some public method. Then why we have private?!
Answer: There's no equivalent to protected in Swift where only subclasses have access to the method.  Personally, I don't miss it.
In Swift (as Objective-C) there is far less emphasis on subclassing than other languages.  If you find you have a set of methods that you want to be protected, it is probably better to factor them out as a delegate.
Comment: I would like to hear more about how to factor them out as a delegate.
Comment: @DavidRector If you have a load of protected methods that must be implemented by a subclass, put them all in a protocol and have a delegate property which is an object that implements the protocol. Then your main class calls methods on the delegate instead of the protected methods.
Comment: @Arsen What do you mean by "secretly"?
Comment: That's not an option. I have an `NSOperation` subclass and I want to expose a method to `finish` the operation. Only subclass should be able to call it. Doing so from the outside would cause an internal state inconsistency and potentially wreck my entire app. Delegate _is not an option_, **protected** method is. It looks like my only solution besides ignoring the problem is to pass around closures that call into private methods.
Comment: @BenAffleck `NSOperation` is an Objective-C class. Even private methods don't really have meaning with Objective-C classes. I think your best option is to make the method more robust so calling it from outside of the class doesn't damage the state.
Answer: In Ruby's point of view, it may be important. However in Swift, neither it is useless, nor it is a matter of the language.
Swift language is primarily based on modules when it comes to access levels. It even has public private(set) variables, which is much needed in Objective-C (causes boilerplate).
Answer: Swift 3.0 not cantains protected modifier. In our sdk we use internal(set) modifier that approve set operation only in sdk project.
private var _authorized : Bool = false
public internal(set) var authorized : Bool
{
    get
    {
        return _authorized;
    }
    set
    {
        _authorized = newValue
    }
}

Comment: you really could just use `public internal(set) var authorized : Bool` instead of splitting the two properties and have the getter and setter for the public one
Comment: How is this even related?

Protected Access Level in Swift


Linear Algebra, Linear Operators

Question:
State if the given map is a linear operator from $V$ to $W$. Explain your answer.
$V = W = \{f(x)\mid f(x) \text{ is a polynomial, degree of $f$ is } \le 5 \text{ and } f(1) = f′(1) = 0 \}$, $D(f) = (x − 1)2f′′$

Does anyone know how to set up this question?
Comment: If $f, g \in V$, does $D(f+g) = D(f) + D(g)$? For $r$ a real, does $D(rf) = rD(f)$? If so, it's a linear operator.
Comment: @BrianO It's a linear operator from where to where?
Comment: from $V$ to $W$ ($=V$)
Comment: Really? What is $D(x-1)^2?$ (Perhaps the intention was to define $Df(x) = (x-1)^2f''(x).$)
Answer: The problem seems badly posed to me. Perhaps it should be stated this way: Let $\mathcal P$ be the set of all polynomials. For $f\in \mathcal P,$ the function $(x-1)2f''(x)$ is a polynomial. So we can define a map $D: \mathcal P \to \mathcal P$ by setting $(Df)(x) = (x-1)3f''(x).$ Question 1: Is $D$ linear?
Now define $V$ as in the question. Question 2: Is $V$ a linear subspace of $\mathcal P?$ If so, does $D$ map $V$ into $V?$ (There is no need to introduce the notation $W.$)

Linear Algebra, Linear Operators


Redirecting old unused domain to new domain will help to increase Google authority?

Question: I have been doing blogging since 5 years back and from last year i had stopped blogging and delete the domain content. (During last year all pages are removed from indexed )
now I had purchased a new domain BlogTechie and i am planning to 301 redirect that old domain to new domain.
Is It helped to gain SEO authority in Google or I should start from scratch without worrying about old domain.
I am also adding settings in webmaster tools to inform Google for the change.
Answer: SEOs attribute a large portion of most search engines' ranking algorithms to link-based factors.  It's possible there may be old links to your pages out there on the internet on other websites.  You can capitalize on this if you still own the old URL and boost your new domain's ranking with redirects.
If you know some of your older content's URLs, it might make sense to have a one to one redirect to the new page.  If you're using apache, you can do this with an .htaccess file:
RewriteEngine On
RedirectMatch 301 /folder/oldpage.php http://www.newdomain.org/newpage.php

Anything remaining can redirect to the root.
RewriteRule ^(.*)$ http://newdomain.com/ [R=301]

Check out SEO Moz for more explanation on this: http://moz.com/learn/seo/redirection


Referencing a Worksheet: Application-defined or Object-defined error

Question: I managed to get my code working except this part:
' colle data / année
Windows(Namepatch3).Activate
For j = 0 To (finas - debutas)
    Worksheets(1).Cells(2 + cpt, debutad + j) = Vcol(j)
    'MsgBox (Vcol(j))
Next j

cpt = cpt + 1

Returning into an

"Application-defined or Object-defined error"

All variables are declared and Namepatch3 is declared As ThisWorkbook.
EDIT: Here the full code of this part:
Sub Chiffres()
    Application.ScreenUpdating = True

    Dim ThisWorkbook As Workbook
    Dim Filt As String
    Dim IndexFiltre As Integer
    Dim NomFichier As Variant
    Dim Titre As String
    Dim o As Integer
    Dim p As Integer
    Dim Msg1 As String
    Dim ConsoPDC As Workbook
    Dim Fichier As String
    Dim chaine As String
    Dim feuille As Variant
    Dim Reponse As Integer
    Dim Config As Integer
    Dim nomClasseur As Variant
    Dim vclasseur As Workbook
    Dim resum As Workbook

    [B65000].End(xlUp).Offset(0, -1).Select

    Excel.Application.DisplayAlerts = False
    '   Définit la liste des filtres de fichiers
    Filt = "Fichiers texte (*.txt),*.txt," & _
      "Fichiers Lotus (*.prn),*.prn," & _
      "Fichiers séparés par des virgules (*.csv),*.csv," & _
      "Fichiers ASCII (*.asc),*.asc," & _
      "Tous les fichiers (*.*),*.*"

    '   Affiche *.* par défaut
    IndexFiltre = 5

    '   Définit la légende de la boîte de dialogue
    Titre = "Sélectionner les fichiers à traiter"

    '   Obtenir le nom de fichier
    NomFichier = Application.GetOpenFilename _
      (fileFilter:=Filt, _
      FilterIndex:=IndexFiltre, _
      Title:=Titre, _
      MultiSelect:=True)

    '   Quitter si la boîte de dialogue est annulée
    If Not IsArray(NomFichier) Then
        MsgBox "Aucun fichier n'a été sélectionné!"
        GoTo TheEnd
    End If

    '   Affiche le chemin complet et le nom des fichiers
    Config = vbYesNo + vbInformation + vbDefaultButton2
    For o = LBound(NomFichier) To UBound(NomFichier)
         Msg = Msg & NomFichier(o)
    Next o
    Reponse = MsgBox("Ci-dessous vos fichiers selectionnés :" & vbCrLf & Msg & vbCrLf, Config, _
      "MAJ resum")
    If Reponse = vbNo Then GoTo TheEnd

    For p = LBound(NomFichier) To UBound(NomFichier)
        Msg1 = NomFichier(p)
    Next
    Application.ScreenUpdating = False
    Workbooks.Open Filename:=Msg1

    Application.Calculation = xlCalculationManual

    'Declare le classeur actif
    Set wkb = ActiveWorkbook

    'Affiche la barre de statut en bas à gauche de l'écran (si elle ne l'est pas déjà)
    Application.StatusBar = "MAJ resum - Traitement fichier " & _
      ActiveWorkbook.Name & " - merci de patienter SVP ..."
    '----------------------------------------------------------------------------
    'Ne selectionne que le nom du fichier à l'intérieur du chemin
    fichier1 = Right(Msg1, Len(Msg1) - InStrRev(Msg1, "\", -1, 1))
    Fichier = Left(fichier1, InStr(fichier1, ".xls") - 1)

    'traitement import
    '----------------------------------------------------------------------------
    ' ***************
    ' *      Macro1
    ' ***************

    ' appel raz dest
    'Call M_raz_dest

    Dim i As Integer
    Dim j As Integer
    Dim K As Integer
    Dim l  As Integer

    Dim debutcols As Integer ' année en nombre ?
    Dim fincols As Integer ' année en nombre ?
    Dim debutas As Integer ' n° col année debut
    Dim finas As Integer ' n° col année fin
    Dim debutcold As Integer
    Dim fincold As Integer
    Dim debutad As Integer
    Dim finad As Integer
    Dim rowmaxwallets As Integer
    Dim rowmaxwalletd As Integer
    Dim c As Object
    Dim therow As Integer
    Dim Nlp As String
    Dim Vcol(30) As Long ' data col année
    Dim com(30) As String  ' data col commentaires
    Dim cpt As Integer

    Windows(fichier1).Activate
    Sheets("DataBase").Select

    ' lire Année début dans col V / 22 onglet source et n° de colonne
    debutcols = CInt(Worksheets("DataBase").Cells(1, 22))  ' (col V)  XXXX
    debutas = 22
    fincols = 0
    fincold = 0
    finas = 0
    debutad = 0
    finad = 0

    ' lecture colonne de fin dans Onglet Source
    i = 0
    For i = 1 To 30
        If Len(Worksheets("DataBase").Cells(1, i + 22)) = 4 Then
            ' année 4 digits trouvée
        Else
            ' plus une colonne Année
        i = i - 1
        finas = (22 + i)
        fincols = CInt(Worksheets("DataBase").Cells(1, i + 22))
        GoTo sortie
    End If
    Next i

sortie:
    'MsgBox ("Lettre de colonne de début sur Source :" & ConvertCol(debutas))
    'MsgBox ("Lettre de colonne de fin sur Source :" & ConvertCol(finas))
    Columns(ConvertCol(debutas) & ":" & ConvertCol(finas)).Select
    'ThisWorkbook.Worksheets(1).Select
    i = 0

    For i = 1 To 70
        If Worksheets(1).Cells(2, i) = debutcols Then
            debutcold = i
            debutad = i
            'MsgBox ("N° de colonne de début sur Dest : " & debutad)
            GoTo sortie2
        End If
    Next i

sortie2:
    'MsgBox ("Lettre de colonne de début sur onglet Dest :" & ConvertCol(debutad))
    finad = debutad + (finas - debutas)
    'MsgBox ("Lettre de colonne de fin sur onglet Dest :" & ConvertCol(finad))
    Windows(fichier1).Activate
    Sheets("DataBase").Select
    rowmaxwallets = CInt(Worksheets("DataBase").Cells(Columns(1).Cells.Count, 1).End(xlUp).Row)
    'MsgBox ("Nbr de lignes dans onglet Source à traiter : " & rowmaxwallets - 2)
    'rowmaxwalletd = CInt(Worksheets("LP").Cells(Columns(1).Cells.Count, 1).End(xlUp).Row)
    'MsgBox ("Nbr de LP dans onglet LP à parcourir : " & rowmaxwalletd - 2)
    i = 0
    cpt = 1

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    'lecture fichier source
    For l = 1 To rowmaxwallets
        ' copie data année en dynamique / colonne

        Windows(fichier1).Activate
        For j = 0 To (finas - debutas)
            Vcol(j) = Worksheets("DataBase").Cells(1822 + l, debutas + j)
        Next j

        ' colle data / année

        For j = 0 To (finas - debutas)
            ThisWorkbook.Worksheets("Feuil1").Cells(2 + cpt, debutad + j) = Vcol(j)
            'MsgBox (Vcol(j))
        Next j

        cpt = cpt + 1

    Next l
fin:
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

    Sheets("Dest").Select
    Range("A3").Select
    MsgBox ("Import terminé !")

TheEnd:

End Sub

I know there is still some .Activate but I need to make the code works before optimizing it.
Comment: Should I erase Worksheets(1) or define Namepatch3 again ?
Comment: Now it gives me the error:
"Object doesn't support this property or method"
Glad to see that we are moving forward :)

Just to be a bit more precise: I need to import datas from one workbook into another one. Those datas are in a range of column that always begin in V but It's size is variable (can go from V to W to V to AE approx.). And each column may see it's header changed (from 2010 to 2030 approx.)
Comment: Maybe include the line where you are defining Namepatch3.
Comment: Namepatch3 is defined as below:

    'Namepatch3 = ThisWorkbook.Name'
Comment: Same error: Object doesn't support this property or method" but on the `Namepatch3 = ThisWorkbook` line

Dim Namepatch3 is:
`Public Namepatch3 As String`
Answer: Remove the Activate line as that is unnecessary. Instead, fully qualify your worksheet reference like this:
Dim Namepatch3 As WorkBook
Set Namepatch3 = ThisWorkbook

Then in your Loop:
Namepatch3.Worksheets(1).Cells(2 + cpt, debutad + j) = Vcol(j)

Or just simplify it all like this:
ThisWorkbook.Worksheets(1).Cells(2 + cpt, debutad + j) = Vcol(j)

Comment: New error on another line a bit above:
`Namepatch3.Worksheets(1).Select`
System is telling me "Select method of worksheet class failed."

Thanks for your time and attention buddy, really really appreciated :)
Comment: I do not see the  need for `Namepatch3` in this context. You can just use `ThisWorkbook` instead. See the last line of my answer.
Comment: Ok, I just replaced my `Namepatch3` with `ThisWorkbook`.
A new error replaced the old one:
"Object Variable or With block variable not set"

Once again, glad to see that we are going forward on the issue :)
Comment: Did you also remove all references to `Namepatch3`? You may want to update your question with more complete code of what you currently have.
Comment: I removed all references to Namepatch3, i'll update my original question with my code :)


Develop $f(z) = (1- \frac{1}{z} )^3$ to Laurent's series around $z_{0} = i$.

Question: Develop $f(z) = (1- \frac{1}{z} )^3$ to Laurent's series around $z_{0} = i$.
I was thinking to cube it first and than observe each member of that sum of four elements and find Laurent's series for it. Is that good thinking?
Comment: That function is analytic on $\;\Bbb C\setminus\{0\}\;$ thus that Laurent series will have only positive powers of $\;z-i\;$ .
Comment: @user Read my answer below. Try to make sense of all the steps.
Comment: @DonAntonio can you please explain what does that mean for developing it? I'm begginer in this so everything is new to me
Comment: In the title, you wrote that $z_0=1$, but in the body you wrote that $z_0=i$. Which one is correct?
Comment: @JoséCarlosSantos the one in body
Answer: Just do Taylor around $\;z_0=i\;$ :
$$\begin{cases}f(i)=\left(1-\frac1i\right)^3=(1+i)^3=2i(1+i)=-2+2i\\
f'(z)=\frac1{z^2}\implies f'(i)=\frac1{i^2}=-1\\
f''(z)=\frac{-2}{z^3}\implies f''(i)=-\frac2{i^3}=-2i\\
f'''(z)=\frac6{z^4}\implies f'''(i)=6\\
\ldots\\
f^{(n)}(z)=\frac{(-1)^{n+1}\,n!}{z^{n+1}}\implies f^{(n)}(i)=\frac{(-1)^{n+1}n!}{i^{n+1}}\\
\ldots\end{cases}$$
Thus, the series you're looking for is
$$-2(1-i)+\sum_{n=1}^\infty\frac{(-1)^{n+1}n!}{i^{n+1}}(z-i)^n$$
Comment: Thanks, this is very helpful :)


Exibir dados do array ngRoute

Question: Boa noite, tenho a seguinte situação. Preciso exibir todos os dados do usuário quando o mesmo for acionado.
Minha view

Lista de usuários

{{usuario.nome}}

Meu módulo
var app = angular.module("myApp", ["ngRoute"]);

app.config(function($routeProvider) {
    $routeProvider
        .when("/", {
            templateUrl: "views/home.html",
            controller: "homeCtrl"
        })
        .when("/detalhes/:id", {
            templateUrl: "views/detalhes.html",
            controller: "detalhesCtrl"
        })
        .otherwise({
            redirectTo:'/',
            templateUrl:'views/home.html',
            controller: 'homeCtrl'
        });
});

app.controller("homeCtrl", function($scope, $http) {
    $http.get("json/data.json").then(function(response) {
        $scope.usuarios = response.data;
    });
})

app.controller("detalhesCtrl", function($scope, $routeParams) {
    $scope.usuario = $scope.usuarios[$routeParams.id];

    console.log($scope.usuarios);
    console.log($routeParams);
})

Página onde os dados serão exibidos

Dados do usuário

{{usuario.nome}}

{{usuario.idade}}

{{usuario.time}}

    Home

Se alguém puder me ajudar, ficarei grato!
Answer: Eu utilizaria com rootScope da seguinte forma:
<!DOCTYPE html>

    <title>Projeto</title>

    <ng-view></ng-view>

Comment: Obrigado @Virgilio Novic, dessa maneira funcionou perfeitamente.

Exibir dados do array ngRoute


Change default favicon programmatically

Question: I know I can load a favicon though the user interface, but is there a way of setting the default favicon for your theme, so that when someone enables the theme, the default icon is immediately used?
Answer: You can place the favicon.ico in your theme folder (at the same level as your_theme.info) and it will be used automatically.
Works for Drupal 6, 7 & 8.
Note: The favicon is heavily cached by some browsers, you may need to go to extra lengths to see the new one.
Comment: The favicon needs to be in the root of your theme to get picked up.   It can't be in an images folder for example
Comment: Also, this does not work with png favicons, only favicon.ico is found. So convert to ico before you use this.
Comment: It should also be noted that this will only work for the respective theme. E.g. your admin pages won't get the new favicon, if you use an administration theme.
Comment: what about drupal9, 10 ? is there something to configure there ?/admin/appearance/settings/my theme. In my case, putting favicon.ico in my theme folder is not enough
Answer: In Drupal 8, you can use the settings.yml file, located at themes/YOURTHEME/config/install/YOURTHEME.settings.yml
Here is an example for theme logo/favicon customization:
logo:
  use_default: false
  path: 'themes/YOURTHEME/logo.png'
favicon:
  use_default: false
  path: 'themes/YOURTHEME/favicon.png'

However, if you change these settings whereas your theme is already installed in Drupal administration, you will need to uninstall your theme and then reinstall it. Else, even if you clear all caches, Drupal will not take in consideration your changes.
Answer: <?php
function hook_page_alter(&$pages) {
  $favicon = "http://example.com/sites/default/files/favicon.ico";
  $type = theme_get_setting('favicon_mimetype');
  drupal_add_html_head_link(array('rel' => 'shortcut icon', 'href' => drupal_strip_dangerous_protocols($favicon), 'type' => $type));
}
?>

Comment: This adds a new tag for the favicon, but does not replace the old one.
Answer: Method 1 - via template.php
/**
 * Implements hook_html_head_alter().
 */
function MYTHEME_html_head_alter(&$head_elements) {

  // Remove existing favicon location
  global $base_url;
  $default_favicon_element = 'drupal_add_html_head_link:shortcut icon:' . $base_url . '/misc/favicon.ico';
  unset($head_elements[$default_favicon_element]);

  // Specify new favicon location
  $element = array(
    'rel' => 'shortcut icon',
    'href' => '/path-to-favicon/favicon.ico',
  );
  drupal_add_html_head_link($element);
}

Method 2 - via custom module
/**
 * Implements hook_html_head_alter().
 */
  // Remove existing favicon location
 function MODULENAME_html_head_alter(&$head_elements) {
   global $base_url;
   $default_favicon_element = 'drupal_add_html_head_link:shortcut icon:' . $base_url . '/misc/favicon.ico';
   unset($head_elements[$default_favicon_element]);

  // Specify new favicon location
  $element = array(
    'rel' => 'shortcut icon',
    'href' => '/path-to-favicon/favicon.ico',
  );
  drupal_add_html_head_link($element);
 }

See hook_html_head_alter for more info.
Note: It's not required to list the new favicon location in hook_html_head_alter(). I usually specify it in THEMENAME_preprocess_html() or MODULENAME_init().
Answer: The following code (in a custom module) replaces the favicon, instead of adding an additional one.
/**
 * Implements hook_html_head_alter().
 *
 * Replaces the favicon.
 *
 * @param array $head_elements
 */
function MYMODULE_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => $element) {
    if (1
      // The array key can vary, depending on the original favicon setting.
      && 0 === strpos($key, 'drupal_add_html_head_link:shortcut icon:')
      && !empty($element['#attributes']['href'])
      && 'shortcut icon' === $element['#attributes']['rel']
    ) {
      // Make sure to use a file that actually exists!
      $favicon_path = drupal_get_path('module', 'MYMODULE') . '/img/favicon_32.png';
      $favicon_url = file_create_url($favicon_path);
      // If the favicon path came from a user-provided setting, we would also need drupal_strip_dangerous_protocols().
      $element['#attributes']['href'] = $favicon_url;
      $element['#attributes']['type'] = 'image/png';
      $head_elements[$key] = $element;
    }
  }
}

For the favicon file location I would suggest either the module folder of MYMODULE, or sites/default/favicon.ico. The goal is to have the file in version control, and NOT in the public files folder. We don't want it to be web-writable.
I assume most people will use *.ico instead of *.png, in this case the 'type' can keep its original value.
Answer: In Drupal 8 you must set favicon to true in YOUR_THEME.settings.yml (located at themes/YOUR_THEME/config/install) and put your favicon file at your theme root directory with the name "favicon.ico"
features:
   favicon:true

Change default favicon programmatically


SPSS K means cluster

Question: I'm working on car accident cases
1500 accident data and 33 variables
When I use k means cluster, in the Anova table i see to high F values like 5x10E5 with 0,00 significance.
And also there are some F values like -17x10E23 with same
significance value (-17x10e23).
Why F values are so high or negative?
Answer: The ANOVA table is to be interpreted with much caution in clustering (I often ignore it). Model assumptions for the F-test run in the ANOVA are violated in clustering, because the groups are not pre-specified but are rather chosen to minimize the sum of squares, which the F-test doesn't take into account. Therefore best advice is probably to ignore F- and p-values. By the way F-values cannot be negative by definition and chances are your negative one is the result of a rounding error (assuming that you did everything else right).

SPSS K means cluster


Number of asymmetric partial functions over a finite non-empty set

Question: Let $S$ be a finite non-empty set.
I recently used the presumed fact that the number of asymmetric partial functions over $S$ is $3^{|S|-1}(|S|-1)!$, after I became quite convinced of it, since it worked for $|S|\in\{1,2,3,4\}$ and would be rather unusual not to continue like that. Unfortunately, I could not come up with a proof since.
I unsuccessfully tried it by induction, and to derive it from the number $3^{\frac{|S|^2-|S|}{2}}$ of asymmetric relations, and the number $(|S|+1)^{|S|}$ of partial functions, over $S$, which are both easy to show. Also, I failed to find an existing proof on the internet.
Does anyone know or see how this could be done, and might have some hint?
Comment: I also noticed that it coincides with the number of antisymmetric functions over $S$, which did not help.

Clearly, if my conjecture is true, for a possible inductive proof one would have to show that when a distinct element is added to $S$, the number is multiplied by $3|S|$.
Comment: What is an "asymmetric partial function", please?
Comment: An asymmetric (that is, antisymmetric and irreflexive) relation which is a partial function.
Comment: So, if $f(a)=b$, then $f(b)$ is not $a$?
Comment: Yes, precisely.
Comment: If you include the empty function then my count for $n=4$ is $163$ whereas your formula gives $162$.
Comment: I see, and how did you come up with $163$?
Comment: Brute force exhaustive count.
Comment: You seem to be right, I just write a program to count it. With pen and paper, the cases just seemed too similar. I will check my program once more for correctness, but since we got the same result, it will probably be fine. But maybe this gives rise to another (correct) formula. Thanks anyway.
Answer: OEIS sequence A089466 seems to be what you're looking for. The first few values, starting with $n=0$, are
$$1,1,3,18,163,1950,28821$$
It says here that

$a(n)$ is the number of functions $f:\{1,2,\dots,n\}\to\{1,2,\dots,n\}$ such that the functional digraph contains no cycles of length $2$ — Geoffrey Critzer

which are the same as your "asymmetric partial functions" if you delete the cycles of length $1$.
Comment: Yes, or just "antisymmetric functions", as I wrote in another comment. But that's it, exactly, thanks!
Comment: Just to make that clear, since there seemed to have been some more confusion about this before, **anti**symmetry allows cycles of length $1$, but none of length $2$, whereas **a**symmetry allows neither of them. Thus, there is an obvious bijection between the set of **a**symmetric **partial** functions over $S$ and the set of **anti**symmetric functions over $S$. In any case, that sequence perfectly captures it.


AttributeError: 'tuple' object has no attribute 'run' when using LangChain LLMChain

Question: I'm building my first langchain app by following https://www.youtube.com/watch?v=MlK6SIjcjE8&t=189s
Here's my code:
<code>#bring in deps
import os
from apikey import apikey

import streamlit as st
from langchain import LLMChain, OpenAI, PromptTemplate

os.environ['OPENAI_API_KEY'] = apikey

#app framework
st.title('YouTube GPT Creator')
prompt = st.text_input('Plug in your prompt here')

# Prompt templates
title_template = PromptTemplate(
    input_variables = ["topic"],
    template = 'write me a youtube video title about {topic}'
)

#Llms
llm = OpenAI(model="text-davinci-003",
             temperature=0.9)
title_chain = LLMChain(llm=llm, prompt=title_template, verbose=True),

#show stuff to the screen if it has prompt
if prompt:
    # response = llm(prompt)
    response = title_chain.run(topic=prompt)
    st.write(response)
</code>
When I try to run it, I get this error:
<code>AttributeError: 'tuple' object has no attribute 'run'
File "D:\Coding\langchain\app.py", line 30, in <module>
    response = title_chain.run(topic=prompt)
               ^^^^^^^^^^^^^^^
</code>
I'm not familiar with LangChain yet and I wonder if anyone can lend a hand to a potentialy real simple problem. Thank you for your time
Comment: You have an extra comma in the end of this line `title_chain = LLMChain(llm=llm, prompt=title_template, verbose=True),` remove that comma and things should work.
Comment: I cannot help you but you should check what LLMChain(...) returns in its docs. Obviously it is a tuple, check its contents maybe one of it is what you need.
Answer: When we put a comma at the end it considers it as a tuple. So, Just remove the comma.
Answer: Thank you @EwyynTomato

You have an extra comma in the end of this line title_chain = LLMChain(llm=llm, prompt=title_template, verbose=True), remove that comma and things should work.

Silly me. Problem solved.


seating arrangements : How many seating arrangements there is such that between every two men there is an even number of women

Question: How many seating arrangements on a table there is such that between every two men there is an even number of women ( Note : there is an equal number of women and men such that the number of men is n and the number of women is also n and there is 2n seats around the table )
Answer: Write the number of women as $n=\sum_{i=1}^{n-1} b_{i}$ where $b_{i}$ is the number of women between man $i$ and man $i+1$. If all the $b_{i}$ are to be even, so must $n$. Therefore the answer is $0$ for odd $n$.
Supposing then that $n=2k$ is even, first imagine arranging the $n$ women in a circle. Label the women $1,2,...,n$. If a man sits with woman $1$ on his left and woman $2$ on his right, then every man must sit with an odd-numbered woman on his left. Once we choose "odd" or "even", there are $n/2$ permissible locations for each man to sit. Therefore we can place them in $(n/2)^{n}$ ways (this assumes that we can have strings of men sitting sitting next to one another i.e. some of the $b_{i}$ above may equal $0$).
There are $n!$ orderings for each the men and the women. Therefore the number of total arrangements is $(n!)^{2}(n/2)^{n}$
Answer: Obviously $2|n$ for any such arrangement to be possible. Let the seats "marked" for men to be $m_1,m_2,\cdots m_n$. Let the number of seats between $m_1,m_2=x_1; m_2,m_3=x_2;\cdots , m_n,m_1=x_n$. Note that $\sum_{i=1}^{n}x_i=n$. Also, all $x_i$s are even. Then using generating functions, $Z$=possible values of $x_i=$ Coeff. of $z^n$ in:
$$(z^0+z^2+\cdots+z^n)(z^0+z^2+\cdots+z^n)\cdots(z^0+z^2+\cdots+z^n)\ \ (n\ times) $$
$$=(1+z^2+z^4+\cdots upto\ \infty)^n$$
$$=(1-z^2)^{-n}$$
$$=\binom{3n/2-1}{n/2}$$
Note that I took it to infinity because the terms with power $>n$ won't affect the coeff. of $z^n$.
Since it will be a circular permutation, men can sit in $(n-1)!$ ways. After that, women will sit in $n!$ ways.
Answer, Total ways$=Z*(n-1)!*(n!)$
Comment: Ah, if the arrangement is meant to be a circle then you are correct.
Comment: Your first claim is false.  With $n=3$ the pattern $W^3MMM$ works, as does $MW^2MMW$, just to mention two.
Comment: In the question, it's written to be a table. Please read again
Comment: but how is it that for seating n men on a table with 2n chairs there is an equal number of ways for seating n men on a table with n chairs ? (n-1)! , isn't supposed to be more ways for seating them ?
Comment: The number of ways are NOT $(n-1)!$, they are $Z*(n-1)!$. As I've explained, Z is the number of ways of "selecting" those seats, and (n-1)! #ways of sitting on those, since it's a circular permutation
Answer: (I assume the table isn't round. A similar argument reduces the problem either way) Perhaps we're familiar with how many ways $n$ men and $m$ women could be arranged, a brief review if not: we need to pick $m$ spots from the $n+m$ seats for the women. This can be done in $\binom{n+m} m$ ways.
Now in this problem, we have a restriction, so we'll use a trick to convert this problem into the above: instead of placing each women separately, we place them in pairs. We have $n$ men and $w = n/2$ pairs of women (round down, we'll deal with the remainder in a moment). By the above, we then have $$\binom{n+w}{ n}$$ ways of arranging them.
Now what happens if $n$ is odd? In this case we must have a woman at the start or end of our table! To see why, note that if a man is at the beginning and end then every woman will be placed between 2 men, and hence should be able to be 'paired' together. In fact, we must have an odd number of women starting or ending the table. So when $n$ is odd, we have an extra choice of placing the last woman at the start or end of the table (if she goes in between some men, we break the rule), and so the total number of arrangments for $n$ odd is:
$$2 \binom{n+w} n$$
Once we've decided where to seat the men and women, multiply by $(n!)^2$ to get the number of seat assignments for the guests.


node express public folder 404 error

Question: I got a very similar problem with this post Learning Node - Express Public folder not working
I added to my server.js
app.use("public",express.static(__dirname + '/public'));

But when I do
http://localhost:8081/public/css/styles.css
http://localhost:8081/styles.css

Neither works. I got "Cannot GET /public/css/styles.css" and "Cannot GET /styles.css" respectively.
Here is my server.js
var express = require('express')
    , cors = require('cors')
    , app = express()
    , mongoose = require('mongoose')
    , models = require('./models')
    , bodyParser = require('body-parser')
    , controllers = require('./controllers')
    , port = 8081//process.env.PORT || 3000

// Config
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

app.set('views', __dirname + '/views')
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

app.use("public",express.static(__dirname + '/public'));
app.use('/', controllers);
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/db', function (err) {
    if (err) throw err;

    console.log("mongoose connected")
    var server = app.listen(port, function () {
        var host = server.address().address
        var port = server.address().port
        console.log("RESTful Web Services listening at http://%s:%s", host, port)
    })
})

Here is the index.js in the controller folder
var express = require('express')
  , router = express.Router()
  , users = require('./api/users.js')

router.use('/api/user', users);

router.get('/', function (req, res) {
    res.render('index.html')
})
//router.use(express.static('public'));
//router.use(express.static('views'));

router.get('/views/demo', function (req, res) {
    res.sendFile('/views/demo.html')
})

module.exports = router

Actually, if I run
http://localhost:8081/views/demo.hmtl

I would again get "Failed to load resource: the server responded with a status of 404 (Not Found)"
What did I miss?
Comment: Here's how I setup EJS and public static. `app.set("view engine", "ejs").use(express.static(__dirname+"/public"));`
Comment: Sterling, thanks to the reply. I used your code and the error persists. I updated my post to show index.js. Any other idea?
Answer: I added the following to the server.js and it worked.
app.use('/views', express.static(path.resolve(__dirname, 'views')));
app.use('/public', express.static(path.resolve(__dirname, 'public')));

node express public folder 404 error


How should I troubleshoot a problem with sending email?

Question: I have a Drupal 9.5 test server and a production server. The test server is working fine but the production server suddenly stopped sending emails (new accounts, custom form output, etc.). The settings should be the same on both but I double-checked the Drupal settings to be sure.
The Drupal logs don't say anything more than "error sending email". I tried the system maillog but there was nothing helpful there.
I also have the mimemail module installed. Neither mimemail nor system emails are going out.
Where should I look next to troubleshoot this? Is there a common solution to this problem?
Thanks!
Answer: If MailInterface::mail returns FALSE ("TRUE if the mail was successfully accepted for delivery, otherwise FALSE"), Error sending email (from %from to %to with reply-to %reply) is logged.
So, if this is PhpMail, which I think is the default MailInterface implementation, then PhpMail called PHP's mail function ("Returns true if the mail was successfully accepted for delivery, false otherwise"). That returned false.
Therefore, probably the email was not accepted for delivery by whatever way PHP is set up on that system to send mail. The answer to your question is: you should next look to why PHP's mail function is returning false.
Additionally some of the answers on https://stackoverflow.com/questions/3186725/how-can-i-get-the-error-message-for-the-mail-function/20203870#20203870 may be useful to you.
Comment: Thanks, @cilefen. Heading down that path, I see that php.ini uses sendmail. I tried sending an email from command line with sendmail and it worked fine. The maillog says the email was sent but Drupal says there was an error and I never received the email. Where can I look next?
Comment: https://stackoverflow.com/questions/3186725/how-can-i-get-the-error-message-for-the-mail-function
Comment: That would be useful if I were writing code but I'm not. I'm trying to figure out what changed in a system that functioned fine for months.
Comment: It seems you may have to write some code, in a test program that could help you drill-down to the interface between PHP and sendmail. I can see no other way. Anyway, as Drupal Answers isn't a forum I'll leave my answer here, which explains the next troubleshooting step.


Sub-bass on DAW?

Question: I don't know much about how sub-bass is generated but is it possible to program in mainstream tools such as Ableton or Logic Pro? I was wondering if can it be represented as a Midi track or if elements such as the 'wobble' require a dedicated tool.
I am specifically thinking about sub-bass as used in dub-step and modern electronic music.
Answer:
is it possible to program in mainstream tools such as Ableton or Logic
Pro?

Yes. You could technically use most vst synths to create a sub bass since it is only a bass which sounds in the very low frequencies. Unwanted high frequencies could be cut off by a filter. There are also dedicated vst's for generating sub bass. Here are some examples vst's you can use:

Trillian
Xsub
X-Eight Lite

I have found this tutorial on how to make a sub bass in ableton:

Make a separate MIDI track
Drag your favorite synth or synth VST on that track.
Keep only one oscillator
Set the wave shape to 'sine'
Draw a MIDI pattern in the very low octaves on the piano roll (below C3)

I was wondering if can it be represented as a Midi track or if
elements such as the 'wobble' require a dedicated tool.

Representing a sub bass as midi would just be a midi note in a very low octave.
I am not sure if I really understand what exactly you mean by "wobble". But if you mean the wobbling effect which is often used in dub step music, Here is a question on how to create these "wobble" effects. Those could also be used on a very low sounding sub bass.
Comment: Sorry yes I should have specified dub-step, I'm not sure on the terminology.
Comment: @Mr.Boy Then will the second link in my answere be helpfull for you
Comment: Yes it is - thanks for the link. I am not looking to get into the nuts and bolts of creating my own waveforms so I was hoping you can find pre-made sounds... looks like you covered this too.
Answer: Midi note number 0 is C_{-1}, corresponding to a frequency of 8.175 Hz.  Is that low enough for your purposes?  Of course, you'll need a Midi synth that is willing to produce signals at those frequencies: sampled voices will not exist at those pitches and will have to be synthesised or interpolated.
Comment: Midi notes place no restriction on the actual pitch of the note.  Of course it's convenient to have your synthesizer to produce A4 when you press A4, but many synths can be programmed to transpose or scale pitches freely.
Answer: I do not use Logic/Ableton but that might prove useful or not.
Midi are just information that need to be transformed into sound by a synthesizer.
Most (every?) virtual or real synth is fitted with one or several Low Frequency Oscillators (LFO). These are oscillators which are specially made to produce very low oscillations (usually from 0.1Hz to 50Hz approximately).
Frequency and amplitude of these oscillators, and on what they are acting (on the gain for instance, or the filter) can usually be controlled by MIDI Control Change (MIDI CC), even thought the number of the CC controlling these parameters is not standardized, so you can control them with a MIDI track with control changes automations.
So not complete answer as this depends on the synth you are using to translate you MIDI track to sound, but LFOs should be the ones to look at!

Sub-bass on DAW?


Firefox styling discrepancy with nav bar

Question: I'm having a CSS styling problem between Chrome/Safari and Firefox. In both Chrome and Safari, the hidden drop down is correctly positioned, but in Firefox, the subnav menu is off by a few pixels. After looking into the issue with the inspection tools of both browsers, it seems that Firefox is making the #main_nav_bar ul 10px wider than Chrome. The issue I'm having is that I'm not sure how to change this while not messing up the way the nav bar looks.
The link is http://www.tamidgroup.org.
Any suggestions on a fix are much appreciated.
Comment: You are in quirks mode and modern web pages should never be in quirks mode. Is there a reason for that? (Not using a doctype)
Answer: Definitely add a doctype in there. You could also target those browsers with a media query.
Example for chrome and safari
@media screen and (-webkit-min-device-pixel-ratio:0){
   //add your browser specific code here
}

That way you can target specific issues you see from one browser to the other.


Webbed gloves for spearfishing or snorkling will give me more speed?

Question: I like to have more speed when swimming as I feel this is safer due to being able to escape dangerous situations. Would webbed gloves provide this in a spear fishing or snorkeling environment?
Comment: I'm voting to close this question as off-topic because this is not a question about sports; it is on-topic at The Great Outdoors in the case of aquatic spearfishing, and Physical Fitness in the general case of equipment or technique not related to the competitive aspect of swimming.
Answer: Generally speaking, no.  Spear fishing and snorkeling generally employ swim fins for propulsion because they occur mostly either underwater or when holding something in your hands.  At slow speeds, the strength in your legs with swim fins far exceeds what you can generate with your arms, so the vast majority of the time you use your legs only for propulsion while snorkeling and/or spear fishing.
Even more importantly, your question seems to imply that you could escape some danger by outracing it.  In any aquatic situation, this is extremely unlikely.  Humans are very poorly adapted to functioning in the water and any serious threat won't be outrun, even by an Olympic swimmer.  You would quickly exhaust yourself with your gloves and become helpless in very short order.
Comment: great thx!!!!!!!!!!!!!


Granger Causality test pre-conditions

Question: I am trying to analyse the causation between individual stock returns and index returns. I have taken the log return values of both stock and index values. Unit root test suggest that the values are stationary; but Johansen cointegration test resulted with two cointegrating equations in both Trace and Eigenvalues.
Can I apply Granger causality test?
Answer: If you have two time series, then the univariate unit-root test results coincide nicely with the cointegration test results. Both indicate that the series are stationary. Moreoever, this is as expected; financial returns are normally considered not to have unit roots.
However, you could think about cointegration between the stock price and the level of the stock index. They will both be integrated of order one (as they are cumulative sums of processes that do not contain unit roots, as per your current analysis), so there is at least the theoretical potential for cointegration. Whether cointegration would make sense in practice is another question and depends on the application. Here your subject-matter expertise will come in handy.
In any case, once you decide on presence/absence of cointegration between the stock price and the level of the stock index, you can proceed to Granger causality testing.

In case of cointegration you would use the Toda-Yamamoto procedure described clearly in Dave Giles blog post "Testing for Granger Causality".
In case of no cointegration, you may run a simple vector autoregression and test for Granger causality in the regular way.
Comment: I have taken the stock and index price data and found the order of integration as 1 (q) , there after i have tried to find the number of lags . If i have taken maximum number of lags to check  as 5 the AIC lag selection criterion has shown me best as lag 1 (p) , but i cannot take lag 1 as p>q . Only i have got different lag result if i set my maximum number of lags to check as 20. Then i got the AIC best lag to select as 19 which is greater than order of intergration. I am really not sure if such high numbered lag is valid to create a model. Please kindly provide me your insights
Comment: *Lag order* and *order of integration* are not related. One does not depend on the other.
Comment: Thanks for the clarification! should i take the optimal lag length for my model as 1 or 19 as mentioned to you in the last comment?
Comment: Do you mean the VAR model that will be used for Granger causality testing?
Comment: yes you are correct
Comment: Well, 19 looks quite a lot. Is your sample very large? If not, perhaps rely on BIC instead of AIC; BIC will likely suggest a more parsimonious model.
Comment: my sample is monthly data from Apr 83 till Dec 2015. In my case both AIC and BIC is suggesting for lag 1.
Comment: I guess, 1 lag sounds more reasonable than 12 lags for monthly data with roughly 400 observations.

Granger Causality test pre-conditions


Laravel != operator in where not working

Question: This query is returning null when an object is expected.
$vow = DB::table('media_featured')->where('is_video_of_the_week', 1)->
where('video_of_week_expired', '!=', 1)->first();

CREATE TABLE `media_featured` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`media_id` int(10) unsigned DEFAULT NULL,
`is_video_of_the_week` tinyint(1) DEFAULT NULL,
`is_featured` tinyint(1) DEFAULT NULL,
`video_of_week_expired` tinyint(1) DEFAULT NULL,
`featured_expired` tinyint(1) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `media_featured_media_id_foreign` (`media_id`),
CONSTRAINT `media_featured_media_id_foreign` FOREIGN KEY (`media_id`) REFERENCES `media`        (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

A record might have is_video_of_the_week = 1 and video_of_week_expired = NULL but the above query returns null.
Any ideas?
Answer: NULL values are not equal or not equal to anything else.
So column != NULL is always falsy as well as column = NULL
To check if a column contains NULL value you need to use IS NULL operator.
In case of laravel db query generator you could use
->whereNull('video_of_week_expired')

method.
PS: if video_of_week_expired is assumed to be a flag-alike column, you better make it NOT NULL and use 0/1 values, instead of NULL/1
Comment: The above did work for me before I posted to SO. I'm planning on flagging the column as is_expired = 1 once it's no longer featured, that's why I wanted to compare against not =1 as opposed to whereNull, but I guess I will just have to be careful in my code execution?
Answer: If the value for video_of_week_expired is NULL or 1 then you can use

->whereNull()

else
if the value is like a flag 0 or 1 then you can try using

->where('video_of_week_expired', '<>', 1)

Here <> is a 'not equal to' operator.
Answer: Based on the documentation and the source-code.
You should use whereNull:
$vow = DB::table('media_featured')
          ->where('is_video_of_the_week', 1)
          ->whereNull('video_of_week_expired')
          ->first();


volume of solid of revolution. Can someone please check my work?

Question: Original question: Find the volume of the solid formed by revolving the region bounded by the graphs of $y=\ln x$ and $x-2y=1$ about the x-axis.
Here's what I did:

Get $x-2y=1$ in terms of y, therefore $y=\frac{1}{2}x-\frac{1}{2}$
Find intersection points for the bounds, $(1,0),(3.51286,1.25643)$
(Not sure how to set up integral on here, sorry) I used the washer method and came up with $\displaystyle \pi \cdot \int_1^{3.51286}\left((\ln x)^2 - (\frac{1}{2}x - \frac{1}{2})^2\right) dx$
ended up with $7.34579$

Did I do this correctly?
Answer: The setup is correct.
I did the numerical integral on Wolfram Alpha (see here), and got $\approx 0.421573 \pi \approx 1.3244111$ instead.
Comment: ok thank you! I plugged it back into my calculator a second time and got 1.32 as well :) Thanks for your help


Criação e implementação de classe Exception

Question: Estou tendo problemas na implementação de uma classe Exception. A explicação do programa é:

As strings do vetor devem estar inicializadas com "", e não com null.
A capacidade do vetor deve poder ser alterada através de um método.
A classe deve ter como atributos (variáveis do objeto) um String[] e um int.
Crie os métodos 'String at( int i )' e 'void put( int i, String st )', que respectivamente retornam a String na posição i e mudam o valor da String na posição i.
Cada acesso deve ser verificado e se houver um erro de limites, a exceção ArrayIndexOutOfBounds deve ser lançada.
Crie um método 'int find( String st )' que retorna a posição de St no vetor, ou -1 se ele não está lá.
Se um vetor for redimensionado para um tamanho inferior ao atual, deve-se primeiro eliminar as Strings vazias ("") e verificar se o novo tamanho comporta as Strings restantes. Se não comportar, deve-se lançar uma exceção VectorSizeException (crie essa classe).

A tarefa explicada tá aí, então só preciso saber como fazer pra implementar essa exceção.
Meu código:
A classe Teste (não pode ser alterada):
package Lab4;

public class Teste {

    public static void main( String argc[] ) {
      StringVector v = new StringVector( 10 );

      v.put( 1, "Janeiro ");
      v.put( 2, "fevereiro" );

      System.out.println( v.at( 3 ) );

      System.out.println( v.at( 13 ) ); // Exceção

      System.out.println( v.at(1));

      v.newSize( 2 ); // OK

      v.newSize( 1 ); // Exceção
    }
}

A classe StringVector (eu implementei, pode ser alterada):
package Lab4;

public class StringVector {
    String[] vetor;
    int inteiro;

    public StringVector (int vectorCapacity) {
        vetor = new String[vectorCapacity];
        for(int i = 0 ; i < vetor.length ; i++) {
            vetor[i] = "";
        }
    }

    public void newSize (int newSize) {

        String[] novo = new String[ newSize ];

        if (newSize < vetor.length) {
            while(find("") != -1) {
                vetor[find("")] = null;
            }

            /*print pra testar o find e a substituição de valores
            int i = 0;
            while (i < vetor.length) {
            System.out.println(vetor[i]);
            i++;
            }
            */

            completeVector(novo);

/*          try {
                completeVector(novo);
            } catch (ArrayIndexOutOfBoundsException error) {
                System.out.println("erro: "+ error);
            }*/
        }
        else {
            completeVector(novo);
        }
    }

    public String at(int inteiro) {
        try {
            return vetor[inteiro];
        } catch (ArrayIndexOutOfBoundsException error) {
            return "erro: " + error;
        }
    }

    public void put(int inteiro, String st) {
        try {
            vetor[inteiro] = st;
        } catch (ArrayIndexOutOfBoundsException error) {
            System.out.println("erro: " + error);
        }
    }

    public int find(String st) {
        for(int i = 0 ; i < vetor.length ; i++) {
            if(st.equals(vetor[i])) return i;
        }
        return -1;
    }

    public void completeVector (String[] novo) {
        int position = 0;
        for(int i = 0; i < vetor.length ; i++) {
            if(vetor[i] != null ) {
                novo[position] = vetor[i];
                position++;
                /*if(position > newSize) {
                    throw new VectorSizeException();
                }*/
            }
        }
    }
}

E a minha tentativa de classe Exception:
package Lab4;

public class VectorSizeException extends Exception {

    private static final long serialVersionUID = 1L;

    public VectorSizeException () {
        System.out.println("erro: VectorSizeException");
    }
}

Comment: Não consegue fazer o que, especificamente?
Comment: como assim? Onde deve ficar a exceção?
Comment: O que você não sabe fazer? Lançar a exceção?
Comment: Ah, sim. Preciso implementar a classe Exception com aquele nome que tá ali.

Se um vetor for redimensionado para um tamanho inferior ao atual, deve-se primeiro eliminar as Strings vazias ("") e verificar se o novo tamanho comporta as Strings restantes. Se não comportar, deve-se lançar uma exceção VectorSizeException (crie essa classe).
Comment: Exatamente, eu não sei se a minha classe de exceção ta criada corretamente, e não sei como lançar
Comment: Tou fazendo uma explicação pra você =D
Comment: valeu, mt obrigado :D
Answer: Bem, primeiramente (eu creio que) a sua implementação da classe VectorSizeException esteja errada. Sintaticamente ela está perfeita, mas semanticamente não faz muito sentido. Exceções devem ser lançadas, neste caso, você apenas mostra na tela o erro. Obviamente para o seu uso, que é simples, isso pode parecer extremamente útil, já em outros casos eu posso te garantir que a utilidade disto é ínfima, senão inexistente.
Então, a classe VectorSizeException deveria ser assim
public class VectorSizeException extends Exception {

    private static final long serialVersionUID = 1L;

    public VectorSizeException (String message) {
        super(message);
    }
}

Perceba que o construtor pede uma string como parâmetro e chama o construtor da superclasse passando este argumento recebido como parâmetro. Na documentação da classe Exception você pode ver a definição deste construtor. Também é possível usar o construtor sem nenhum parâmetro, neste caso eu mantive o parâmetro para ilustrar que uma exception pode receber uma descrição quando for lançada.
Agora vamos aos pontos do exercício:
O quinto ponto, diz o seguinte

Cada acesso deve ser verificado e se houver um erro de limites, a exceção ArrayIndexOutOfBounds deve ser lançada.

Os métodos que fazem um acesso ao vetor são at e put. Nos dois métodos você comete o mesmo erro, está capturando uma exceção, ao invés lançá-la, como é pedido no exercício. Vejamos o método at:
public String at(int inteiro) {
    try {
        return vetor[inteiro];
    } catch (ArrayIndexOutOfBoundsException error) {
        return "erro: " + error;
    }
}

O bloco catch captura a exceção que pode ser lançada se houver uma tentativa de acessar um indíce inexistente do array chamado vetor. O exercício pede para que seja lançada uma exceção do tipo ArrayIndexOutOfBoundsException quando ocorrer um acesso indevido.
Logicamente há duas maneiras de se fazer isso: a primeira é deixar correr a exceção normalmente ao tentar acessar uma posição inválida do array vetor. Por exemplo, uma tentativa de acessar o índice -1, vai causar o lançamento de uma ArrayIndexOutOfBoundsException. Ou seja, só é necessário fazer uma tentativa de acesso indevido. Ilustrando, o método ficaria
public String at(int inteiro) {
    return vetor[inteiro];
}

Você também pode explicitar isso (possivelmente é isso que seu professor quer), verificando a posição que se deseja acessar e lançando a exceção manualmente
public String at(int inteiro) {
    if(inteiro < 0 || inteiro => vetor.length) // qualquer coisa fora de 0 e vetor.length -1 é indevido
        throw new ArrayIndexOutOfBoundsException();

    return vetor[inteiro];
}

Isso vale também para o método put.
Agora vamos ao último ponto

Se um vetor for redimensionado para um tamanho inferior ao atual, deve-se primeiro eliminar as Strings vazias ("") e verificar se o novo tamanho comporta as Strings restantes. Se não comportar, deve-se lançar uma exceção VectorSizeException (crie essa classe).

A classe já está criada, eu vou supor que a implementação dos métodos newSize e completeVetor estejam corretas e partir deste ponto. Perceba que o exercício diz que é necessário lançar a exceção.
Vou considerar que a verificação será feita no método newSize.
Note que a assinatura do método contém o a instrução throws, isso acontece porque VectorSizeException é uma checked-exception (sempre que herdar de Exception será checked), então é necessário adicionar isso na assinatura do método. Por via disto, o Java te obriga a tratar esta exceção no momento que for chamar este método ou então adicionar no método esta mesma declaração throws na assinatura do método que chamar newSize (no seu caso, quem faz isto é o método main).
public void newSize (String[] novo) throws VectorSizeException {
    // Verificar se o novo tamanho é válido
    if(invalido){ // Se o novo tamanho for inválido
        throw new ArrayIndexOutOfBoundsException("Alguma mensagem");
    }
}

Tem algumas coisas que eu falei na resposta que talvez não fiquem bem claras pra você, então vou deixar aqui algumas referências sobre exceções

Qual é a diferença entre exceções checadas (checked) e não checadas (unchecked)?
O que são Exceptions?
Comment: Na verdade ficou tudo absurdamente claro! Muito obrigado pela atenção e pelo comentário! Grande abraço


What is this instrument called and can you give me suggestions which one to buy if i am a beginner?

Question: I really want to learn this instrument, but I dont know how it is called those are two youtube videos that people are using the instrument -

and this one

On the second video I know he is using a lot of instruments, but the one I am looking for is the one that can repeat your sounds.
And as I am a complete beginner what models and brands do you suggest me to buy and practice? [This part of the question is off-topic]
Comment: @topomorto I see. My read of that meta is that "what type of instrument is this?" is on-topic" and "what exact example of this type of instrument is this?" is not on topic. So if the answer "looper and/or sampler" is acceptable for this asker, then the identification part of this question is on topic, IMHO. If the asker is looking for the exact make and model of something, then that seems to be off topic.
Comment: There seemed at one point to be consensus that some instrument identification questions should be on topic - https://music.meta.stackexchange.com/questions/2443/why-are-instrument-identification-questions-off-topic. Has there been any development since then?
Comment: @ToddWilcox that seems a reasonable conclusion - hopefully in this case 'looper/looping' is all the OP needs to start the research process!
Comment: @CarlWitthoft, yes, but in my case I am just interested of knowing what is the name of the instrument :)
Comment: The problem is that there's a ton of electronics there, and knowing what they are won't necessarily lead to knowing how to reproduce the sounds.
Answer: As per Todd's comment, both of these performers are doing 'live looping', using equipment that you could broadly describe as 'loopers'.
Reggie Watts is using the Electro-Harmonix 2880 Super Multi-track Looper.
I'm not sure what beardyman is using in the video, but there's an article here about the development of his setup.
It's very hard to recommend specific models, because every performer might need something different from a looper. I've seen some performers create intricate masterpieces using simple loopers, and then there are those performers (like beardyman) who can't find anything off-the-shelf that works for them. I can only recommend doing some reading around about current models of looper, and try to get hold of one for a price that allows you to flip it for something else for not too much of a loss if it doesn't work out (i.e. possibly second hand!).
Comment: It might help to add that there are many devices that are called "samplers" or "performance samplers" that can do looping and much more also.
Comment: The most "famous" one (in the sense of "number of people that have heard music made using it"), is probably Ed Sheeran's *Chewie Monsta II*, although that is a purpose-built one-of-a-kind (technically two-of-a-kind for redundancy) piece of kit made specifically for him (and with the design heavily influenced by him).
Answer: If you indeed want a 'buffet (of sound) in a box' then look at this ... OP-1.
https://www.teenageengineering.com/products/op-1
Is it for a beginner?

It's incredible what folks are doing with this.
https://www.youtube.com/channel/UChnxLLvzviaR5NeKOevB8iQ


Google maps crashes in every screen that containing map ('int android.graphics.Bitmap.getWidth()' on a null object reference)

Question: Suddenly Google maps crashes in every screen that containing map which cause app crash.
AndroidRuntime: FATAL EXCEPTION: GLThread 56854
Process: com.interface_fze.dawana.pharmacy, PID: 3151
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
    at com.google.maps.api.android.lib6.gmm6.vector.gl.aj.b(:com.google.android.gms.dynamite_mapsdynamite@email@example.com (150400-0):11)
    at com.google.maps.api.android.lib6.gmm6.vector.gl.aj.<init>(:com.google.android.gms.dynamite_mapsdynamite@firstname.lastname@example.com (150400-0):3)
    at com.google.maps.api.android.lib6.gmm6.vector.gl.g.<init>(:com.google.android.gms.dynamite_mapsdynamite@email@example.com (150400-0):18)
    at com.google.maps.api.android.lib6.gmm6.vector.bs.d(:com.google.android.gms.dynamite_mapsdynamite@email@example.com (150400-0):14)
    at com.google.maps.api.android.lib6.gmm6.vector.av.run(:com.google.android.gms.dynamite_mapsdynamite@firstname.lastname@example.com (150400-0):44)

Comment: Yes, it is mentioned in the below answer.
Comment: Do you find any solution ?
Answer: I fixed issue by adding implementation 'com.google.maps.android:android-maps-utils:2.3.0' in app level build.gradle
Source
Answer: Removing app/clearing cache fixed issue for me.
Comment: This actually fixes my issue, I am wondering if this issue will show up in production.