Calling Java method from HTML link

Question: I'm currently building a Twitter client in Java using the Twitter4J API. To create a Twitter "timeline", I am currently pulling data from Twitter such as profile images, tweets and usernames, then displaying them in a JTextPane, formatted using HTML. Code example below:
StringBuilder out = new StringBuilder();

       try {
           List<Status> statuses = HandleEvents.instance().twitter.getHomeTimeline();

           out.append("");

           for (Status status : statuses)
           {
               out.append("").append(status.getUser().getName())
                       .append(": ").append(status.getText())
                       .append("

");
           }

           out.append("");

           tweetsTextPane.setText(out.toString());

This displays a timeline of 20 tweets, separated by two line breaks. Under each tweet, I would like to place a simple  hyperlink, called "Retweet", which calls one of my Java methods - HandleEvents.instance().twitter.retweetStatus(status.getId())
How would I got about doing this? Can the call be made directly between the  tags, or do I have to make the call using JavaScript?
Any help would be appreciated. Many thanks.
Comment: Kind of [bad timing](http://arstechnica.com/software/news/2011/03/twitter-tells-third-party-devs-to-stop-making-twitter-client-apps.ars) to be building a Twitter client
Comment: You need to explain the context in which the code above gets executed.  Is it client side in an applet, ... or called from Javascript?  Is it server-side?
Comment: @Stephen C - Apologies. This is a JButton action performed method in a client-side GUI. A "refresh" button is clicked, then this code is executed.

@Cameron - Agreed. This is a college project though, so I'll still get the credit :)
Comment: @Stephen C - Forgot to tag you in this comment earlier: No it's an application. The HTML is used only within the JTextPane for formatting.
Answer: You don't really need to have a hyperlink do you? Since it's a Swing app you could just add a JLabel that only looks like a hyperlink (but if you put in a little effort, it could behave like one as well). Add a listener for mouse clicks on that JLabel and you've can hook your current handler there.
On the other hand, if you do want actual HTML links, what you can do is implement your own HyperlinkListener.
Here are a couple of examples:

http://www.java2s.com/Tutorial/Java/0240__Swing/HyperlinkListenerExample.htm
http://www.java2s.com/Code/Java/Event/DemonstratingtheHyperlinkListener.htm
http://www.devx.com/tips/Tip/12997
Comment: Ah, I had never thought about making clickable JLabels for each tweet. I just thought HTML hyperlinks would be the way to go. Many thanks for all the contributions. I've been refreshing the page and following all your suggestions!
Comment: I really should stop making so many changes - but I either spot a mistake or something new strikes right *after* I hit save! :)
Comment: Not at all! If you can spot your own mistakes or notice places where you can write something better, it means you're a good programmer! I'm going to try and throw in an array of 20 JLabels now alongside each tweet. Will worry about the event listening after that. Should be no bother!
Comment: Silly question (and one that I may figure out before you can answer), how does one add a JLabel to a JTextPane?

edit - never mind, there was a bug in my code. I was correct all along!

Calling Java method from HTML link


Monte Carlo simulations in Python using quasi random standard normal numbers using sobol sequences gives erroneous values

Question: I'm trying to perform Monte Carlo Simulations using quasi-random standard normal numbers. I understand that we can use Sobol sequences to generate uniform numbers, and then use probability integral transform to convert them to standard normal numbers. My code gives unrealistic values of the simulated asset path:
import sobol_seq
import numpy as np
from scipy.stats import norm

def i4_sobol_generate_std_normal(dim_num, n, skip=1):
    """
    Generates multivariate standard normal quasi-random variables.
    Parameters:
      Input, integer dim_num, the spatial dimension.
      Input, integer n, the number of points to generate.
      Input, integer SKIP, the number of initial points to skip.
      Output, real np array of shape (n, dim_num).
    """

    sobols = sobol_seq.i4_sobol_generate(dim_num, n, skip)

    normals = norm.ppf(sobols)

    return normals

def GBM(Ttm, TradingDaysInAYear, NoOfPaths, UnderlyingPrice, RiskFreeRate, Volatility):
    dt = float(Ttm) / TradingDaysInAYear
    paths = np.zeros((TradingDaysInAYear + 1, NoOfPaths), np.float64)
    paths[0] = UnderlyingPrice
    for t in range(1, TradingDaysInAYear + 1):
        rand = i4_sobol_generate_std_normal(1, NoOfPaths)
        lRand = []
        for i in range(len(rand)):
            a = rand[i][0]
            lRand.append(a)
        rand = np.array(lRand)

        paths[t] = paths[t - 1] * np.exp((RiskFreeRate - 0.5 * Volatility ** 2) * dt + Volatility * np.sqrt(dt) * rand)
    return paths

GBM(1, 252, 8, 100., 0.05, 0.5)

array([[1.00000000e+02, 1.00000000e+02, 1.00000000e+02, ...,
        1.00000000e+02, 1.00000000e+02, 1.00000000e+02],
       [9.99702425e+01, 1.02116774e+02, 9.78688323e+01, ...,
        1.00978615e+02, 9.64128959e+01, 9.72154915e+01],
       [9.99404939e+01, 1.04278354e+02, 9.57830834e+01, ...,
        1.01966807e+02, 9.29544649e+01, 9.45085180e+01],
       ...,
       [9.28295879e+01, 1.88049044e+04, 4.58249200e-01, ...,
        1.14117599e+03, 1.08089096e-02, 8.58754653e-02],
       [9.28019642e+01, 1.92029616e+04, 4.48483141e-01, ...,
        1.15234371e+03, 1.04211828e-02, 8.34842557e-02],
       [9.27743486e+01, 1.96094448e+04, 4.38925214e-01, ...,
        1.16362072e+03, 1.00473641e-02, 8.11596295e-02]])

Values like 8.11596295e-02 should not be generated, hence I think there is something wrong in the code. If I use standard normal draws from the numpy library rand = np.random.standard_normal(NoOfPaths) then the price matches with the Black Scholes price. Hence I think the problem is with the random number generator. The value 8.11596295e-02 refers to a price in a path, and it's very unlikely that the price would come down from 100 (initial price) to 8.11596295e-02.
References: 1, 2, 3.
Comment: Is `sobol_seq` a library? Because I was looking for an implementation of the algorithm inside some Python library and `SciPy` has it: `scipy.optimize._shgo_lib import sobol_seq`
Comment: @David: yes, the reference is here : https://github.com/naught101/sobol_seq.
Answer: It appears there is a bug in sobol_seq. Anaconda, python 3.7, 64bit, Windows 10 x64, installed sobol_seq via pip
pip install sobol_seq

# Name                    Version                   Build  Channel
sobol-seq                 0.1.2                    pypi_0    pypi

Simple code
print(sobol_seq.i4_sobol_generate(1, 1, 0))
print(sobol_seq.i4_sobol_generate(1, 1, 1))
print(sobol_seq.i4_sobol_generate(1, 1, 2))
print(sobol_seq.i4_sobol_generate(1, 1, 3))

produced output
[[0.5]]
[[0.5]]
[[0.5]]
[[0.5]]

Code from http://people.sc.fsu.edu/~jburkardt/py_src/sobol/sobol.html, sobol_lib.py behaves reasonable (well, except first point).
Well, enclosed code looks like it might work, keeping seed together with sampled array. Slow, though...
import sobol_seq
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

def i4_sobol_generate_std_normal(dim_num, seed, size=None):
    """
    Generates multivariate standard normal quasi-random variables.
    Parameters:
      Input, integer dim_num, the spatial dimension.
      Input, integer n, the number of points to generate.
      Input, integer seed, initial seed
      Output, real np array of shape (n, dim_num).
    """

    if size is None:
        q, seed = sobol_seq.i4_sobol(dim_num, seed)
        normals = norm.ppf(q)
        return (normals, seed)

    if isinstance(size, int) or isinstance(size, np.int32) or isinstance(size, np.int64) or isinstance(size, np.int16):
        rc = np.empty((dim_num, size))

        for k in range(size):
            q, seed = sobol_seq.i4_sobol(dim_num, seed)
            rc[:,k] = norm.ppf(q)

        return (rc, seed)
    else:
        raise ValueError("Size type is not recognized")

    return None

seed = 1
x, seed = i4_sobol_generate_std_normal(1, seed)
print(x)

x, seed = i4_sobol_generate_std_normal(1, seed)
print(x)

seed = 1
x, seed = i4_sobol_generate_std_normal(1, seed, size=10)
print(x)

x, seed = i4_sobol_generate_std_normal(1, seed, size=1000)
print(x)

hist, bins = np.histogram(x, bins=20, range=(-2.5, 2.5), density=True)
plt.bar(bins[:-1], hist, width = 0.22, align='edge')

plt.show()

Here is the picture
Comment: Thanks for this, the problem with the random numbers seems to be solved. However, I am still getting erroneous values for the paths, i shall look into the GBM function in more detail.
Comment: @SPaul Good. If you are happy with the answer, please accept it and ask another one wrt GBM - few narrow, focused questions is quite a lot better that one wide question
Answer: For future reference, we added Sobol' sequence in SciPy 1.7: scipy.stats.qmc.Sobol


How to correctly access entity elements in a twig template

Question: I have an array of entities that i would like to render in a list.
$ids = \Drupal::entityQuery('chemical')
  ->condition('tid', $tid)
  ->execute();
$controller = \Drupal::entityManager()->getStorage('chemical');
$entities = $controller->loadMultiple($ids);

$chemicals = [];
foreach ($entities as $entity){
  $chemicals[] = ['id' => $entity->id(), 'label' => $entity->label()];
}

$output[] = [
  '#theme' => 'chemical_taxonomy',
  '#chemicals' => $chemicals,
];
return $output;

The twig template then creates the unordered list of URLs using the array of {{ chemicals.label }} and {{ chemicals.id }}. However, I should be able to just pass $entities to the template instead of extracting the id and label and building a new array, shouldn't I?
If I replace '#chemicals' => $chemicals with '#chemicals' => $entities I receive an error:
Uncaught PHP Exception Exception: "Object of type Drupal\\Core\\Field\\FieldItemList cannot be printed." at /var/www/Drupal_Sites/console/core/lib/Drupal/Core/Template/TwigExtension.php line 443,

Comment: The `id` property of taxonomy terms is `tid` and the `label` property is `name`. And to access their values you will need to use either `{{ entity.tid.value }}` or `{( entity.id() }}`. I'm writing this from a phone so syntax errors are possible.
Comment: You can, but you are probably trying to print the field item instead of the value. Can you add the twig that you tried to apply onto the entities array?
Comment: I kept it the same. The twig documentation says that foo.id should access 'methods or properties of Objects'. I assume this means foo->id or foo->id().
Comment: This is not a taxonomy term, but a custom entity which contains an entity_reference to a taxonomy term. I am trying to print the label and id of the custom entity, not the taxonomy term. However, this might still be the right answer. I'll have to try it out tomorrow.
Comment: The tid confused me a bit.
Comment: @Eyal - the parens were the answer. if you type this in the answers area, I'll accept it.
Answer: As the exception explains, you tried to print an object that is not renderable and cannot be converted to a string. In this case it was Drupal\Core\Field\FieldItemList which is the object returned by drupal entities when you ask for a field ({{ entity.id }} / {{ entity.label }}).
To get the actual value you need to call to methods of your entity (the actual value of the fields is protected from outside access).
The long way:
{{ entity.get('id').get(0).get('value').getValue() }}

The above is the actual path you need to take to get from the entity object to the value of the id field.
However drupal supplies shortcuts through what is known as magic properties.
The short way
{{ entity.id.value }}

Comment: In addition to "the long way", you can also use:
{{ node.field_from_node.field_from_inner_entity[0].get('value').getValue() }}

If you are trying to obtain one url link:
{{ node.field_from_node.field_from_inner_entity[0].get('uri').getValue() }}
Answer: To get the full objects in your twig file, you could have done this:
$ids = \Drupal::entityQuery('chemical')
  ->condition('tid', $tid)
  ->execute();
$controller = \Drupal::entityManager()->getStorage('chemical');
$entities = $controller->loadMultiple($ids);

$output[] = [
  '#theme' => 'chemical_taxonomy',
  '#chemicals' => $entities,
];
return $output;

Then, in your twig file just do:

{% for chemical in chemicals %}

{{ chemical.label() }}

{% endfor %}

Answer: You have to implement function template_preprocess_chemical_taxonomy(&$variables) where you prepare you variables for your template.
As an example have a look in core regarding function template_preprocess_item_list(&$variables) for item-list.html.twig.
Answer: You have to render the entity before passing it to twig.
$render_controller = \Drupal::entityManager()->getViewBuilder('chemical');

foreach ($entities as $entity){
  $chemicals[] = $render_controller->view($entity);
}

Of course, this means creating a custom viewbuilder for your entity, if you haven't already, which may be more work, but would a nicer solution than creating a custom array each time you want to render your entity.
You could copy another view builder, such as core/modules/node/src/NodeViewBuilder.php
move it into your project and alter it to work with your custom entity.
Comment: To render something before passing it into a view (template) should not be allowed anymore since almost 10 years. Thats very very bad practice. https://de.wikipedia.org/wiki/Model_View_Controller

And it causes an unlimited amount of problems inside of Drupalprojects.


The idea of the transverse to a vector field

Question: I have a quick question. I am independently reading a book on three dimensional geometry and topology. One line has been stumping me. Here is the following paragraph I do not understand:
"Let $X$ be a vector field on a surface with an isolated zero at a point $z$. Construct a small polygon containing $z$ in its interior and having edges transverse to $X$."
What does it means to have edges transverse of $X$ in this case?
Answer: In this case transversality just means that the vector field is not tangent to any edge.


How to use EditorJS in NuxtJS project?

Question: I'm trying to use EditorJs in NuxtJs project.
Medium has an article on https://medium.com/code4mk-org/editorjs-vue-a78110c3fff8.
It works, but if I reload the page I get a "window not defined" error because the code is trying to run on the server side.
There is a package called https://github.com/ChangJoo-Park/vue-editor-js that works for NuxtJs, but it has an issue with image upload.
//I try change

import EditorJS from '@editorjs/editorjs'

//to
const EditorJS = require('@editorjs/editorjs')

It's works, but i got error on load tools
//   ImageTool = require('@editorjs/image')
   // got error
Perhaps there is another way?
Answer: Here is an example of how I used it in a Nuxt.js project:
Using with Nuxt.js (2.15.x)
Tested with editor.js 2.22.x and nuxt 2.15.x. You will obviously have to expand for your needs but this is the basics.
Install modules
Install all your modules: npm i --save @editorjs/editorjs @editorjs/header
Create plugin
1. Create the following in your Nuxt project plugins/editor.js
import EditorJS from '@editorjs/editorjs';
import Header from '@editorjs/header';

export default (context, inject) => {
  const defaultOptions = {
    id: '',
    data: {},
    onChange: () => {},
  }

  const editor = (options = defaultOptions) => {
    return new EditorJS({
      placeholder: 'Let`s write an awesome story!',
      /**
       * Id of Element that should contain Editor instance
       */
      holder: options.id,
      /**
       * Available Tools list.
       * Pass Tool's class or Settings object for each Tool you want to use
       */
      tools: {
        header: Header,
      },
      /**
       * Previously saved data that should be rendered
       */
      data: options.data || {},
      onChange(data) {
        // pass in function from component to run on change
        options.onChange(data)
      }
    })
  };

  inject('editor', options => editor(options));
}

2. Edit your nuxt.config.js plugins block to include it:
  plugins: [
    ...
    { src: '~/plugins/editor.js', mode: 'client' },
    ...
  ],

3. Create component components/Editor.vue
<template>

</template>

4. Create component to display editor results in components/Blog.vue
<template>

    <template v-for="block in editorContent.blocks">

{{ block.data.text }}

{{ block.data.text }}

{{ block.data.text }}

    </template>

</template>

4. Example using in pages/index.vue
<template>

    <Editor
      :blog-content="editorContent"
      @contentChanged="onChange"
    />
    <Blog :editor-content="editorContent" />

</template>

Answer: <template>

</template>

How to use EditorJS in NuxtJS project?


Supporting multiple versions of models for different REST API versions

Question: Are there any best practices for the implementation of API versioning? I'm interested in the following points:

Controller, service - e.g. do we use a different controller class for each version of the API? Does a newer controller class inherit the older controller?
Model - if the API versions carry different versions of the same model - how do we handle conversions? E.g. if v1 of the API uses v1 of the model, and v2 of the API uses v2 of the model, and we want to support both (for backward-compatibility) - how do we do the conversions?
Are there existing frameworks/libraries can I use for these purposes in Java and JavaScript?

Thanks!
Answer:
I always recommend a distinct controller class per API version. It keeps things clean and clear to maintainers. The next version can usually be started by copying and pasting the last version. You should define a clear versioning policy; for example N-2 versions. By doing so, you end up with 3 side-by-side implementations rather than an explosion that some people think you'll have. Refactoring business logic and other components that are not specific to a HTTP API version out of controllers can help reduce code duplication.
In my strong opinion, a controller should absolutely not inherit from another controller, save for a base controller with version-neutral functionality (but not APIs). HTTP is the API. HTTP has methods, not verbs. Think of it as Http.get(). Using is another language such as Java, C#, etc is a facade that is an impedance mismatch to HTTP. HTTP does not support inheritance, so attempting to use inheritance in the implementation is only likely to exacerbate the mismatch problem. There are other practical challenges too. For example, you can unherit a method, which complicates the issue of sunsetting an API in inherited controllers (not all versions are additive). Debugging can also be confusing because you have to find the correct implementation to set a breakpoint. Putting some thought into a versioning policy and factoring responsibilities to other components will all, but negate the need for inheritance in my experience.
Model conversion is an implementation detail. It is solely up to the server. Supporting conversions is very situational. Conversions can be bidirectional (v1<->v2) or unidirectional (v2->v1). A Mapper is a fairly common way to convert one form to another. Additive attribute scenarios often just require a default value for new attributes in storage for older API versions. Ultimately, there is no single answer to this problem for all scenarios.
It should be noted that backward-compatibility is a misnomer in HTTP. There really is no such thing. The API version is a contract that includes the model. The convenience or ease by which a new version of a model can be converted to/from an old version of the model should be considered just that - convenience. It's easy to think that an additive change is backward-capable, but a server cannot guarantee that it is with clients. Striking the notion of backwards-capable in the context of HTTP will help you fall into the pit of success.
Using Open API (formerly known as Swagger) is likely the best option to integrate clients with any language. There are tools that can use the document to create clients into your preferred programming language. I don't have a specific recommendation for a Java library/framework on the server side, but there are several options.


Oracle 11g SQL assignment

Question: I'm really battling with a question in my Textbook that I can't quite understand. The entire book (A guide to SQL 9th Edition) focuses on Oracle 11g via SQL commands in the SQL workshop of oracle AE.
However, the latest chapter (Chapter 8) talks about using PL/SQL in Procedures and the wording of the question is confusing to me, can someone help me understand what the answer is?
<code>    22. When you run the following SQL command, the result is "no data found."
    You know that one record should be retrieved.
    Rewrite the SQL command using a function that will retrieve the record.

    SELECT ITEM_NUM, DESCRIPTION PRICE
    FROM ITEM
    WHERE DESCRIPTION = 'patience';
</code>
What is confusion to me is that the question appears to be in relation to a procedure and yet the wording and sample code makes me thing they are asking for a standard command. I also don't see how the error can be given if there is supposed to be a record matching the criteria.
Comment: They want you to add a built-in or standard function to the query.  I'll  you a hint that Oracle is case sensitive.
Comment: In other words they are wanting me to make use of a function to change case such as:

  SELECT ITEM_NUM, DESCRIPTION, PRICE
  FROM ITEM
  WHERE UPPER(DESCRIPTION) = 'PATIENCE';
Answer: Answer is to use the upper or lower function to specify case as surmised by question poster.
<code>SELECT ITEM_NUM, DESCRIPTION, PRICE
FROM ITEM
WHERE UPPER(DESCRIPTION) = 'PATIENCE';
</code>

Oracle 11g SQL assignment


Confidence Interval's equivalence to hypothesis tests

Question: Theoretically, I was having a debate with my friend about confidence intervals and I got confused.
So, my understanding is the whole confidence interval is essentially the same as a two-tailed hypothesis test.
So, a 95% confidence interval is essentially the same as a two-tailed hypothesis test with significance level 10%.
So for example, if you have
H0: μ = x
and H1: μ ≠ x
with significance level 10%
You could turn this into a z-statistic and do a hypothesis test, or you could set up a 90% confidence interval.
The problem for me, theoretically comes in with one-tailed.
So for example, if you have H0: μ < x, and you see that it lies in the confidence interval, but above the sample mean. Do you reject H0? Do you split the hypothesis test essentially down the sample mean and use x̄ > the lower half of the interval when it's a one-tailed test, and do the opposite if you want to see if the mean has increased?
Comment: (1) You are right that there is often a duality btw a 2-sided test and a 2 sided CI, both with same 'error probability' $\alpha$ (with the CI containing 'non-rejectable' null values. An exception is with tests binomial proportion and Wald CIs.// (2) Although not always covered in elementary courses, there are 'one-sided CIs' that essentially give an upper or lower bound for the parameter value. I'll show results for a one-sided t test in R to illustrate.
Comment: [One possibly useful link](https://stats.stackexchange.com/questions/179902/confidence-interval-p-value-duality-vs-frequentist-interpretation-of-cis?rq=1) from the right-hand margin.
Answer: Comment on One-sided t confidence intervals continued:
Start with a sample of 25 observations from $\mathsf{Norm}(\mu = 100, \sigma=10):$
set.seed(505)
x = rnorm(25, 100, 10)
mean(x);  sd(x)
## 97.0539         # sample mean
## 9.853215        # sample standard deviation

The sample mean is about $\bar X = 97.05,$ which
is smaller than $\mu_0 = 100.$
Is that sufficient evidence to reject  $H_0: \mu = \mu_0 = 100$ against the one sided alternative $H_a: \mu < \mu_0?$
t.test(x, mu = 100, alte="less")

        One Sample t-test

data:  x
t = -1.495, df = 24, p-value = 0.07397
alternative hypothesis: true mean is less than 100
95 percent confidence interval:
     -Inf 100.4254
sample estimates:
mean of x
  97.0539

Because the P-value (about $7.4\%)$ exceeds 5%, we do not reject $H_0: \mu = \mu_0$ against the left-sided
alternative at the 5% level of significance.
The left-sided 95% confidence interval is $(-\infty, 100.4254).$ This indicates that data are consistent with a true mean below $100.4254.$
For example, in terms of possible null values $\mu_0:$ We would not have rejected with $\mu_0 = 100.4$ or with  $\mu_0=99.2$
(or any other hypothetical mean below $100.4254.)$
Below we show just the P-values for the two values of $\mu_0$ mentioned above:
t.test(x, mu = 100.4, alte="less")$p.val
## 0.05122181     # barely avoids rejection at 5%

t.test(x, mu = 99.2, alte="less")$p.val
## 0.1434768      # not even close to rej at 5%

Note: A direct computation of the upper limit
of the left-sided 95% CI shown in R's output
for the t test above is as follows:
$$\bar X + t_U S/\sqrt{n},$$
where $\bar X$ and $S$ are the respective sample mean and standard deviation and $t_U$ cuts probability 5% from the upper tail of Student's t distribution with 24 degrees of freedom. This computes to $100.4254.$
t.u = qt(.95, 24); t.u
## 1.710882
mean(x) + t.u*sd(x)/sqrt(25)
## 100.4254


Time Series Theorem

Question: Consider the following theorem:

Theorem. For any sequence of autocovariances $\{ \lambda_k \}$ generated by a stationary process, there exists a function $F$ such that $$\lambda_k = \int_{(-\pi, \pi]} e^{ik \lambda} dF(\lambda)$$ where $F$ is the unique function on $[-\pi, \pi]$ satisfying

$F(-\pi) = 0$
$F$ is non-decreasing and right continuous
For any $0 \leq a \leq b \leq \pi$ we have $F(b)-F(a) = F(-a)-F(-b)$.

Then $F$ is called the spectral distribution function.

So basically, given a set of autocovariances (e.g. $\{E(X_{t}X_{t+1}), E(X_{t}X_{t+2}), \dots, E(X_{t}X_{t+10}) \}$), we can express each of these autocovariances in terms of the spectral distribution function?
Added. What is the purpose of the this theorem?
Comment: Isn't that (part of) what the theorem asserts? Perhaps you could be a little more precise about what your difficulty is?
Answer: I think a theorem states (and proves) a truth; it does not necessarily have a purpose other than our enlighthening. That said, from the theorem you mention several interesting facts derive. If $dF(\lambda)$ happens to be continuous with respect to the Lebesgue measure, then you can restate the theorem as
$$ \lambda_k = \int_{(-\pi,\pi]}e^{ik\lambda} f(\lambda)d\lambda $$
with $f(\lambda)$ being the spectral density function and having an interesting interpretation. It is particularly clear when $k=0$; then you have
$$ \lambda_0 = \sigma^2 = \int_{(-\pi,\pi]} f(\lambda)d\lambda $$
which shows that the total variance of the process can be decomposed in the freuency domain, the contribution of oscillations in one band being given by the integral of $f(\lambda)$ over that band.

Time Series Theorem


Theme taxonomy term page with template override

Question: I know this is far from duplicate but im a bit stupid.
I am trying to theme the terms page for each term for a specific vocabulary i created.
I 've used path auto when i was creating the terms so i have a specific path for each vocabulary term.
My website is using a subtheme that i created by copying and pasting the main theme which is ninesixty. So i have tried creating a new template for taxonomy terms like taxonomy-term--12.tpl.php added my html code and unfortunately the template wasnt overridden.
I have also tried to override the template using the template.php file with no luck.
 I dont want to use any module so any clear answer will be helpful.
Answer: You can use the below filename structure to create a taxonomy term template:
<code>taxonomy-term--[vocabulary-machine-name|tid].tpl.php
</code>
Comment: so if i have vocabulary machine name as company_news_categories and term id 8 that will be taxonomy-term--company_news_categories8.tpl.php ?
Comment: No, because `|` means "or". Use `taxonomy-term--company_news_categories.tpl.php` to format all terms of your vocabulary, _or_ use `taxonomy-term--8.tpl.php` to format only term 8.

Term IDs are unique across all vocabularies, so there is no need to have both pieces in the filenames.


Java RTP/RTCP library using NIO

Question: Is there a Java RTP/RTCP library based on Java NIO or some Java NIO framework (Netty, MINA, ...)?
Answer: You would have to write a wrapper yourself, I'm afraid. Netty has a pretty flexible architecture that would allow that.
Answer: In Red5, we are adapting an RTP/RTSP library written using Mina. If you would like to check it out, go here: http://red5.googlecode.com/svn/java/plugins/trunk/rtspplugin/
The original library was written by Matteo Merli (firstname.lastname@example.com) and yes, we have his permission to modify it.
Comment: Thanks for the info. But the RTP part of the library seems not to contain the actual RTP/RTCP handlers, just packet classes, or am I mistaken?
Comment: I was under the impression that everything needed was there. I am not absolutely sure of this however.
Comment: @PaulGregoire link is not working.
Comment: Updated links for Red5 and RTSP: https://github.com/Red5/red5-plugins/tree/master/rtspplugin and https://github.com/Red5/red5-rtsp-restreamer

Java RTP/RTCP library using NIO


Improper Integrals (Very Basic)

Question: So im having a huge amount of trouble with some basic improper integrals of different types.
as they are very basic im going to post the ones i got incorrect. ( my textbook just labels converges or diverges as answers)
1)$\int^{\infty}_{1}  \frac{dx}{x(x+3)^{1/2}}$
 Clearly  the problem occurs at infinity
2)$\int^{\infty}_{3}  \frac{(x^{2}-3x-1)dx}{x(x^{2}+2)}$
Again at infinity
3)$\int^{\infty}_{3}  \frac{(\sin 4x)dx}{x^{2}-x-2}$
Again at infinity
4)$\int^{\infty}_{1}  \tan(\frac{1}{x})dx$
I have the basic methods as well as the ratio test im just not well versed in implementing it these are ones that i thought i had figured out but did incorrectly. if someone could give me a simple function or layout to apply to these i would really appreciate it
Answer: The common thread in these problems is the behaviour for large $x$.
1) Informally, for large $x$ our function behaves like $\frac{1}{x^{3/2}}$. You should know that for $p\gt 1$, $\int_1^\infty \frac{dx}{x^p}$ converges.
So our integral should converge. More formally, we have
$$0\lt \frac{1}{x(x+3)^{1/2}}\lt \frac{1}{x^{3/2}},$$
 so by the Comparison Test our integral converges.
2) Informally, the top is dominated by the $x^2$ term for large $x$, and the bottom behaves essentially like $x^3$. So the ratio behaves like $\frac{1}{x}$. Recall that $\int_1^\infty \frac{dx}{x}$ diverges. So our integral should diverge.
To make it formal, use the Limit Comparison Test. That is, if $f(x)$ is our function, show that $\lim_{x\to\infty}\frac{f(x)}{x}$ is positive.
3) Note that $|\sin(4x)|\le 1$. So if we can  show that the integral of $\frac{1}{x^2-x-2}$ converges, we will be finished.
But informally this function behaves like $\frac{1}{x^2}$ for large $x$. You can make it more formal by using the Limit Comparison Test. Or else you can observe   that for large enough $x$, the bottom is bigger than $x^2/2$, and do a Comparison with the integral of $\frac{2}{x^2}$.
4) Note that $\lim_{t\to 0}\frac{\tan t}{t}=1$. So for large $x$, $\tan(1/x)$ behaves like $1/x$. But we know that $\int_1^\infty \frac{dx}{x}$ diverges.
More formally, do a Limit Comparison Test. Or observe that if $x$ is large, then $tan(1/x)\gt \frac{1}{2}\cdot \frac{1}{x}$.
Remark: What was in common here was the family of integrals $\int_1^\infty \frac{dx}{x^p}$. We had to know that there is convergence if $p\gt 1$, and divergence if $p\le 1$.
Then, in these problems, we needed to do some informal thinking about dominant terms ("roughly how big/small is this?"). And finally, for the formal part of the argument, we needed tools such as Comparison and Limit Comparison.
Comment: this is a very good answer its clear cut as to what i am not grasping! Tyvm for your help i have been getting some right some wrong its very frustrating when i don't know why something is incorrect.
Answer: Here is a start,
1) Use the inequality $ x(x+3)^{1/2} > x^{3/2},\, \forall x \geq 1. $
$$ \int^{\infty}_{1}  \frac{dx}{x(x+3)^{1/2}}dx <  \int^{\infty}_{1}  \frac{dx}{x^{3/2}}dx < \infty.$$
2) You can compare with the function $\frac{1}{x}$, since $$\frac{x^{2}-3x-1}{x(x^{2}+2)}\sim \frac{x^2}{x^3}=\frac{1}{x}. $$

Improper Integrals (Very Basic)


iphone - reading an area of an image

Question: Is that possible to read just a small rectangle area of a large image file?
Comment: I have the same question. I want to make an animation through displaying parts of the image in sequence by showing only cropped area for a each small duration. If you have any other solution please let me know. Trying with image cropping. **CICrop**
Answer: This is not possible. First of all the iPhone api certainly doesn't support it. More importantly, image formats such as JPEG generally store the pixels row by row, and then apply sequential compression to the entire stream - that means you must start at the beginning and follow through. (not sure about PNG)
Your best bet, if you need this really bad, for jpeg, is to link against a clone of libjpeg in which you hack some stuff to skip through the Huffman(-ish) encoded 8x8 MCU blocks, and only store the part you need.
From experience I can tell that the speed gain will be some 70% if you apply a truckload of tricks to skip from one MCU block to the next, without actually decoding them. (I needed only the very first entry of each block for a fast 8-to-1 downscaling)
It would be a very interesting project, but unless you feel a pressing need I would just read in the entire image and then slice out the part you need.
Comment: ps. I looked it up, decoding in libjpeg revolves around `decode_mcu()` in `jdhuff.c`
Comment: thanks. This is exactly what I need. I will research if it is viable to continue on this approach... thanks.
Answer: Try: CGImageCreateWithImageInRect
Comment: Thanks but I think this method is for copying part of an image to another. This is not what I need. I need to read from the image file, just the bytes correspondent to a given rect area.

iphone - reading an area of an image


C++ about pointer used

Question: int main()
{
   int rows=0;
   int studId,course;
   char ch;
while(FileIn>>studId>>course)
   {
   for(int i=0;i<5;i++)
   {
       FileIn>>ch;
   }
   rows++;
}
char** questions = new char*[rows];

What is the meaning of new char*[rows]? if rows = 10.
The file content is
20 1 A B C D E
20 1 A B C D E
20 1 A B C D E
20 1 A B C D E
20 1 A B C D E
20 1 A B C D E
20 1 A B C D E
20 1 A B C D E
20 1 A B C D E
20 1 A B C D E

Answer: Allocates an array of 10 elements of type "char*."
Answer: since 'questions' is double pointer, it is made to point an array of pointers of size rows using new char*[rows] that is, after char** questions = new char*[rows];, questions can be made to point to pointers of type char. Hope I answered your question.

C++ about pointer used


Seeking recommendations for feature selection methods before applying a random forest model to high-dimensional data

Question: I'm seeking recommendations for feature selection methods before applying a random forest model to high-dimensional data, specifically with over 60,000 features and only 1,000 samples. My concern is that directly inputting all 60,000 features into the random forest may impact prediction performance and be computationally intensive.
I've explored the Boruta algorithm, but it's too computationally expensive given the number of features. I'm also not sure about using simple filtering methods like univariate filtering, as they might overlook non-linear and complex relationships.
My current plan is to initially run a random forest model with all 60,000 features and then select the top N features (perhaps around 2,000) for further model training and tuning. I am wondering does this make sense?
Btw,we've ruled out PCA due to interpretability concerns.
I'd greatly appreciate any advice!
Comment: Welcome to Cross Validated! What do you mean that you have ruled out PCA due to interpretability concerns? Aren't random forest models quite difficult to interpret and, thus, rather poor model choices if that is a primary concern? Perhaps you can say more about your goals.
Comment: Absolutely, Thank you! Since random forest generates the feature importance metric, we can look at which features are important. We need individual feature as we will later rely on those features to design new experiment. If we do PCA on data and run random forest, we will end up having important PCs, which is difficult to explain.
Answer: I would think twice before approaching this problem without more data.  In your comment to Dave, you mention

Since random forest generates the feature importance metric, we can look at which features are important.

Karandeep Singh has a very insightful twitter thread demonstrating that feature importance scores can sometimes not yield the most important feature.  For this reason, I doubt this method of feature selection (or any other for that matter, but we'll get there) will work.
It sounds like your feature selection procedure will inform some downstream decision.  To me, that would mean you want to do stable feature selection (meaning that you would find the right variables each time, regardless of the sample obtained).  I have a very simple simulation showing that even when all assumptions about the data generating process are met, feature selection can't reliably find the right variables.  Mind you this is with stepwise regression, but I don't have much confidence in other methods.
Can you elaborate on what you intend to use the selected variables for?  What is this experiment you're planning?  What have you captured data on and what are your goals?

From your comment, it sounds like you'd like to:

Identify the genes that are associated with disease, and
Use those genes to predict future disease status.

I have no doubt you can create a model with the data you have.  Personally, I think performing stable feature selection is a fools errand here.  You have 60, 000 genes and only 1000 samples, there are many such combinations of features which could lead to reasonable prediction accuracy, even if no relationship truly exists.  I think it would be a better idea to use all data and reduce the dimension of the problem using something like PCA.  If there is any signal, you could be able to use the PCs to predict outcomes which would fulfill your second goal.
Comment: More importantly, I'm saying you should eschew interpretability; even if you do identify "important" genes, their importance is unlikely to translate to a new sample.  It isn't sensible to do this, so focus in prediction instead.
Comment: Thank you for sharing your insights on feature selectioe and pointing out interesting post.  Our objective revolves around using omics data to predict disease phenotypes. Our primary aim is to achieve high prediction accuracy. Additionally, our secondary primary goal is to identify genes that play a crucial role in prediction. Once identified, we plan to conduct wet lab experiments to validate their association with the phenotype.
Comment: @MeowMix. See my edit.  I think stable feature selection here is nigh impossible, esp given the fact you have 60x more variables than samples.  You may be able to create a prediction model, and validating it with a new sample is a good idea, but identifying which genes are responsible (if any) is a very tough challenge with the size if the data you currently have.
Comment: +1 Readers might also be interested in Frank Harrell's [simulation of LASSO feature selection instability](https://youtube.com/watch?v=DF1WsYZ94Es&pp=ygUVSGFycmVsbCBjb250cm92ZXJzaWVz) and his comments later in the presentation about bootstrap validation of LIME and SHAP feature importance (especially his suspicion that such validation is likely to expose those methods as lacking the desired stability, which some work of mine has suggested will happen).
Comment: @DemetriPananos could you please elaborate more on "If there is any signal, you could be able to use the PCs to predict outcomes which would fulfill your second goal"? If we use Random forest with PCA, we are going to have important PCs.  Do you mean we can look at the loadings of PCs to decide which genes are important?
Comment: @MeowMix. PCA will reduce the dimensionality of the data and facilitate prediction.  You won't need to look at all 60K variables, just the top N principal components.  You can make a model out of those, or alternatively group genes and run principal components on those genes (assuming her you can sensibly group them).


How to force Feeds to import content? (Feeds too lazy to import every minute)

Question: I've setup Feeds to import content every minutes. All settings was fine.
Feed source contains only 1 rss item, and it changed every 1 or 2 minutes.
When I manually click "Import" tab, it will import nicely. But in many times, Feeds too lazy to import it.
By using cron, Is there any way I can force Feeds to import?
Comment: @Karl you can use the [Elysia Cron module](http://drupal.org/project/elysia_cron) to split up your Cron tasks so you could run some every minute and others at different intervals
Comment: I would also like to know this. I don't know if lazy is the right word but I would like to import more often than cron runs, I'm not gonna run Cron every other minute...
Comment: @Karl If you made that its own question, I'd happily answer it, but using cron.php vs. not doing so are different enough that they really shouldn't be lumped together.
Comment: If the source has PubSubHubbub support, that's your best bet.
Answer: Check the minimum refresh period in your feeds setting; feeds will not import anything if the last import is more recent than that setting.
Answer: In the Feeds settings page, in the settings section, check the option 'Skip hash check' -Force update of items even if item source data did not change.
This will prevent the importer from checking for any change, and import every time.
I would also check that the import task is quick enough to happen every minute. Imports can take several minutes, and re-calling the import by the cron every minute may disrupt this.
Comment: +1. Also, don't confuse with the GUID setting. GUID thing is to prevent duplicate items. Hash check is to make imports faster.
Answer: Create drush command and add it in your crontab file on the server.


Equivalent form of biconditional

Question: I'm reading How to Prove It: A Structured Approach (Velleman) Second Ed.
Doing all the end of chapter exercises for chapter 1 and having trouble on problem 5a which reads

Show that $P \leftrightarrow Q$ is equivalent to $(P \wedge Q) \vee (\neg P \wedge \neg Q)$

Clearly they're equivalent to each other based on the truth tables. But is that really the best way to 'show' it? I was able to derive the second form from the first in all the other questions that asked to show two forms are equivalent so far.
Here's what happens when I try to derive it:

$$P \leftrightarrow Q$$
  $$ \text{Form of biconditional} $$
  $$(P \rightarrow Q) \wedge (Q \rightarrow P)$$
  $$ \text{Form of conditional}$$
  $$ (\neg P \vee Q) \wedge (\neg Q \vee P)$$

From here it appears to match the form of a distributive law but with mismatched negations. I just don't know where to go from here...
Answer: So far, so good.  To continue...
$\vdots \\
(\neg P \vee Q)\wedge (\neg Q\vee P)
\\ \Updownarrow (\text{Distribute})\\
(\neg P\wedge (\neg Q\vee P)) \vee (Q\wedge (\neg Q\vee P))
\\ \Updownarrow (\text{Distribute, twice})\\
(\neg P\wedge \neg Q)\vee(\neg P\wedge P)\vee (Q\wedge \neg Q)\vee (Q\wedge P)
\\ \Updownarrow  \\
\vdots
$
Can you see where to go from here?
Comment: You'd remove the two contradictions because of the contradiction laws and be left with (not P && not Q) || (Q && P), then use commutative laws to arrive at exactly the answer?
Comment: Yes, that's correct.  Are you comfortable with the distributions?
Comment: Yes I worked out your answer. I was going to edit the question mark and say thanks when my internet went out, so thanks for that.

Equivalent form of biconditional


What is the appropriate random effect model and R-code for following data and question?

Question: I attached a data here called image_study. The "image_study.csv" dataset contains data from a study examining the speed of classification of two different types of image: artworks, and natural images.
There are four variables in the data as follows:
participant – a unique identifier for each participant
image – a unique identifier for each image
image_type – a factor indicating whether a given image is an Artwork or a Natural image.
RT – reaction time in milliseconds
I want to model reaction times (RT) as a function of the other variables in the dataset. The purpose here is to examine the effect of Image-type on RT.

Which of the fixed effect, random effect, or mixed effect model modes should I choose?
Which participant or image variables should be considered as a random effect in the model?
Comment: @MrFlick I want to know the code related to R software about this question.
Comment: You need to choose a model first. R can't tell you which model to use or how to model your data (fix vs random effects). Those are statistical concerns, not programming concerns. You need to know what you want to do before you can write R code to do it.
Comment: @MrFlick Both model selection and code writing in R are what I want. I also do not know what model to choose, nor do I know how to run it in R. (I am very familiar with R software).
Comment: What do *you* think is the appropriate model, given your data and question?
Comment: @AngelosAmyntas the crossed mixed effect model is the appropriate model for this question.
Answer: Since you say:

The purpose here is to examine the effect of Image_type on RT.

then we need a regression model with RT and the response and image_type as the main exposure (fixed effect).
Since you have repeated measure within both participant and image then you should fit random intercepts for both of these.
Furthermore, since participant and image appear to be crossed (from the data picture all images were seen by participant 1 and that appears to repeat for participant 2), then the following model should be appropriate:
RT ~ image_type + (1|participant) + (1|image)

which is the syntax you would use with popular R packages such as lme4. eg:
library(lme4)
model <- lmer(RT ~ image_type + (1|participant) + (1|image), data = image_study
summary(model)

Comment: people often use identity-link Gamma models to model reaction time (I don't necessarily think this is a good idea, but they do it): `glmer(..., family=Gamma(link="identity"))`
Comment: @BenBolker what is the default link function and distribution for random effect models?
Comment: See [here](https://stats.stackexchange.com/questions/370011/is-the-canonical-parameter-and-therefore-the-canonical-link-function-for-a-gam) for a discussion about the link function for gamma models
Comment: @BenBolker Indeed, I have seen that too, it often seems to arise from poorly fitting linear models, but I'm not sure the gamma models always improve things. For example [here](https://stats.stackexchange.com/questions/486476), [here](https://stats.stackexchange.com/questions/482600),and [here](https://stats.stackexchange.com/questions/482141)
Comment: @MehdiLoohs generally Gaussian/identity
Comment: @RobertLong yes its a correct answer to my question. Thank you Robert
Comment: @RobertLong Done. Can you please introduce me to a reference or book so that I can learn longitudinal analysis in R. I'm very familiar with R.
Comment: Sure.
http://www.drizopoulos.com/courses/EMC/ESP72.pdf


What is the effect of increasing the sample size in ANOVA?

Question: Assume that a one-way ANOVA is performed on 3-4 groups of the same size.
What is the effect of increasing the sample size (equally for all groups)?
Answer: Since the essential computation is the F-test:
$$F=\frac{\text{variance between treatments}}{\text{variance within treatments}}=\large\frac{\frac{\text{Sum Sqs}_{\text{treatments}}}{\text{no. treatments}-1}}{\frac{\text{Sum Sqs}_{\text{errors}}}{\text{no. cases}-\text{no. treatments}}}$$,
increasing the number of cases will decrease the denominator, and increase the $\ F$ test statistic, making it more likely to obtain a small p-value with everything else constant.
In other words, it will result in increased power, and decreased type II errors.
And following up on the comments from @whuber, the increase in the number of observations also has an effect in the mean squared residuals (MSR or RSE), and by extension on the standard error (SE) on the estimates. This is clear when considering that the standard error of the estimates is simply the square root of $\widehat{\textrm{Var}}(\hat{\mathbf{\beta}}) = \hat{\sigma}^2  (\mathbf{X}^{\prime} \mathbf{X})^{-1}$, and that the model matrix $X$ in this case of one-way ANOVA is as simple as an intercept and dummy coded entries:

with the defining value $\hat\sigma^2=\frac{u^Tu}{\text{df}}$ and $\text{df}=\text{cases}-\text{groups}-1$, which is roughly the mean of the squared residuals. Carrying out a Monte Carlo simulation by drawing three groups of observations from normal distributions with the same variance $\sigma^2=9$, but with means $x_1=10$, $x_2=15$ and $x_3=20$

with increasing numbers of balanced observations from $5$ to $1000$ we can see how the mean squared of the residuals display a funneled shape, rapidly dropping the spread of the mean squared residuals as the sample size increases:
Comment: You appear to be confusing the standard deviation with the standard error! The interesting point is that although the *expected* variance remains the same in each group, regardless of sample size (and you can terminate your answer with this observation if you wish), it is of practical interest to wonder what the chances are that the variances in the new sample will be at least twice the variances of the current sample.  Such a question has both Bayesian and Classical answers (in the form of prediction intervals for the variances).
Comment: Although this is correct, it appears to be incomplete: you need to say something about how the sums of squares in one sample relate to the sums of squares in another sample.
Comment: @whuber Are you referring to the effect of increased subjects when the variances are different across groups?
Comment: No--as you add to the sample, the variances will almost surely change. You implicitly assume they do not.
Comment: Let me approach it from the gut - the variations within the groups is the annoying noise that we want to get rid of. If there was no noise, there wouldn't be a need for a test... In general the more data points the less noise. So presumably the variance within treatments drops with the sample size, but this effect goes beyond the degrees of freedom...
Comment: @whuber Did I even come close?
Comment: +1 The final graph is particularly interesting because it clearly shows there really is some chance that $\hat\sigma^2$ as estimated in small samples could substantially change, either up or down, when larger samples are collected.  This illustrates the risk attendant to performing sample size calculations based on limited preliminary data.  A good sample size calculation therefore would estimate that risk and incorporate it in its results (rather than assuming a known effect size and known variance).


Counting on minesweeper

Question: Given a minesweeper configuration. How many way are there to fill it to make the configuration correct.
Is there any better solution than brute-force method ?
Example:
Given configuration:
1_11_2__b (b = bomb, _ = blank)
one way to fill it is:
1b11b2b2b
Comment: What's a minesweeper configuration?
Comment: Do you mean the Windows game Minesweeper? Also, you'll have to be clearer about what "filling it with number 0,1, or 2" means.
Comment: Can you precise your question? What is a "configuration". A set of mines, or a set of visible squares, or a size of borad?
Comment: Please wait a second, I'll edit my question
Comment: Bilou06: all of them, A set of visible mines and a set of visible squares and size of board. Sorry for my english.
Comment: In this case, you can deduce that any $2$ will have a bomb on either side, and that any $1$ on the edge will have a bomb next to it.  In this case, the only free choice is the last blank, so it's clear that there are $2$ ways to fill the configuration.
Answer: Standard 2D minesweeper has been shown to be NP complete-that finding if there is a way to solve a given partially filled in board is hard.  I would guess that 1D is not, there isn't enough room to make the required structures.  In any case, you probably want one pass that fills in all the squares that have to be one kind or the other-for example your first blank.  That would solve all the squares except the last, which can be b or 2.  Then start a backtracking algorithm-try one and see if it works, then the other.  You may well have to split into subcases.  Dynamic programming makes structuring this easier.

Counting on minesweeper


Solving systems of equations for m and b when you know they are both positive?

Question: I am trying to make a website that runs off of this equation. I am only in algebra but I am trying to solve a systems of equation where instead of solving for $x$ and $y$ I am solving for $m$ and $b$. Here is the equation:
$$100,333.333333=m10.3333333+b$$
$$6000=(m10.333333+b)-(m5+b)$$
I solved this by solving it the same way you would solve for $x$ and $y$ and I got:
$1125=m$
$-1291.66666666=b$
For the equation to work perfectly it would be best if I could make both $m$ and $b$ positive. Is there any way that I could make it so that the equation is true but both $m$ and $b$ are positive?
Thank you for your response!
Comment: i don't know if this helps but there was a typo.
Comment: If you expected a positive result and didn't get it, then there is something wrong in your model (the equations or the solution). Maybe a coefficient or a sign somewhere. I get $m=1125$ and $b=88700$. I suggest showing how you get your values.
Answer: A linear system of equations either has zero solutions, one solution or infinitely many solutions. So no, you can't find another value of $b$.
Comment: even though you can also change the m variable to make a kind of new equation and you have new information about both the variables?
Comment: It's likely you'll simply make the system insolvable.


How to remove span from rewrite result in a field view?

Question: In a custom view I have several fields excluded from display.
I wanted to use their values within an global:fieldset with rewrite output option.
This works but the values are embedded in a  that I don't want, and I didn't find the way to remove it. i.e. if rewrite text use the replacement patterns [field1],[field2],[field3] I got as result
field1 result, field2 result, field3 result

instead of only:
field1 result, field2 result, field3 result
Answer: You will need to click on the fields you excluded (one by one), click on Style settings and select Customize field HTML. Then select -None- under HTML Element. You may need to do this for Customize label and Customize wrapper. Click Apply. Don't forget to click Save.

EDIT: Since you have now clarified that you are using Views Fieldsets (and for next time, be sure to provide ALL details about your problem!), I believe you will need to override the default tpl.php file for the Views Fieldset fields.
Views Fieldset provides default tpl.php files inside the template folder inside the module folder (usually found in /sites/all/modules/views_fieldset. You need to copy the content of that file, save it in your theme's template folder and modify it. Follow the steps in this general tutorial (you will need to adapt it to your problem) to override the default template for Views Fieldset fields.  Good luck.
Comment: Thanks for your answer but it does not work, I still have the span around the alter text. I edited my question to show it better.
Comment: Where are you trying to rewrite the fields? Are you creating a `Global: Custom text`? If so, you will ALSO need to customize the style for that custom text field (the SPAN is probably coming from that custom field)
Comment: I rewrite the field `Global:fieldset` that does not provide the possibility to customize the style.  But when I look at the code of this module I do not find where a span is added.
Comment: See my edited answer now.
Comment: Thanks for you edited comment and help. I already overided this template without success because the content of the rewriten global:fieldset (the result)  is provided in the `$legend` variable. The content of $legend is embeded within the span tag that I want to avoid. A solution would be to remove it by extracting this tag from the $legend variable directly within the template tpl file. I expected that some one may explain me from where this span tag comes and how to remove it.


A locally bounded family must not be a bounded family

Question: I have read that a locally bounded family is not a bounded family, and that the following family shows that:
$\mathcal{F} = \{ f_n : n \in \mathbb{N} \}$, $f_n : \mathbb{E} \to \mathbb{C}$, $f_n(z) =n z^n$. Where $\mathbb{E}  = \{z \in \mathbb{C} : \vert z \vert < 1\}$
(So that this is a locally bounded family but not a bounded family)
Unfortunately I am stuck at both claims.
The definitions are as follows:
Def. bounded family: A familiy $\mathcal{F} \subset \mathcal{O} (D)$ is called bounded in a subset $A \subset D$, if there exists a real number $M > 0$ s.t. for all $f \in \mathcal{F}$ it holds that $\vert f \vert _A \leq M$.
Def locally bounded family: A family $\mathcal{F} \subset \mathcal{O} (D)$ is called locally bounded in $D$ if for each point $z \in D$ there exists a neighborhood $U \subset D$ s.t. $\mathcal{F}$ is bounded in $U$.
What confuses me the most is that on one hand we have the times $n$ in $f_n(z) =n z^n$, on the other hand there is the to the power of $n$. So as $n$ gets bigger, $z^n$ gets smaller, as $z \in \mathbb{E}$.
What I have tried/where I am stuck:
Claim 1: $\mathcal{F}$ is not bounded.
Proof: To show this, we have to show, that there exists no $M>0$ s.t. for all $f \in \mathcal{F}$ it holds that $\vert f \vert _A \leq M$, or equivalently that $\sup\limits_{f \in \mathcal{F}} \sup \limits_{z \in \mathbb{E}} \vert f(z) \vert = \infty$. For a fixed $f \in \mathcal{F}$ we have:
$$ \sup \limits_{z \in \mathbb{E}} \vert f(z) \vert = \sup \limits_{z \in \mathbb{E}} n \vert z^n \vert = n \cdot 1^n = n $$
Then
$$ \sup\limits_{f \in \mathcal{F}} \sup \limits_{z \in \mathbb{E}} \vert f(z) \vert = \sup\limits_{f \in \mathcal{F}} n = \infty$$
I can say that the last equation holds because $\sup\limits_{f \in \mathcal{F}}$ is like $f_\infty$, so $n = \infty$.
Claim 2: $\mathcal{F}$ is locally bounded.
Proof: To show this, we have to show that for each point $z \in D$ there exists a neighborhood $U \subset D$ s.t. $\mathcal{F}$ is bounded in $U$. In this claim we use the following Lemma: A family $\mathcal{F} \subset \mathcal{O}(\mathbb{B})$ in a ball $B_r(c)$, $r>0$ is locally bounded in $B$ iff $\mathcal{F}$ is bounded in every ball $B_\rho (c)$, $\rho < r$.
With that we have to show that our family $\mathcal{F}$ is bounded in every ball $B_\rho (0)$, $\rho < 1$, i.e. $\sup\limits_{f \in \mathcal{F}} \sup \limits_{z \in B_\rho (0)} \vert f(z) \vert < \infty$.
For a fixed $f \in \mathcal{F}$ we have:
$$ \sup \limits_{z \in B_\rho (0)} \vert f(z) \vert = n \cdot \sup \limits_{z \in B_\rho (0)} \vert z^n \vert = n \cdot \rho ^n $$
Then
$$ \sup\limits_{f \in \mathcal{F}} \sup \limits_{z \in B_\rho (0)} \vert f(z) \vert = \sup\limits_{f \in \mathcal{F}} n \cdot \rho ^n$$
Now I have the problem that $n$ gets very big and $\rho ^n$ gets very small. How can I conclude from here on, that this is $< \infty$?
Proof of the Lemma:
$\Rightarrow$:  We assume that a family $\mathcal{F} \subset \mathcal{O} (B)$ in a ball $B_r(c)$, $r>0$ is locally bounded in $B$. We want to show that it is then bounded in every ball $B_\rho(c)$, $\rho < r$.
Is there a trick for proving this?
$\Leftarrow$: We assume that $\mathcal{F}$ is bounded in every $B_\rho (c)$, $\rho <r$ and want to show that $\mathcal{F}$ is locally bounded in $B_r(c)$. Isn't this direction just clear by the definition of locally bounded? So by the definition of locally bounded, we have to show that for every $z \in B_r(c)$ there exists a nhood $U \subset B_r(c)$ s.t. $\mathcal{F}$ is bounded in $U$. We could take the balls $B_\rho(c)$, $\rho <r$ as $U$. But what about the points "between" the balls $B_\rho (c)$ (where here $\rho$ is the biggest possible) and $B_r (c)$
Thank you for your help.
Comment: I am sorry, I tried to write down as much as I got now. Thank you for your advice.
Comment: I continued the proofs in my question with your help. I think Claim 1 is pretty clear now. For Claim 2 I am stuck with my problem that n is growing and the "to the power of n" is shrinking.

I also added the Lemma, I'd love to see that proof. I wrote my attempt for both sides.

Thank you for your help :)
Comment: Oh alright, I added this and posted a self-answer. Thank you very much for your help!
About the Lemma: I am still very curious how the proof of this would work, do you maybe know how it goes or where I could find it?
Comment: For the lemma, *you proved $\Leftarrow$, which is all you needed!*
Comment: To prove $\Rightarrow$, use that for every $\rho<r$, the closed ball $K:=\overline{B_\rho(c)}$ is a [compact subset](https://en.wikipedia.org/wiki/Compact_space#Compactness_of_subsets) of $B_r(c)$: given that every $z\in K$ has a neighborhood $U_z\subset B_r(c)$ on which $\mathcal F$ is bounded, $(U_z)_{z\in K}$ is an open cover of $K$, from which you can extract a *finite* subcover $(U_{z_1},\dots,U_{z_r})$. If $M_k$ is a bound for $\mathcal F$ on $U_{z_k}$, $\max(M_1,\dots,M_r)$ is then a bound on $U_{z_1}\cup\dots\cup U_{z_r}\supset K$.
Comment: That makes perfect sense. Thanks a lot!
Answer: Claim 1: $\mathcal{F}$ is not bounded.
Proof: To show this, we have to show, that there exists no $M>0$ s.t. for all $f \in \mathcal{F}$ it holds that $\vert f \vert _A \leq M$, or equivalently that $\sup\limits_{f \in \mathcal{F}} \sup \limits_{z \in \mathbb{E}} \vert f(z) \vert = \infty$. For a fixed $f\in \mathcal{F}$ we have $f=f_n$ for some $n\in \Bbb N$, and:
$$ \sup \limits_{z \in \mathbb{E}} \vert f(z) \vert = \sup \limits_{z \in \mathbb{E}} n \vert z^n \vert = n \cdot 1^n = n $$
Then
$$ \sup\limits_{f \in \mathcal{F}} \sup \limits_{z \in \mathbb{E}} \vert f(z) \vert = \sup\limits_{n\in \Bbb N} n = \infty$$
Claim 2: $\mathcal{F}$ is locally bounded.
Proof: To show this, we have to show that for each point $z \in D$ there exists a neighborhood $U \subset D$ s.t. $\mathcal{F}$ is bounded in $U$. In this claim we use the following Lemma: A family $\mathcal{F} \subset \mathcal{O}(\mathbb{B})$ in a ball $B_r(c)$, $r>0$ is locally bounded in $B$ iff $\mathcal{F}$ is bounded in every ball $B_\rho (c)$, $\rho < r$.
With that we have to show that our family $\mathcal{F}$ is bounded in every ball $B_\rho (0)$, $\rho < 1$, i.e. $\sup\limits_{f \in \mathcal{F}} \sup \limits_{z \in B_\rho (0)} \vert f(z) \vert < \infty$.
For a fixed $f \in \mathcal{F}$ we have $f=f_n$ for some $n\in\Bbb N$, and:
$$ \sup \limits_{z \in B_\rho (0)} \vert f(z) \vert = n \cdot \sup \limits_{z \in B_\rho (0)} \vert z^n \vert = n \cdot \rho ^n $$
Then
$$ \sup\limits_{f \in \mathcal{F}} \sup \limits_{z \in B_\rho (0)} \vert f(z) \vert = \sup\limits_{n\in \Bbb N} n \cdot \rho ^n < \infty.$$
Where the "$< \infty$" holds, as $\lim \limits_{n \to \infty} n \cdot \rho^n = 0$ and every converging sequence is bounded.
Comment: great, thanks for the polishing. I see that it makes more sense like that.
Comment: Ok, then if you agree, please correct the end of your answer. (Incidentally, another argument could be an explicit upperbound. $\max_{x\in\Bbb R}x\cdot\rho^x$ is not extremely difficult to calculate. But the argument that every converging sequence is bounded seems simpler.)
Comment: i changed the $\to 0$ to $< \infty$ now.
Comment: I added a justification, I hope you are happy with that. Unfortunately, I don't know how to add the link to the other question where it's shown that the limes goes to 0.
Comment: Thank you, for your correction. I accepted my answer now.


Altering a form to set it's target to _parent

Question: I have a form in an iframe, when the form gets submitted I need the target to be _parent.
How do we add target="_parent" to a form element in drupal 7. I am pretty sure hook_form_alter is the best way to go just not sure about what var gets edited and how.
-thanks.
Answer: to change your form you can use hook_form_alter
example
function login_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id=="user_login_block")
    {
         $items[] = ''.t('Request new password').'';
         $form['links'] = array('#markup' => theme('item_list', array('items' => $items)));
    }
}

Comment: @ChrisBorgia `$form['#attributes']['target'] = '_parent';` should do the trick
Comment: edited question to ask HOW we do it with hook_form_alter
Comment: If you want something like that I edit my answer
Comment: Hi ahmed, close but, i need to add target="_parent" to the actual  element, not to an object in the form.
Comment: i think u can use this $form['#attributes'] = array('target' => '_parent');
Comment: Thank you @Clive, and thank you Ahmed, `$form['#attributes']['target'] = '_parent';` did the trick
Answer: Just use $form['#attributes']['target'] = '_parent'. If the form is implemented from another module, you can use hook_form_alter(), or hook_FORM_ID_alter() to add that attribute.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the form ID for the form you need to target') {
    $form['#attributes']['target'] = '_parent';
  }
}


Filtering numpy character array

Question: I have a numpy array of letters and '-' - it may have tens of thousands rows and thousands of columns. I would like to move all the '-' to the right (without changing the order of the other letters), and then truncate the array so that no column contains all '-'. I am looking for a fast solution, using perhaps some ingenious use of the built-in numpy routines.
Background:
Every row in the array is actually a genetic sequence, where '-' are inserted somewhat randomly for reasons which are not important here. Instead of dealing with an array I could actually save all the sequences as strings, pad them on the right with '-' to match the maximum non-trivial sequence length, and transform into an array. This however turns out rather slow, which is why I am looking for a clever way to do it starting with an array of letters, which is easily obtained
as np.array(aln), where aln is sequence biopython alignment object.
Update
Here is an example, that hopefully clarifies the question. If I start with array
np.array([['-', 'A', 'C', '-', 'T'], ['A', 'G', '-', 'T', 'T']])

I want it to be transformed to
np.array([['A', 'C', 'T', '-', '-'], ['A', 'G', 'T', 'T', '-']])

and ultimately to
np.array([['A', 'C', 'T', '-'], ['A', 'G', 'T', 'T']])

Comment: To me it is not clear, what you mean exactly with "I would like to filter all the '-' to the right". Could you maybe append an example array to your question together with the expected result?
Comment: I would like to move all the '-' to the right. @LydiavanDyke
Answer: See if this works for you
import numpy as np

data = np.array([['-', 'A', 'C', '-', 'T'], ['A', 'G', '-', 'T', 'T']])
new_data = np.tile('-', data.shape)

longest_line = 0
for i, line in enumerate(data):
    not_dash = line != '-'
    n_characters = sum(not_dash)
    new_data[i, :n_characters] = line[not_dash]
    longest_line = n_characters if n_characters > longest_line else longest_line

new_data = new_data[:, :longest_line]

Outputs
>>> new_data
array([['A', 'C', 'T', '-'],
       ['A', 'G', 'T', 'T']], dtype='<U1')

Filtering numpy character array


How does one differentiate a song in Dorian vs. a song in Aeolian?

Question: How does one determine whether a song is in Dorian or Aeolian?
As an example:
The melody of Pink Floyd's "Another Brick in the Wall" seems to be in the Dorian mode, but there is a G chord in the second half of the verse. So would the song be considered Dorian overall, despite the "foreign" chord, or would it be Aeolian?
Comment: Asked under false premises?
Comment: The harmony does **not** contain Bb, and does contain B (in the G chord).
Comment: For example in this thread.  https://music.stackexchange.com/questions/1262/what-is-a-good-solo-to-learn-in-the-dorian-mode
Comment: The main reason for Dorian is the G-chord after the phrase "teacher leave these kids alone" containing a B as 3rd which is the major sixth of D Jonian! "All in all you're just another ..." is a minor sixth= Bb which speaks for Aeolian. But mind that the dorian mode often has a flattened sixth (b flat and b natural have been marked as "accidentally". That's the way that the ambiguity of flats or sharps has been developed. (Often it was up to the performer to decide which accidental he would choose.) So the modes can also show this ambiguity ...
Comment: From the  point of modes the "tenor" tone should be A but this crucial note is a G! Btw. this is not a Greogorian chant, and Pop songs follow  their own rules.
Comment: @AlbrechtHügli in English we say "Ionian," pronounced as four syllables ("eye-OH-nee-an").  Even I (and I speak German reasonably) read "Jonian" with a hard J, so for a split second I thought it had something to do with Joni Mitchell. :-)
Comment: yes, also in German it must be Ionian.
Answer: The dorian and aeolian scales differ by 6th step, which is Bb in D aeolian or B in D dorian. The chords used in the song: Dm, G, F, C all consist of notes from the D dorian scale, which suggests dorian harmony. The note Bb does not appear in the song.
The vocal melody has ambitus of just a sixth (C–A), and doesn't get to B neither at the top nor at the bottom. The guitar solo consistently jumps over the 6th step. The resulting scale: D E F G A C could be called D-minor hexatonic.
However, as the note B clearly appears in the song, I think it's more accurate to say the song bases on dorian harmony with melody omitting the 6th step.
If you play D dorian scale over the recording, it agrees, though the B note introduces a color which is apparently purposely avoided in the original. If you play A aeolian, it sounds either wrong, or suggests an alteration of the original harmony.
Answer: TL;DR
The song is not in Dorian or Aeolian. It's built around the D minor pentatonic scale.
But to understand how the determination is made...
From the Department of Taking Things too Far
There is general agreement that the primary pitches are D, E, F, G, A, C. So, here's a detailed look at the other pitches that occur in the song.
album version, part I

B: 00:21 - 00:24. Guitar lick.
B-something: 00:50 - 01:01. (implied) In neither the G5 power chord, nor in the vocal harmonies it accompanies, do I hear a clearly articulated B or Bb; however, I hear the chord more easily as G than Gm; possibly because B occurs before Bb in the G overtone series.
B: 00:29 - 00:30. Same as 00:21.
Ab: 01:38 - 01:40. To be really picky about figuring out the mode, one must acknowledge the A flat in the guitar.
B: 01:43 - 01:45. Same as 00:21.
Ab and Db: 01:48 - 01:51. A variation on 00:21.
B and Bb (and Gb): 01:53 - 01:56. Another variation on 00:21 .
B: Passing notes in the guitar at 02:17 - 02:18 (ascending) and (maybe, but definitely not B-flat) 02:27 - 02:28.
B: 02:31 - 02:33. Guitar ascending passing tone.

album version, part II

B: 00:33 - 00:43. The topmost note of the rhythm guitar G chord.
B: 00:46 - 00:47. Passing tone.
B: 01:38 - 01:47. Same as 00:33 - 00:43.
B: 01:50 - 01:51. Same as 00:46 - 00:47.
B: 02:47 - 02:52. Keyboard G chord.
B: 02:56 - 03:01. Keyboard G chord.
Bb: 03:10 - 03:15. Keyboard Bb chord.
B: 03:14 - 03:15. Guitar (against Keyboard Bb chord!)

PULSE restored and re-edited
This is essentially the same as the album version of part II, except for the clear modulation to F from 01:24 - 01:43, which oscillates between F and Bb chords (temporary I and IV) before moving to a transitional C (V/F and bVII/D).
Bb chords occur during the guitar solo in the same context as the album version, part II, but more frequently. For example, 06:05 - 06:19.
Finally, during the guitar solo, at 04:43, there's a passing Eb.
Conclusion
It's easy to see why the song would be interpreted as Dorian: the primary note selection corresponds to that mode. B predominates by far, so can be considered far more influential in determining the mode than Bb. All other pitches (Db, Eb, Gb, Ab) are rare and clearly do not contribute to determining the mode. (Note that the Db in part I, 01:48, is playing the role of Db and not acting as the leading tone C#.)
However ...
This is not Dorian. To be truly modal, one would expect to hear far more of the B to emphasize the modality. Further, it would occur in different contexts. B only occurs when accompanied by G. In a truly Dorian setting, we would hear, say, B against the F chords, or in more rhythmically or melodically accented positions. Further, the only times we hear Bb, it's clearly intended as a chromatic alteration (part I, 01:53) or part of a modulation to F.
It's also not Tonal Minor. To be minor in the Tonal sense, there would have to be the presence of a leading tone; i.e., C#. This never occurs (see above regarding the Db).
It's also not Modal Aeolian (natural minor). To be Aeolian, Bb would be essential, and B to be avoided.
Therefore ...
The song is decidedly built around the D minor pentatonic scale, with lots of E for color, and a fair number of G-B pairs just to make things confusing also for color, but occurring through modal mixture via D major, rather than as an indication a true Dorian.
Comment: Major and minor tonality aren't defined by scale.  Pentatonic is.
Comment: I'll have to back up phoog here - you conclude by saying "The song is decidedly **`D` minor pentatonic**", with the "built around" not being clear enough, especially at this point.
Comment: How can this be pentatonic when it prominently features six pitch classes?
Comment: @phoog I said "built around", and gave a more than thorough explanation. How can a piece be in C major if it has an f# in it?
Comment: @phoog That's far too restrictive. Pieces built primarily around any particular scale can vary from that scale.
Comment: @Dekkadeci That's helpful, thanks. Does the revised language (just that sentence) better communicate the conclusion?
Comment: @Aaron Yes, the revised language for that sentence does communicate your conclusion better.
Comment: Sorry, was traveling for a bit so lost sight of this. "Pieces built primarily around any particular scale can vary from that scale": on what basis can one decide that a piece using  D, E, F, G, A, C is pentatonic with an added note or Dorian with an omitted note?  To me it seems that my comment is restrictive _because the definition of pentatonic is restrictive._  One prominent characteristic of the minor pentatonic scale is that it contains no half steps, so the opening phrases of the song with their emphasis on D-E-F-E-D put us squarely outside pentatonic territory. (also @Dekkadeci)
Comment: On top of that, your own analysis shows that B natural is prominent and B flat is used rarely for color.  The proposition that B natural should be more frequently juxtaposed against F to be "truly Dorian" doesn't have any basis.  This answer basically says "look how prominent B is, but it's not prominent enough to be Dorian."  The closer I look, the more I'm convinced that the analysis in this answer is correct and that it points to the conclusion that the song is correctly analysed as Dorian.
Comment: @phoog I don't restrict Dorian to B against F. That's an example of a larger concept, and I also describe the lack of B in rhythmically and melodically significant moments. The song, overall, does not have a "Dorian sound". My entire answer is built around your question of how one decides whether a piece using a particular note collection is interpreted one way or another, and harmonic, rhythmic, and melodic context is how that's done.
Comment: It sounds very much Dorian to me -- on account of the prominent B naturals, no less.  That B only occurs with G is not a convincing argument since G major, a chord featured prominently in this song (at rhythmically and harmonically significant moments, if not melodically) is among the principal elements that distinguishes D Dorian from D Aeolian.  You cite all this evidence in favor of Dorian but then discount it all without any firm reason.  I'd be interested to hear an example of a piece that you do think sounds Dorian.  It might help explain why you don't think this piece sounds Dorian.
Answer: I don't remember the details of the chorus, but B natural is pretty prominent throughout the verse. For instance the first chord after the d minor i chord is a G major IV chord. It's true that lots of professional transcriptions will still have a flat in the key signature, under the rule (which I think is a bad rule) that you should always use the nearest minor or major key signature, but the Bb is naturalized throughout the verse.
Again, maybe that changes for the chorus, in which case we would say that there's some kind of modal shift there, but the majority of the song is in D Dorian, regardless of any key signatures.
Answer: This song contains both B and B&flat. Putting it not into any mode, but squarely into D minor. Many pieces in D minor will use both these notes - they're found in the melodic minor scale.
But in any case, as Laurence Payne states - a song doesn't have to choose one mode and stick to it. There may be some rules pertinent in music, but that's certainly not one of them!


Unbound not forwarding query

Question: I'm having some trouble getting Unbound to forward queries correctly.
My current unbound.conf looks something like this:
  forward-zone:
      name: "google.com"
      forward-addr: 126.96.36.199

  forward-zone:
      name: "."
      forward-addr: 127.0.0.1@1066  # An Unbound server with a single catchall

  remote-control:
      control-enable: no

The 'google.com' zone returns correctly but the catch all zone doesn't. (Even though the query appears to be received and returned correctly on the 2nd unbound server)
Answer: I have the same problem, after searching I found the solution at the mailing list unbound-users: [Unbound-users] forwarders problem. Simply set:
do-not-query-localhost: no

Comment: It's worth noting that the above config option needs to be set in the `server:` section of the conf file.
Answer: I am a little confused, are you trying to query another server or the localhost on port 1066? If the latter you need to use the IP address that you have set under the interface portion of the config.
server:
     interface: <real ethX IP>

forward-zone:
  name: "."
  forward-addr: <real ethX IP>@1066

Unbound won't let you query localhost/127.0.0.1 by default.

Unbound not forwarding query


What is wrong with the following function $f:ON \rightarrow ON$?

Question: Define the following function on ON (The class of ordinals):
$f(0)=0$ and for every $\alpha >0$, if $\alpha$ is a successor then $f(\alpha) = \alpha -1$ and if $\alpha$ is limit then, $f(\alpha) = \alpha$.
I get, by this, a regressive function on the class of all ordinals, s.t. for each $\gamma \in ON$, the set $\{ \alpha | f(\alpha) < \gamma \}$ is bounded.
I think this can not be true so:
What is wrong with the function that I have defined?
Thanks
Edit: The reason I ask this is that if this is true then wouldn't it make the following exercise trivial?

$\bf 8.4$ If $X\subseteq\kappa$ is nonstationary, then there exists a regressive function $f$ on $X$ such that $\{\alpha:f(\alpha)\leq\gamma\}$ is bounded for every $\gamma<\kappa$.
     [Let $C\cap X=\varnothing$ and let $f(\alpha)=\sup(C\cap\alpha)$.]
Comment: Check the definition of "regessive" (hint)
Comment: What's the problem? If $f$ were the identity, then $\{\alpha \,|\, f(\alpha) \leq \gamma \} = \{\alpha \,|\, \alpha \leq \gamma \}$ were bounded too, no?
Comment: I added an edit
Answer: The function is not regressive at all on non-successor ordinals. Regressive means $f(\alpha)<\alpha$, but if $\alpha$ is not a successor, then $f(\alpha)=\alpha$.
This shows that the class of successor ordinals is not stationary. Which is what it should be, since the limit ordinals is a closed and unbounded class of ordinals.


Join folders in windows server 2k12r2

Question: I have a Windows Server 2012r2.  And due to poor planning on my side, i did not allocate enough space for the my documents folder.
I have added a new hard drive in the system, now I would like to have all of my documents folder be saved or joined on the new E drive.
I thought there was a 'join directory' command, but i cannot remember the actual name.
thank you
tony
Answer: You can do a couple of things.

Mount the new drive inside of your users folder. You do this through disk management (diskmgmt.msc). If you do this, it won't have a drive letter.
Configure your server to store profiles on the E:\ drive, and copy all of the profiles that are currently on C:\ to E:\
Comment: I love the idea of storing profiles on alternate locations...   would you suggest a good link so i learn more about the correct way to implement this?  thank you
Comment: http://answers.microsoft.com/en-us/windows/forum/windows_7-security/redefine-userprofile/e011afa5-e104-4a73-a1c6-54d22f8c02d3
Comment: this solution has provided me with the SAME results as the user that finished up with this comment...    Edit:

So Mo--- Fu--ing awesome: I am not allowed to access Explorer.exe any more.  I can't open My Computer or the Control Pannel.  AWESOME.

Join folders in windows server 2k12r2


Swift is not setting a value in return statement

Question: I have an issue which should not be an issue in my opinion.
When I load this 'simple' function, it should return the users within the DB.
 - returns usersDictionary: All the users in a dictionary
*/
func getAllUsers() -> Dictionary<String, AnyObject> {
     var usersDict = Dictionary<String, AnyObject>()

    if userIsLoggedIn() == true{
        FIRDatabase.database().reference().child("users").observeSingleEvent(of: .value, with: { (snapshot) in
            if let userDictionary = snapshot.value as? [String:AnyObject]{
                for user in userDictionary{

                    usersDict.updateValue(user.value as AnyObject
                        , forKey: user.key as String)

                }
                print("TEST")
                print(usersDict)
            }
            print("TEST2")
            print(usersDict)
        })
        print("TEST3")
        print(usersDict)
        return usersDict

    }
    return usersDict
}

However it does not return usersDict with value, but just empty which is strange because it prints out the value of TEST and TEST2 usersDict.
But Test3 remains empty, how is this possible? If I look in the Console, it does Test3 first and then test and then test2.
This is what console prints:
TEST3
[:]
TEST
"ZuUiTSu142P5NTc9VfekRbuFcny2": {
    address = "testAddress";
    email = "email@example.com";
    name = "testuser";
    phonenumber = "1234567890";
    rol = Customer;
}]
TEST2
"ZuUiTSu142P5NTc9VfekRbuFcny2": {
    address = " testAddress ";
    email = " email@example.com ";
    name = "testuser";
    phonenumber = "1234567890";
    rol = Customer;
}]

Comment: It's not strange at all: `observeSingleEvent` works **asynchronously**, the data is returned later in the closure. You need a completion handler, returning something directly is impossible.
Comment: Possible duplicate of [Returning data from async call in Swift function](http://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function)
Answer: @vadian is right on spot with his comment: You are trying to synchronously return a value in a function while you are fetching the data asynchronously. Everything happening with your // lines of code here:
FIRDatabase.database().reference().child("users").observeSingleEvent(of: .value, with: { (snapshot) in
  // ...
  // lines of code
  // ...
})

Is happening asynchronously. Meaning: it happens in the background, and whatever code you have after the observeSingleEvent call is executed first, hence you see TEST3 as the first line of output.
There are several different ways to design your code around an Asynchronous Model. Probably the easiest of which would be passing a Callback function to be called once the Async code finishes executing.
Sounds confusing? Don't worry, it IS confusing at first, but once you get it you'll be amazed by how simple the concept is.
I am not going to explain how Callbacks and Async works, but I would point you towards a similar problem that has a very good answer. Give it a look and you should get the idea.
Best of luck!
Answer: Thank you guys for the answers, maybe a little bit too late because I skipped this part for a while and focused on other things, but I looked at it today and managed to do it which on the end was very easy.
 func loadBusiness(busUID: String,with completion: @escaping(_ business: [String:AnyObject], _ error: NSError?) -> Void){
        FIRDatabase.database().reference().child("businesses").child(busUID).observeSingleEvent(of: .value, with: { (snapshot) in
            if let busDict = snapshot.value as? [String:AnyObject]{
                completion(busDict, nil)
            }
        }) { (error) in
            print("Error occured: " + error.localizedDescription)
        }
    }

Just a simple example on how I manage to do it and I can call it everywhere now with:
// Load basic company info
        db.loadBusiness(busUID: db.getMyUID()) { (business, error) in
            self.myCompany = business
        }


How could i configure drush to be always affirmative and verbose in a drush.ini-file?

Question: Could I configure drush for non-interacive usage from bash-scripts to be always affirmative as I would pass the --yes and -v-option in /etc/drush/drush.ini? I'm aware that I could set a bash-alias and that I could set it in /etc/drush/drushrc.php. But for reasons of clarity I'd like to use the ini-style-configuration.
Answer: Drush will not read options from php.ini / drush.ini by default.  Your best option would be to use a bash alias, or set $options['yes'] = TRUE; in a drushrc.php file.
If you really really have to set an option in drush.ini, you could hack this functionality by writing a policy file.  It would look something like this:
function policy_init() {
  if (ini_get('drush_yes')) {
    drush_set_option('yes', TRUE);
    // Drush does not expect a globla option to change
    // at this time, so you need to re-call _drush_preflight_global_options().
    // This is not a public API, so the name may change, etc.
    _drush_preflight_global_options();
  }
}

The only motivation I can see for doing this is if you already have some fancy mechanism for selecting your php.ini based on context.  If you wanted to do that, then put policy.drush.inc in ~/.drush, or some other location where Drush searches for commandfiles.
I have not tested this; post a follow-up comment if you really want to do this and have trouble with it.


Invertibility of a Matrix - Specifically Commutativity

Question: I am reviewing some Basic Linear Algebra.
They define:
A Matrix A is invertible if and only if there exists some matrix B such that $AB=I$ and $BA=I$.
So, in a slightly separate line of thought, I was wracking my brain trying to see if it is always the case that if $AB=I$ then $BA \neq I$. Essentially I was looking for a counter example. I wanted to show that if $AB=I$ then it is not enough to say that B is the inverse of A. I couldn't find an example. So it made me wonder if you could prove if $AB=I$ then $BA=I$ for basic matrix algebra.
I don't know know if this is possible. I appreciate any insights and or corrections. Similarly if you can provide one counter example then that would be most helpful also!!
Kind thanks MathExchange :)
Comment: These are possible ($AB=I$ and $BA\neq I$) when $A$ is not square.  For a square matrix $A$, $AB=I$ implies $BA=I$..
Comment: @hardmath correct. At least for the finite dimensional cases. Otherwise consider the left/right shift operator.  (But finite dim seems to be implied by the question)
Comment: @lalala:  Yes, I assume "Matrix $A$" means a finite number of rows and columns.
Comment: yes, deinitely for finite dimensional matrix.
Answer: For a square matrix $A$: if there is a matrix $B$ such that $AB = I$, then it will also be the case that $BA = I$.  Some proofs of this fact are presented here.
As for non-square matrices, we can say the following: if $A$ is $m \times n$ with $m > n$, then there can be no matrix $B$ such that $AB = I$.  When $m \geq n$, there exists a matrix $B$ such that $BA = I$ if and only if $A$ has "full column-rank", which is true if and only if the transformation associated with $A$ is injective.  If $m < n$, there can be no matrix $B$ such that $BA = I$.  When $m \leq n$, there exists a matrix $B$ such that $AB = I$ if and only if $A$ has "full column-rank", which is true if and only if the transformation associated with $A$ is surjective.


Why TS complains with function declarations inside function body

Question: I have this error from TS:

It's pretty clear why the error occurs:
function outer(){

   if (true) {
        function inner(){    // nested function declaration

       }
   }
}

but my question is - why does TS complain about that - is there some technical reason I should avoid nested function declarations when transpiling to ES5?
Would a function expression be a better choice, and why?
Comment: Possible Duplicate: http://stackoverflow.com/questions/10069204/function-declarations-inside-if-else-statements
Comment: Some useful links also here: http://stackoverflow.com/questions/33359840/functions-may-be-declared-only-at-top-level-in-strict-mode
Answer:
Would a function expression be a better choice

Yes. The following is the way to go:
function outer() {
  if (true) {
    const inner = function() { // OK
    }
  }
}

Why?

ES modules are in strict mode by default.
strict mode does not allow function declarations in blocks

Reason why it was disallowed is covered in the original JavaScript specification. Short version: The behaviour was inconsistent between implementations.

NOTE Several widely used implementations of ECMAScript are known to support the use of FunctionDeclaration as a Statement. However there are significant and irreconcilable variations among the implementations in the semantics applied to such FunctionDeclarations. Because of these irreconcilable differences, the use of a FunctionDeclaration as a Statement results in code that is not reliably portable among implementations. It is recommended that ECMAScript implementations either disallow this usage of FunctionDeclaration or issue a warning when such a usage is encountered. Future editions of ECMAScript may define alternative portable means for declaring functions in a Statement context.

So when strict mode came into being (ES5) it made it disallowed.


Why isn't text-color working in Tailwind css + next.js project

Question: I have a Next js project with tailwind. For whatever reason, certain colors work while others don't. For example:

{title ? <div className={`text-2xl mt-2 mb-2 ${title==='Valid Url!' ? 'text-blue-400' : 'text-red-400'}`}>{title}
 : null}

When I run the code and "title" is not null, text-blue-400 actually changes the text color. But when I run it with "title" as null text-red-400 doesn't actually change the text color. it just remains black. It's really odd because if I use text-red-500 it works!!!
this is my tailwind.config.js

module.exports = {
  mode: 'jit',
  purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {
      width: {
        '92': '23rem',
        '112': '28rem',
        '128': '32rem',
        '160': '40rem',
        '192': '48rem',
        '224': '56rem',
        '256': '64rem',
        '288': '72rem',
        '320': '80rem'
      },
      minWidth: {
        '20': '5rem',
        '400': '400px'
      }
    },
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

here are the imports in _app.js
import 'tailwindcss/tailwind.css';
import '../styles/globals.css';
import 'react-datepicker/dist/react-datepicker.css'

and finally this is globals.css
html,
body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
/*
a {
  color: inherit;
  text-decoration: none;
}

* {
  box-sizing: border-box;
}*/

.tooltip {
  display: none;
  position: absolute;
}

.has-tooltip:hover .tooltip {
  display: block;
  z-index:50;
}

If anyone can help I'd greatly appreciate it. Idk why this isn't working.
Comment: Does any other class other than `text-color` working properly?
Comment: I think you have some misconfiguration in your `_app.js`, because you `import 'tailwindcss/tailwind.css'` and `import '../styles/globals.css' at the same time. Please read [this part of the docs](https://tailwindcss.com/docs/guides/nextjs#include-tailwind-in-your-css) carefully.
Comment: Hi hisam, yeah this is the only tailwind related code that is not working properly. I'll try removing globals.css and instead just use css modules directly in components when needed. My globals.css file is super small anyways so not really necessary.
Comment: I removed my globals.css and I still have this issue. has anyone experienced something similar?
Comment: I was having the same issue and then I realized that I was not including a directory in the content: [] portion of the tailwind.config.js file. In my case it was './lib/**/*.{js,ts,jsx,tsx}'
Comment: I was having a similar issue before I discovered that including the `colors` property in the `theme` object in `tailwind.config.js` means you have to specify every color you want to use in the project (you no longer have access to the built-in colors by default). See https://tailwindcss.com/docs/customizing-colors#using-the-default-colors
Answer: Sometimes you need to stop and restart when installing Tilwindcss.
Did you try to stop it and run it again?

also, if you don't need the second conditional operator argument, you can use just
a double "&&"
<>
      {title &&
      <div className={`text-2xl mt-2 mb-2 ${title==='Valid Url!' ? 'text-blue-400' : 'text-red-400'}`}>{title}

      }
</>


How to parse only valid numbers in default locale using NumberFormat

Question: I'm using a NumberFormat instance to parse text using default locale.
If a string is not a valid numeric value, I have to return 0. The problem is that parse method,according to Javadocs:

Parses text from the beginning of the given string to produce a
  number. The method may not use the entire text of the given string.

So, if I parse (I'm using italian locale) "BAD 123,44" I correctly get a ParseException and return 0, but if I parse "123,44 BAD", I get a value of 123.44, while I have to return 0 in this case.
And worse, if I parse "123.44 BAD", I get value 12344!
 class RateCellReader {
      public static final NumberFormat NUMBER_FORMAT =
          NumberFormat.getNumberInstance(Locale.getDefault());

      ...

      try {
         number = NUMBER_FORMAT.parse(textValue);
      } catch (ParseException e) {
         number = 0;
      }

      ...
 }

How can I do an exact parse of text, or check if text correctly represent a number in default locale?
EDIT:
Getting inspired by the response linked by @yomexzo, I changed my code like this:
 class RateCellReader {
      public static final NumberFormat NUMBER_FORMAT =
          NumberFormat.getNumberInstance(Locale.getDefault());

      ...

      ParsePosition pos = new ParsePosition(0);
      number = NUMBER_FORMAT.parse(textValue,pos);
      if (textValue.length() != pos.getIndex())
          number = 0;

      ...
 }

Comment: A similar question was asked and answered in the link http://stackoverflow.com/questions/1102891/how-to-check-a-string-is-a-numeric-type-in-java
Comment: Thanks @yomexzo, that check is exactly what I was searching for!
Comment: But that is good for US/UK locale and you asked for default locale. It wont work for locales where . is not the decimal separator.
Comment: By asking for default locale I mean any default locale, not your :-)
I even specify that my default locale is Italian
Answer: How about this
    boolean isValid;
    try {
        Number n = NUMBER_FORMAT.parse(s1);
        String s2 = NUMBER_FORMAT.format(n);
        isValid = s1.equals(s2);
    }catch(ParseException e) {
        isValid = false;
    }

Comment: this fail to correctly parse values as "1234,56", because the formatter reformat them as "1.234,56". Or, if we use a format string without thousand separator, we got the opposite problem, with "1.234,56" reformatted as  "1234,56"
Comment: right, it was just an idea, the issues you mentioned seem to be fixable
Comment: Sure, but I feel the code I dervide from the answer linked by @yomexzo is simpler, more elegant and maybe faster (we avoid a reformat of the value)