Duplicação do conteúdo da página (HTML/PHP)

Question: Estou com um problema de duplicação na minha página. O conteúdo que deveria se organizar dentro a index principal se duplica no cabeçalho na página como na imagem abaixo.

- Minha index.php
<?php

require './lib/autoload.php';

$smarty = new Template();
Rotas::get_pagina();

//valores para o template
$smarty->assign('NOME', 'Julio Cesar de Camargo');
$smarty->assign('GET_TEMA', Rotas::get_SiteTEMA());
$smarty->assign('GET_HOME', Rotas::get_SiteHOME());
$smarty->assign('PAG_CARRINHO', Rotas::pag_Carrinho());
$smarty->assign('PAG_CONTATO', Rotas::pag_Contato());
$smarty->assign('PAG_MINHACONTA', Rotas::pag_MinhaConta());
$smarty->assign('TITULO_SITE', Config::SITE_NOME);

$smarty->display('index.tpl');
 ?>

- Minha index.tpl
<!DOCTYPE html>

        <title>{$TITULO_SITE}</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link href="{$GET_TEMA}/tema/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
        <link href="{$GET_TEMA}/tema/contatos/contatos.css" rel="stylesheet" type="text/css"/>

        <link href="{$GET_TEMA}/tema/css/tema.css" rel="stylesheet" type="text/css"/>

                           <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                               Toggle navigation

                           </button>

 Home

 Minha Conta

 Carrinho

 Contato

                            <form class="navbar-form navbar-right" role="search">

                                    <input type="text" class="form-control" placeholder="Digite para buscar" required>

                                <button type="submit" class="btn btn-primary">Buscar</button>
                            </form>

                     Categorias

                     Presentes
                     Brinquedos

                     Presentes
                     Brinquedos

                     Presentes
                     Brinquedos

 Home

 Produtos

 Info

                    {php}

                    Rotas::get_Pagina();

                    {/php}

{$TITULO_SITE}

 Todos os diretos reservados

- Minha classe de rotas
<?php

Class Rotas{

    public static $pag;
    private static $pasta_controller = 'controller';
    private static $pasta_view = 'view';

    static function get_SiteHOME(){
        return Config::SITE_URL . '/' .Config::SITE_PASTA;
    }

    static function get_SiteRAIZ(){
        return $_SERVER['DOCUMENT_ROOT'] . '/' .Config::SITE_PASTA;
    }

    static function get_SiteTEMA(){
        return self::get_SiteHOME(). '/' .self::$pasta_view;
    }

    static function pag_Carrinho(){
        return self::get_SiteHOME(). '/carrinho';
    }

    static function pag_Contato(){
        return self::get_SiteHOME(). '/contato';
    }

    static function pag_MinhaConta(){
        return self::get_SiteHOME(). '/minhaconta';
    }

    static function get_Pagina(){
        if(isset($_GET['pag'])){

            $pagina = $_GET['pag'];

            self::$pag = explode('/', $pagina);

            $pagina = 'controller/' .$_GET['pag'] . '.php';
            if(file_exists($pagina)){
                include $pagina;

            }else{
            include 'erro.php';
        }
        }
    }
}

 ?>

Por favor me ajudem, preciso muito resolver isso.
Answer: Olá, Júlio!
Eu refiz a estrutura do código, mudei posicionamento, acredito que resolva seu problema, peço que teste essa estrutura, tirei algumas tags do php na hora da montagem.

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>

 Home

 Minha Conta

 Carrinho

 Contato

      <form class="navbar-form navbar-right" role="search">

          <input type="text" class="form-control" placeholder="Digite para buscar" required>

        <button type="submit" class="btn btn-primary">Buscar</button>
      </form>

           Categorias

                 Presentes
                 Brinquedos

                 Presentes
                 Brinquedos

                 Presentes
                 Brinquedos

 Home

 Produtos

 Info

                {php}

                Rotas::get_Pagina();

                {/php}

{$TITULO_SITE}

 Todos os diretos reservados

Espero que tenha te ajudado!


C# StringWriter is faster than C++ ofstream (via pinvoke)?

Question: I'm just a beginner at c++ so I might be doing something wrong but anyways I created a c++ dll and I call it from my wpf project:
c++ code:
extern "C" __declspec (dllexport) double writeTxt()
{
    ofstream mf("c:\\cpp.txt");
    for(int i=0;i<999;i++)
    {
     mf<<"xLine: \n";
    }
    mf.close();
    return 1;

}

calling code from c#:
[DllImport(@"C:\Users\neo\Documents\visual studio 2010\Projects\TestDll\Debug\TestDll.dll",
       CallingConvention = CallingConvention.Cdecl)]
    public static extern double writeTxt();

Now I'm trying to compare the execution time with this c# function:
double writeTxtCs()
    {
        StreamWriter sw = new StreamWriter(@"c:\cs.txt");
        for (int i = 0; i < 999; i++)
        {
            sw.WriteLine("Line: " + i);
        }
        sw.Close();
        return 0;
    }

but the c# function is about twice as faster than the c++ function.
tested like this:
private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        long[] arr = new long[100];
        Stopwatch sw = new Stopwatch();
        for (int i = 0; i < 99; i++)
        {
            sw.Start();
            //double xxx = writeTxt();
            double xxx = writeTxtCs();
            arr[i] = sw.ElapsedMilliseconds;
            sw.Reset();
        }
        MessageBox.Show(arr.Average().ToString());
        Close();
    }

When running the c# function I normally get ~0.65ms and when running the c++ function I get ~1.1ms.
my question is: am I doing something wrong or does c# really is faster in this scenario than c++?
Comment: have you tried running maybe 1000 times more tests than 100 at a time, to get a better idea? Maybe go for about 100k iterations, minimum.
Comment: Since you mentioned you were a beginner, I would suggest that until you have an actual problem with performance, [do not do any pre-optimization as it will most likely be a waste of time](http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html).
Comment: I agree that the benchmark is not adequate; actually, it is a very poor microbenchmark. In any case, note the when writing to IO, buffering is often of great importance (perhaps more so than raw CPU speed).
Comment: @Erik the whole purpose of this project is to learn c++, it isn't a part of a real project.
Comment: So you're asking a question stated in the [FAQ What kind of question should I not ask here - You should only ask practical, answerable questions based on actual problems that you face.](http://stackoverflow.com/faq#dontask)
Answer: You're not testing C++ vs. C#. You're testing [C++ plus libraries] vs. [C# plus libraries].
In order to find out why ofstream is slower than StreamWriter you'd need to profile the code or look into the internals.
Anyway, single milliseconds are a very small amount of time for a computer. I'd repeat the test with 1000 times the load to make timing jitter irrelevant.
Comment: I tried to increase the for loop that calls the functions by 10 but the difference is just getting bigger.
Comment: The difference getting bigger means that your old benchmark was wrong. The difference should stay the same. Try increasing the load even more. Go into the seconds range.
Answer: All other answers have valid points. In addition to those:
You are testing against "Debug" build of your C++ DLL and that might be degrading C++ performance more than how it affects C#'s performance. Try unleashing optimizations on both and see how it works out for you.
Nevertheless I/O doesn't have much to do with the "language". It's more about runtime and the OS.
Comment: Well changing both projects to release mode made the difference.
I'll keep on testing it but now the c++ function is 10 times faster than the c# function.
Answer: It could be a buffering issue, i.e. the C# and C++ file writing guts might be buffering data in a different way, which would result in performance differences.
I recommend you use an operation which is purely CPU bound for benchmarking, rather than something IO bound (such as writing to a hard drive).  For instance, see how fast each function can count from 0 to MAX_INT.
Comment: Benchmarking languages like that is crap. You can't use the result for anything. It is purely artificial.
Comment: There is not one score per language. There is one score per language and per workload. You need to choose a set of representative loads. That is hard.
Comment: mixed arithmetic plus conditionals then.
Answer: That's not really a reliable benchmark. You're doing file IO there, which is highly dependent on the implementation of ofstream and StreamWriter. Also, is it a problem?


Show that $\mu(f_n^+) \rightarrow \mu(f^+) $ and $\mu(f_n^-) \rightarrow \mu(f^-) $, using Fatou's Lemma.

Question: I'm starting learning about Fatou's lemma. How would you apply it to solve the following problem:
Let $g^+ = max (g,0)$ and $g^- = max (-g,0)$.
Let $f_n$ be integrable on measure space with measure $\mu$.
Assume $f_n \rightarrow f$ almost everywhere and $\mu(|f_n|) \rightarrow \mu(|f|) $.
Show that $\mu(f_n^+) \rightarrow \mu(f^+) $ and $\mu(f_n^-) \rightarrow \mu(f^-) $.
Comment: Does is a measure function a measure? If so, what does $\mu(|f|)$ mean?
Comment: $\mu$ is a measure. edited.
Comment: So what does $\mu(|f|)$ mean?
Comment: @MichaelAlbanese $\mu\left(f\right)$ is a (nice) abbreviation of $\int fd\mu$ so
$\mu\left(\left|f\right|\right)=\int\left|f\right|d\mu=\int f^{+}d\mu+\int f^{-}d\mu=\mu\left(f^{+}\right)+\mu\left(f^{-}\right)$. This way measure $\mu$ takes values on functions instead of sets
and is linear upto a certain level.
Answer: Fatou's lemma claims that $\text{liminf} \int{f_n}\ge\int\liminf {f_n}$ where $f_n\ge0$ pointwise
According to your assumption $f_n\to f$ a.e.,we have $f_n^+\to f^+$ a.e. and similarly for $f^-$
By Fatou's lemma you have $\liminf\int f_n^+ \ge \int f^+$ and
$\liminf\int f_n^- \ge \int f^- $
$\int|f_n| \rightarrow \int |f| $ shows$\int f_n^+ +\int f_n^- \rightarrow \int f^+ +\int f^- $
But you know $\int f_n^+\ge\liminf\int f_n^+ $. So you arrive at the conclusion.
($\lim(\int f_n^++\int f_n^-)\ge\liminf \int f_n^++\liminf \int f_n^- \ge \int \liminf f_n^++\int \liminf f_n^-=\int f^++\int f^-$ so each step is equallity, especially the middle one is what the conclusion claims)
Hope it helps.


Module installed by Luarocks not found

Question: I am working on Debian Stable Linux. I installed luafilesystem module by command:
luarocks --local install luafilesystem

However, it is not found when any of following is used in lua source files:
require ("lfs")
require ("luafilesystem")

(Although these files run properly when ran from within ZeroBraneStudio IDE).
From a suggestion on the web, I ran following command also:
luarocks --local install luarocks

But it does not help. I checked with luarocks-admin command, which showed:
CONFIGURATION
    Lua version: 5.1
    Configuration files:
        System: /etc/luarocks/config.lua (ok)
        User  : /home/abcd/.luarocks/config-5.1.lua (not found)

    Rocks trees in use:
        /home/abcd/.luarocks
        /usr/local

Currently, I only have these 2 modules installed:
$ luarocks list

Installed rocks:
----------------

luafilesystem
   1.7.0-2 (installed) - /home/abcd/.luarocks/lib/luarocks/rocks

luarocks
   2.4.3-1 (installed) - /home/abcd/.luarocks/lib/luarocks/rocks

Should I copy /etc/luarocks/config.lua to /home/abcd/.luarocks for this? Thanks for your help.
Comment: Do you `require "luarocks.loader"` first?
Comment: I installed modules using `sudo luarocks install luafilesystem` (without --local option) and it works. So luarocks.loader is needed for locally installed modules?
Answer: The LUA_PATH and LUA_CPATH environment variables control the paths searched by lua when looking for packages.  These are probably not set correctly.  Include the paths used by luarocks in these variables by running
eval "$(luarocks path)"

and you should be all set.
Answer: Eval works fine when executing the code from the terminal, but it doesn't work when executing it using the vscode debugger.
To get around this problem, I did the following.
local LUA_PATH = 'my LUA_PATH from "$ luarocks path"'
local LUA_CPATH = 'my LUA_CPATH from "$ luarocks path"'

package.path = package.path .. ';' .. LUA_PATH
package.cpath = package.cpath .. ';' .. LUA_CPATH

With this change, I can run the code using the debugger.

Module installed by Luarocks not found


Are there any differences between these two higher-order function definitions?

Question: Are there any differences among 4 statements in main?
I feel only apply2(&func) makes sense. However, all 4 return the same value.
int func(void)
{
    return 1;
}

int apply1( int f1(void) )
{
    return f1();
}

int apply2( int (*f1) (void) )
{
    return f1();
}

int main()
{
    apply1(func);
    apply1(&func);
    apply2(func);
    apply2(&func);

    return 0;
}

Comment: @flee What an amazing first question.
Comment: How are you testing the return value? How about trying a different return value, like 197, that is less likely to be a coincidence.
Comment: Doesn't f1 need a dereference in apply2?
Comment: @abiessu, nope: function pointers are just as callable as functions.
Answer: First off, function pointers are hard. Thinking that you can pass a function as a parameter to another function requires some mind-bending similar to understanding recursion. You won't get it at first, but then all of a sudden it's like the floodgates of understanding open in your brain and you're enlightened.
But then, you still have to know the rules of passing functions as parameters in C and C++. In these languages, functions are not first-class citizens, so there are a lot of restrictions on what you can do with them.
Syntax
The function pointer syntax is a little ugly. The basic anatomy is [return type] (*[name])([argument list]). The parentheses around *name are necessary to disambiguate between a function pointer and a function returning a pointer:
// not function pointers: * not grouped to function name
int x(); // function that returns an int
int* x(); // function that returns an int*
int *x(); // also a function that returns an int*, spaces don't matter

// function pointers: * grouped to function name
int (*x)(); // pointer to a function that returns an int
int* (*x)(); // pointer to a function that returns an int*

Decay
In terms of passing as parameters, functions behave about the same as arrays. When passed, they change into a pointer. Compare:
void Foo(int bar[4]); // equivalent to: void Foo(int* bar)
void Bar(int baz()); // equivalent to: void Bar(int (*baz)())

This is simply because functions and arrays are non-assignable and non-copyable:
int foo[4];
int bar[4] = foo; // invalid

int foo();
int bar() = foo; // invalid

Therefore, the only way to pass them as function parameters is to pass their address instead of copying them. (This is disputable for arrays, but that's how it works.) The fact that these "values" are transformed into pointers when passed as parameters is called "decay".
These two prototypes are compatible (that is, they refer to the same function, not different overloads), and therefore, there is no difference between the two:
int foo(void bar());
int foo(void (*bar)());

Visuals aside, there is absolutely no difference between those two declarations. Both functions accept a function pointer, whether it looks like it or not, because of decay. Though, since decay is often considered a nasty and confusing thing, most developers will prefer to explicitly ask for a function pointer (and a lot of developers don't even know function types can decay).
Implicit Conversions
Now, about passing functions as parameters. This one is simply a consequence of decay: functions have to be implicitly convertible to their function pointer type. This means that you can pass a function where a function pointer is expected, and the compiler will get its address for you. For this purpose, these are, once again, the same:
int foo();
int (*bar)() = foo; // the compiler implicitly assigns the address of foo to bar
int (*baz)() = &foo; // you explicitly assign the address of foo to baz

Combine those two explanations, and you'll realize that your four function calls are all the same. apply1 and apply2 both accept the same type of parameter (int (*)(void)), even if it's not obvious for apply1; and when you call the functions with func instead of &func, the compiler implicitly takes the address for you and makes it equivalent to &func.

The following is outside the scope of the question, but it elaborates on the previous part, and I think it's kind of neat.
Function References [C++ only]
It is a little-known fact, but it is also possible to pass references to arrays and functions: in this case, no decay happens. Like this:
void Foo(int (&bar)[4]); // NOT equivalent to void Foo(int* bar)
void Bar(int (&baz)()); // NOT equivalent to void Bar(int (*baz)())

In this scenario, you are not allowed to use the address-of operator, because there is no implicit conversion between pointer types and reference types. Defeating decay is generally seen as a good thing, as decay is often confusing.
int baz();
Bar(baz); // valid
Bar(&baz); // INVALID

Function references obey the same rules as normal references: they can be assigned only at definition time, and cannot be null.
Typedefs
You can make function pointers less ugly using typedef.
typedef int (*X)();
X func; // func is a pointer to a function that returns an int

Things get more interesting if you take out the (*) part:
typedef int X();
X* func; // func is a function pointer
X& func; // func is a function reference [C++ only]
X func; // func is a function declaration (!!)

In the latter case, X func; is equivalent to a declaration saying int func();. Don't do this at home, unless you want to confuse the hell out of everyone.
decltype makes a difference [C++ only]
Another interesting difference between functions and function pointers arises with the use of decltype. decltype "returns" the type of an expresson. For this construct, there is a difference between function and &function:
int bar();
decltype(bar); // type is int ()
decltype(&bar); // type is int (*)()

This difference is especially important if you want to pass the type as a template parameter, say, to std::unique_ptr.
std::unique_ptr<void, decltype(free)> foo; // INVALID
std::unique_ptr<void, decltype(&free)> foo; // valid

The first is invalid because it would attempt to create a function as an instance field of unique_ptr.
Comment: "pointer to an array" makes me cringe. I know what you're saying, but it's confusing since `p` is a "pointer to an array" if it is declared, for example, as `int (*p)[4]`. An array name that decays to `int *p` is becomes a pointer to the first element, not the entire array.
Comment: It's not any more wrong than the declaration `apply(int foo[4])`. You're not actually passing an array, you'll be passing a pointer to that array. This is what is called "decay": some types (functions and arrays) *decay* to their pointer type when you pass them as parameters.
Comment: You could add that `decltype((bar))` will give you the type `int (&)()`.
Comment: Thank you for your answer. Now I understand there is no difference between apply2(func) and apply2(&func). However, I cannot still understand why apply1 works.
Comment: @user2748866 Why would it not? `apply1(int fn(void))` is the same as `apply1(int (*fn)(void))`; and `apply1(func)` is the same as `apply1(&func)`.
Comment: Because void foo(int x); and void bar(int* x); requires different types of parameter.
Comment: For your previous concern, it's all about the placement of the `*`. Compare these two: `apply1(int* fn())` and `apply1(int (*fn)())`. The first one accepts a function that returns a `int*`; the second accepts a function pointer that returns a `int`. These two declarations are **not** compatible because the functions have a different return type. By grouping the `*` with the function name, you tell the compiler you want a function pointer, instead of a function that returns a pointer.
Comment: Here's a small (useless) program that could help you spot the differences: http://ideone.com/kn18pz
Comment: `std::decay::type` might be worth mentioning somehow.
Comment: The question is tagged both C and C++. C doesn't have references, `decltype`, or `std::` *anything*.


Calculating per cent improvement in test error

Question: I've come across this statement regarding an improvement percentage and I don't know if it's okay. It says this:

The training error and test error using the neighborhood model are
  0.34 and 0.54 respectively, compared to 0.51 and 0.64 using the baseline predictor. This represents a 16% improvement in RMSE for the
  test set.

How does it get that 16%?
I would do:
Initial : 0.64
Final :0. 54
final - initial = |0.54 - 0.64 |=0.10
0.10 / 0.64 = 0.1562
0.1562 x100 = 15.72%
Is that correct?
Comment: You are comparing 0.54 (test error with your model) to 0.64 (test error with the baseline predictor), so your result is how much much the model improved the results in the test set.
Comment: I get that! It was confusing of how it calculated that 16%. I wanted to be sure I was doing the right calculation.
Answer: Yes, your calculation is correct. I've removed my previous answer because it was based on a misinterpretation.
Comment: @Delan My mistake, I misinterpreted your question initially.
Comment: Actually, the baseline model (predictor) performs worse


What is the sum of the maximum and minimum values BC can take?

Question: $\small AB$, $\small BD$ and $\small BC$ are are integer measurements
If $\small AB + BD = k$, find the maximum and minimum values that the $\small BC$ side can assume and then add the values found. (Answer: $k$)
My progress:
$\small \triangle ADB: |AB - BD |< AD < AB + BD \therefore \boxed{|AB-BD| < AD < k}\\$ $\small
\triangle BCD: \boxed{|BD-DC| < BC < BD+DC}\\$ $\small
\boxed{\measuredangle B = 180^o -4\theta}\\$ $\small
\triangle ABC:\dfrac{AB}{\sin\theta}=\dfrac{BC}{\sin3\theta}\rightarrow \boxed{\dfrac{AB}{\sin\theta}=\dfrac{BC}{3\sin\theta-4\sin^3\theta}}\\\small \triangle BCD: \boxed{\frac{BC}{\sin 2\theta}=\frac{BD}{\sin\measuredangle C}}$
These are the relationships I found but I can't "see" how to get the answer.
Comment: Not sure I understand.  Are $A$ and $D$ fixed points?
Comment: @coffeemath The problem only mentions AB, BD and BC with integers. It's a peruvian problem.
Comment: @BrianTung +1, I also am confused.  **To the OP**: +1 to your question for work shown, embedding a clarifying diagram into the question, and for making a serious effort to explain the problem.  However, I agree with Brian Tung: it is unclear what you are asking.  Please proofread your question and try to edit it so that it is (ideally) absolutely impossible for anyone to be in any way confused about what you are asking.  Often, with a complicated question, such editing can be challenging.
Comment: Yes..A and D are fiexd points.. I  have two triangles..ABC e BCD, AB + BD = k.. I need find maiximum e minimum value that BC can assume. and then add the two values. The triangle sides are integer values
Comment: @useer2661923  Sorry, I tried to explain it better now..
Comment: There are two larger and three smaller triangles. Do you mean all sides of each are integers, or just the larger ones? Please specify.
Comment: @user2661923 The problem only mentions AB, BD and BC with integers. It's a peruvian problem.
Comment: B is on an ellipse with A and D as ellipse foci.
Comment: @user2661923 This problem follows the same idea, maybe help: https://math.stackexchange.com/questions/4200250/find-the-largest-and-smallest-values-of-the-angles-of-a-triangle?noredirect=1#comment8714595_4200250
Comment: @BrianTung  This problem follows the same idea, maybe help: https://math.stackexchange.com/questions/4200250/find-the-largest-and-smallest-values-of-the-angles-of-a-triangle?noredirect=1#comment8714595_4200250
Comment: Why the use of "sen" - do you mean the simple sine function? Your equation in the Rectangle does not seem right.
Comment: @Moti ..Why is it not correct? È the simple application of the sine theorem...
Comment: Because both BC and BD are above the line - the sine theorem
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/127732/discussion-between-peta-arantes-and-moti).
Comment: I see you corrected it.
Answer: $AB=a, BD=b, BC=c$
$\triangle ABC: a\sin 3\theta=c\sin \theta \Rightarrow$
$a(3\sin\theta-4\sin^3\theta)=c\sin\theta\Rightarrow$
$a(3-4\sin^2\theta)=c\Rightarrow$
$\sin^2\theta=\frac{3a-c}{4a}\Rightarrow$
$c<3a$
$\triangle BCD: c\sin\angle BCD=b\sin 2\theta \Rightarrow$
$\sin\angle BCD=\frac{b}{c}\sin 2\theta$
$0 < \angle CBD < 180^\circ-4\theta$,
$\angle BCD=180^\circ-\angle CBD-2\theta\Rightarrow$
$2\theta < \angle BCD < 180^\circ-2\theta\Rightarrow$
$\sin\angle BCD > \sin 2\theta\Rightarrow c<b$
Any $c<{\rm min}(3a,b)$ is satisfying conditions.
Addition of positive integer requirements gives
$c_{min}=1$, $c_{max}=k-1$, $c_{min}+c_{max}=k$.
Comment: Excellent..GratefulL
Comment: Reviewing the question I had a doubt.. $csin\angle BCD = bsin 2\theta$..Would not be $csin\angle BCD = BDsin 2\theta$ and not  $bsin2\theta$ ?


O que significa 'redacts password'?

Question: Na documentação do InfluxDB, encontrei a seguinte nota:

Note: InfluxDB redacts passwords when you enable authentication.

Fonte: https://docs.influxdata.com/influxdb/v0.13/administration/authentication_and_authorization
Comment: Acho que isso aí tá dizendo que o tal do InfluxDB cria uma senha quando tu ativa autenticação, mas é só um palpite.
Comment: *Redact*, neste contexto, significa *censura*, *alteração* ou *remoção*.
Answer: Recomendo usar esse link para que o usuário seja automaticamente levado à sessão da pergunta.
Até onde sei, redacts significa "censura" ou "esconde" no indicativo do presente, isso seria necessário se por exemplo a base de dados fosse mostrada públicamente, ou para assegurar os usuários do fato de que a pessoa com acesso à base de dados não pode saber sua senha, que poderia ser usada para fins maliciosos em um cenário em que o usuário usa a mesma senha para vários serviços.
Ainda seria mais recomendado que a base de dados usasse um sistema de "hashing" de senhas, em que a senha que é enviada pela pessoa passa por um processo em que ela é tornada em outra string de caracteres, se a string que se formou é a mesma no site, o usuário é garantido o acesso ao serviço, com esse mecanismo um administrador de um site não sabe a sua senha, mas ele precisa ter o senso ético de implementar o mesmo.
Um processo de hashing só pode funcionar de um jeito, com uma série de processos fixos, do contrário isso é um processo de criptografia, uma criptografia precisa ser implementada com no mínimo dois elementos - geralmente o conteúdo a ser passado e uma "chave".
O usuário cantoni apontou algo importante:
o processo de hashing deve ser irreversível de formas convencionais, do contrário também haveria a possibilidade de que uma pessoa com acesso à base de dados recuperasse a informação dos usuários mesmo que a mesma nunca tivesse sido hospedada no servidor.
Comment: Base64 não é hashing. É apenas uma maneira de codificar uma String. É um processo completamente reversível (e deve ser). Algoritmos pra hashing de senha devem ser, necessariamente, unidirecionais. Nesse contexto, existem vários tipos, como MD5, SHA256, etc.

O que significa 'redacts password'?


Where to edit Wordpress widgets?

Question: Where do I edit the content of Wordpress widgets? When I open a specific widget inside our Wordpress CMS, all I see is:
[cl_display_thumbnail_list]
A sample page is http://www.criminal-lawyers.com.au/lawyer-profiles/bill-doogue and the section I want to edit is the lower portion with small images. I want to put them in multiple columns instead of being individually displayed in block. The problem is I don't know where to find the part where I can change class names or divs, etc.
Any feedback will be greatly appreciated.
Answer: Just open notepad++ and find cl_display_thumbnail_list in plugin folder that you use.I can help you if I know which widget are you used.Its Generally in function.php or shortcode.php file.
Answer: [cl_display_thumbnail_list] is a shortcode. Typically, shortcodes are defined in edited in a shortcodes.php or functions.php file, within a theme's root folder. However, it's also possible that a custom plugin is doing it.
You'll want to have a basic understanding about the WordPress Shortcode API before changing anything.
Comment: Thanks for the tip. I think I may have found where adjustments should be made (a function.php file) but the codes are far from the HTML codes I expect. I thought maybe I should just get rid of the shortcode inside the widget and replace it with fresh HTML codes. Will most likely solve the problem but I would've wanted to tackle the shortcodes.
Answer: WP uses core widgets :
    wp-includes/widgets.php: register_widget()
core register for widgets:
WP_Widget_Factory::register ( string $widget_class )
But some custom themes biuld a own way of widgets of shortcodes in own theme...
For ex:  yourtheme/widgets.php or shortcode.php
Answer: It depends where your widget code is.
There are two places from where you can find your widget.
1. functions.php (Within your theme folder)
2. Plugins folder. (If a plugin is used to create a widget)
Check both of the above folders to find your widget coding.
Make changes according to your need.
[cl_display_thumbnail_list] is a shortcode, you need to learn about shortcodes before making any change.
Follow the link below to understand shortcodes.
https://codex.wordpress.org/Shortcode

Where to edit Wordpress widgets?


ativar onclick no Select de um form

Question: Preciso fazer que com ao clicar no select ative a popup porem não esta funcionando, já o input funciona normalmente
$("#alert_button").click( function() {
jAlert('Selecione Primeiro o Estado', 'Classificados Publico');
});

<input id="alert_button" type="button" value="Show Alert" />

<select id="alert_button">
<option value="index.php?s=<?php echo "$termo"; ?>" selected> Cidade </option>
</select>

Comment: Qual a versão do jquery-ui que você está usando ?
Answer: Arsom, tens dois elementos com a mesma ID.
IDs têm de ser unicas. Muda para classes e vai funcionar.
jQuery
$(".alert_button").click( function() {
    jAlert('Selecione Primeiro o Estado', 'Classificados Publico');
});

HTML
<input class="alert_button" type="button" value="Show Alert" />

<select class="alert_button">
    <option value="index.php?s=<?php echo "$termo"; ?>" selected> Cidade </option>
</select>

$(".alert_button").click( function() {
    alert('Selecione Primeiro o Estado');
});

<input class="alert_button" type="button" value="Show Alert" />
<select class="alert_button">
   <option value="index.php?s=termo" selected> Cidade </option>
</select>

ativar onclick no Select de um form


What is the name of shorting algorithm used?

Question: For example,

Set X = { Apple = 1, Banana = 2, Cucumber = 3 }
Set Y = { CFO = 1, CFO = 2, CSO = 3 }

Combinations are in some order
[X, Y] = K
[1, 1] = 1
[1, 2] = 2
[2, 1] = 3
[1, 3] = 4
[2, 2] = 5
[3, 1] = 6
[2, 3] = 7
[3, 2] = 8
[3, 3] = 9

what is the name of this kind of shorting order?
I agreed now that its not in lexicographical order.
Comment: now I only want to know which method used to short combinations?
Answer: This is definitely not lexicographic, which would be
$11,12,13,21,22,23,31,32,33$.
What you are doing can be thought of as follows. Create a $n \times n$ matrix of indices, and enumerate it by diagonal strips from upper left to lower right corners. I don't think there is a specific name for this traversal.
Comment: You got it what i wanted to know.
Answer: If you start your numbering at $0$ rather than at $1$ and really order lexicographically (you didn't) you will have just written the numbers from $0$ to $8$ in base $3$ - in your example with the units and $3$'s column reversed.
This generalizes to sets with different numbers of elements if you allow "mixed bases" with a different number of digits allowed in each column.
Indexing from $0$ is common and useful in computer science. It's rarer in mathematics but often useful there.
Comment: I have also done indexing from 0 and with different bases but here I wanted to know more about the topic so I kept it simple.


Discrete Probability Question With No Named Distribution

Question: I've got a real world probability problem that I have been able to solve easily using simulation but that I am struggling to find (out of pure interest) an analytic solution to. For privacy reasons, I have changed both the context and the actual numbers.
A vendor is selling tickets. Customers either purchase 1 ticket with probability 60%, 2 tickets with probability 30%, or 3 tickets with probability 10%. If the vendor needs to sell 10 tickets, how many customers on average does he need to sell to (assuming customer purchases are iid)?
A simulation produces an average of 6.6 customers, but I am curious what an analytic solution to this might look like (if there exists a convenient one) as there is no named distribution I can think of that corresponds to this problem.
Comment: Should say:  when I ran this computation I got $6.9\overline 3$ which is significantly greater than your $6.6$ though perhaps I did it too hastily.
Comment: @lulu, back at my desk, I checked my simulation and realized that I was undercounting the number of customers by one when the ticket count was reached at either 11 or 12 (not strictly 10), which explains the difference between our answers and why yours is correct.
Comment: I would go by backwards induction.  If the vendor has sold $9$ tickets, then only $1$ more customer is needed.  If the vendor has sold $8$ then you expect it to take $2$ customers with probability $.6$ and $1$ customer with probability $.4$ and so on.
Comment: I would be interested in comparing our code to see what we are doing differently but I'm not sure if it's generally approved to post code in comments?
Comment: @lulu Not exactly $6.9\overline 3$ but exactly $6.933335296$
Comment: @Henry. Yes, you are right.
Comment: @SimonSaltine  Thanks for confirming that.
Answer: One analytical approach is find the probability that you have not sold $10$ tickets after seeing $n$ customers. This is the sum of the coefficients of $x^k$ with $0\le k \le 9$ in the expansion of $$\left(0.6x+0.3x^2+0.1x^3\right)^n$$
For example with $n=2$ you get $0.36x^2+0.36x^3+0.21x^4+0.06x^5+0.01x^6$ and adding up the coefficients with $0\le k \le 9$ gives $1$ as you might have thought anyway; it becomes interesting when $4 \le n\le 9$ as then you may or may not have sold $10$ tickets. For various values of $n$ this gives
<code>n customers      0 1 2 3  4      5       6       7          8           9           10+
P(tickets < 10)  1 1 1 1  0.9909 0.90126 0.64152 0.3055968  0.0839808   0.010077696  0
</code>
and if you add these probabilities up then you get the expected number of customers when you have sold at least $10$ tickets of $6.933335296$, as lulu found
Comment: I assume you mean $0.1x^3$ instead of $0.1x^4$?
Comment: Also, could you provide some intuition as to why you would start at n=0? My intuition would be to start at n=1, but then I'd be off by 1.
Comment: @SimonSaltine I did mean $0.1x^3$ - thank you -edited
Comment: @SimonSaltine. The expectation of a non-negative integer random variable is $E[X]=P(X>0)+P(X>1)+P(X>2)+\cdots$.  It is also $E[X]=P(X\ge 1)+P(X\ge 2)+P(X\ge 3)+\cdots$ but the first of these two expressions is easier to calculate here
Comment: I understand how you calculate the probabilities above, and I'm familiar with this property of the expectations of non-negative integers, but I am having conceptual difficulties seeing how you tie these two together here. It seems to me like you've calculated P(tickets<10|N=n) where N is the number of customers. If that's the case, then I'm not sure I see how we are using the above property of expectation. If this is not the case, then I guess I'm not clear what exactly the random variable X is when you employ the above property of expectation.
Comment: I am saying for example, that if the probability you have sold fewer then ten tickets after $n=7$ customers is $0.3055968$ then the probability the number of customers you need to sell ten tickets exceeds $7$ is also $0.3055968$.  So yes: $P(X>n)=P(T <10 \mid N=n)$ where $X$ is the number of customers needed to have sold ten tickets; if you have not sold ten tickets by the $n$th customer then you need more than $n$ customers to have sold ten tickets
Comment: Thank you for your explanation; this was very helpful!
Answer: To write out the recursive solution sketched in the comments:  Let $E_n$ denote the expected number of customers needed to sell $n$ tickets.  Then, of course, $E_0=0, E_1=1$  We compute $E_2=.6\times 2+.4\times 1 =1.6$.
Recursively, we see that, for $n≥3$,  $$E_n=1+.6E_{n-1}+.3E_{n-2}+.1E_{n-2}$$
Since the associated cubic does not have pleasant roots, the closed form for the solution is not pleasant.  It is, however, easy to compute $E_n$ for small $n$ and one gets $$\boxed {E_{10}=6.933335296}$$  matching the result obtained by @Henry.


What is the main note you hear when hearing a chord?

Question: I've done experiments on my friends and myself, and when listening to chords, the note we end up hearing at the forefront (in other words the note we hum when  reproducing the song) is actually the highest note in the chord. For example, in the C major chord of C,E,G, the note that will be hummed is G. I looked online to see if anyone else has the experience, and there appears to be a lack of information. Some people said that they guess you should head the root/dominant note (C in our example), but all my tests have shown otherwise. Is there any research that has been done about this, or anyone with different experience?
Comment: 'Root/dominant' is a dangerous term to use here! Consider a different adjective, as the  'dominant' of C is actually G! Expect you mean strongest?
Comment: There is no "main note" in a chord. There is a _fundamental_, but this isn't necessarily more prominent than the other notes.
Comment: I'm not sure enough to submit this as an answer, but as a singer in a SATB choir, a bass voice would maybe be drawn more to the C note, but tenors and altos often sing the 3rd or 5th note and might be drawn more to the E or G notes.
Comment: I think you need to add specifics about *range* of both the singers and in what octave you are playing the chord. Some info about any ear/voice training of your test subjects would be important to know.
Comment: yeah, use root, 3rd of chord, etc. not 'dominant' not interchangeable terms in this context.
Comment: Depends on which notes the trumpets or trombones are playing. ;)
Answer: As a generalisation, the note heard best is often the highest being played. So, it will depend greatly on which inversion is being listened to. I suspect so far, as intimated from the question, that it's the root version being played. So no great surprise that the 5 is spotted. think about it - if you were harmonising a melody on, say, piano, you'd be putting the melody notes on top of the harmonies. that's because we tend to hear the highest notes better. If we lost that melody note inside the harmony, we wouldn't be hearing the tune we're supposed to.
The other end of the spectrum is also valid. In a full-blooded chord with maybe 6 or 7 notes, the lowest will quite often be the root - played by a low sounding instrument - maybe bass. Making it a root version, regardless of what's above. That note defines the chord best. In a C major or C minor, it's still that C. It's what I listen to initially when transcribing chords as it's going to be the first part of what I write down.
Answer: Given a single chord, all played on the same instrument, with no notes doubled, there's no set answer to the question. Probably your ear will pick out either the highest or lowest note.
But, as always, context is all.  Some music is led by the bass line - often played on a separate instrument.  Some by the melody - again maybe with an individual sound.  Often the melody is the highest note in the chord, but it doesn't have to be.  It's common to have a variant harmonisation of a hymn tune where e.g. the tenors have the melody.
Answer: It is the top pitch(highest note) that is heard normally.
Example) If all four voices in SATB are singing, Soprano is heard and hummed clearly compared to the other voices. Similarly with the C chord, G is the most heard/hummed note.
However the Chord name or chord root note is the fundamental main note which is being supported/harmonized by the other notes (3rd note supports the root note's major/minor quality similarly 5th note harmonizes the root note), in other words we hum the top note to support the root note.
Answer: The simplest question is usually the least considered, a search on "voice leading" will show that classical composers thought of a progression of 4 note chords as a progression of 4 single note melodies so obviously the top notes spell out the top melody and obviously the top melody dominates!This is almost never mentioned so when it is mentioned theorists sometimes don't know what to say. For chord sequences the lowest note is the bass and the highest note the melody, but ether bass or melody may be followed at the others expense because we direct our attention where we like, the casual default seems to be to pay the most attention to the highest melody note at nearly all times, so the inversion of a chord is crucial to the perception of melody unless there is a voice above the chords to carry the melody regardless of instrumental inversions
Comment: *"so obviously the top notes spell out the top melody and obviously the top melody dominates"* If it's so obvious that the top melody dominates, explain why! That's what OP's asking, you know...


Tete de la course, why are they at front?

Question: What is tete de la course? And why are they at the front of the pack leading the peleton by quite a high time margin? And who decides the riders to be at tete de la course? And I think everybody at Tour de France should start at the same, it isn't fair for a pack to start early than the rest of the riders?
Answer: Tete de la course is French for head of the course, and means the front of the race that day.
All riders start at the same time each day, and their time to complete the course is accumulated to decide who wins.
On different days different riders decide to break away and try for the stage win, or more realistically to improve their profile within a team, or advertise their sponsor more effectively. These riders simply pedal faster than the others, and if a few work together and the peleton don't actively chase, they can gain quite an advantage.
If a team in the peleton decides to chase, however, most breaks will be caught.
Tactically a break may succeed if nobody in the group poses a threat to the race leader or one of the jersey holders, but if they do the break will be chased down. This has resulted in riders being ejected from a breakaway as they will cause the peleton to chase the break down!
Comment: Thanks for the answer.I was in total confusion all these years.


"Vary for Traits" button not shown on storyboard

Question: I'm on Xcode 9.4.1 and usually there is a "very for Trait" button in the right side of the pane where you can configure the device the storyboard should display. But for one app, I only see iPhone in the device pane (I don't see iPad) and I can't see the "Vary for Trait" button in the storyboard, is there any setting I need to configure to have it shown?
Answer: When viewing your storyboard / xib in Interface Builder, make sure the right pane is open (or click the button in the top right farthest to the right)
Make sure you have selected the root view for which you wish to have traits enabled.
Click the document icon to open the general document panel (with the first category of "Identity and Type")
Enable "Use Trait Variations" under "Interface Builder Document"
This will enable the "Vary for Traits" button, along with the various + buttons throughout the document and view options.


Limit on the expression containing sides of a triangle

Question: To find the bounds of the expression $\frac{(a+b+c)^2}{ab+bc+ca}$, when a ,b, c are the sides of the triangle.
I could disintegrate the given expression as $$\dfrac{a^2+b^2+c^2}{ab+bc+ca} + 2$$  and in case of equilateral triangle, the limit is 3.
Now how to proceed further?
Comment: @gt6989b It has to form the sides of a triangle. So $a$ can't tend to infinity (or go past the golden ratio).
Comment: In what sense are you taking the limit? Consider, e.g. $b = a^2$ and $c=a^3$. Then your expression becomes
$$
\frac{a^2+a^4+a^6}{a^3+a^5+a^4} \sim \frac{a^6}{a^5} = a \to \infty...
$$
Comment: @CalvinLin Interesting there when you say it cant go past the golden ratio, can you please tell me more about that?
Comment: In his special case where the sides are $a, a^2, a^3$, it must satisfy the triangle inequality, so if $a>1$, then we must have $a + a^2 > a^3 $. Solving this tells you that $(1<) a < \phi$
Answer: Hint: The issue is that the condition "sides of a triangle," though it poses an easily stated set of constraints ("Triangle Inequality") is not easy to work with algebraically.
There is, however, a standard trick. The positive numbers $a$, $b$, and $c$ are sides of a triangle if and only if there exist positive numbers $p$, $q$, and $r$ such that $a=q+r$, $b=p+r$, $c=p+q$.
(The numbers $p,q,r$ have a simple geometric interpretation. Draw the incircle of the triangle. This meets the sides of the triangle at $3$ points, which divide each side of the triangle into $2$ segments. These segments are equal in pairs, and $p$, $q$, and $r$ are the three lengths of these segments.)
If we substitute for $a$, $b$, and $c$ in our expression, we get fairly quickly the desired bounds.
Answer: Without loss of generality, $a \leqslant b \leqslant c = 1$. Thus it remains to see that
$$1 \leqslant \frac{1+a^2+b^2}{a + b + ab} \leqslant 2.$$
For the left inequality, we rewrite
$$a + b + ab \leqslant 1 + a^2 + b^2 \iff 0 \leqslant 1 - a - b + ab + a^2 -2ab + b^2 = (1-a)\cdot(1-b) + (b-a)^2,$$
which is evident.
For the right inequality,
$$1+a^2+b^2 \leqslant 2(a+b) + 2ab \iff 1 + (b-a)^2 \leqslant 2(a+b),$$
which is seen to be true since by assumption - that $a \leqslant b\leqslant 1$ be the sides of a triangle - $0 \leqslant b-a \leqslant 1 \leqslant a+b$.
letting $a \to 0$ resp. $a \to 1$ (both imply $b \to 1$) shows that the bounds are sharp.
Answer: (Without using the condition that $a, b, c$ are sides of a triangle) We know that
$$(a-b)^2+(b-c)^2+(c-a)^2 \geq 0 $$
This implies that $a^2 + b^2 + c^2 \geq ab + bc + ca$. Hence $\frac{a^2+b^2+c^2} { ab+bc+ca} \geq 1$, so the minimum of the initial expression is 3.

To find the maximum, you will need to use the triangle inequality, which states that $a + b \geq c $.
It might be easier for you to try and find what the limiting case is.
Answer: Let $x=p-a$, $y=p-b$, and $z=p-c$, where $p=(a+b+c)/2$. The main expression is equal to $$F:=\frac{4(x+y+z)^2}{x^2+y^2+z^2+3(xy+yz+zx)}=\frac{4\sum x^2+8\sum yz}{\sum x^2 +3\sum yz}\\=4-\frac{4}{\sum x^2/\sum yz +3}.$$ From Cauchy-Schwarz we know that $\sum x^2 \geq \sum yz$. Thus, $F\geq 3$. Furthermore, it is obvious that $F<4$. The lower bound is attainable at $x=y=z$ (i.e., $a=b=c$) while you can only tend to the upper bound by tending two of $x$,$y$, or $z$ two zero while keeping the third fixed.


Linear Combination of Vectors simple problem

Question: So I've embarked on teaching myself Linear Algebra with G. Hadley's book which I found in my mom's library. The first chapter teacher vectors, linear dependence, and define subspaces and bases but I can't solve this simple problem in the problems section:
Express x=[4,5] as a linear combination of a=[1,3], b=[2,2].
So by my understanding this is asking what scalars can you multiply these vectors by and then add them so you get [4,5] as a solution. But it seems to me logically that no matter how you manipulate these values you can't get the difference between them to be only 1, since [1,3] has a difference of 2 and [2,2] just scales both values up equally. I'm sure I'm missing something simple and fundamental. Thanks for any help!
Comment: You can also scale by non-integers.
Comment: Try to solve $c_1\Bbb a+c_2\Bbb b = \Bbb x$.
Comment: First solve the first component, that is find $x,y$ so that $1x+2y = 4$. This has many solutions, $x = 4-2y$. Now solve for the second component, using **the same** $x,y$ to get $2x+2y = 5$.
Answer: Solve the linear system
$$\begin{cases}x\;\,+2y=4\\3x+2y=5\end{cases}$$
and you'll find the coefficients $\;x,y\;$ that give you the linear combination. As observed in the comments, these coefficients do not have to be integers, and also check the above system has a unique solution (why?)
Comment: oh ok, I knew it was something fundamental. I was thinking of the definition of linear dependence. Thank you.


$\lvert y-z\rvert<\delta \implies \lvert y-\alpha\rvert<\delta_0$ and $\lvert z-\alpha\rvert<\delta_0$ continuity problem

Question: In Spivak's book there is a theorem proved that if $f$ is continuous on $[a,b]$ then $f$ is uniformly continuous on $[a,b]$ which starts as follows:

For $\epsilon>0$ let the function be $\epsilon$-good on $[a,b]$ if
there is some $\delta>0$ such that for all $y$ and $z$ $\in [a,b]$:
If $\lvert y-z\rvert<\delta$, then $\lvert f(y) - f(z)\rvert<\epsilon$

Consider any particular $\epsilon>0$.
Let $A = \bigl[\space x:a\le x\le b$ and $f$ is $\epsilon$-good on $[a,x]\space\bigr]$
Clearly $a\in A$ and $A$ is bounded above (by b), so the least upper bound $\alpha$ exists.
If $\alpha<b$, then because $f$ is continuous, there is $\delta_0>0$ such that:
$\lvert y-\alpha\rvert<\delta_0 \implies \lvert f(y)-f(\alpha)\rvert<\frac\epsilon2$
Consequently if $\lvert y-\alpha\rvert<\delta_0$ and $\lvert z-\alpha\rvert<\delta_0$ then $\lvert f(y)-f(z)\rvert<\epsilon$.

So $f$ is surely $\epsilon$-good on
$[\alpha-\delta_0,\space\alpha+\delta_0]$

I am unable to reproduce the last conclusion.
By definition, in order for $f$ to be $\epsilon$-good on $[\alpha-\delta_0,\space\alpha+\delta_0]$ for $\epsilon>0$, we must find $\delta>0$ such that for all $y,z\in[\alpha-\delta_0,\space\alpha+\delta_0]$:
If $\lvert y-z\rvert<\delta$, then $\lvert f(y) - f(z)\rvert<\epsilon$
I suspect that in order to do so, we want for some $\delta$: $\lvert y-z\rvert<\delta \implies \lvert y-\alpha\rvert<\delta_0$ and $\lvert z-\alpha\rvert<\delta_0$, however I am definitely missing some obvious step that would allow me to reach this conclusion.
Answer: If $x,y\in[\alpha-\delta_0,\alpha+\delta_0]$, then $|f(x)-f(\alpha)|<\frac\varepsilon2$ and $|f(y)-f(\alpha)|<\frac\varepsilon2$. Therefore,\begin{align}|f(x)-f(y)|&=\left|\bigl(f(x)-f(\alpha)\bigr)-\bigl(f(y)-f(\alpha)\bigr)\right|\\&\leqslant|f(x)-f(\alpha)|+|f(y)-f(\alpha)\\&<\varepsilon.\end{align}
Comment: I proved that for *any* two elements $x$ and $y$ of $[\alpha-\delta_0,\alpha+\delta_0]$, we have $|f(x)-f(y)|<\varepsilon$. Therefore, *in particular*, if $x,y\in[\alpha-\delta_0,\alpha+\delta_0]$ *and* $|x-y|<\delta$, then $|f(x)-f(y)|<\varepsilon$.
Comment: @schn Yes, it should have been $\alpha$ instead of $z$. I've edited my answer. Thank you. Concerning your other remark, yes, you are right here too, but it is not a big deal. If$$x\in(\alpha-\delta_0,\alpha+\delta_0)\implies|f(x)-f(\alpha)|<\frac\varepsilon2,$$then simply take $\delta_1\in(0,\delta_0)$, and then$$x\in[\alpha-\delta_1,\alpha+\delta_1]\implies x\in(\alpha-\delta_0,\alpha+\delta_0)\implies|f(x)-f(\alpha)|<\frac\varepsilon2.$$
Comment: This follows in a straightforward manner. However how can one reach the conclusion that if above holds then $\lvert y - z \rvert < \delta \implies \lvert f(y)-f(z)\rvert < \epsilon$ ?

After all, the definition of $\epsilon$-good clearly states that we want above to hold.
Comment: Could you make this statement even more explicit? Although it is obvious, on what basis we can infer that the assumption about $\vert x-y\rvert<\delta$ won't "mess" with our conclusion?
Comment: That's as if I wrote "every number from the set $S$ is greater than $0$" and you asked me how to deduce that every integer from the set $S$ is greater than $0$. If it happens for every *number*, then it happens for every *integer*. It's the same thing here. If it is *always* true that $x,y\in[\alpha-\delta_0,\alpha+\delta_0]\implies|f(x)-f(y)|<\varepsilon$, then it is still true that $x,y\in[\alpha-\delta_0,\alpha+\delta_0]\text{ and }|x-y|<\delta\implies|f(x)-f(y)|<\varepsilon$.
Comment: Just to drive things home, does it boil down to the fact that $[(P \implies Q)]\implies [(P \land R)\implies Q]$ is a tautology?
Comment: Yes, that is correct.
Comment: @JoséCarlosSantos In your answer, by $z$ do you mean $\alpha$? Also, I do not understand how you conclude if $x\in[\alpha-\delta_0,\alpha+\delta_0]$ then $|f(x)-f(\alpha)|<\frac\varepsilon2$ (I used $\alpha$ here instead of $z$). Since $f$ is continuous at $\alpha$, we have $\lvert x - \alpha \rvert < \delta_0 \implies \lvert f(x)-f(\alpha)\rvert < \frac\varepsilon2$. So for $x\in(\alpha-\delta_0,\alpha+\delta_0)$, then $\lvert f(x)-f(\alpha)\rvert < \frac\varepsilon2$. How can you make any implications for $x$ in the *closed interval* $[\alpha-\delta_0,\alpha+\delta_0]$?


Modify SSRS 2010 with Visual Studio 2017

Question: I have to modify some reports SSRS, so I downloaded them and update them with Visual Studio 2017 (I have SSDT 2015 and SQL Server 2008).
Then when I wanted to upload them on the SSRS server, I have an error about the versions. So I checked the lines with notepad of the .rdl and they're in 2010.
I just notice that when I upload them in my SSRS project with Visual Studio, they change to 2016.
I don't achieve to create a SSRS project that allow the 2010 .rdl.. It always change them to 2016.
Did I have to use an older version of Visual Studio ?
2 days that I search and don't found .. :|
Thanks !
Answer: Two things:
1)  Your project must specify the version if you are using the deploy option from visual studio.  This is found under properties for the project:

2)  If you are using the upload function from Report Manager, you need to use the file found in the bin\debug folder, not in the main folder of the project


open subspace of locally compact

Question: It is kown that

A closed subspace of a locally compact space is locally compact
If $X$ is locally compact Hausdorff and a dense subspace $Y\subseteq X$ is locally compact iff $Y$ is open.

From the informations above, I have questions as follow:

If $X$ is locally compact, is there any open subspace $Y$ of $X$ which is not locally compact?
If $X$ is locally compact Hausdorff, is there any closed subspace $Y$ of $X$ which is not locally compact?
Comment: Isn't question 2 answered by fact 1? And open subspaces of locally compact spaces are locally compact as well. More generally, if $Y$ is the intersection of an open and a closed subspace, then it is locally compact.
Answer: The definition of locally compact can be: (i) every point has a ndhd basis of compact nbhds, or the weaker (ii) every point has a compact neighborhood. In case the space is Hausdorff, both are equivalent, and then, the locally compact subspaces are exactly the locally closed subsets, that is, the intersections of an open and a closed subset. Clearly, for the definition (i) open subsets are always locally compact. For (ii) however, there are compact (non-Hausdorff) spaces which have non locally compact open subsets. Besides the usual bibliography, one can always take a look at the Steen-Seebach counterexample bible!

open subspace of locally compact


Visualization/Drawing Request of a line L intersecting all three coordinate planes Oxy, Oyz, and Ozx

Question: I'm not sure how to draw a line that intersects all three coordinate planes. I'm suspicious that such a line doesn't exist. How do we prove its existence? I guess we should try draw a picture. I beg for a picture.
Comment: Just draw a line through the origin...
Comment: the point common to all three axis is the origin?
Comment: .. or *almost* any line - it just shuold not be parallel to einther of the three planes. For example, the points $(1,1,0)\in O_{xy}$, $(2,0,1)\in O_{xz}$, and $(0,2,-1)\in O_{yz}$ are collinear.
Comment: Yes ${}{}{}{}{}$
Comment: what is the
"it" that shouldn't be parallel to either of the 3 planes?
Comment: Why do we use a big O before writing $_{xy}$ in small case?
Comment: What set is the point (1,1,0) an element of? is the point (1,1,0), an element of $\mathbb{R^n}$?
Comment: https://i.stack.imgur.com/qCdSk.png
Answer: All the lines that are not parallel to a coordinate plane intersect all the three coordinate planes.
In the figure you can see the line that passes thorough the points $A=(2,1,0)$ and $ B=(0,2,1)$, that has equation $(x,y,z)=t(2,-1,-1)+(0,2,1)$ and intesects the plane $y=0$ at $C=(4,0,-1)$.


error noCamerasAvailable, which is only on iPhone <8+ Swift

Question: i have a strange issue which I can notice only on devices older than iPhone 8+,
I don't know how can I fix that but error message is very simple 'noCamerasAvailable,'
Everything with permissions should be okay cause it works on my iPhone XS Max and my friend's iPhone X. That is my simply code to display camera view
cameraController.prepare {(error) in
             if let error = error {
                 print("Camera error:")
                 print(error)
             }

             try? self.cameraController.displayPreview(on: self.view)
         }

Answer: Fixed I had to replace this
let session = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInDualCamera], mediaType: AVMediaType.video, position: .unspecified)

to this
let session = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .unspecified)


Erro :"GetLifeCycleBase" not found. You need to call "Get.put(GetLifeCycleBase())" or "Get.lazyPut(()=>GetLifeCycleBase())"

Question: Estou usando o getX para gerência de estado e estou tendo um erro que diz o seguinte:

"GetLifeCycleBase" not found. You need to call "Get.put(GetLifeCycleBase())" or "Get.lazyPut(()=>GetLifeCycleBase())"

Eis a view:
import 'package:flutter/material.dart';
import 'package:flutter_application_stock/controllers/product_controller.dart';
import 'package:get/get.dart';
class HistoryScreen extends GetWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
            child: GetX<ProductController>(
      init: Get.put(ProductController()),
      builder: (ProductController productController) {
        if (productController != null) {
          return Expanded(
            child: ListView.builder(
              itemCount: productController.produtos.length,
              itemBuilder: (_, index) {
                return Text(productController.produtos[index].nome);
              },
            ),
          );
        } else {
          return Text("Loading");
        }
      },
    )));
  }
}

O controller:
import 'package:flutter_application_stock/models/produto_model.dart';
import 'package:flutter_application_stock/services/database.dart';
import 'package:get/get.dart';
class ProductController extends GetxController {
  Rx<List<ProductModel>> productList = Rx<List<ProductModel>>();
  List<ProductModel> get produtos => productList.value;
  @override
  void onInit() {
    productList.bindStream(Database().productStream());
  }
}

A database:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_application_stock/models/produto_model.dart';
class Database {
  Firestore _firestore = Firestore.instance;
  Stream<List<ProductModel>> productStream() {
    return _firestore
        .collection("products")
        .snapshots()
        .map((QuerySnapshot query) {
      List<ProductModel> retVal = List();
      query.documents.forEach((element) {
        retVal.add(ProductModel.fromDocumentSnapshot(element));
      });
      return retVal;
    });
  }
}

o model:
import 'package:cloud_firestore/cloud_firestore.dart';
class ProductModel {
  String id;
  String nome;
  String embalagem;
  String categoria;
  ProductModel({this.id, this.nome, this.embalagem, this.categoria});
  ProductModel.fromDocumentSnapshot(DocumentSnapshot snapshot) {
    id = snapshot.documentID;
    nome = snapshot.data["nome"];
    embalagem = snapshot.data["embalagem"];
    categoria = snapshot.data["categoria"];
  }
}

Agradeceria qualquer ajuda
Answer: Acredito que até seja má pratica registrar singleton dentro de init: do GetX(), o init já precisa de uma instância pronta para usá-la e não que ainda precise registrá-la.
init: Get.put(ProductController())

Normalmente você registra antes em algum lugar, por exemplo no main, ou usando bindings, onde registra suas dependencias automaticamente.
Experienta chamar o códido abaixo no main.dart para ver se da o mesmo erro.
Get.put(ProductController())
// ou
Get.lazyPut(() => ProductController());


Commerce 2 Twig and Retail Price

Question: I have a use case that I need to add the retail price on a receipt twig next to the discounted unit price. Ive tried every possible field syntax I could think to try, looked everywhere and stumped...
{{ order_items.i_need_the_retail_price... }}
Is it possible to get that related field with twig syntax? It doesnt appear to be carried into Order Items.
Comment: Did you try dumping the variable?

https://www.drupal.org/docs/8/theming/twig/discovering-and-inspecting-variables-in-twig-templates
Comment: Ill give it a shot thank you.
Comment: Using dump on the totals key gives me this data in an array: price (with the discount), percentage off, amount off etc all based on the entire line item though.

The order_entity key hangs on a dump, can I drill down inside that dump somehow?
Comment: Maybe just tell it to print 1-20 then I can try 21-40 etc? Im looking thru docs...
Comment: You can inspect all the available variables inside the twig file and then use your logic to combine the numbers to get the result. Can't you?
Comment: I cant seem to get a list of Order Item or Order Entity available fields using dump. Im relatively new to this. I was reading this was by design because pricing can change, products are discontinued etc but the order shouldn't change.

The available relevant fields in Order_Items totals that Im finding are discount (.365), discounted unit price and line item total. Just doing math, larger quantities could make a price round the wrong the wrong way and this wouldnt be valid for different currencies would it?
Comment: Where are you looking to get this themed? Which part of the buying process?
Comment: This is the documentation on Receipt emails - https://docs.drupalcommerce.org/commerce2/developer-guide/orders/customize-order-receipt-emails
Comment: As part of a line item in the email receipt twig.

Im not sure how to find out what fields are available in order_entity, and what syntax to use to pull the orig unit price if its there.
Comment: {{ dump(_context|order_entity) }} this gives me a white screen, and other versions of it I may be doing that all wrong...
Comment: You will only be able to dump variables that are available in the context.
Answer: After a few more hours learning twig filters I can calculate the retail price in each line item with this:
<code>{% for adjustment in totals.adjustments %}
{% set disc_percent_remainder = 1 - adjustment.percentage %}
{% set disc_unit_price_raw_2 = order_item.getUnitPrice|commerce_price_format %}
{% set disc_unit_price_raw_1 = disc_unit_price_raw_2|trim(' USD', 'right') %}
{% set disc_unit_price_raw = disc_unit_price_raw_1|trim('$', 'left') %}
{% set disc_unit_price = (disc_unit_price_raw * 100) / disc_percent_remainder %}
${{ (disc_unit_price / 100)|round(2, 'ceil') }}
{% endfor %}
</code>
This is a horrible work-around I'm sure, ruins any chance of multiple currencies and Im sure can be cleaned up a lot with nesting some of this. But, it comes up with the correct retail pice.

Commerce 2 Twig and Retail Price


Is there a "reverse clip" function in numpy?

Question: I have working code, but am wondering if there is a numpy implementation for it. This more for satisfying my curiosity and about optimising and making code prettier; I don't have an acute problem. Still, I guess this situation is common enough to be interesting to others than just myself.
So, the situation: I'm calculating a value many times in a loop, and would like to only save the minimum and maximum value.
Initially, I used
import numpy as np
vals = []
for obj in objects:
    #...do stuff...
    vals.append(obj.calc_value())
    #...do more stuff
minmax = [np.min(vals), np.max(vals)]

which works and is nice and short. However, because I'm storing all values, yet only need the min and max, this seems like a waste of perfectly good memory space. Therefore I changed it to
import numpy as np
minmax = [np.inf, -np.inf]
for obj in objects:
    #...do stuff...
    val = obj.calc_value()
    if val < minmax[0]:
        minmax[0] = val
    if val > minmax[1]:
        minmax[1] = val
    #...do more stuff

which also work, but is a bit verbose. Sure, I could extract the four lines in the code into a function I guess, but...
I couldn't help but wonder, if there isn't a numpy function for this. Something like a "reverse" clip function. A function which, like clip, compares a value to an interval. But which does not return the (possibly changed) value so that it lies in the provided interval (which is what clip does), but rather returns the (possibly extended) interval that is needed so that the provided value lies in it.
import numpy as np
minmax = [np.inf, -np.inf]
for obj in objects:
    #...do stuff...
    minmax = np.reverse_clip(minmax, obj.calc_value())
    #...do more stuff

If there is, I'd love to hear about it. Also, any ideas how I could have found it without asking here? I looked at numpy's array methods, but couldn't find it there.
Comment: Similar question: [numpy: function for simultaneous max() and min()](https://stackoverflow.com/questions/12200580/numpy-function-for-simultaneous-max-and-min)
Comment: I guess I could change the 4 lines into 2, with `minmax[0] = min(minmax[0], val)`. That's better already, but I'm still curious about a `numpy` implementation.
Answer: You can reverse the sign on the first item and apply max on both, then change it back after the loop:
for obj in objects:
    i = obj.calc_value()
    minmax= map(max, zip([-i, i], minmax)) # using python
    minmax = np.vstack((minmax, [-i, i])).max(0) #using numpy
minmax *= np.array([-1, 1]) #using numpy
minmax = [i * j for i, j in zip(a1, [-1, 1])] # using python, or do list(a1) * np.array([-1, 1])

Comment: You can replace `[-i, i]` with `np.array([-1, 1]) * obj.calc_value()` to eliminate the temporary variable
Comment: Thanks @Mstaino for your answer! I wouldn't call it more readable, but it's definitely creative ;) I probably should have been more clear in my question but, due to the `[-i, i]` list, it's unfortunately not possible to forgo using a temporary variable here.
Comment: I personally find the `map` + `zip` combination very readable, and more performant for small operations. The `vstack` option less so, it is just to give you a different alternative


Enable gzip with docker and bitnami/nginx

Question: I deployed a website with docker and bitnami/nginx as image: https://www.10studio.tech/demo. After deployment, I realized that files like analyzejs.js was not gzipped:

Here is docker-compose.yml:
version: "3"
services:
  docusaurus:
    image: bitnami/nginx:1.16
    restart: always
    volumes:
    - ./build:/app
    - ./certs:/certs:ro
    - ./my_server_block.conf:/opt/bitnami/nginx/conf/server_blocks/my_server_block.conf:ro
    ports:
    - "3001:3001"
    - "3002:3002"

Here is my_server_block.conf:
server {
  listen  3002;
  absolute_redirect off;
  root  /app;

  location = / {
    rewrite ^(.*)$ https://$http_host/docs/introduction redirect;
  }

  location / {
    try_files $uri $uri/ =404;
  }
}

server {
  listen  3001 ssl;

  ssl_certificate      /certs/server.crt;
  ssl_certificate_key  /certs/server.key;

  ssl_session_cache    shared:SSL:1m;
  ssl_session_timeout  5m;

  ssl_ciphers  HIGH:!aNULL:!MD5;
  ssl_prefer_server_ciphers  on;

  location / {
    proxy_pass http://localhost:3002;
    proxy_redirect off;
    proxy_set_header Host $host:$server_port;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Ssl on;
  }
}

Here is /opt/bitnami/nginx/conf/nginx.conf, where gzip seems to be enabled:
I have no name!@8317023de7ec:/app$ cat /opt/bitnami/nginx/conf/nginx.conf
# Based on https://www.nginx.com/resources/wiki/start/topics/examples/full/#nginx-conf
# user              www www;  ## Default: nobody

worker_processes  auto;
error_log         "/opt/bitnami/nginx/logs/error.log";
pid               "/opt/bitnami/nginx/tmp/nginx.pid";

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    log_format    main '$remote_addr - $remote_user [$time_local] '
                       '"$request" $status  $body_bytes_sent "$http_referer" '
                       '"$http_user_agent" "$http_x_forwarded_for"';
    access_log    "/opt/bitnami/nginx/logs/access.log";
    add_header    X-Frame-Options SAMEORIGIN;

    client_body_temp_path  "/opt/bitnami/nginx/tmp/client_body" 1 2;
    proxy_temp_path        "/opt/bitnami/nginx/tmp/proxy" 1 2;
    fastcgi_temp_path      "/opt/bitnami/nginx/tmp/fastcgi" 1 2;
    scgi_temp_path         "/opt/bitnami/nginx/tmp/scgi" 1 2;
    uwsgi_temp_path        "/opt/bitnami/nginx/tmp/uwsgi" 1 2;

    sendfile           on;
    tcp_nopush         on;
    tcp_nodelay        off;
    gzip               on;
    gzip_http_version  1.0;
    gzip_comp_level    2;
    gzip_proxied       any;
    gzip_types         text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    keepalive_timeout  65;
    ssl_protocols      TLSv1 TLSv1.1 TLSv1.2;

    include  "/opt/bitnami/nginx/conf/server_blocks/*.conf";

    # HTTP Server
    server {
        # port to listen on. Can also be set to an IP:PORT
        listen  8080;

        location /status {
            stub_status on;
            access_log   off;
            allow 127.0.0.1;
            deny all;
        }
    }
}

Does anyone know what's wrong here and how I could enable gzip?
Answer: Your .js file is sent as application/javascript but that string is not listed in gzip_types. Either add it or correct the content type that is sent along with your file.
Comment: On a side note, you should disable the old and insecure TLS variants and use TLSv1.3.
Comment: If I correct this `/opt/bitnami/nginx/conf/nginx.conf`, will the change stay after recreating the docker container?
Comment: Of course not. You will either have to create your own image from that or mount the file from the outside.


How do I console log every name in an array using a forEach method and a callback as my only argument?

Question: I'm given an array called "names". Using a forEach method and a callback as its only argument, how do I console log every item in the array?
I've tried creating a "for" loop. But that's not what the problem asked for. Although the question is pretty straightforward, I'm just not sure what I'm missing
namesArray.forEach (callback);
console.log(names);

The error message says "expected 0 to be 5" I'm expecting the entire array to appear
Comment: What language is this? Looks like javascript or typescript. If you add the "javascript" tag you'll get lots more useful answers.
Answer: Reading between the lines a bit, I suspect the answer you're looking for is something like this:
namesArray = ['a', 'b', 'c'];
namesArray.forEach(elt => console.log(elt));

You can see the callback is an arrow function that prints the element to the console.
For more about the forEach() method, see here.
Answer: You can use a function like so:

const namesArray = ["John", "Jack", "James"];
const callback = elem => console.log(elem);
namesArray.forEach(callback);


How to extract the hyper links from a webpage in javascript

Question: As soon as the web page loading is completes and whenever the cursor will be clicked/hover on any hyper links in that web page, I want to extract that particular link on which my mouse clicked/hover. So what is the JavaScript code snippet for this ?
Answer: <code>window.onload = function() {
document.onclick = function(e) {
    var target = e.srcElement;
    if (target != null) {
         var href = target.href;
         if (href != null) {
             alert("link extracted: " + href);
         }
    }
    return false;
};
}
</code>
Answer: <code>$(document).click(function(e){
    if($(e.target).closest('a').length){
        alert('You clicked a link');
        alert($(e.target).closest('a').attr('href'));
    }
    else{
        alert('You did not click a link');
    }
});
</code>


sort an array in specific order using php

Question: I have an array
$user=array(
        "20163_100011100001_Guarantor_address_Proof.jpg",
        "20163_100011100001_Guarantor_Identity_Proof.jpg",
        "20163_100011100001_Guarantor_Photo.jpg",
        "20163_100011100001_Member_Address_proof.jpg",
        "20163_100011100001_Member_Identity_proof.jpg",
        "20163_100011100001_Member_Photo.jpg"
     );

And I want to sort $user array in given order
$order=array(
        "20163_100011100001_Member_Photo.jpg",
        "20163_100011100001_Member_Address_proof.jpg",
        "20163_100011100001_Member_Identity_proof.jpg",
        "20163_100011100001_Guarantor_Photo.jpg",
        "20163_100011100001_Guarantor_address_Proof.jpg",
        "20163_100011100001_Guarantor_Identity_Proof.jpg"
     );

Answer: Isn't it better to have $user be filled in the right order from the start? Anyhow you could try this
$order=array(user(6), user(4), user(5), user(3), user(1), user(2))
Comment: $user array is taken in randomly.
Comment: As DarkBee suggested, you could use `sort` to sort `$user` alphabetically and change the code handling whatever you want with this array to accept `$user` alphabetically.


What is appropriate statistical test for one condition?

Question: There is one chemical for plants; in absence of it (control) all 3 of them live. In presence 5 of 6 die, only 1 lives. So how can we show if it is significant or not? It may be basic but I appreciate your help.
Comment: Please don't just reject proposed solutions without stating what bothers you. If anything it will prevent more people from contributing. As things stand, I think the exact test is your best option.
Answer: Five of all the plants in the experiment died.  If the experiment was well-run, the only difference between the two groups under the null hypothesis was the randomized choice of $6$ out of $9=3+6$ plants that were placed into the  treatment group.
An accurate model puts nine balls into an urn, one for each plant: five of them black (to represent plants that eventually died) and four of them white (the plants that lived). The randomization selected six of those balls from the urn, leaving just three to be in the control group.
The probabilities of all the possible outcomes are elementary to compute: the chances of drawing $5$, $4$, $3$, and $2$ black balls in the treatment group are $1/21$, $5/14$, $10/21$, and $5/42$, respectively.  (This is a hypergeometric distribution.)
An "extreme" result contrary to the null hypothesis--assuming the only plausible effect of the treatment would be to make the plants more likely to die--would be the appearance of a large proportion of black balls in the treatment group.  There are three critical regions for such a "one-sided" test:

$C_5$ is the event that all five black balls were randomized into the treatment group.  Its probability is $1/21 \approx 4.8\%$.
$C_4$ is the event that four or more black balls were in the treatment group.  Its probability is $1/21 + 5/14 \approx 40.5\%$.
$C_3$ is the event that three or more black balls were in the treatment group.  Its probability is $1/21 + 5/14 + 10/21 \approx 88.1\%$.

(There are no more critical regions because at least two of the black balls had to be in the treatment group.)
The smallest of these critical regions (in the sense of its probability) into which the experimental outcomes belong is $C_5$.  Its chance, $4.8\%$, is the p-value.  If your threshold for significance is larger than this, you may conclude the results are significant.  That is, you observed an outcome that (a) was relatively rare if only chance determined the differences between control and treatment groups yet (b) would be relatively likely if the plants in the treatment group were adversely affected by the chemical.

This analysis is called Fisher's Exact Test.  In R it could be conducted exactly with a command like
fisher.test(cbind(c(3,1), c(0,5)))$p.value

or approximately with the command
chisq.test(cbind(c(3,1), c(0,5)), simulate.p.value=TRUE)

The concepts underlying the probability model and hypothesis testing are discussed--from several points of view and at greater length--at What is the meaning of p values and t values in statistical tests?, inter alia.
Answer: I suggest to use the Fisher's Exact test in order to test if there is a statistically significant difference between the proportions of survivors in the two samples (treatment and control).
Check http://en.wikipedia.org/wiki/Fisher%27s_exact_test
The contingency table will look like:
................. Alive | Dead | Row Total
Treatment 1 | 5 |6
Control..... 3 | 0 | 3
Col Total..  4 | 5 | 9
Comment: Thnak you, i looked at wikipedia and it says, it calculates exact p value and it is good for small data. I can't accept as answer but i appreciate your help.
Comment: That's OK, but I don't understand why Fisher's test doesn't suit your needs...
Comment: It suits and i just said that. I dont know the details of that test, I will definitely look more in detail, but according to introduction in wikipedia, it suits just as you suggested. Edit: I said I cant accept your answer because this site didnt let me because i needed some reputation. but now it let me, i dont know why


How do I programmatically set the default value of an exposed filter?

Question: I seen many answers for Drupal 7, but I can't find any information for Drupal 9.
In hook_form_alter(), $form['field_assigned_location_target_id']['#default_value'] = '553'; doesn't alter the default value for an exposed filter, which uses the value in the settings.
$form['field_assigned_location_target_id']['#value'] = '553'; changes
the value initially displayed on the filter, but it's the value submitted from the exposed filter form, independently from the value the users want to submit.
Comment: What kind of field is the exposed filter?  Code is slightly different depending on what kind of field it is.
Comment: I tried it for textfield as well as for select. The results are the same.
Comment: I think you are using the wrong hook. This hook will alter the form, but not the view, which I think will have already been processed. A views hook is probably what you're looking for. I would start with `hook_views_pre_execute()` or `hook_views_pre_render()`, or use a preprocess hook and alter the View executable object. https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/8.9.x
Comment: @PatrickKenny, can you elucidate your comment and/or point to something that explains what and how they are different?  I am trying to change the default value of a select filter.
Answer: I know the question is old, but hopefully this will help someone else.  After working extensively to use hook_views_pre_view, I finally found the solution by switching to hook_views_pre_build.  This code allowed me to make the changes I needed.
/**
 * Implements hook_views_pre_build().
 */
function  msul_newsletter_helper_views_pre_build(Drupal\views\ViewExecutable $view){
  /*
   * to check the format of the argument for setExposedInput, view the results
   * of getExposedInput on your view WHICH HAS HAD EXPOSED FILTERS SUBMITTED.
   * I use dpm($view->getExposedInput());
   */

  //always check the view ID so you don't affect all views.
  if($view->id()=='newsletter'){
    //check display id if you don't want to affect all displays in view.
    if( $view->current_display == 'page_2') {
      if(empty($view->getExposedInput())){
        //in my case I get $editionList from a database query.

        // because I am putting this as a default, I don't worry about other input,
        // but if you are concerned about other input, modify the array
        // from $view->getExposedInput() instead of just placing the information.
        $view->setExposedInput(['newsletter_edition_public_filter'=>
            ['edition'=>$editionList]
        ]);
      }
    }

    //in this case, I affect 2 displays.
    if($view->current_display == 'page_4'
        || $view->current_display == 'block_1'
      ){
      if(empty($view->getExposedInput())){
        //in my case I get $latestEdition from a database query.
        $view->setExposedInput(['edition'=>['edition'=>[$latestEdition]]]);
      }
    }
  }
}

Comment: But once this code works, you won't be able to use other filters.


Automatically fill title attribute of image

Question: I defined a content type that consists of a field photo for which I can add up to 20 photos. I'm using the Multiupload Imagefield Widget module to be able to upload several images to one node. Since I'm using descriptive filenames, I would like the title attribute of each image to be automatically filled (instead of filling them all by myself). Does anybody know how to do this?
I looked at the File entity module, but this creates individual pieces of content for each Image I upload. That is not the direction I want to go in.
UPDATE: I'm using D7
Comment: AgA: The descriptive filename is shown nowhere. I would like to use the descriptive filename in the title attribute of the Image.
Answer: If you use D6 try image_fupload module.

Automatic node title creation and predefining of imagefield fields (customisable / themeable / editable by user / token support [imagefield])
Comment: I updated my question: I'm using D7


What is the difference between a blacklist of JWT's and sessions?

Question: Implementing a login flow and have been persuaded by JWT's because we have scaling as priority.
In the past, the system would be based on session tokens in a monolith application.  JWT's mean we don't need to have a caching server for user sessions anymore apparently.  So then here's where I am confused:
If I get round the issue of revocation and token stealing by keeping a blacklist of keys (is the suggestion) then that now looks from above exactly the same thing as session tokens, because I'm doing a lookup with every request.
Perhaps I am not fully appreciating something or thinking of this wrong.
Perhaps - the result of not finding the blocked JWT is faster than a full retrieval.
Thanks for anything that would clear this up :)
Answer: If you implement a feature where you keep a blacklist of tokens then indeed this does not change much from a session. You still need to lookup the token, keep the blacklist updated, properly replicated, etc.
What might work better is to have access tokens with a very short expiration time, like 5 or 15 minutes. A time short enough that you can accept the risk of someone stealing the token and using it for this short time. Then you can only keep a blacklist of refresh tokens, which are used less often.
Comment: Thank you.  I was planning on that part too but wasn't quite appreciating how this was really the main thing that you can do.  Possibly the only thing. :)


Simplex Random Walk Mean

Question: Hi I have two questions related to a previous question I asked here:
Simplex Random Walk
In this link it describes how to perform a random walk on the simplex.
http://en.wikipedia.org/wiki/User:Skinnerd/Simplex_Point_Picking
It says that "This procedure effectively samples $x_{new}$ from a gamma random variable with mean of $x_{old}$ and standard deviation of $h*x_{old}$."
My first question is why would the mean be $x_{old}$?
As per the answer to my previous question the proposal distribution is a log-normal with parameters $(\ln(x_{old}),h)$. Wiki says the mean of a log-normal distribution is $e^{\mu + \frac{\sigma^2}{2}}$, which would evaluate to $e^{\ln(x_{old}) + \frac{h^2}{2}} = x_{old}e^{\frac{h^2}{2}}$. Am I missing something?
My second question is: What other ways are there to perform a random walk on a simplex? Is there a "standard" method? I've tried searching but am curious if I've missed something.
Thanks for any help.
Comment: You may draw from a Dirichlet distribution centered at the previous point. http://en.wikipedia.org/wiki/Dirichlet_distribution
Comment: Thanks Zen, so given my current categorical distribution is $(p_1, p_2, \dots, p_k)$ I could set the concentration parameter to $(\alpha_1, \alpha_2, \dots, \alpha_k)$ where $\alpha_i = h*p_1$ and $h$ is my stepsize, and sample the new point from a Dirichlet with that concentration parameter.
Comment: After trying this, it doesn't work as well as I imagined. I want the Dirichlet to be centered on my current categorical i.e. $p_i = \alpha_i / \sum_{j=1}^k \alpha_j$ so $\alpha_i = p_i*\sum_{j=1}^k \alpha_j$. But if $p_i = 0$ then $\alpha_i = 0$, yet there is the restriction that $\alpha_i > 0$. So I tried $\alpha_i + h$ where $h > 0$ is a stepsize (or inverse stepsize since bigger $h$ makes a more peaked distribution). The problem is that large $h$ (small steps) never seems to explore the boundary and small $h$ gives steps that are too large. Is there a way around this?
Answer: You are currently at $(x_1,\dots,x_k)$, with $x_i>0$ and $\sum_{i=1}^k x_i=1$. If one ore more of the $x_i$'s is exactly zero, add a small "jitter" $\epsilon>0$ to them and renormalize $(x_1,\dots,x_k)$. Now you pick some $a_0>0$ and draw $(Y_1,\dots,Y_k)\sim\mathrm{Dir}(a_0x_1,\dots,a_0x_k)$. It follows that $\mathrm{E}[Y_i]=a_0x_i/\sum_{j=1}^k a_0x_j=x_i$. For small steps choose large $a_0$'s, and vice-versa.

Simplex Random Walk Mean


How to log assert messages with a custom `TraceListener`

Question: I have implemented a custom TraceListener which both logs the messages sent to method Write and outputs them to the Win32 trace, using the Win32 API function OutputDebugString. Whenever my application uses System.Diagnostics.Debug.Write or System.Diagnostics.Trace.Write, the messages get properly handled by the trace listener.
However, if my application runs into an assertion such as System.Diagnostics.Debug.Assert I would like to intercept what is sent to the debug output. Somehow, the trace listener does not get called with the messages produced by the assert. Is this possible? Or do I have to provide my own implementation of Assert in order for this to work?
Answer: Are you building in Release mode? Debug.Assert has the ConditionalAttribute for the DEBUG symbol defined so the calls are removed by compiler in Release mode.
Debug.Assert calls the Fail method on your trace listener. Is that implemented correctly? If you haven't overridden it, then it defaults to calling WriteLine prepended with "Fail: ".
Comment: No, I am running in a Debug environment. The assert displays an alert box and dumps its output to the attached debugger (for instance DbgView), but it does not seem to go through the trace listener.
Comment: You are right, I had to override the Fail method. Please edit your reply to reflect this, so that I can accept your answer.


How to use Django test without Django models?

Question: I have a Django app for REST api, but not using Django REST Framework.
I don't use models for any tables, only using Raw SQL query. Could've used flask since not using any Django features, but higher ups decided to use Django.
I want to use Django test but digging in the source code I can see both dumpdata and loaddata which test uses to create Test DB uses app's model. But since I don't have any models how do I test my Django app?
It is OK to use the actual development DB for testing.
I see django overrides the DEFAULT_DB_ALIAS connection param with the newly created test db params, should I just override the param with the actual default db connection param instead?
So

can I use django test without models and migrations?
can I use default database for testing and prevent django from creating a test db?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/255406/discussion-between-daviid-and-akx).
Comment: Actually, instead of Flask you could've used FastAPI, really easy to use and setup. Django might be too much for just an API.
Comment: @Daviid ... Flask isn't even mentioned here?
Comment: @AKX `Could've used flask since not using any Django features, but higher ups decided to use Django.`
Comment: Ah, my bad. Well, in any case they won't probably OK using FastAPI either then, so bit of a moot point.
Comment: That's where the developers have to push and try to [convince the higher ups](https://medium.com/@ShortHills_Tech/django-vs-fast-api-a-detailed-comparison-df8d00f3c3b2).
Comment: @Daviid Maybe the higher-ups have an idea of e.g. using Django's built-in authentication stuff at some future point, or maybe the rest of the company is 100% Django so having one unfamiliar FastAPI or Flask app is not a great idea?
Answer: Using the actual development DB sounds like a bad idea since you can't easily reproduce it anywhere else (e.g. your CI server).
If you use Pytest (and pytest-django), you can use its setup fixtures to import some known default data into the test database instead, e.g. with loaddata or just SQL statements.
Comment: but the `loaddata` uses Django model right? also how do I create the fixtures, cause Django `dumpdata` also uses models to get the data!

Using Insert query? what about the 100s of tables? Do I create everything manually?
Comment: Well, you could dump table creation SQL from your development database, yeah – and probably cull it down to the tables you actually need for your tests. Another option is to use `inspectdb` to (try to) auto-generate models to work with...
Answer: The  django-app (django-test-without-migrations ) help to run django tests without considering the migrations/migration conflicts.
pip install django-test-without-migrations

add it it in INSTALLED_APPS
 INSTALLED_APPS = (
    # ...
    'test_without_migrations',
)

Then run test using the following command
python manage.py test --nomigrations

--nomigrations make sure your tests won't fail due to the migrations issues.
Reference : https://pypi.org/project/django-test-without-migrations/
Its solution for your first question.
Its recommended to use a separate database for testing.
Specify the test database to be created in  DATABASES  section in setting.py. In the following 'mytestdatabase' will be used for testing.
settings.py

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "USER": "mydatabaseuser",
        "NAME": "mydatabase",
        "TEST": {
            "NAME": "mytestdatabase",
        },
    },
}

reference: https://docs.djangoproject.com/en/4.2/ref/settings/


Is there an elementary way to show $\sum_n (\sin n)^{2^n}$ converges?

Question: So I asked earlier whether $\sum_n (\sin n)^{n^k}$ converges for some $k$, and if so then what $k$, and I got an interesting comment/answer saying that supposedly it boils down to the irrationality measure of $\pi$, and the series should converge for example for $k \geq 8$. But that seems like pretty deep math. What if we make it easier to converge by considering $\sum_n (\sin n)^{2^n}$. Is there a fairly elementary way to see that this series converges?
Here's the original question. Does $\sum_n |\sin n|^{cn^2}$ converge?
Comment: @SimonS sure, done.
Comment: A probabilistic approach is worth a try. If $X$ is a random variable uniformly distributed over $[-1,1]$, then $X+X^2+X^4+X^8+X^{16}+\ldots$ belongs to $L^1$, hence the series is almost surely convergent. In this framework, $\sin n$ behaves like $X$.
Answer: Comparison test. In fact, $2^n$ is greater than $n^8$ starting from some rank.
Comment: Sure, I know the previous question I asked already answers this one, but the math referenced there seemed disappointingly deep. This is a strictly easier question and I'm hoping there's an "elementary" proof that doesn't talk about how irrational $\pi$ is.
Comment: I don't see how.  If you replace $\sin(n)$ by $\sin(r \pi n/2)$ where $r$ is a rational number with odd numerator, the sum would diverge.  It would also diverge if you used $\sin(\alpha n)$ where $\alpha$ can be very well approximated by $r \pi/2$ for such rationals $r$.
So in order to prove it, you must somehow show that $1$ can't be so approximated.
Comment: @RobertIsrael, the success of the comparison test relies on the fact that $|sin(n)|^{n^8}$ converges (As mentioned by the OP). Though, it seems that this isn't what OP is looking for.


Assets audio player doesn't work any more

Question: i use flutter and i used assets_audio_player library to run sounds in my app, it was working fine until last day, when i run the code it gives me PlatformException(OPEN,nul,null,null).
I tried to change the version and also tried to restart the app but nothing worked.
I used AudioWidget.assets() to run the sound, it was working fine but when version 3.0.6 was released it didn't work and gives a rethrow error.
enter image description here
enter image description here
enter image description here
Answer: I solved this problem by changing my asset String:
'sounds/x.ogg'  to ->  'assets/sounds/x.ogg'
make sure your audio path is exactly like what you wrote in pupspec.yaml
Answer: I think it can be an Incompatibility or even some error that could happen with build files being not updated or synchronised.
Just to have a clear conscience, please, on your project terminal, run the very old classic:
flutter clean

Then, run
flutter pub get

Stop your running project and rebuild your application
In fact, if it doesn't solve your problem, i would suggest you to downgrade the assets_audio_player to the previous version to when it was working.
Update me if none of this solve your problem.
Comment: hello macros, thanks, your answers worked .