Understanding why a vector topology is completely determined by any local base.

Question: What is shown below is a reference from the text Functional Analysis by Walter Rudin.
If $X$ s a vector space over the field $\Bbb F$ then  the following notation well be used
$$
x+A=\{x+a:a\in A\}\\
x-A:=\{x-a:a\in A\}\\
A+B:=\{a+b:a\in A\wedge b\in B\}\\
\lambda A:=\{\lambda a:a\in A\}
$$
for any $A,B\subseteq X$, for any $x\in\ X$ and for any $\lambda\in\Bbb F$.

Definition
If $\tau$ is a topology on a vector space $X$ such that

every point of $X$ is a closed set
the vector space operation are continuous with respect to $\tau$

we say that $X$ is a topological vector space equipped with the vector topology $\tau$.

So we note that the condition $1$ imply that any topological vector space will be $T_1$ but many authors omitted the above condition from the definition of a topological vector space.

Proposition
Let be $X$ a topological vector space over the field $\Bbb F$ and for some $v\in X$ and $\lambda\in\Bbb F$ we define the $v$-traslation and $\lambda$-multiplication functions through the condition
$$
T_v(x):=x+v\,\,\,\text{and}\,\,\,M_\lambda(x):=\lambda x
$$
for any $x\in X$. So the above two defined functions are homeomorphisms.
Proof. Omitted.

One consequence of the above proposition is that every vector topology $\tau$ is translation-invariant, that is a set $E\subseteq X$ is open if and only if each of its translates $v+E$ is open and thus $\tau$ is completely determined by any local base so that the open sets of $X$ are then precisely those that are unions of translates of memebrs of any local base.
So I like to discuss the last statement: indeed since a neighborhood is not union of basic neighborhoods then the image of local base undera traslation is not a base so what means that a vector topology is completely determined by any local base? Could someone help me to understand this statement, please?
Answer: If $\mathscr{B}_x$ is a local base at $x$, $\mathscr{B}_y=\{B+(y-x):B\in\mathscr{B}\}$ is a local base at $y$, and $\bigcup_{y\in X}\mathscr{B}_y$ is a base for the topology of $X$. In other words, we can get a base for the topology and therefore the whole topology directly from that one local base $\mathscr{B}_x$.
Comment: +1. To the OP, the point is that once we know a single local base we know the entire topology; it's in this sense that any local base determines the whole topology (analogously to how if $V,W$ are vector spaces and $f:V\rightarrow W$ is a linear map, the behavior of $f$ on any basis of $V$ determines the whole of $f$).
Comment: @AntonioMariaDiMauro: The argument in your first comment is fine. In any topological space $X$ it is true that if $\mathscr{B}_x$ is a local base at $x$ for each $x\in X$, then $\mathscr{B}=\bigcup_{x\in X}\mathscr{B}_x$ is a base for $X$: if $U$ is an open nbhd of some $x\in X$, there is a $B\in\mathscr{B}_x\subseteq\mathscr{B}$ such that $x\in B\subseteq U$.
Comment: @BrianM.Scott So fixed $x$ for any $y$ we observe that $x\in T^{-1}_{(y-x)}[U]=(x-y)+U$ for any neighborhoods $U$ of $y$ and so there exist $B\in\mathscr B_x$ such that $B\subseteq T^{-1}_{(y-x)}[U]$ so that $T_{(y-x)}[B]\subseteq U$ from which we conclude that $\mathscr B_y=T_{(y-x)}[\mathscr B_x]$ is a local base for $y$ (**right**?) but unfortunately I do not see why $\bigcup_{y\in X}\mathscr B_y$ is a base for $X$ so could you explain this, please? Forgive my confusion.
Comment: @BrianM.Scott Perhaps I understood. If $A$ is open then for any $y\in A$ there exist $B\in\mathscr B_x$ such that $y\in T_{(y-x)}[B]\subseteq A$ and so $A$ is union of this such opens, right?
Comment: Okay, all clear now. Thanks too much for your assistance!!!
Comment: @AntonioMariaDiMauro: You're welcome!


Função em Python de coluna para uma lista

Question: Preciso criar uma função que adiciona colunas de uma lista em outra lista na mesma ordem seguindo essa estrutura aqui (pode usar FOR).
def column_to_list(data, index):
    column_list = []
    # código entra aqui nesta parte
    return column_list

Como posso fazer isso? Ainda não aprendi direito a utilizar os argumentos em meu favor.
Um exemplo seria uma coluna Gênero, com diversas entradas de Masculino e Feminino. Preciso pegar estes resultados destas linhas e transformar em uma única lista.
output = ['M','F','F','M','F']
Comment: Quando for [edit] aproveita para colocar exemplos de resultados que a função deverá retornar.
Comment: Ainda precisamos de mais detalhes. Por favor, crie essa lista que possui diversas entradas de masculino e feminino e a partir dela nos mostre como seria a chamada da função que retornaria a saída citada.
Comment: Como que é o formato da entrada? A saída já temos. Passa exemplos de entrada (os dados que você insere por parâmetro em data e index) que a gente te ajuda pra obter aquela saída.
Comment: Opa, coloca em português, esse Stack Overflow é só nessa língua.
Comment: Desculpe, agora que percebi! Irei alterar!
Answer: banco = [['Carlos', 'M'],
         ['Frenanda', 'F'],
         ['Gilberto', 'M']]

def column_to_list(data, index):
    column_list = []
        for pessoa in data:
            column_list.append(pessoa[index])
    return column_list

generos = column_to_list(banco, 1)

ñ testei, mas 99% de chace de funcionar


Does the human voice qualify as noise?

Question: If we follow a common definition of noise, which is an aperiodic signal... Then is voice a noise? I've read lots of definitions on a certain free encyclopedia, but it could be that due to the nature of the site, I am mixing up terminology of different fields. Maybe it is neither, because it varies, since some consonants are periodic/more periodic than others(voiced), for example? But as what would you categorize it then?
Comment: Any plant that you don't want in your garden is a weed, no matter how beautiful it is. Same thing for sounds.
Comment: > common definition of noise, which is an aperiodic signal...

No, absolutely not.
Comment: @PeteBecker I was going to comment the same thing. The reverse also holds: any sound/plant that you DO want is not noise/weed no matter how ugly.
Comment: I planted an intentional 'meadow' in my back garden - it still has weeds. My neighbours have a lovely lawn, but all summer I consider their voices whilst they're sitting on it to be nothing but bl**dy noise! One man's meat is another man's fish, as they say...
Comment: The human voice has four [registers](https://en.wikipedia.org/wiki/Vocal_register). And qualifies as a string and a wind instrument. https://soundbridge.io/human-voice-instruments/ .... And art is anything worth more than its scrap value.
Comment: @ToddWilcox: Unless you're making [noise music](https://en.wikipedia.org/wiki/Noise_music), e.g. by shaping / filtering white noise.  There can be rhythm to the changes, but usually still has energy distributed across a wide band of frequencies most of the time, and thus most clearly described as "noise".  In that case it's sound you do want, even though it's noise.  (But if you were making a recording of noise music, and people were talking in the background, or playing a piano, that would be "noise" in the sense of signal to noise ratio and desired vs. not.)
Comment: @DataProcessing +1 Actually I'm struggling to find *any* application where the definition would be useful.
Comment: @JiK Okay okay, I just cited this from Wikipedia.
Comment: The English language version of Wikipedia that I read says that "there is no distinction between noise and desired sound" and that the only difference is how a brain perceives it.  It doesn't mention aperiodicity at all.
Comment: @DataProcessing Yes, it's a different language.
Comment: Can't resist: "in some cases, yes." :)
Answer: Your "common definition" is not usefully applicable to real signals since there are no truly periodic real signals (they all start and end at some point of time).
Signals can have recognizably limited-time near-periodic components, and numerous such components are building blocks of speech phonemes.  Other building blocks are spectrally colored noise (fricatives and plosives, with plosives having phase-coherence that fricatives lack) which has a more spread-out spectrum compared to the near-line spectra of near-periodic components.
"Noise" typically is the opposite of "signal", meaning that it does not convey information.  That is not really a good categorisation for parts of speech.  The normal distinction here is to talk about "voiced" and "unvoiced".
With regard to musical instruments, one uses "pitched" and "unpitched" in related categories, and the categories are somewhat fluid as well: timpani generally count as pitched and drums as unpitched, but tuning/detuning can make them rather similar.
Comment: You paired up terms, and separated linguistics, acoustics, electronics, and music very nicely.
Answer: Sounds produced by the human voice are too varied to fit into a single category. Rather that "the human voice qualifies as noise", it would be best to say "the human voice is capable of producing noise".
For example, singing "ah" on an open vowel, would not be noise by the definition offered. But clearing ones throat or growling would be noise.
Answer:
"...mixing up terminology of different fields..."

I was thinking you might be. When you mention "consonants", "voiced", it sounds like linguistics. On a music forum "voice" strongly implies singing, and that is at least similarly periodic to other musical instruments that I think most would qualify as not noise.

...I've read lots of definitions on a certain free encyclopedia...

Don't be coy. If you link the page and point out the key parts of the text, it might help clarify the issue.
Answer: The letter S is very noisy. So is letter T and K, and SH, CH. Consonants are often filtered noise. Vowels are harmonic. White TV noise is noise. Percussion is mostly noise, it spans many random frequencies. Ocean is mostly noise. Nearly all mammals produce mostly harmonic vocals. Voice is harmonic frequency formants with a little noise in it. Only sine tones are pure harmony. Only tv type noise is pure noise. Even seawaves and letter S have some tonal information.
https://en.m.wikipedia.org/wiki/White_noise
https://en.m.wikipedia.org/wiki/Colors_of_noise
Comment: @DanPiponi - You can get the same thing by tuning a radio between stations.  The static can be used as a noise machine for sleep.
Comment: I think white TV noise might be a thing from a bygone age :)
Comment: Synthesizers also have pink, red, and purple noise... https://en.m.wikipedia.org/wiki/White_noise ... https://en.m.wikipedia.org/wiki/Colors_of_noise
Answer:
a common definition of noise, which is an aperiodic signal

The important word there is actually "a". This is "a" definition of noise.

due to the nature of the site, I am mixing up terminology of different fields

You most certainly are.
From personal observation, English speakers hate making up words and would rather just repurpose old ones to have a new meaning and often this usage is figurative rather than literal. And of course you can do this multiple times to the same word. So a single word can actually can become multiple words that have the same spelling and pronunciation and are related by having a common ancestor, but aren't actually the same as the common ancestor and aren't the same as each other. (If they  have different spelling, they are called "doublets"...)
So you have a colloquial definition of "noise" (this is what you get if you ask a small child)--something that is loud, unpleasant, obscures whatever it is you're trying to hear, and so on. A loud, continuous hum from a fan would certainly be considered "noise".
And then you have new, specialized definitions of noise, each useful in their own context, but also could be considered as different words when compared to each other--for example, the "noise" in my photograph when the lighting is poor (not necessarily "loud", but random/with no meaning).
But you can't really treat them as the same word--any more than you can treat "guest" and "host" as the same word.
And to be complete, the definition you're using of noise is closer to the noise in my photograph, just an overly fancy way of saying "junk that is messing up the signal I was trying to send/receive".
Answer: As posted in the Music stack exchange, by that definition, yes voice is noise, as is pretty much everything other than string instruments. Wind instruments being are a close approximation of "not noise" and percussion is solidly "noise" and voice is somewhere in between. In the musical context that definition is trying to separate out harmonic sources from non harmonic sources.
If the same question was posted on a the signal processing stack exchange I would say that it is not noise. In that field voice channels are historically the most common signal transmitted, so you could ask about the signal to noise ratio of radio broadcast as someone speaking and would not consider the voice as part of the noise.
For a signal to be perfectly periodic it has to continue for all time, and since that can't happen in reality, everything is aperiodic to some extent so the definition breaks down at long time periods in reality as well.
One place where that definition is particularly useful is when analyzing the sounds various shapes make when perturbed (plucked, struck, etc). When you analyze a circle (E.G. a drum head) you will see that you get aperiodic signals (specifically Bessel functions), while if you analyze a line (E.G. a violin string) you will get sin functions that are periodic. If you run the same analysis on a human vocal tract, you don't get periodic sin functions so it is noise. On the other hand it is not "as noisy" as a drum head.

Does the human voice qualify as noise?


Is it possible to use Poisson Regression for binary outcome?

Question: First of all, I should say that I've just started to learn most of the terms I'll use in my question. Therefore I am sorry for any inconvenience I cause.
I have a dataset with 2000 instances. The dependent variable is a binary variable (either 0 or 1) and I have 3 independent varibles where one of them is categorical (Male or Female) and other two are continious (between 0 and 1). Here i a couple of examples:
     Gender       Freq_A       Freq_B Labels
1    Female 5.842289e-03 9.090465e-03      0
2      Male 3.180251e-03 4.009848e-03      1
3      Male 2.060638e-05 2.365917e-04      0
4      Male 1.930360e-02 3.868656e-03      0
5    Female 2.551375e-03 1.110913e-02      0
6    Female 3.564216e-02 3.755856e-02      1

I first apply logistic regression. However, the McFadden R2 I obtained was too small (6 e-3)
   llh       llhNull            G2      McFadden          r2ML          r2CU
-1.230380e+03 -1.239047e+03  1.733430e+01  6.995017e-03  9.583948e-03  1.281971e-02

Then, it has been told that maybe Poisson Regression might be a better fit for my case. However, all of the resources I read about Poisson regression was saying that it is a regression model best for explaning counting data.
But then I found that it can also be used for binary outcome. (Source: Poisson regression for binary outcomes , link) So, I decided to apply it in my data as follows:
mydata1 <- read.csv(fname)
mydata <- mydata1[sample(nrow(mydata1)),]
train <- mydata[1:1800,]
test <- mydata[1801:2000,]
model <- glm(Labels ~ Gender + Freq_A + Freq_B,family=poisson(link='logit'),data=train)

When I do that, I get error saying:

Error in family$linkfun(mustart) : Value 1.1 out of range (0, 1)

This error disappears if I don't use logit as a link  function however I think I should use it because my output variable is binary.
So basically, I am wondering what I am doing wrong and is it possible to apply poisson regression for binary outcome data in R ?
Answer: 1) Poisson regression is for Poisson outcomes, not for binary outcomes, so using Poisson regression for this is a bad idea indeed.
2) The logit link is for binary outcomes and probabilities, it won't work for Poisson regression.
3) McFadden R^2 is about predictive power, not about whether the model is appropriate. The value is low indeed, which indicates that you can't predict your binary variables well from your explanatory variables. It might be that another model would do a better job (there are other link functions for binary data, such as probit, and there are loads of supervised classification methods such as nearest neighbours with a suitable distance that could in principle be tried). However it might also be (and is often the case in practice in my experience) that your explanatory variables just don't carry much information about your dependent variable, in which case whatever you do will lead to a bad prediction quality. You might want to look at plots (or suitable tables) of your explanatory variables against your labels to assess how much hope there is to find something good.
Answer: Please see the same link again. It says that it uses "log" link rather than "logit".
Use "log" in link function.


"Digging Deeper" with Twig

Question: I created a custom twig file that outputs a few basic fields, such as images and text. Here's what my twig file looks like:

    {{content.field_image}}

    {{content.field_year}}

{{content.field_heading_text}}

I'm trying to have a little more control of the HTML that gets output. Here's what I'm seeing for a few of these fields:

I want to either, A, get rid of the div element that outputs "1963" or "Imagining a better world" or, B, get control over the div element so I can add a class to it and later style it.
Thank you in advance!
Answer: The easiest way to avoid the standard field divs is to only print out the first delta. That works well for single-value fields, for multiple, you'd need to loop over it yourself.
So, just do this: {{ content.field_year.0 }} and it will only print out the actual field content, without the wrapping field type. Might not work for every formatter, depending on what they do, but it should work for most of them.
Answer: The theme debug info in the source gives you a hint. If you want control of how certain fields are displayed you can create templates for them using a filename that refers to that specific field. For example if we wanted to change the output of the year we could create
field--field-year.html.twig

in the templates folder of your theme. First I would copy the default contents of the core field.html.twig file into field--field-year.html.twig first. You can find the default field template in /core/themes/classy/templates/field/field.html.twig.
In case you can't find it the contents are
{#
/**
 * @file
 * Theme override for a field.
 *
 * To override output, copy the "field.html.twig" from the templates directory
 * to your theme's directory and customize it, just like customizing other
 * Drupal templates such as page.html.twig or node.html.twig.
 *
 * Instead of overriding the theming for all fields, you can also just override
 * theming for a subset of fields using
 * @link themeable Theme hook suggestions. @endlink For example,
 * here are some theme hook suggestions that can be used for a field_foo field
 * on an article node type:
 * - field--node--field-foo--article.html.twig
 * - field--node--field-foo.html.twig
 * - field--node--article.html.twig
 * - field--field-foo.html.twig
 * - field--text-with-summary.html.twig
 * - field.html.twig
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - multiple: TRUE if a field can contain multiple items.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item's content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 *
 * @see template_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}
{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{% if label_hidden %}
  {% if multiple %}

      {% for item in items %}

{{ item.content }}

      {% endfor %}

  {% else %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
  {% endif %}
{% else %}

{{ label }}

    {% if multiple %}

    {% endif %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
    {% if multiple %}

    {% endif %}

{% endif %}

Once you copy and paste that into your field--field-year.html.twig you can start editing it however you want. If you change

{{ item.content }}

to
{{ item.content }}

It will output only the content of the field not the surrounding div or classes.
Answer: cp themes/custom/aqair/templates/field/field.html.twig themes/custom/aqair/templates/field/field-string.html.twig

Or any of the other suggestions noted in your twig debug, then just edit the template to not include the surrounding div element.
Clear your cache drush cr

"Digging Deeper" with Twig


Dynamic Programming problem help. Maximizing stair sum given a set number of steps

Question: I have to create a dynamic programming solution to the following problem:
Given a set of n stairs, such that each step of the stairs has a positive value how can we maximize the value if we are allowed k steps up the stairs and we can choose to skip 1 or 2 steps at a time
Example:
Given arr: 5, 1, 6, 2, 8, 9  n=6
k = 3 we would take 6,8,9
k = 2 we would take 6,9
k = 1 we could not make it to the top of the stairs, furthest we could get is to value 6
k=n we would take all the steps

What's tripping me up is the fact that you have to take the last value (to make it to the top of the stairs) and you have to take values in such a way that you can actually reach the end. Any help, or pointers in the right direction would be appreciated, thanks!
Update:
I was able to cache the recursive calls and reach O(n*k), not sure how to achieve a DP solution from here.
int myMem(int arr[], int n, int L)
{
count += 1;
if (L == 0 && n < 1)
    return 0;

if (L == n/3)
{
  if(mem[n-1][L] == 0)
    mem[n-1][L] = myMem(arr, n-3, L-1);
  return arr[n-1] + mem[n-1][L];
}

if (n < 1)
    return INT_MIN;

if (L > n/3)
{
    if(mem[n-1][L] == 0)
        mem[n-1][L] = myMax( myMem(arr, n-1, L-1), myMem(arr, n-2, L-1), myMem(arr, n-3, L-1));

    return arr[n-1] + mem[n-1][L];
}
return INT_MIN;
}

Answer: We can have a naive recurrence that considers fixing each used step and taking the best of the possible steps that came before it. Note that the answer in that case is one of three (assuming there are at least three steps) since we can reach the top from either of the last three steps.
Top-down JavaScript code without memoisation (bottom-up left to the reader):

function f(A, n, k){
  if (k == 0 && n < 1)
    return 0

  if (k == n / 3)
    return A[n-1] + f(A, n - 3, k - 1)

  if (n < 1)
    return -Infinity

  if (k > n / 3){
    return A[n-1] + Math.max(
      f(A, n - 1, k - 1),
      f(A, n - 2, k - 1),
      f(A, n - 3, k - 1)
    )
  }

  return -Infinity
}

var A = [5, 1, 6, 2, 8, 9]
var n = A.length
var k = 3

console.log(`A: ${A}`)
console.log(`k: ${k}`)
console.log(`max of (${f(A, n, k)}, ${f(A, n - 1, k)}, ${f(A, n - 2, k)})`)
console.log('')

k = 2

console.log(`k: ${k}`)
console.log(`max of (${f(A, n, k)}, ${f(A, n - 1, k)}, ${f(A, n - 2, k)})`)
console.log('')

k = 1

console.log(`k: ${k}`)
console.log(`max of (${f(A, n, k)}, ${f(A, n - 1, k)}, ${f(A, n - 2, k)})`)
Comment: I was able to modify your recursive approach to cache the recursive calls. I'm not sure how to jump to DP from here though.
Comment: @JeremyLeon if the recurrence works and makes sense, we can think of each call to `f` with a smaller `k` or `n` as a lookup in the DP table of a cell we already iterated on as we build bottom-up. If you can get the table initialised using the base case logic, you could then try to use the recurrence logic, assigning to the current cell.


How do I add og:image script in meta?

Question: My facebook is grabbing the wrong image.
I try to adding this open graph image in my head.
<meta property="og:image" content="<?= $_GET['image'] ?>" />

and
<meta property="og:image" content="<?php echo $image; ?>"/>

but the content image path is not shown.
It became this
<meta property="og:image" content="" />

I want it to be like this.
If the article A have image a_name.jpg, the meta will be <meta property="og:image" content="/images/a_name.jpg"/>
If the article B have image b_name.jpg, the meta will be <meta property="og:image" content="/images/b_name.jpg"/>
Answer: You need to supply the tag the full URL to the image. If you install the Metatag module not only can you have full control over keyword, description, etc. but also all the og tags too per node.
Comment: I want the Metatag open graph image has a unique image path in every pages.

Insert a URL will define showing the same image all articles.
Comment: Yes that's exactly what I'm saying, and the Metatag module does it for you
Comment: What is the code should I put?
Comment: No code, install the module and when editing the node in the vertical tabs at the bottom one is called Meta tags and you can override the default settings
Comment: I get you. It needs to add in every node.

How do I add og:image script in meta?


How to debug 404 on user/login user/register user/logout?

Question: I have a Drupal 8 site on 8.4.2.  When I upgrade it to 8.5.1, after running the database updates, the paths /user/register, /user/login, and /user/logout return a 404.

I can log in with Drush (drush uli myuser), so it is possible to actually log in, but the log in page is not displayed.
I tried uninstalling my custom modules, but the problem persists.
I looked at /admin/reports/dblog, but it just says "page not found" as the error for /user/login.

This question about a similar problem was closed as off topic because it was too specific; my question is about "how can I debug this?" not "what is the cause of my problem?"
Comment: https://www.drupal.org/forum/support/upgrading-drupal/2018-03-30/since-upgrading-to-851-userlogin-userlogout-userregister added this on the drupal support forum and also put the problem on the Drupal Support group in Facebook.
Comment: I have exactly the same problem going from 8.6.4 to 8.5.1...  I'm in the process of making a module to check the routes that exist.
Comment: I checked the routeProvider and the settings match the expected values and exist properly.  Also tried adding some debug stuff into the form that is called and the controller that manages it all.  Nothing shows.  It feels like the symphony router is not getting as far as loading the login process before it gives a 404... more investigations tomorrow.
Comment: Checked with Devel and it says "Unable to load route for url '/user/login'" when checking the user.login route.
Answer: @AndrewKillen:

Checked with Devel and it says "Unable to load route for url
  '/user/login'" when checking the user.login route.

How this could be debugged (on an working example, because I don't have a broken site):
Enable Xdebug and go to the url: /devel/routes/item?path=/user/login
Drupal\devel\Controller\RouteInfoController::routeDetail:
  public function routeDetail(Request $request, RouteMatchInterface $route_match) {
    $route = NULL;

    // Get the route object from the path query string if available.
    if ($path = $request->query->get('path')) {
      try {
        $route = $this->router->match($path);

Set a breakpoint for the last line and step into match($path). Then after a new request with the path info is created you get to:
Router::matchRequest:
  public function matchRequest(Request $request) {
    $collection = $this->getInitialRouteCollection($request);
    if ($collection->count() === 0) {
      throw new ResourceNotFoundException(sprintf('No routes found for "%s".', $this->currentPath->getPath()));
    }
    $collection = $this->applyRouteFilters($collection, $request);

    if ($ret = $this->matchCollection(rawurldecode($this->currentPath->getPath($request)), $collection)) {
      return $this->applyRouteEnhancers($ret, $request);
    }

getInitialRouteCollection() results in three possible matches:

user.login
user.login.http
entity.user.canonical

The second one is filtered in applyRouteFilters() because this is POST only and for JSON. The entity route is removed after the compiled routes are matched in matchCollection() because "login" is not a valid user.
And so the route user.login is the last one remaining and returned. If not you have to check where on this way the route is not collected or filtered out.
Comment: the problem (thanks to luis below) is that we had a view that is on /user/% that normally showed the Author stories as a list when clicking on the authors name on an article, and also re-direct from /user/UID to /author/author-name.

Removing that view allows for the login/logout/register to be visible.
Comment: OK, in this case you would have seen this view route while debugging the route match.
Comment: @4x4 I'm still going to go through the debug process to see that things are truely fixed and we are dealing with these overview pages properly along with the login/logout pages.  Many thanks indeed for your time and help
Comment: Thanks Andrew - that was it for me as well. Commenting just in case anyone else hits this snag - I had a view set to /user/content and even that was messing with the default routing of /user. Changed from /user/content to /content/all and voila, it works again.


Procurar valores duplicados - Excel

Question: Como retornar uma empresa com base em um valor, mesmo que a Matriz tenha varios duplicados. Pode retornar o primeiro encontrado.
Comment: `=PROCV` procura somente na primeira coluna, então não é recomendada para procurar numa matriz 2D.
Answer: Resolvi utilizando a função matricial:
<code>{=SEERRO(ÍNDICE($A$1:$C$1;;MENOR(SE((COL($A$2:$C$5)-COL($A$2)+1)*($A$2:$C$5=$F$2)=0;99;(COL($A$2:$C$5)-COL($A$2)+1)*($A$2:$C$5=$F$2));COL(B1)));"")}</code>

Procurar valores duplicados - Excel


How could I do a FULL OUTER JOIN?

Question: What code should I use to execute the following SQL query?
SELECT column_name(s)
  FROM table1
  FULL OUTER JOIN table2
  ON table1.column_name = table2.column_name;

Answer: Dynamically it would look like this:
$q = db_select('table1')
  ->fields('table1', array('column_name'));

$q->addJoin('FULL OUTER', 'table2', NULL, 'table1.column_name = table2.column_name');

Which will give you
SELECT table1.column_name AS column_name
FROM
{table1} table1
FULL OUTER JOIN {table2} table2 ON table1.column_name = table2.column_name

Or you can run any SQL string with db_query():
$sql = <<<SQL
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;
SQL;

$result = db_query($sql);

Comment: what is the NULL?
Comment: It's the desired alias for the table - if it's omitted one will be generated for you
Comment: look at this thing: $type: The type of join. Typically one one of INNER, LEFT OUTER, and RIGHT OUTER. It do not have FULL OUTER
Comment: WOW also look at this: http://stackoverflow.com/questions/4796872/full-outer-join-in-mysql it says that in mysql we have no full outer... :'( What is going on?
Comment: That's correct, MySQL doesn't support such a join. The code above makes the necessary assumption that you're using a DBMS which _does_ support it.
Comment: with db_query() how I can add a range and a codition?
Comment: with db_query code it gives me: syntax error, unexpected end of file why this error takes place??

How could I do a FULL OUTER JOIN?


Melhor forma de fazer preload em AngularJs num Ionic app

Question: Estou com uma dúvida de arquitetura de apps.
tenho um projeto IONIC onde o app salva alguns dados básicos no local storage para não ter de pedir login do usuário toda vez que é aberto.
Porém esses dados são essenciais pro restante da aplicação.
atualmente eu tenho as seguintes rotas de entrada:

'app.home' -> quando os dados já existem no localstorage
'app.login' -> quando os dados não existem e é preciso fazer login.

o negócio é que é na rota 'app.home' que eu faço a verificação do localstorage e dalí decido se permaneço na rota ou direciono para 'app.login'. Só que na 'app.home' eu já preciso de dados que deveriam estar no localstorage, e quando quando redireciona pra login e depois volta pra home, essa view já havia sido carregada e os dados salvos depois do login não atualizam essa view.
Então pensei, 'qual seria a melhor forma de fazer, então, esse preloader dos dados e direcionar para login ou home comforma a necessidade?'.
Essa é a questão.
Answer: Não é "na rota" que você faz a verificação do localStorage, é no controller dela.
Veja, você está executando um código que não pertence ao controller em questão.
Melhor seria definir qual é a rota a ser carregada antes de entrar em um controller específico:
<code>angular.module('App', [ 'ionic',...])

.run(function($state) {

     //faça sua pesquisa na localstorage aqui
     if ( ... ) {
            $state.go('app.home');
     else {
            $state.go('app.login');
     }

});
</code>


Confusion on hinge loss and SVM

Question: I'm reading a book on data science and get confused about how the book describes the hinge loss of SVM. Here is a figure from the book on Page 94:

This figure shows the loss function of a NEGATIVE instance. It seems there is no penalty if the instance lies within the margin even on the positive side. Also on Page 95, the author explains:

However, from what I read about SVM, there should be penalty as long as the negative instance lies within the negative margin or on the wrong side. I updated the loss function as below with orange color:

Can someone tell me if I'm correct or not? Thanks!
Updates:
In Wikipedia, it says:

Correctly classified points lying outside the margin boundaries of the support vectors are not penalized, whereas points within the margin boundaries or on the wrong side of the hyperplane are penalized in a linear fashion compared to their distance from the correct boundary
Answer: Searching for the quoted text, it seems the book is Data Science for Business (Provost and Fawcett), and they're describing the soft-margin SVM. Their description of the hinge loss is wrong. The problem is that it doesn't penalize misclassified points that lie within the margin, as you mentioned.
In SVMs, smaller weights correspond to larger margins. So, using this "version" of the hinge loss would have pathological consequences: We could achieve the minimum possible loss (zero) simply by choosing weights small enough such that all points lie within the margin. Even if every single point is misclassified. Because the SVM optimization problem contains a regularization term that encourages small weights (i.e. large margins), the solution will always be the zero vector. This means the solution is completely independent of the data, and nothing is learned. Needless to say, this wouldn't make for a very good classifier.
The correct expression for the hinge loss for a soft-margin SVM is:
$$\max \Big( 0, 1 - y f(x) \Big)$$
where $f(x)$ is the output of the SVM given input $x$, and $y$ is the true class (-1 or 1). When the true class is -1 (as in your example), the hinge loss looks like this:

Note that the loss is nonzero for misclassified points, as well as correctly classified points that fall within the margin.
For a proper description of soft-margin SVMs using the hinge loss formulation, see The Elements of Statistical Learning (section 12.3.2) or the Wikipedia article.
Comment: I've got to add here: great graph and explanation. I directly got the point by glancing at the graph alone, something other explanations (such as Wikipedia's) failed to do so.
Comment: @AlbertoA Thanks glad it was useful to you
Answer: The (A) hinge function can be expressed as
$$y_{i} = \gamma \max{\left(x_{i}-\theta, 0\right)} + \varepsilon_{i},$$
where:

$\gamma$ is the change in slope after the hinge. In your example, this amounts to the slope following the hinge, since your hinge-only model (see below) assumes zero effect of $x$ on $y$ until the hinge.
$\theta$ is the point (in $\boldsymbol{x}$) at which the hinge is located, and is a parameter estimated for the model. I believe your question is answered by considering that the location of the hinge is informed by the loss function.
$\varepsilon_{i}$ is some error term with some distribution.

Hinge functions can also be useful in changing any line:
$$y_{i} = \alpha_{0} + \beta x_{i} + \gamma \max{\left(x_{i}-\theta, 0\right)} + \varepsilon_{i},$$
where:

$\alpha$ is the model constant, and the intercept of the curve before the hinge (i.e. for $x < \theta$). Of course, if $\theta < 0$, then the curve intersects the $y$-axis after the hinge so $\alpha$ will not necessarily be the $y$-intercept of the bent line.
$\beta$ is the slope of the line relating $y$ to $x$
$\gamma$ is the change in slope after the hinge.

In addition, the hinge can be used to model how a functional relationship between $y$ and $x$ changes form, as in this model where the relationship becomes quadra
$$y_{i} = \alpha_{0} + \beta x_{i} + \gamma \max{\left(x_{i}-\theta, 0\right)^{2}} + \varepsilon_{i},$$
Comment: Hi Alexis, thanks for your great input. Actually I'm confused about whether there are different hinge functions defined for SVM or just this is a typo in the book.
Comment: Well, I gave you an example of another hinge function in my last equation.  Hinge functions can also be defined sequentially, as in slope changes at more than a single point. They can also be defined using the $\min()$ function, instead of $\max()$.

Confusion on hinge loss and SVM


Receiving jQuery JSON data as JSON in PHP

Question: I guess this is the opposite of normal case. I wish to receive the data in PHP as String with JSON in it, and I wish jQuery to Encode the data.
currently PHP decodes automatically the data to an array.
PHP 5.3.10 ( hosted ).
<?php
if( isset( $_REQUEST['arr']))
{
    $arr = $_REQUEST['arr'];
    $obj = $_REQUEST['obj'];
    $res = "arr is of type ".gettype( $arr).", var_export (".var_export( $arr, true).")\n"
         . "obj is of type ".gettype( $obj).", var_export (".var_export( $obj, true).")\n";
    die( json_encode( $res ));
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>test</title>

<form><input type="submit" value="click" id="csubmit"></form>

Result is always
Got back:(arr is of type array, var_export (array (
  0 => 'one',
  1 => 'two',
))
obj is of type array, var_export (array (
  'one' => '1',
  'two' => '2',
))
)

even though I'd like it to be a few strings.
Answer: You can encode your JavaScript object to JSON before sending it to server. Then you have to manually decode the json to use it as an array. In your ajax method do something like following.
   data : JSON.stringify(data),

EDIT:
JSON object is natively supported in newer browsers. For those that do not support it you can still achieve the functionality by including json2.js from http://json.org.
For more info on JSON visit https://developer.mozilla.org/En/Using_native_JSON
Comment: In order to encode objects to JSON, you will need to donwload this API: http://www.json.org/js.html
Answer: Ommit the dataType: 'json' in an AJAX request, encode the data to a JSON within a jQuery and pass it to the PHP.
That should work.
Answer: While you are accepting back JSON, you are sending normal form-encoded data (application/x-www-form-urlencoded):
arr%5B%5D=one&arr%5B%5D=two&obj%5Bone%5D=1&obj%5Btwo%5D=2

aka
arr[]=one&arr[]=two&obj[one]=1&obj[two]=2

You can confirm this from PHP by doing
$raw_input = file_get_contents("php://input");
echo urldecode($raw_input);

You are not sending {"arr":["one","two"],"obj":{"one":1,"two":2}} unless you explicitly convert in JavaScript, as the others have noted.
Comment: Good point. Seems dataType json does not make jQuery to send the arrays as JSON.
Comment: I was initially confused by that too, but ```dataType``` is what we expect back from the server.  You can send JSON in the way you'd expect by using passing the options ```data: JSON.stringify(data), processData: false, contentType : "application/json"``` to $.ajax(), but it's awkward to catch with PHP


Solution for derivative example

Question: I trying understand derivatives and faced with this example, but my low math background don't allow me undestand all steps of this solution.
Can anyone clarify for me in details every step of this example.
$$\begin{align}
{\partial \over \partial \theta_{j}}J(\theta)&={\partial \over \partial \theta_{j}}{1\over 2}(h_{\theta}(x)-y)^{2}\\
&=2.{1\over 2}(h_{\theta}(x)-y).{\partial \over \partial \theta_{j}}(h_{\theta}
(x)-y)\\
&=(h_{\theta}(x)-y).{\partial \over \partial \theta_{j}}(\sum_{i=0}^{n}\theta_{i}x_{i}-y)\\&=(h_{\theta}(x)-y)x_{j}\end{align}$$
Comment: Any particular point you don't understand?
Comment: There are are lot of elements in that that doesn't have a mening without any context.
Comment: @Henrik: Things are pretty easy to understand from just the given elements: it seems that $\theta = (\theta_1, \dots, \theta_n)$ and $J(\theta) = \frac 1 2  (h_\theta (x) - y)^2$ with $h_\theta (x) = \sum _{i=0} ^n \theta_i x_i - y$, and $x = (x_1, \dots, x_n)$ and $y$ being constants.
Comment: @AlexM. Thanks, Alex. All right.
Comment: The notation suggests that $\theta$ must be a vector or tuple of parameters, in order for those partial derivatives to make sense.  But we lack a definition of $J(\theta)$ necessary to proceed in taking these partial derivatives.
Answer: Do you know the chain rule? Look that up. And apply it to your Q. What part are you actually stuck on? What subject is it for? Regression analysis? What do the terms mean?
Comment: Right, it's from regression analysis. J is a cost function, theta - parameter
Comment: Okay, well apply the chain rule as mentioned above. Substitute in $x-j$. Which is what by the way?
Comment: Edit: $x_j$ term
Comment: I don't know chain rule. Thanks for this rule, I need learn it before I will can understand your advices.
Answer: I am giving you an example to explain few basics.
Let y = $(2x + 1)^3$
Then differentiate with respect to x.
First we have to differentiate the power then term.
So we have,
$\frac{dy}{dx} = 3(2x+1)^{3-1} \cdot \frac{d}{dx}(2x + 1)$
$\frac{dy}{dx} = 3(2x+1)^2 \cdot (2.1.x^{1-1} + 0)$
As differentiation of constant term is zero.
So we have,
$\frac{dy}{dx} = 3(2x+1)^2 \cdot 2 $

Edit -

Here are some formula you can see and learn.
Comment: Can you clarify, why multiplier 3 appear in first term and why we decrease a degree 3 by one?
Comment: I provided a link. See 4th formula.
Comment: In place of x any term is used.
Comment: I understand what in practice we need use list of formulas like this, for resolving any derivative expression? Right?
Comment: Formula are only one part. Practice is important thing. You can start with easy questions and after sometime you can do any question.
Comment: In your question in first step derivative for power  2 comes forward and power of function becomes 1. Then now we have to differentiate term.
Comment: In third term h(x) replaced by value. Then in next step its derivative.
Comment: Great thanks! You really helped me undestand question better.
Comment: Derivative of y w.r.t theta is 0.
Comment: Your welcome. From the next time please add what you tried. So that no one can down vote your question. I upvoted your question because you are new here and your question not enough bad.

Solution for derivative example


Python: replacing a variable in a looping list

Question: I'm trying to go through a list and print out the list using a secondary list of variables.
The problem is that the variables in the list are getting assigned and set, but are not getting printed out properly. This feels like something really simple but I've been stumped for a day or so on it. Any help would be appreciated!
side = ""
sideLong = ""
sideShort = ""
sideList = ["Right", "Left"]

jointRemapList =[
    ["Char_Hips", "Root_M"],
    ["Char_" + sideLong + "Finger1", "IndexFinger1_" + sideShort],
    ["Char_" + sideLong + "Finger2", "IndexFinger2_" + sideShort]
    ]

for side in sideList:
    sideLong = side
    sideShort = side[0]

    for jointPair in jointRemapList:

        print sideLong, sideShort, jointPair

Expected output would be:
Left L ['Char_Hips', 'Root_M']
Left L ['Char_LeftFinger1', 'IndexFinger1_L']
Left L ['Char_LeftFinger2', 'IndexFinger2_L']
Right R ['Char_Hips', 'Root_M']
Right R ['Char_RightFinger1', 'IndexFinger1_R']
Right R ['Char_RightFinger2', 'IndexFinger2_R']

Comment: Python doesn't keep pointers to variables this way. `"foo" + bar` is not the string "foo" with the suffix of "whatever bar is when we print it", `bar` is evaluated *immediately* and the string is "foo" + "whatever bar is right now."
Answer: I think the problem is happening because you are creating jointRemapList outside of your sideList loop. You want the list to be created dynamically by sideLong and sideShort, so you need to recreate it on each increment of your loop. Like the following:
side = ""
sideLong = ""
sideShort = ""
sideList = ["Right", "Left"]

for side in sideList:
    sideLong = side
    sideShort = side[0]

    jointRemapList =[
        ["Char_Hips", "Root_M"],
        ["Char_" + sideLong + "Finger1", "IndexFinger1_" + sideShort],
        ["Char_" + sideLong + "Finger2", "IndexFinger2_" + sideShort]
        ]

    for jointPair in jointRemapList:

        print sideLong, sideShort, jointPair

Comment: I agree this is the better solution, though it's going to be a bit slower than the `str.format` approach of Jared's.
Answer: So the issue is that you are creating the strings when jointRemapList is created, and updates to sideLong and sideShort are not going to be reflected in those strings because strings are immuatable. Try using string formatting instead.
from itertools import product

joint_remap_list = [
    ["Char_Hips", "Root_M"],
    ["Char_{side}Finger1", "IndexFinger1_{abbrev}"],
    ["Char_{side}Finger2", "IndexFinger2_{abbrev}"]
]

sides = ["Left", "Right"]

for side, pair in product(sides, joint_remap_list):
    abbrev = side[0]
    formatted = [s.format(side=side, abbrev=abbrev) for s in pair]
    print side, abbrev, formatted

Comment: consider defining the formatted list on a separate line. `fmtd_joint_pair = [s.format(long=sideLong, short=sideShort) for s in jointPair]; print sideLong, sideShort, fmtd_join_pair` feels nicer to me.


Number of Total orders of a dependency graph

Question:  Define a dependency graph to be a graph $G=(V,E)$ such that an edge between vertices $v$ and $u$ in $V$ is present if $v<u$ i.e. $v$ comes before $u$ in our ordering (I'm not very concise here, I just want to give you my idea).  My quesion now is how many total orders do we have on such a graph ? Is there a closed formula for this?
 What I thought of doing is make something like a decision tree that has as root the first element in the ordering and as leaves the final one and do topological sorting on the graph to produce paths from the root to the leaves
 As a concrete example lets look at the graph below. I know that it has 30 total orders.
Comment: I think without more information about the graph all you can say is that it's somewhere between 1 and $|V|!$, which is not very useful.
Answer: It appears in your example that your dependency graph consists of a collection of total orders, each independent from each other.  With this restriction, the solution you seek is $$\frac{n!}{n_1!n_2!\cdots n_k!}$$
Where there are $k$ total orders, and the $i^\textrm{th}$ contains $n_i$ elements, and there are $n=n_1+n_2+\cdots+n_k$ total elements in your graph (not counting the max and min).
In the example shown $n_1=2, n_2=1, n_3=2, n=5$.
The explanation is as follows: we begin with $n!$ orders on the $n$ elements.  However, within each of the $k$ columns, we must choose a linear order that respects the original order of that column; exactly $\frac{1}{n_i!}$ of the linear orders respects the order of the $i^\textrm{th}$ column.
Comment: Oh thanks, I didn't think of using multinomial coefficients for this :D Now I see it !


Como deixar o @EditorFor desativado?

Question: Estou fazendo um projeto de CRUD no ASP NET MVC na parte de editar as informações o código do time está sendo puxado do banco e está aparecendo no @EditorFor e gostaria de fazer com que ele não pudesse ser editado. como se fosse um readonly do html
Segue o código do campo:
@Html.EditorFor(model => model.cd_time, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.cd_time, "", new { @class = "text-danger" })

Answer: Somente acrescente readonly na parte dos atributos:
@Html.EditorFor(model => model.cd_time, new {
    htmlAttributes = new { @class = "form-control", @readonly="readonly" }
})

Referencias:

InputExtensions.TextBox Method
How to create a readonly text using html helper in asp.net mvc?
HTML  readonly Attribute
Comment: consegui! obrigada!
Comment: Se for util assinale como resposta da sua pergunta @BeatriceBenetti

Como deixar o @EditorFor desativado?


Carregar codigo de acordo com dispositivo

Question: O trecho abaixo é similar ao que tenho na pagina inicial do site:

        <a href="<?php echo get_site_url(); ?>/texto-1/">texto 1
       <a href="<?php echo get_site_url(); ?>/texto-2/">texto 2
        <a href="<?php echo get_site_url(); ?>/texto-3/">texto 3

Nesse codigo tem php e html, a minha duvida é sobre quais funções do jquery posso estudar para possibilitar imprimir esse trecho no código dependendo do tamanho do dispositivo (desktop, celular, etc) usado?
Sei que é possivel usar @media queries como referencia ao carregar, mas como capturo isso com o jquery, quais funções possibilitam isso
Comment: A questão é como capturo o tamanho do dispositivo, ao carregar a página, pelo DOM
Comment: Como assim "imprimir esse trecho no código"? Quer que essa div só exista no código-fonte da página em um certo tipo de dispositivo? Não há Javascript no mundo que faça isso.
Comment: Agradeço resposta, mas acredito ser possivel, sobre imprimir acho que pode usar o `.append()`, depois de uma condicional que verifica o tamanho do dispositivo usado
Answer: Você não precisa de jQuery. Com Javascript puro você consegue acessar o objeto screen da variável global window e obter a resolução da tela, i.e.:
console.log('Minha resolução é ' + screen.width + 'x' + screen.height);

Note que isso é a resolução do dispositivo. A área realmente visível da sua página, com o navegador maximizado, será quase sempre um pouco menor.
Agora, lembre-se sempre:

Resolução não é tamanho. Um tablet ou mesmo um celular high end podem ter a mesma resolução de um monitor antigo, em uma tela menor;
Nunca tente determinar o tipo do dispositivo pela resolução de sua tela. Hoje existem ecrãs grandes que são sensíveis a toque, por exemplo, então você pode servir-lhes interfaces amigáveis. Caso deseje realmente segregar seu conteúdo por dispositivos diferentes, trate-os por capacidades, não por resolução (nem por useragent). Eu tenho algumas respostas mais elaboradas sobre o assunto em algumas perguntas anteriores:

Identificar se o dispositivo é pc ou celular e utilizar um código diferente pra cada
Executar javascript apenas quando acessar o site de um celular
Como detectar um dispositivo móvel em Javascript?
Comment: `if (screen.width < 640 || screen.height < 480) {
    // sirva a versão pra celular
}...` Obrigada Renan, é exatamente isso
Answer: Com Jquery tem como vc capturar o tamanho da viewport com o código:
$( window ).width(); e $( window ).height();
Ainda não está muito claro o que você deseja fazer, mas creio q se vc utilizar esta forma para buscar a largura e a altura atual da sua viewport, vc possa fazer os calculos que deseja.
Comment: Usar jQuery para obter esses valores é como usar um tiro de escopeta para matar uma mosca. Além disso esse é o tamanho da janela, não a resolução do dispositivo.
Comment: Eu apenas respondi o q ele perguntou. Ele quis saber como capturar o tamanho por Jquery, E foi o q respondi. Tem milhares de maneiras de fazer isso, e tudo depende do que o usuário prefere. Eu particularmente prefiro utilizar frameworks com grids. Mas como não sei o q ele quer fazer, então passei o q ele pediu.

O código retorna o tamanho da janela que está sendo exibida, independente do tamanho do dispositivo, o que pode ser bastante útil em alguns casos. Ai depende dele.
Comment: @FernandoVR Agradeço pela sua resposta também, muito obrigada
Comment: Disponha @Gislef ^_^


Console FTPS (not SFTP) client?

Question: I need to automate some transfers but it seems i can't find a decent command-line ftp client supporting FTPS for the windows platform? winscp supports SFTP but there's no good SFTP server for windows either, only FreeSSHDService which don't seems to be actively supported anymore.. therefore i want to use FileZilla Server which supports FTPS..
Comment: Do you need a FTPS or SFTP client? Those are very different things - FTPS is simple FTP+SSL, and SFTP is a separate protocol that uses SSH.
Comment: As stated both in title and in body I'm looking for a FTPS client, not a SFTP client from which there are many to choose from...
Answer: Since i wrote the question WinSCP has been updated to support FTPS!
http://winscp.net/eng/docs/ftps
Answer: You could use Cygwin and select the openssh lftp package.
(It has a dependency to openssl, so I assume it was compiled using configure --with-openssl)
Comment: lftp is great, but cygwin is always such a hassle :(
Comment: Cygwin a hassle? Why? (I read in your profile *Works just as easily in windows servers as in a linux system*...?)
Answer: The cURL library http://curl.haxx.se/ lists FTPS support in its list of features, so presumably the reference client provided with it can be used to make FTPS transfers from the command line.
On the point of "no good SFTP servers for Windows", cygwin (http://www.cygwin.com/) includes the full OpenSSH package, which comes with both

a SSH server capable of allowing SFTP (or SCP) transfers
a command-line sftp/scp client (called scp) which can be called from Windows scripts (batch files and WSH scripts via the shell.run method) - you just need to be careful to specify paths correctly.

I have used the SSH server provided by cygwin to provide SFTP/SCP support on several Windows systems. Thsi might be better to use instead of FTPS if only because FTPS is not as widely supported, as you have found.
Comment: seems ok, except you only can upload one file at a time.. i want to upload a folders without have to specify each filename..
Comment: True. You could try using the Windows "forfiles" command [a simple utility found in recent versions (you'll find it in the resource kits for older Windows releases) that does the basics of the "find" command you may be familiar with from Unix/Linux/BSD/cygwin] to run multiple calls curl for the files in a directory structure.
Answer: SFTPPlus has some automation features.

Secure file transfer using Open
  Standards (SSH, SFTP, FTPS, HTTP, PGP
  etc) plus additional audit &
  automation for enterprise strength
  usage.
Comment: too bad you have to pay for it..
Answer: if your going to automate transfers I would highly recommend going the SFTP route , using either WinSCP(free) or "CoreFTP client ($20)"  since those will support "scheduled" transfers.   FTPS clients "generally" dont support scheduled transfers although some GUI clients do support "queuing".
Answer: C-Kermit contains a very good scriptable FTPS client.
The Windows version costs money, but not very much. Unix/Linux versions are free.
Answer: Most of the SSHDs havent seen an update in years because there really hasn't been much to add to these applications.
Personally i use http://sshwindows.sourceforge.net/ for the server side and one of the putty clients for scripted sftp.
The website above mentions a new developer who's making some minor if nice changes, but as stated, i've never need anything beyond what was already there.
Your right there's not much in the way of ftps clients, it's the less loved of the two options, primarily due to the dual network port requirement, inconsistent character sets and different ways of listing dirs.
Cheers
M.
Comment: true, SFTP feels more solid, but i still think it's strange that there's hundreds of normal FTP clients but so few with FTPS support, when only need to wrap the FTP socket in a SSL tunnel..
Answer: PuTTY has a nice SFTP client (x86 EXE reference)
And, whatever you do, please use public key authentication.

I stand corrected; PuTTY uses FTP tunneling through SSH which is different from your request for a FTP through SSL.
Comment: indeed PSFTP is a great SFTP client, but it isn't a FTPS client as i was asking for..
Comment: @Carl, My bad. I misread your need for a SSL FTP connection. Sorry for that.
Comment: Yep, Putty is pretty much a standard FTP client (and it supports regular non-ssl ftp) but the difference is that it connects on the telnet port 22 and it accepts a cert and it tunnels through into the ftp service on port 21.
Comment: A minor annoyance for those using client certificates to connect: PuTTY uses some proprietary format. (It does offer a free tool to convert standard certs into PuTTY certs, but it does take some extra effort to get it running.)
Comment: I agree, If you can use Cygwin, it would solve the problem any day. PuTTY is only if you choose to not use Cygwin on windows.
Comment: @djangofan Maybe you figured this out by now but, putty is not an FTP client. It supports SFTP, which is basically an FTP/SSH hybrid protocol. Doesn't really work anything like FTP. Also, telnet is port 23. SSH is port 22.
Answer: Try CoreFTP?  I checked it out a while ago - it does have a command line interface - but I ended up not using it (I had no requirement for command-line use).  Also, some features you have to pay for - but there is a free version.
Comment: ah, this could work.. but it doesn't give a feeling of a very solid application thou.. the command-line options are very limited and the GUI is kind of ugly..

Console FTPS (not SFTP) client?


Why can't files from sassDir of discovered eyeglass modules be imported?

Question: I am trying to start using firstname.lastname@example.com and am running into problems where, although eyeglass modules are discovered, @importing them fails.
Here is the gulp task (only wrapped with gulp at this point because I don't know how to get pretty eyeglass debug output otherwise) which uses node-sass to compile a single file.
gulp.task('sass', () => {
  const options = eyeglass({
    file: path.join('test', 'test.scss'),
    engines: {
      sass: nodeSass
    }
  });
  return nodeSass.render(options, (err, result) => console.log(err, result));
});

This happens:
eyeglass:modules discovered modules
eyeglass:modules    :root(test)
eyeglass:modules    ├── firstname.lastname@example.com
eyeglass:modules    ├── email@example.com
eyeglass:modules    └── firstname.lastname@example.com
eyeglass:modules     +0ms
eyeglass:functions functions discovered in module eyeglass:
• eyeglass-asset-uri($registered-assets, $relative-path)
• eyeglass-normalize-uri($uri, $type: web)
• eyeglass-uri-preserve($uri)
• eyeglass-uri-restore($uri)
• eyeglass-version($module: eyeglass)
• eyeglass-fs-absolute-path($fs-registered-pathnames, $path-id, $segments...)
• eyeglass-fs-join($segments...)
• eyeglass-fs-exists($absolute-path)
• eyeglass-fs-path-separator()
• eyeglass-fs-list-files($directory, $glob: '*')
• eyeglass-fs-list-directories($directory, $glob: '*')
• eyeglass-fs-parse-filename($filename)
• eyeglass-fs-info($filename)
• eyeglass-fs-read-file($filename) +13ms
eyeglass:functions functions discovered in module eyeglass-sample:
• hello($name) +1ms
eyeglass:functions all discovered functions:
• eyeglass-asset-uri($registered-assets, $relative-path)
• eyeglass-normalize-uri($uri, $type: web)
• eyeglass-uri-preserve($uri)
• eyeglass-uri-restore($uri)
• eyeglass-version($module: eyeglass)
• eyeglass-fs-absolute-path($fs-registered-pathnames, $path-id, $segments...)
• eyeglass-fs-join($segments...)
• eyeglass-fs-exists($absolute-path)
• eyeglass-fs-path-separator()
• eyeglass-fs-list-files($directory, $glob: '*')
• eyeglass-fs-list-directories($directory, $glob: '*')
• eyeglass-fs-parse-filename($filename)
• eyeglass-fs-info($filename)
• eyeglass-fs-read-file($filename)
• hello($name)
[19:25:56] Finished 'sass' after 97 ms
eyeglass:import true can be imported from ~/eyeglass-test/test/test.scss +5ms
{ [Error: Error: Could not import true from any of the following locations:
  ~/eyeglass-test/test/true.scss
  ~/eyeglass-test/test/true.sass
  ~/eyeglass-test/test/true.css
  ~/eyeglass-test/test/_true.scss
  ~/eyeglass-test/test/_true.sass
  ~/eyeglass-test/test/_true.css
  ~/eyeglass-test/test/true/index.scss
  ~/eyeglass-test/test/true/index.sass
  ~/eyeglass-test/test/true/index.css
  ~/eyeglass-test/test/true/_index.scss
  ~/eyeglass-test/test/true/_index.sass
  ~/eyeglass-test/test/true/_index.css]
  status: 1,
  file: '~/eyeglass-test/test/test.scss',
  line: 1,
  column: 9,
  message: 'Error: Could not import true from any of the following locations:
    ~/eyeglass-test/test/true.scss
    ~/eyeglass-test/test/true.sass
    ~/eyeglass-test/test/true.css
    ~/eyeglass-test/test/_true.scss
    ~/eyeglass-test/test/_true.sass
    ~/eyeglass-test/test/_true.css
    ~/eyeglass-test/test/true/index.scss
    ~/eyeglass-test/test/true/index.sass
    ~/eyeglass-test/test/true/index.css
    ~/eyeglass-test/test/true/_index.scss
    ~/eyeglass-test/test/true/_index.sass
    ~/eyeglass-test/test/true/_index.css',
      formatted: 'Error: Error: Could not import true from any of the following locations:
    ~/eyeglass-test/test/true.scss
    ~/eyeglass-test/test/true.sass
    ~/eyeglass-test/test/true.css
    ~/eyeglass-test/test/_true.scss
    ~/eyeglass-test/test/_true.sass
    ~/eyeglass-test/test/_true.css
    ~/eyeglass-test/test/true/index.scss
    ~/eyeglass-test/test/true/index.sass
    ~/eyeglass-test/test/true/index.css
    ~/eyeglass-test/test/true/_index.scss
    ~/eyeglass-test/test/true/_index.sass
    ~/eyeglass-test/test/true/_index.css
  on line 1 of test/test.scss
  >> @import "true";
     --------^
  ' } null

I've tried this with several potential eyeglass dependencies, e.g.

eyeglass-sample
eyeglass-math
susy
true

I get the same type of failure for all of them, where they appear to be available in debug output, but attempting to @import them by name or @import anything in their sass directories fails.
I get these failures even when very specific messages that say things are importable show up:
eyeglass:import susy can be imported from ~/eyeglass-test/sass/_test.scss +14ms
...
Error: File to import not found or unreadable: susy.

If I start from scratch again, I run into this, which I've gotten past (though I don't remember how):
> DEBUG=* gulp sass
[12:51:50] Requiring external module babel-register
[12:51:53] Using gulpfile ~/Projects/eyeglass-test/gulpfile.babel.js
[12:51:53] Starting 'sass'...
  eyeglass:modules discovered modules
  eyeglass:modules  :root(eyeglass-test)
  eyeglass:modules  ├── email@example.com
  eyeglass:modules  └── firstname.lastname@example.com
  eyeglass:modules   +0ms
[12:51:53] 'sass' errored after 29 ms
[12:51:53] TypeError: this.main is not a function
    at EyeglassModule.init (~/eyeglass-test/node_modules/eyeglass/lib/modules/EyeglassModule.js:80:33)
    at ~/eyeglass-test/node_modules/eyeglass/lib/modules/EyeglassModules.js:83:9
    at Array.forEach (native)
    at EyeglassModules.init (~/eyeglass-test/node_modules/eyeglass/lib/modules/EyeglassModules.js:82:13)
    at new Eyeglass (~/eyeglass-test/node_modules/eyeglass/lib/index.js:35:16)
    at Eyeglass (~/eyeglass-test/node_modules/eyeglass/lib/index.js:18:13)
    at Gulp.<anonymous> (~/eyeglass-test/gulpfile.babel.js:7:19)
    at module.exports (~/eyeglass-test/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (~/eyeglass-test/node_modules/gulp/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (~/eyeglass-test/node_modules/gulp/node_modules/orchestrator/index.js:214:10)

The above is the most simplified case for illustration purposes. I have tried this using alternatives from eyeglass docs and issues such as new Eyeglass and eyeglass.Eyeglass and eyeglass.sassOptions(). I have tried it with and without enableImportOnce: false.  I've tried manually adding the modules via the eyeglass options.  I have tried it with and without engines. I have tried it with and without providing a default importer as mentioned in eyeglass docs and issues. I've tried it using node-sass, gulp-sass, and sass-true's runner method (through which true but nothing else can be imported because true adds itself to includePaths).
The only thing I have not tried--although I am very sure it will work--is manually creating my own includePaths configuration to include the sass directories of the eyeglass modules, because not having to do that is one of two reasons I'm interested in using eyeglass. I'd gotten the impression that typically it isn't supposed to be necessary to set up includePaths to use eyeglass modules, but, assuming it's caused by something I'm doing, it's not clear to me what inevitable common circumstance I've created in all of these various attempts that has consistently required my doing so.
Cross posted to https://github.com/sass-eyeglass/eyeglass/issues/164
Answer: I was able to reproduce this several times, but had to put it down for a bit. When I came back to it and set up individual examples for the various things I tried, I discovered that I had gotten further than I'd thought and my main issues were:

True is unique. There're still some parts of how to best work with True and eyeglass that I'm fuzzy on, but the main points are there.
Eyeglass doesn't support transitive dependencies if they are devDependencies; module authors need to make sure to list any eyeglass dependencies in dependencies.

Here are all the examples I ultimately created for troubleshooting, in case they are useful to others.
https://github.com/morewry/sass-eyeglass-examples


Can I increase readility of nftables ruleset syntax and does it affect its function?

Question: It is not clear to me from the manual if this commands are equal in their function:
meta skuid == "root" counter accept
skuid 0 counter accept

also
ct state == { established,  related } counter accept
ct state established,related counter accept

My questions about syntax is:

can I skip word meta (seems it must be skipped when item used in log flags)?
can I add == sign in any command that match something (for readability)?
can I write list (set of items) as item1,item2 and not { item1, item2 } or it's only for ct command?
Comment: I don't have exact knowledge of this, but I would say this is not possible. Supporting multiple input syntaxes creates extra complexity in the parser, which makes the utility more difficult to maintain and keep it bug-free.
Answer: To verify two rules are identical even beyond being displayed the same (in rare cases involving multiple protocol layers, rules can display the same, be functionally equivalent but not be exactly the same at the bytecode level, that's almost a reproducibility bug), use the option --debug=netlink which will also display bytecode sent to the kernel. If the bytecode is identical, the rules are identical.
Here's an interactive example (using nftables 1.0.9. Results can slightly change depending on version):
$ unshare -Urnm
# nft -V
nftables v1.0.9 (Old Doc Yak #3)
  cli:      editline
  json:     yes
  minigmp:  no
  libxtables:   yes
# nft add table t
# nft add chain t c
# nft --debug=netlink add rule t c 'meta skuid == "root" counter accept'
ip t c
  [ meta load skuid => reg 1 ]
  [ cmp eq reg 1 0x00000000 ]
  [ counter pkts 0 bytes 0 ]
  [ immediate reg 0 accept ]

# nft --debug=netlink add rule t c 'skuid 0 counter accept'
ip t c
  [ meta load skuid => reg 1 ]
  [ cmp eq reg 1 0x00000000 ]
  [ counter pkts 0 bytes 0 ]
  [ immediate reg 0 accept ]

# nft --debug=netlink add rule t c 'ct state == { established,  related } counter accept'
__set%d t 3 size 2
__set%d t 0
    element 00000002  : 0 [end] element 00000004  : 0 [end]
ip t c
  [ ct load state => reg 1 ]
  [ lookup reg 1 set __set%d ]
  [ counter pkts 0 bytes 0 ]
  [ immediate reg 0 accept ]

# nft --debug=netlink add rule t c 'ct state established,related counter accept'
ip t c
  [ ct load state => reg 1 ]
  [ bitwise reg 1 = ( reg 1 & 0x00000006 ) ^ 0x00000000 ]
  [ cmp neq reg 1 0x00000000 ]
  [ counter pkts 0 bytes 0 ]
  [ immediate reg 0 accept ]

As can be seen the 2 first rules are the same. Indeed "root" is resolved as usual to the uid 0 by userspace, and the meta keyword is optional (at least with the version here).
The two last rules, even if functionally equivalent, aren't identical. On case uses an anonymous set of two values. But these two values are meant to be combined in a bitwise manner (ie: all possible symbols have different exponent of 2 as value), that's what is doing the last rule instead where the , takes a different role. At a glance, I'd tell the 2nd ct rule is more optimized than the first: no need to involve a set lookup.
Still use of the first case exist: when using vmap (a verdict map rather than a simple set) to call different verdicts depending on the conntrack state in a single rule.
Whatever you choose, for a given nftables version, it will always be displayed back in one way:
# nft -s list ruleset
table ip t {
    chain c {
        meta skuid 0 counter accept
        meta skuid 0 counter accept
        ct state { established, related } counter accept
        ct state established,related counter accept
    }
}
#

That should probably be what to use, or that might anyway end up being used, just because when handled manually rather than by tools it's often practical to dump the ruleset, edit it, and reload it.
The case in ct cannot be generalized at all: the 2nd variant can be done (if specific syntax support is implemented anyway) only where power of two values are involved so they can be combined in bitwise operations:
# nft describe ct state
ct expression, datatype ct_state (conntrack state) (basetype bitmask, integer), 32 bits

pre-defined symbolic constants (in hexadecimal):
    invalid                         0x00000001
    new                             0x00000008
    established                     0x00000002
    related                         0x00000004
    untracked                       0x00000040
#

An obvious example is the use of the TCP flags with nftables:
# nft describe tcp flags
payload expression, datatype tcp_flag (TCP flag) (basetype bitmask, integer), 8 bits

pre-defined symbolic constants (in hexadecimal):
    fin                             0x01
    syn                             0x02
    rst                             0x04
    psh                             0x08
    ack                             0x10
    urg                             0x20
    ecn                             0x40
    cwr                             0x80
#

So just like ct:
# nft --debug=netlink add rule t c 'tcp flags { ack,syn } accept'
__set%d t 3 size 2
__set%d t 0
    element 00000010  : 0 [end] element 00000002  : 0 [end]
ip t c
  [ meta load l4proto => reg 1 ]
  [ cmp eq reg 1 0x00000006 ]
  [ payload load 1b @ transport header + 13 => reg 1 ]
  [ lookup reg 1 set __set%d ]
  [ immediate reg 0 accept ]

# nft --debug=netlink add rule t c 'tcp flags ack,syn accept'
ip t c
  [ meta load l4proto => reg 1 ]
  [ cmp eq reg 1 0x00000006 ]
  [ payload load 1b @ transport header + 13 => reg 1 ]
  [ bitwise reg 1 = ( reg 1 & 0x00000012 ) ^ 0x00000000 ]
  [ cmp neq reg 1 0x00000000 ]
  [ immediate reg 0 accept ]

# nft --debug=netlink add rule t c 'tcp flags ack|syn accept'
ip t c
  [ meta load l4proto => reg 1 ]
  [ cmp eq reg 1 0x00000006 ]
  [ payload load 1b @ transport header + 13 => reg 1 ]
  [ bitwise reg 1 = ( reg 1 & 0x00000012 ) ^ 0x00000000 ]
  [ cmp neq reg 1 0x00000000 ]
  [ immediate reg 0 accept ]

#

The two last rules (note the use of | for a bitwise OR operation instead of , for the built-in syntax) are exactly the same. But first rule uses an anonymous set just like in the previous case. In all cases in this example, one matching TCP flag among multiple is enough to match: functionally equivalent. Had there been the need to match two flags at once, only the 2nd case would have been usable.
Typically the rule below, that requires the presence of two flags at once, cannot be implemented with an anonymous set:
# nft --debug=netlink add rule t c 'tcp flags & (syn|ack) == syn|ack accept'
ip t c
  [ meta load l4proto => reg 1 ]
  [ cmp eq reg 1 0x00000006 ]
  [ payload load 1b @ transport header + 13 => reg 1 ]
  [ bitwise reg 1 = ( reg 1 & 0x00000012 ) ^ 0x00000000 ]
  [ cmp eq reg 1 0x00000012 ]
  [ immediate reg 0 accept ]

# nft list ruleset
[...]
        tcp flags syn,ack / syn,ack accept
[...]

Note: it doesn't make sense to combine in this manner flags with ct because contrary to TCP flags, only one flag at once is supposed to exist (a given packet can not have multiple conntrack states at once).


Socket.IO's io.emit works, but socket.emit / io.to().emit / io.in().emit don't

Question: I'm trying to make a simple instant messaging app and I've been struggling getting the websocket part to work. I'm finding that the client can successfully send requests to the server, but when I try to have the server emit back to the client it only works with io.emit rather than socket.emit, and even using io.emit doesn't work when I try to make it emit to a specific room using to() or in(), which I need it to do. Instead it times out for those.
Client:
      const socket = io('http://localhost:3000');

      socket.on('connect', () => {
        console.log('connected to socket');
      });

      socket.on('chat-message-out', (msg) => {
        console.log('incoming message thru socket: ', msg);
        setConvoMessages((prevMessages) => [msg, ...prevMessages]);
      });

    const sendMessage = (message, recipient) => {
      socket.emit('chat-message-in', message, recipient);
    };

    const joinRoom = (convoId) => {

      socket.emit('join-room', convoId);
      console.log('joining room ', convoId);
    };

Server:
io.on('connection', (socket) => {
  console.log(`User connected with socket ID: ${socket.id}`);

  socket.on('chat-message-in', (message, convoId) => {
    console.log(`User ${socket.id} sending message to conversation ${convoId}: ${message.msgtext}`);
    io.to(convoId).emit('chat-message-out', message, (error) => {
      if (error) {
        console.error('Error sending message:', error);
      } else {
        console.log('Message sent successfully');
      }
    });

  });

  socket.on('join-room', (convoId) => {
    console.log(`User ${socket.id} joined conversation ${convoId}`);
    socket.join(convoId);
  });

  socket.on('disconnect', () => {
    console.log(`User ${socket.id} disconnected`)
  });
});

instrument(io, {
  auth: false,
});

For this, my server logs:
User cW-J0NoNfpTTMjMKAAAL sending message to conversation BhzO0KukuC4zHb3o: dumb
Error sending message: Error: operation has timed out
    at Timeout._onTimeout (/home/rvcross/repos/messaging-app/server/node_modules/socket.io/dist/broadcast-operator.js:182:17)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7)

but if I were to remove the to() part it will send the message to all sockets successfully.
The "user ____ sending message to conversation" part gets logged out correctly, for what it's worth.
I have used the Admin-UI to confirm that the sockets are in fact in the room (convoId), so I don't think that is the issue.
Any help would be appreciated!
Answer: Okay, I seem to have gotten it working. The client is written with React, and I had most of the socket stuff in a useEffect, but not where I declared that socket = io('http://localhost:3000'), which I just had at the top with my imports. Whenever the component rerendered it would create a different socket connection, but the previous connections created by previous renders still were out there. I'm not entirely sure how this resulted in the problem I had, but anyway, moving the socket declaration inside the useEffect got the to().emit working properly, although my server is still giving me timeout error messages.


(RaphaelJS) - How to Fill the inside of a path?

Question: I have a path for the RaphaelJS library, I can't seem to get the fill to change its color.
var mypage = ScaleRaphael('mainContainer', 1000, 1000);
 mypage.setStart();
mypath.path('M794.33,21.5l152.3-0.76L946,21.5v-0.22l1.39,0.01l-1.17,206.61l-0.04,0.3l-0.15,0.27l-0.04,0.07l-0.18,0.35l-0.34,0.2 L786.4,321.59l-159.22,92.27l-2.12,1.18l-0.07-2.36v-1v-0.28l0.18-0.26l42.1-97.5l42.26-97.43l21.13-48.71l21.21-48.68 L794.33,21.5z M794.33,21.5l-41.46,97.76l-20.76,48.87l-20.84,48.83l-41.68,97.67l-41.78,97.59l0.18-0.54v1l-2.11-1.18 l159.08-92.46l159.23-92.21l-0.52,0.54l0.03-0.07l-0.14,0.57l2.04-206.6l1.39,0.01v0.22l0.13,0.77l-0.69,0L794.33,21.5z')
    .attr({"type":"path","stroke":"none","fill":"blue"});

The path is created correctly but the fill attribute only makes the stroke blue and not the filling, what am i doing wrong?
Comment: Where did you get that path? it's shaped like a stroke, if you do `.attr({"type":"path","stroke":"blue","fill":"none", "stroke-width":0.5});` you will understand what is going on.
Comment: Its the output from Illustrator, what can i do to fill the inside?
Answer: Your path is shaped like a stroke, to make it fill modify the path by removing everything starting from the second M:
var stage = Raphael('stage',1000, 1000);
var path = stage.path('M794.33,21.5l152.3-0.76L946,21.5v-0.22l1.39,0.01l-1.17,206.61l-0.04,0.3l-0.15,0.27l-0.04,0.07l-0.18,0.35l-0.34,0.2 L786.4,321.59l-159.22,92.27l-2.12,1.18l-0.07-2.36v-1v-0.28l0.18-0.26l42.1-97.5l42.26-97.43l21.13-48.71l21.21-48.68 L794.33,21.5z')
    .attr({"type":"path","stroke":"none","fill":"blue"});

http://jsfiddle.net/YzMCG/
Comment: The perfect answer. Thank you.
Answer: There is quite a nice explanation here that suggests adding a transparent fill to the CSS in order to hide the coloured fill and make it look like a path only:
Raphael Js can't fill path with Image


A problem in fractions from a very old arithmetic textbook

Question: Similar in vein to a problem I posted before here, I would be interested if anyone can give me any pointers as to how one might solve this question from the same arithmetic textbook:
"Simplify
$$\frac{23401369863013698630136986301369629}{34500729927007299270072992700729582}"$$
It is important to note that the book was originally published in 1947, well before any electronic calculation aids were available in schools, so there must be a method which can be carried out on pencil and paper without a ridiculous amount of effort (and paper).
I have tried looking for ways of spotting some pretty large common factors of the numerator and denominator which could be easily cancelled, but without success. There ought to be some cunning way to do this which makes use of the "almost periodic" nature of the digits in both numbers, but I have failed to see it.
Note: the simplified answer has just 7 digits in the numerator and denominator.
Comment: The gcd is $9999000099990000999900009999$. Maybe you can find it by looking at the numbers?
Comment: Yes, it follows from $1369863-234=1369629$ (last digits of the numerator), same for $729927-345=729582$.
Comment: Do the long division as in polynomial long division, with the "variable" being $10^4$ raised to the power $k$, and coefficients of $9999$. Note that multiplying $9999$ by any other 4 digit unit won't be large enough to throw the subsequent result "past the zeros".
Comment: Aww, I see that I was missing all the fun while working on the problem.
Comment: I would guess that the calculation for $\gcd$ of your two numbers is unusually clean and brief; and that the  $\gcd$ is huge. The latter is something we already know, given the nature of the answer.
Comment: calculating the gcd vy repeated subtraction should be feasible
Comment: Yes, I had thought of that - but wouldn't you then have to carry out an enormous long division process on both numbers?
Comment: @Listing Thanks - that looks like the beginning of a clever trick - I will have a think ...
Comment: @CalvinLin Thanks! I think I can now turn that into a complete solution, but I will wait to see if anyone else wants to post an answer first
Comment: Wait a minute. I was born in 1956, to commemorate one of the last "Subway Series." Were you born in 1947? http://en.wikipedia.org/wiki/1956_World_Series  and  http://en.wikipedia.org/wiki/Subway_Series
Comment: @WillJagy Nope, I was born in 1952, but I found the book in the library at one of the first places I taught - I withdrew it (but kept it for my own amusement) since much of referred to obsolete units such as poles, chains, scruples, grains and drachms.
Comment: So, why were you born in that year? I know why my parents picked 1956. He was at Columbia U., she was at Barnard, it all made sense.
Answer: The repeating block in the numerator is $01369863$; the last block, $01369629$, is defective by exactly $234$, the first three digits. The same thing happens in the denominator: the repeating block is $00729927$, and the last block, $00729582$, is defective by $345$, the leading three digits. Let $a=01369863$, $b=00729927$, and $x=10^8$; then the fraction is
$$\begin{align*}
\frac{234x^4+a(x^3+x^2+x+1)-234}{345x^4+b(x^3+x^2+x+1)-345}&=\frac{234+\frac{a}{x-1}}{345+\frac{b}{x-1}}\cdot\frac{x^4-1}{x^4-1}\\\\
&=\frac{234(x-1)+a}{345(x-1)+b}\\\\
&=\frac{234\cdot99999999+1369863}{345\cdot99999999+729927}\\\\
&=\frac{23400000000-234+1369863}{34500000000-345+729927}\\\\
&=\frac{23401369629}{34500729582}\\\\
&=\frac{2600152181}{3833414398}\\\\
&=\frac{236377471}{348492218}\;,
\end{align*}$$
Still not quite down to six digits, but better; the last two steps took out factors of $9$ and $11$, which are recognizable by elementary tests. Knowing that it can be further simplified, I might think of testing for divisibility by $101$: $71-74+37-36+2=0$ and similarly in the denominator. That reduces it finally to
$$\frac{2,340,371}{3,450,418}\;.$$
(In fact I got that ex post facto from Old John's comment.)
Comment: Very neat! Not quite the simplest form, though - I get a bit more cancellation to give $2340371/3450418$. The is an interesting connection between the last 3 digits of $2340371$ and $3450418$ compared with those of the original numerators and denominators ...
Comment: Shouldn't the end of your first line be $\dfrac{x^4-1}{x^4-1}$ and not $\dfrac{x^8-1}{x^8-1}$?
Comment: @Ivan: Yep. I originally had $x=10^4$ and didn't change everything. Thanks.
Comment: Well done indeed - and despite the fact that I can't count - there are 7 not 6 digits in the final numerators and denominators. I blame it on my eyesight after too much hill-walking.
Answer: Evidently the gcd is a long calculation by hand, and prone to error in any case. So, trickery it is. Does it  say anything relevant in the text?
<code>Tue Nov 26 13:37:03 PST 2013
GCD ( 34500729927007299270072992700729582, 23401369863013698630136986301369629 )
 quotient 1
GCD ( 23401369863013698630136986301369629, 11099360063993600639936006399359953 )

 quotient 2
GCD ( 11099360063993600639936006399359953, 1202649735026497350264973502649723 )

 quotient 9
GCD ( 1202649735026497350264973502649723, 275512448755124487551244875512446 )

 quotient 4
GCD ( 275512448755124487551244875512446, 100599940005999400059994000599939 )

 quotient 2
GCD ( 100599940005999400059994000599939, 74312568743125687431256874312568 )

 quotient 1
GCD ( 74312568743125687431256874312568, 26287371262873712628737126287371 )

 quotient 2
GCD ( 26287371262873712628737126287371, 21737826217378262173782621737826 )

 quotient 1
GCD ( 21737826217378262173782621737826, 4549545045495450454954504549545 )

 quotient 4
GCD ( 4549545045495450454954504549545, 3539646035396460353964603539646 )

 quotient 1
GCD ( 3539646035396460353964603539646, 1009899010098990100989901009899 )

 quotient 3
GCD ( 1009899010098990100989901009899, 509949005099490050994900509949 )

 quotient 1
GCD ( 509949005099490050994900509949, 499950004999500049995000499950 )

 quotient 1
GCD ( 499950004999500049995000499950, 9999000099990000999900009999 )

 quotient 50
GCD ( 9999000099990000999900009999, 0 )

Tue Nov 26 13:37:03 PST 2013
</code>
Comment: There are no hints or other clues in the textbook, as the problem was in the section labelled "Harder Problems" at the back of the book, so there is presumably something somewhere in the earlier part of the book which gives a clue, but I haven't got the patience to read all 456 pages of the ancient tome, unfortunately.
Comment: @OldJohn But you can walk up and down hills for ten hours. Where is your sense of discipline? Evidently Basel-Chelsea is over, probably also Arsenal-someone.
Comment: Only five hours today - but covered 10 miles. Man Utd tomorrow is more important in this part of the world :)
Comment: @OldJohn, right tomorrow is United- Leverkusen, City - Victoria Plzen. Barcelona tripped up today.


To find number of $x$ such that $sin(2x)=1$

Question: To find number of  $x$ such that $sin(2x)=1$ in interval $[-2\pi,2\pi]$. Now i made graph and i found 4 points. But textbook states 2 points. I would like to know where i am wrong? Thanks
Comment: One needs to restrict $x$ such that $\sin(x)>0$ and $\cos(x)>0$.
Comment: Your textbook is wrong. There are indeed four solutions in the given interval.
Comment: Actually this a part of $$\log_{0.5}sin(x)=1-\log_{0.5}cos(x)$$
Comment: I have to find number of x
Comment: Er... you've got the wrong interval? Should be $[0,2\pi)$.
Comment: @Dr.MV Yes i think this happens on extreme left end near -2pi and one at pi/4
Answer: This question may better solve algebraically, not graphically.
First we observe the range of the angle: $x\in[-2\pi,2\pi]\Rightarrow 2x\in[-4\pi,4\pi]$.
Then, since $\sin(2x)=1$, then $\displaystyle 2x=\frac{\pi}{2}+2k\pi$, where $k\in\mathbb{Z}$.
How many $k$ is possible, then that many $2x$ is in $[-4\pi,4\pi]$, then that many $x$ is possible. So we turn to solve this inequality.

$$\displaystyle -4\pi\leq2x=\frac{\pi}{2}+2k\pi\leq4\pi$$

Sol:
$$\begin{alignat*}{2}&-4\leq\frac{1}{2}+2k\leq4\\
\Rightarrow &-8\leq1+4k\leq8\\
\Rightarrow &-9\leq4k\leq7\\
\Rightarrow &\frac{-9}{4}\leq k\leq\frac{7}{4}\\
\Rightarrow &-2.\cdots\leq k\leq1.\cdots\\
\Rightarrow &k=-2,-1,0,1
\end{alignat*}$$
So four solutions. You're right.


running eclipse from usb key: java enviroment error

Question: I am trying to install Eclipse IDE in portable USB key.
Java is placed in
f:\commonfiles\java64. the sub folder \bin is in here
I set the environment path by running in f: drive the command 'Set Path=CommonFiles\Java64\bin;%Path%'
although when I run eclipse it returns this error log:
https://ibb.co/7CWm3mw
I have set environment path by running: Set Path=CommonFiles\Java64\bin;%Path%
if i run f:> where java in returns same path
also , if i run java -version from above path CommonFiles\Java64\bin it gives:
java version "1.8.0_231
java (TM) SE Run time environment <build.......>
java Hotspot(TM) 64-bit server vm <.......>

I think i have to change some path in eclipse.ini but i dont know how.
Comment: Instead of putting a link to a random location you should copy the relevant content into the question.
Comment: sorry for mistake. thanks
Answer: Please define JAVA_HOME environment variable. It should point to your installed JDK version. I assume it is JDK since you are interested to run Eclipse. Usually it looks like the following:
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_121


Hiding fields when creating node and showing them only when editing

Question: I'd need to enable editing of certain fields only when the node they're assigned to already exists. Therefore I need to disable them on node create form and enable them on node edit form.
I though I'd do it the same way as with users where you have two separate forms (user profile a user register) and therefore can use settings array on field instance (at least I believe it works this way).
<code>...
'settings' => array(
   'user_register_form' => 0,
),
...
</code>
The problem is you can't do it with nodes as nodes don't have separate forms for edit and create.
I know I can do it directly via altering CONTENTTYPENAME_node_form (changing the access status of the fields to false or unseting them completely when the node does not yet exist) but it doesn't seem to be the very best solution (It doesn't feel systematical to unset it on form alter hook).
BTW: I know that someone asked similar question but he hasn't received any answers.
Comment: There is nothing bad about using #access=false in a hook_form_alter. But avoid deleting fields using unset() because it may produces problems/php notices with other modules which implement hook_form_alter or the form validation.
Comment: Hmm, ok. Will do it that way.
Answer: This is certainly without a doubt a job for hook_form_alter() and quite easy to accomplish, eg, something along the lines of:
<code>function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {

    case 'foo_node_form':

      if ($_GET['q']=='node/add/foo') {

        // we are creating a node of type foo so do stuff to the form one way here

      } else {

        // we are editing a node of type foo so do stuff to the form another way here

      }

      break;

   // other forms here

  }

}
</code>


Grow div container from the bottom without altering the baseline

Question: I have a div that when the mouse is over it, a child div is expanded from the bottom, revealing all of its hidden contents.
However, the div seems to shrink a bit from the bottom, making the elements below it rise slightly.
Here is an fiddle showing exactly what's going on.

body {
  color:white;
}

.game-thumbnail {
    background-color: rgba(23, 30, 26, 0.95);
    margin-top:-15%;
    position:relative;
    z-index:1;
    padding:0.5em 1em;
    transition: margin 0.333s ease-out, padding 0.333s ease-out;
}

.game-entry {
    cursor:pointer;
    width:66vw;
    max-width:500px;
}

.game-entry img {
    width:100%;
    position:relative;
}

.game-entry:hover .game-thumbnail {
        margin-top:-30%;
        padding-bottom:15%;
        bottom:0;
}
.game-entry:hover .moreinfo {
        opacity:1;
        transition:opacity ease-out;
        transition-duration: 0.4s;
        transition-delay: 0.3s;
}

.moreinfo {
    opacity:0;
    transition-duration: 0.2s;
    transition-delay: 0s;
    background-color:#171e1a;
    width:25%;
    padding:5px;
    text-align:center;
    position:relative;
    float:right;
}

My Dog's Tale

Follow the adventures of My Dog

More info...

This should not go up

I was thinking of just repositioning the text upwards, making the div bigger at the top, but the background stays behind the image.
Although I'm looking for a CSS3-only solution, jQuery solutions are welcome.
Answer: When you use margin to adjust the positioning of an element, it will impact the DOM flow of the rest of the page. This is why it is impacting the positioning of the element below.
I would advise using transform to accomplish an animation like this. For example, transform: translateY(-30%);. This will move the element "up" without impacting DOM flow.
See updated fiddle here.


how could I get the content of a common class div

Question: I have two divs one is both are containing one same class and all are in a div named "content" and may be the three div are comes random order.

Hello

How

are you

So how could I get the text of "error messages" both class containing message in JS or jQuery?
I mean, I want to alert the "Hello" text, how can it be possible?
Answer: Use both classes in the selector:
alert($('div.error.messages').text());

http://jsfiddle.net/rPw7F/
Comment: @SubhojitMukherjee np, feel free to accept it by clicking the tick over there <<<
Answer: $(document).ready(function() {
  alert( $('div.error.messsages').text() );
});


Can I add these rules "as-is" into my httpd.conf?

Question: Here are all my rules with comments:
<Directory /home/*/public_html>
    # prevent directory browsing
    Options All -Indexes

    # prevent access to htaccess files anywhere on the site
    <Files .htaccess>
        order allow,deny
        deny from all
    </Files>

    # prevent DIRECT access to the /inc/ directory and its PHP files
    <Files ~ "\.inc$">
        order allow,deny
        deny from all
    </Files>

    # custom error documents
    ErrorDocument 400 /error/400.html
    ErrorDocument 401 /error/401.html
    ErrorDocument 403 /error/403.html
    ErrorDocument 404 /error/404.html
    ErrorDocument 500 /error/500.html

    # security requirement of the rewrite engine
    Options +FollowSymLinks

    # turn on rewrite engine
    RewriteEngine On

    # remove PHP extension
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.php -f
    RewriteRule ^(.*)$ $1.php
</Directory>

and
<Directory /home/*/public_html/images>
    # caching
    <IfModule mod_expires.c>
    ExpiresActive On

    <FilesMatch "\.(jpg|jpeg)$">
            ExpiresDefault "modification plus 1 year"
            Header set Cache-Control: "public, max-age=31536000"
            Header unset Last-Modified
        </FilesMatch>
    </IfModule>

    # turn on rewrite engine
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]

    # if file cannot be found
    RewriteRule ^.*$ /empty.jpg [NC,L]
</Directory>

Can I add these rules as they are to the bottom of my httpd.cnf? Or are there any mistakes? Or anything else I need to pay attention to? I don't want to screw anything up, even tho I'm just running my code on my localhost.
Any help would be appreciated. Thanks.
Comment: Put it there, restart apache, and watch if it spits out any errors about some lines in httpd.conf. That's the best way to find out.
Comment: No errors. But now the rules aren't working. I should probably just leave them in my htaccess file. Thanks anyways.
Answer: you can put them in httpd.cnf file! and they will work! The only thing you should pay attention is that to put them in right place(e.g in right site)


How to create a progress dialog in WP8?

Question: How to create a progress dialog in WP8, similar to ProgressDialog in Android as given here or Progress HUD on IOS as given here ?
Answer: In windows phone Progress Bar available to show Progress Here is a link that describe more about Progress Bar.
If you want to use This type of  progress bar than You have to create your own custom progress bar with a loading image and angle animation.
Here is a link that will help you to create custom loader control in windows phone.

How to create a progress dialog in WP8?


Having trouble proving that this set is a group under matrix multiplication

Question: I am trying to prove that the set of 2x2 matrices $X$, with $det(X) \neq 0$ is a group under matrix multiplication.
The first step for me is to prove closure.
Given $X = \begin{bmatrix}
a & b\\
c & d
\end{bmatrix}$ and $X' = \begin{bmatrix}
a' & b'\\
c' & d'
\end{bmatrix}$ \begin{align}
    det(XX') &= det(\begin{bmatrix}a & b\\c & d\end{bmatrix}\begin{bmatrix}a' & b'\\c' & d'\end{bmatrix})\\
            &= det(\begin{bmatrix}
            aa' + bc' & ab' + bd'\\
            ca' + dc' & cb' + dd'
            \end{bmatrix})\\
            &= (aa' + bc')(cb' + dd') - (ab' + bd')(ca' + dc')\\
            &= (aa'dd' - ab'dc) + (bc'cb - bd'ca')\\
            &= ad(a'd' - b'c) + bc(c'b - d'a)
\end{align}
However, I am not too sure how to go from here. I know that $det(X) = ad - bc \neq 0$ and $det(X') = a'd' - b'c' \neq 0$, but I'm not too sure how to utilize those properties to go further to prove that $det(AB) \neq 0$.
Comment: A well known property of determinants is that $\det(AB)=\det(A)\det(B)$. Are you not familiar with it? If not, I think it shouldn't be a big problem to check this property directly for $2\times 2$ matrices.
Answer: You could use the fact that\begin{align}0&\ne\det(X)\det(Y)\\&=(ad-bc)(a'd'-b'c')\\&=aa'dd'+bb'cc'-a'bcd'-ab'c'd\\&=(aa'+bc')(b'c+dd')-(ab'+bd')(a'c+c'd)\\&=\det(XY).\end{align}More generally, you always have $\det(AB)=\det(A)\det(B)$ when $A$ and $B$ are square matrices with the same sizes.