Can we write php conditions in view field templates?

Question: My view fields are as like shown in screenshot, for each row I need to add comment link,revision link ,edit link, voting icons and topic terms etc And I have large number of views which will share all these fields.

So I thought to remove all the fields and have nid field in all my views. Then create common template file of nid. And in that template file I am planing to use node_laod and fetch all required fields and add them with some common required html structure.
Please suggest if this will be right way to achieve such kind of workflow and reducing work load to add fields in each view, make them easy to edit or make change in fields from template files.
Is this will be good idea to write php code in template file or I am supposed to use some pre process functions etc
Please suggest ! Thanks.
Answer: No. Do not make a view that pulls a nid, then do node_load in the template. This will be a performance killer.
You should create a view mode using Entity View Mode module, add the fields to the display, and theme it with node--node-type--view-mode.tpl.php. Then the configured View only has to show 'Rendered Content' - and pick the view mode. Then you're done.
See: https://www.youtube.com/watch?v=wcskTtvR6Mo
Comment: Thanks you! I will look into this and try according to your suggestion.
Comment: I have gone thorugh video but view modes only allow to create view mode with available fields of content type and the we can use them in views. But in my case I need to fetch voting contorles (used with rate module) , node edit link , comment form link with count of comments, revisions link with rev count. Is that possible without using templates, please suggest !
Comment: It is easy to create those links in a preprocess.
Comment: sorry for bothering but is I have to use some kind of this hook http://drupal.stackexchange.com/questions/60271/what-is-the-hook-to-preprocess-a-view to add such links. I have not done such kind of thing before so just want to handle all views with manageable way, any links to read more or example will be very helpful :)
Answer: It is not a good practice to put php processing in template files. Try to have only variables with the necessary information there and if-then blocks to decide what you need to print in the html. You can preprocess your data in template.php or a module.
But I would go for the "fetch as much as possible in the view" approach. You will actually gain a bit of performance and, as I understand your requirements, you will have all you need, just have to style it. On that point you can go either for different templates for every view, a more common template for multiple views (see the theming information), or even group some of the views creating different displays and providing common/separate templates as needed.
Comment: Thanks for comments, if I use fields in views and I have to make change in one field then I have to edit all views and alter fields. That will b helpful if its possible to provide any links to study :)
Comment: Well, using a single template can also have its gotchas - for example, if you want to show different fields/arrangements in different circumstances.

You'll have to choose the less evil, I guess :)


Unwanted silence in LMMS

Question: There's a pause at the end of a segment of music, in the piano roll, in LMMS. How do I get rid of that pause? Do I use a loop point? If so, how do I set a loop point?
Thank you.
Editor's note: LMMS is free, cross-platform music production software.
Comment: If I rememember well, loop are quantized to bar length
Answer: I assume you're referring to the audio during design, and not the final export? I'm not experiencing the same problem on my edition, but that could be a clue in itself. It sounds like an audio processing artifact.
I suggest two things—look into your buffer size under the Edit→Settings menu, and ensure that it's large enough (mine's at 1024 frames with a 23.2 ms latency, for reference). If that fails, try checking your Audio options under Settings (the one with the speaker icon on it) and ensure that you're using an effective audio interface, as some of them are more cooperative than others. SDL usually works for me.
Hopefully that will help solve your problem.

Unwanted silence in LMMS


Procedure para armazenar em tabelas backup?

Question: Tenho duas tabelas, vendas e vendaProduto por conta do volume de informações nessas tabelas as operações de leitura/escrita ficam lentas. Preciso criar uma procedure que armazene esses dados (das tabelas venda e vendaProduto), de um determinado período, em tabelas de backup (bkpVenda e bkpVendaProduto). Sendo que o período irá ser informado pelo usuário. Como eu devo fazer essa procedure?
create table venda (
ven_ID   int not null identity (1,1) constraint PKVenda primary key,
cli_ID   int not null,
fun_ID   int not null,
ven_Data date not null,
constraint fkVenCli foreign key (cli_ID) references cliente(cli_ID),
constraint fkVenFun foreign key (fun_ID) references funcionario(fun_ID))

;
create table vendaProduto (
vpr_ID          int identity (1,1) constraint PKVendaProduto primary key,
ven_ID          int not null,
liv_ID          int not null,
vpr_Quantidade  int,
vpr_ValorUnit   decimal(15,2),
constraint fkItvVen foreign key (ven_ID) references venda(ven_ID),
constraint fkItvliv foreign key (liv_ID) references livro(liv_ID))

;
Comment: Felipe, os dados que forem copiados para as respectivas tabelas de backup devem ser apagados da tabela original? Se sim, terá que reprogramar o aplicativo para consultar tanto os dados ativos quanto os arquivados.
Comment: Felipe, qual o número aproximado de linhas nas tabelas "venda" e "vendaProduto"?
Answer: Você pode fazer da seguinte forma:
if object_id('realizar_backup', 'P') is null
begin
  exec('create procedure realizar_backup as');
end;
go

alter procedure realizar_backup @data_inicio datetime,
                                @data_fim    datetime
as
begin
  set nocount on;

  insert into bkpVenda(ven_ID,
                       cli_ID,
                       fun_ID,
                       ven_Data)
  select v.ven_ID,
         v.cli_ID,
         v.fun_ID,
         v.ven_Data
    from venda with(readpast) v
   where v.ven_Data between data_inicio and data_fim;

  insert into bkpVendaProduto(vpr_ID,
                              ven_ID,
                              liv_ID
                              vpr_Quantidade,
                              vpr_ValorUnit)
  select vp.vpr_ID,
         vp.ven_ID,
         vp.liv_ID
         vp.vpr_Quantidade,
         vp.vpr_ValorUnit
    from venda with(readpast) v
         inner join vendaProduto with(readpast) vp on vp.ven_ID = v.ven_ID
   where v.ven_Data between data_inicio and data_fim;
end;
go

Porém eu te aconselho a gravar em tabelas de log no momento em que as transações são feitas (insert, update, delete) e depois só consultar por datas. Mas se for só pra salvar essa procedure resolve seu problema.
Answer: Antes de modificar a estrutura do banco de dados, e o respectivo impacto nos  aplicativos, sugiro análise do que está ocasionando a lentidão. Podem ser estatísticas defasadas, alguma consulta que necessita ser otimizada, índices fragmentados ou ausentes etc etc. Em suma, as tarefas típicas de administração de banco de dados.
Após a análise, talvez seja indicada a criação de índices adicionais. Por exemplo, se houver elevado número de consultas na tabela "venda" por período, então é provável que a criação de índice pela coluna ven_Data otimize essas consultas. É claro que, além da coluna ven_Data, é necessário avaliar colunas de cobertura que devam constar nesse índice.
Na tabela vendaProduto me parece que deve ser reavaliado o que comporá o índice clustered. A coluna vpr_ID, como chave do índice clustered, me parece inútil. Ela até poderia ser mantida como chave primária, mas em um índice nonclustered. Ou, melhor ainda, bastaria declarar essa coluna como unique.
Dentre as várias chaves candidatas da tabela "vendaProduto", talvez a coluna ven_ID seja a ideal para ser escolhida como chave do índice clustered. Pode ser uma chave simples, aceitando duplicidades, ou então uma chave composta (ven_ID + vpr_ID), exclusiva (sem repetições).
A sugestão é que, antes de pensar em modificar a estrutura do banco de dados, encontre os gargalos atuais.
Com relação ao espaço físico ocupado, analise quanto ocupa cada coluna. Somente como exemplo, a coluna Quantidade da tabela "vendaProduto" está declarada como int. Ou seja, ocupa 4 bytes e aceita valores de até 2 milhões e pouco. Será que algum livro teve mais de 32 mil exemplares vendidos, em uma mesma transação? Se  a quantidade de cada item vendido for menor do que 32 mil unidades, pode declarar a coluna como smallint, que então a coluna ocupará metade do espaço (2 bytes).
O mesmo raciocício para a coluna fun_ID, na tabela "venda", que também está declarada como int. Existem mais de 32 mil funcionários nessa livraria?! Claro que não! Essa coluna poderia ser declarada como smallint (até cerca de 32 mil funcionários) ou mesmo tinyint (até 255 funcionários).
Na tabela "venda" consta a data da venda mas não consta o horário. Se for necessário registrar também o horário da venda, avalie o uso do tipo smalldatetime. O tipo date ocupa 3 bytes e o smalldatetime ocupa 4 bytes.
São detalhes que, ao final, fazem a diferença na performance.


can't add checked item checkedlistbox form1 to listbox form2

Question: I have 2 form form1 and form2. I want to add checked items from checkedlistbox1 (form1) to listbox (form2) when i click button2. How can i do that
Form1
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2();
        form2.Show();
    }
}

Form2
public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Form1 form1 = new Form1();
        foreach(string item in form1.checkedListBox1.CheckedItems)
        {
            listBox1.Items.Add(item);
        }
    }
}

Answer: Change Form1 like this
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2(checkedListBox1);
        form2.Show();
    }
}

Form 2
public partial class Form2 : Form
{
    public Form2(CheckedListBox checkedListBox1)
    {
        InitializeComponent();
        foreach(string item in checkedListBox1.CheckedItems)
        {
            listBox1.Items.Add(item);
        }
    }
}

Answer: There are some problems.
First of all, every time you press a button, you create a new Form. I think you want to create one instance of it?
The second problem is, you can't access form1.checkedListBox1 from form2 like this.
And I don't think checkedListBox1.CheckedItems is a List of strings. Maybe you want to add the text or the value of the item...
Better try something like this:
Form1
public partial class Form1 : Form
{
    Form2 form2;
    public Form1()
    {
        InitializeComponent();
        form2 = new Form2(this);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        form2.Show();
    }

    public List<string> GetCheckedItems()
    {
        return this.checkedListBox1.CheckedItems;
    }
}

Form2
public partial class Form2 : Form
{
    Form1 form1;
    public Form2()
    {
        InitializeComponent();
    }

    public Form2(Form1 parentForm)
    {
        InitializeComponent();
        this.form1 = parentForm;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        foreach(string item in form1.GetCheckedItems())
        {
            listBox1.Items.Add(item);
        }
    }
}

I didn't check the code, but it should be something like this...


How to update the current page to show new content?

Question: I am currently displaying a list of MySQL database table names, such as table1, table2, table3.
Each table name will be a link; if users click on it, it will display them the data contained in that table.
One way I know I can do this is to create a Drupal page that contains the content of "table1", so that when a user clicks on "table1", they are taken to this page and can see the data of "table1".
However, this soon becomes un-manageable if I have a large databases with many tables.
I'm not quite sure if Drupal can work in this way, but I would like it so that when a user clicks on a table link (either table1 or table2 and so on), the current or a generic page will then be updated with the content of the table chosen and be updated with its content.
Comment: Are you doing this in Code (e.g. a module) or by hand?
Comment: Berdir, I am doing this through PHP code in a Drupal content. However, if there is an easier way, please let me know.
Answer: I am not sure what functionality you are trying to build and if adding PHP code inside a Drupal node is the right way to do it. But assuming that is what you would like to do, here are the steps to achieve what you want:

Create a Drupal node (say the nid of it is NID) and add the following PHP code inside it
$table_name = arg(2); // This grabs the 3rd argument of the page menu path (note: the 1st argument is indexed 0)
print $table_name; // Replace this with PHP code to fetch and print data in the table represented by $table_name

When you are making table1, table2 etc links make sure the URL that they point to is node/NID/<table_name> where <table_name> is table1, table2 respectively.
Comment: Using PHP code inside a node is generally not a good idea.
Comment: @Sumeet, thank you for the response, I believe you have understood me correctly. Could you please tell me how I can find the node ID of the current node or any node? Thanks.
Comment: @Sumeet, I have found out how to find the node ID. Thanks. I will try and let you know. What if I have enabled clean URLs and have created a URL for this node? How should I reference the node then?
Answer: If you have a dynamic list of tables/columns, then you can build this using PHP, you just need a dynamic menu entry that accepts the table name as an argument and then you can re-act to that in PHP. There are many books and online documentation available about how to create modules, try here for example: http://drupal.org/node/361112
If you have a fixed list of tables, you could build this using Views. If these are custom tables, you first will integrate them with Views, however.


Showing that a critical point becomes unstable at a certain value of another parameter

Question: Say I have the following first-order system for $n$:
$$
\dot{n} = \frac{Gnp}{Gn+f} - kn,
$$
where $G$, $f$, and $k$ are always positive, but $p$ can take either sign.
First, I want to find the critical points $n^*$ of this system.  One is obviously $n^*=0$.  I can solve for the other one to get $n^*=\frac{pG-fk}{Gk}$.  Further algebraic rearrangements reveal that the second critical point is negative if $p<\frac{fk}{G}=p_c$ and positive if $p > p_c$.
What should I do to show that $n^*=0$ becomes unstable for $p>p_c$?
Answer: You can check the stability of a fixed point $n^{*}$ of the system $\dot{n} = f(n)$ by checking its derivative at $n^{*}$.
If $f^{'}(n^{*}) < 0$, then $n^*$ is a stable fixed point.  If $f^{'}(n^{*}) > 0$, the fixed point will be unstable.  For $f^{'}(n^{*}) = 0$, we cannot tell whether the fixed point is stable or unstable and have to get another case.
Here, using the quotient rule, we can calculate $f^{'}(n) = \frac{1}{(Gn + f)^{2}} [(Gn + f)Gp - (Gnp)G]-k$.
For unstabilty check for two fixed points ,
$case-1 :$
when $$  n^{*} = \frac{pG - fk}{Gk}$$
$f^{'}(n) = \frac{Gp}{(Gn + f)} - \frac{G^{2}np}{(Gn + f)^2} - k > 0$
So we have three terms above , if we workout for first term it comes out as $k$ and this cancels out with the $-k$ (the third term) , so we are only left with $-\frac{G^{2}np}{(Gn + f)^{2}} > 0$ , and when  we substitute in the latter ones $n = \frac{pG - fk}{Gk}$ we arrive at $-k (1- \frac{fk}{pG}) > 0$ leading to $p < \frac{fk}{G}$ ,so when $p < \frac{fk}{G}$, the fixed point is unstable .
$Case-2$
when $$n^{*} = 0$$
And now for $n^{*} = 0$ , substituting in the expression of $f^{'}$ above we get $\frac{Gp}{f} - k > 0$ implies for $p > (p_{c} = \frac{kf}{G})$ , $n^{*} = 0$ is an unstable fixed point.
Hope this helps !
Comment: Sorry,Will edit soon!
Comment: How it is ? , when we put $n = 0,$ we get $-\frac{G^{2}.0.p}{(G.0 + f)^{2}} = 0$ @infinitylord
Comment: @dbliss $\frac{Gp}{Gn + f} = \frac{Gp}{G.(\frac{pG-fk}{Gk}) + f} =  \frac{Gp}{\frac{pG- fk + fk}{k}} = \frac{Gpk}{pG} = k$...are there any mistakes here ?
Comment: oh.. I actually did for both fixed points ..ok, now i have divided them into cases , hope it is now clear!@dbliss


Dynamic Load DLL with AddeventHandler

Question: I have walkthru much post of stackoverflow and msdn and tried their solution , but I still cannot get it works, so I hope anyone can help me out . Thank you very much
First I havent added
MethodInfo mi = instance.GetType().GetMethod(sMethodName, myBindingFlags);
Delegate del = Delegate.CreateDelegate(typeof(ErrorEventHandler), null, mi);

directly call
 ei.AddEventHandler(instance, handler);

then the error is

Object of type 'xxxxErrorEventHandler' cannot be converted to type
  'xxxxErrorEventHandler'.

Then I follow some post modify my code as below, then raise the error when CreateDelegate
DLL:
public class ErrorEventArgs : EventArgs
{
    public string ErrorMsg;
}

public interface IClassA
{
    bool Run();
}

public class ClassA : IClassA
{

    public delegate void ErrorEventHandler(object sender, ErrorEventArgs data);
    public event ErrorEventHandler OnErrorHandler;
    public void OnError(object sender, ErrorEventArgs data)
    {
        if (OnErrorHandler != null)
        {
            OnErrorHandler(this, data);
        }
    }

    public bool Run()
    {
         // do something inside DLL
         ErrorEventArgs data = new ErrorEventArgs();
         data.ErrorMsg = "Hello World";
         OnError(this, data)
    }
}

EXE:
public delegate void ErrorEventHandler(object sender, ErrorEventArgs data);

void main()
{
    Assembly assembly = Assembly.LoadFile("myDLL.dll");
    Type[] types = assembly.GetTypes();
    for (int i = 0; i < types.Length; i++)
    {
        Type type = assembly.GetType(types[i].FullName);
        if (type.GetInterface("myDLL.IClassA") != null)
        {
             object obj = Activator.CreateInstance(type);
             if (obj != null)
             {
                 MethodInfo methodInfo = obj.GetType().GetMethod("Run");

                 ErrorEventHandler handler = foo;
                 BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public;
                 EventInfo ei = instance.GetType().GetEvent("OnErrorHandler", myBindingFlags);
                 MethodInfo mi = instance.GetType().GetMethod("Run", myBindingFlags);

                 *// System.ArgumentException raised here
                 //  Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.*
                 Delegate del = Delegate.CreateDelegate(typeof(ErrorEventHandler), null, mi);
                 ei.AddEventHandler(instance, del);

                 bool Result = methodInfo.Invoke(instance, null);
             }
        }
    }

    public void foo(object sender, ErrorEventArgs data)
    {
        Console.WriteLine("In Foo!");
    }
}

reply to floor 1
Hi Hans, Thanks a lot for your answer, I following your advise to modify my code. If the Callback function declare like this
private static void Callback(string msg)

and inside ClassA event also declare like this
public delegate void ErrorEventHandler(string msg);
public event ErrorEventHandler OnErrorHandler;
public void OnError1(string msg)
{
    if (OnErrorHandler != null)
    {
        OnErrorHandler(msg);
    }
}

that works fine, but if declare it like before
private static void Callback(object sender, ErrorEventArgs data)

it comes up error " Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type." when run
Delegate del = Delegate.CreateDelegate(ei.EventHandlerType, null, mycallback);

Do you know why , by the way really really thanks for your help.
error if the modified code at EXE side like:
      .......
      BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public;
      EventInfo ei = instance.GetType().GetEvent("OnErrorHandler", myBindingFlags);
      MethodInfo mi = instance.GetType().GetMethod(sMethodName, myBindingFlags);
      var mycallback = typeof(ModuleManager).GetMethod("Callback", BindingFlags.Static | BindingFlags.NonPublic);
      Delegate del = Delegate.CreateDelegate(ei.EventHandlerType, null, mycallback);
      ei.AddEventHandler(instance, del);
      .......

 private static void Callback(object sender, ErrorEventArgs data)
 {
       Console.WriteLine("In Callback!");
 }

Answer: Your program has two delegate types named ErrorEventHandler.  One declared in the upper snippet, another declared in the lower snippet.  They have distinct names and probably don't even live in the same namespace, but that doesn't actually matter.
The CLR categorically refuses to consider two delegate types identical, even if their declaration is the same.  It will not burn the extra CPU cycles to use reflection itself to check if they match, delegates are supposed to be fast and there's nothing cheap about checking compatibility.  Type conversion is a compiler's job.  So it will only accept an exact match, your reflection code needs to create a delegate of type ClassA.ErrorEventHandler.  Of course you can't know the type, it is readily available however.  It is EventInfo.EventHandlerType.
A second problem in your code is the delegate target, the method that runs when the event is raised.  You now pass ClassA.Run(), that is not correct of course.  You need to pass your own method, one that's compatible with the delegate.  It could look like this:
    private static void Callback(object sender, object data) {
        // etc...
    }

And modify the reflection code accordingly:
        object obj = Activator.CreateInstance(type);
        BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public;

        // Find the event and its type
        EventInfo ei = obj.GetType().GetEvent("OnErrorHandler", myBindingFlags);
        var delegateType = ei.EventHandlerType;

        // Use our own event handler
        var mycallback = typeof(Program).GetMethod("Callback", BindingFlags.Static | BindingFlags.NonPublic);
        Delegate del = Delegate.CreateDelegate(delegateType, null, mycallback);
        ei.AddEventHandler(obj, del);

        // Call the Run method
        MethodInfo methodInfo = obj.GetType().GetMethod("Run");
        bool Result = (bool)methodInfo.Invoke(obj, null);

Note that the Callback event handler used object as the second argument type.  Which is fine, it is compatible with the invisible ErrorEventArgs type.  If you need to obtain the values of the passed object then you need to use Reflection in the callback as well.
Comment: Hi Hans , Thanks for your help . I have tested and part of code is working , but still have some issue. I describe details in question thread. Could you please help take a look . thanks
Comment: Looks to me you made the same mistake again by using ErrorEventArgs in the Callback() method.  You don't have the correct type so you must use *object* instead.  As noted in the answer, you must use reflection in the method to obtain the *data* member values.
Comment: Thanks for your Help and reply. I got your answer. thaNks a lot

Dynamic Load DLL with AddeventHandler


Trigonometry in Simple Harmonic Motion

Question: In one of my high school maths questions the example given to find the maximum displacement of a Simple Harmonic Motion where
$ x=2+4\cos \left (2t + \frac{\pi}{3}  \right ) $
and the motion lies in the interval:
$-2 \leq x\leq 6$
is:

let $x=2+4\cos \left (2t + \frac{\pi}{3}  \right )= 6$
then $\cos
    \left (2t + \frac{\pi}{3}  \right )= 1$
$2t + \frac{\pi}{3} =    2\pi$
$t = \frac{5\pi}{6}$

I am getting confused on the transition from line 2 to line 3. I'm confused as to how getting rid of the cos turns 1 into $2\pi$. Could someone please explain this at a high school level?
Answer: Remember: $$\cos x=1\Longleftrightarrow x=2k\pi\,,\,k\,\,\text{an integer}$$so$$\cos\left(2t+\frac{\pi}{3}\right)=1\Longleftrightarrow 2t+\frac{\pi}{3}=2k\pi$$
Assuming, as surely is the case, that it must be $\,t\geq 0\,$ , we get that$$2k\pi>\frac{\pi}{3}\Longrightarrow k=1,2,3,...$$and we can choose $k=1\Longrightarrow 2t+\frac{\pi}{3}=2\pi$
Answer: You normally would apply the $\arccos$ function to both sides - see here. This would yield $2t+\tfrac {\pi} 3=0$, however, and the question implies (or perhaps tacitly assumes) a positive value of $t$. Note that, observing the cosine function, we see that it equals $1$ whenever it's argument is $0,2\pi,4\pi,...$ in general whenever it's argument is $n\cdot 2\pi$, where $n$ is an integer.
There are actually infinitely many values of $t$ for which $\cos(2t+\tfrac{\pi} 3)=1$, but the one provided is the smallest positive value.

Trigonometry in Simple Harmonic Motion


Unexpected token at every .js file at line 2

Question: I'm getting syntax error at every js file i have linked to my page.
The page is working fine when I set DEBUG = TRUE but this error occurs when I set it to False.
<code>Uncaught SyntaxError: Unexpected token <
</code>
when click to see where at line 2 the error is it takes me to  tag of my 404 page.
Comment: Seems like your server is returning HTML (the 404 page), not JS. Make sure your JS files are accessible / the routing configuration of your server is correct.
Comment: It is very likely that those requests for static files are returning a 404 page, thank the actual asset files. Check the path and try again
Comment: Possibly debug = false gives `*.min.js` that aren't actually there?
Comment: @karthikr, on my terminal I am getting HTTP 200 OK response for all the CSS, JS and jpeg files. but they are not getting load on the page.
When I click the link from the page source my bootstrap.min.css is loaded and other css and js files gives 404 error.
all the files were collected in the static root by collectstatic command but I am not able to figure out what is causing the trouble that some files are getting served and some are not.
Comment: Is this using nginx/apache or something? If so, check the settings there. Make sure it points to the right folder.
Answer: When settings DEBUG = False, your static files have to be deployed to be served.
You can find here some information about how deploying your static files : https://docs.djangoproject.com/en/1.8/howto/static-files/deployment/


Como alterar oque está escrito em um tkinter.Text em Python?

Question: Em um tkinter.Entry, para alterar oque está escrito eu poderia colocar uma StringVar em um textvariable e eu poderia alterar essa StringVar há qualquer momento que seria alterado no tkinter.Entry também
Mas em um widget tkinter.Text?
Tentei usar uma StringVar e deu erro.
Meu objetivo era criar um app onde o usuário digita qualquer coisa e quando o botão é pressionando todo aquele texto seria convertido para maiúsculo, o código ficou assim:
from tkinter import *

class Teste:
    def __init__( self ):
        self.app = Tk()
        self.app.title( 'Teste' )
        self.app.geometry( '700x700' )

        self.string = StringVar()

        self.txt = Text( self.app, textvariable=self.string )
        self.txt.pack()

        Button( self.app, text="Converter para Maiúsculo", command=self.converteMaiusculo ).pack()

        self.app.mainloop()

    def converteMaiusculo( self ):
        n = self.txt.get( "1.0", END )
        self.string.set( n.upper() )

myApp = Teste()

Eu não sabia que não poderia usar um text ou textvariable em um tkinter.Text, mas então como poderia fazer isso?
Answer: Neste caso não é muito necessário usar uma StringVar, você pode pegar o conteúdo, armazenar numa string, deletar tudo dentro do Text e inserir com upper
def converteMaiusculo( self ):
        n = self.txt.get( "1.0", END )
        self.txt.delete(1.0,END)
        self.txt.insert("insert",n.upper())

Mas caso você queira usar StringVar com o seu Text pode ser utilizado o bind KeyRelease pra toda vez que o user digitar qualquer coisa, o bind executar uma função para pegar o texto e setar na StringVar
Exemplo:
def salvarStringVar(e):
    self.string.set(self.txt.get("1.0",END))

self.txt.bind('<KeyRelease>',salvarStringVar)


Asynchronous socket Server C#, how to get data from AsyncCallback

Question: I have been trying to learn to use asynchronous sockets, and I'm sure my question is incredibly simple, but I have been having a really hard time finding a solution for it.  I'm going to start from the code provided on MSDN at for Asynchronous Server and Asynchronous Client.  I am following how the code works, except the one big question: How do I get the string the client sends back into the main function of the program?  I see where the string is fully formed in the ReadCallback() function.
The question is how do I get the contents of the string content back to Main()?  I put a few comments in to try and clarify what I am trying to get to where.  Thank you in advance for your help.
Asynchronous Server:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

// State object for reading client data asynchronously
public class StateObject {
    // Client  socket.
    public Socket workSocket = null;
    // Size of receive buffer.
    public const int BufferSize = 1024;
    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];
// Received data string.
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousSocketListener {
    // Thread signal.
    public static ManualResetEvent allDone = new ManualResetEvent(false);

    public AsynchronousSocketListener() {
    }

    public static void StartListening() {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // The DNS name of the computer
        // running the listener is "host.contoso.com".
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp );

        // Bind the socket to the local endpoint and listen for incoming connections.
        try {
            listener.Bind(localEndPoint);
            listener.Listen(100);

            while (true) {
                // Set the event to nonsignaled state.
                allDone.Reset();

                // Start an asynchronous socket to listen for connections.
                Console.WriteLine("Waiting for a connection...");
                listener.BeginAccept(
                    new AsyncCallback(AcceptCallback),
                    listener );

                // Wait until a connection is made before continuing.
                allDone.WaitOne();
            }

        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();

    }

    public static void AcceptCallback(IAsyncResult ar) {
        // Signal the main thread to continue.
        allDone.Set();

        // Get the socket that handles the client request.
        Socket listener = (Socket) ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        // Create the state object.
        StateObject state = new StateObject();
        state.workSocket = handler;
        handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
            new AsyncCallback(ReadCallback), state);
    }

    public static void ReadCallback(IAsyncResult ar) {
        String content = String.Empty;

        // Retrieve the state object and the handler socket
        // from the asynchronous state object.
        StateObject state = (StateObject) ar.AsyncState;
        Socket handler = state.workSocket;

        // Read data from the client socket.
        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0) {
            // There  might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(
                state.buffer,0,bytesRead));

            // Check for end-of-file tag. If it is not there, read
            // more data.
            content = state.sb.ToString();
            if (content.IndexOf("<EOF>") > -1) {
                // All the data has been read from the
                // client. Display it on the console.
                Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                    content.Length, content );
                // Echo the data back to the client.
                // AT THIS POINT content SHOULD HAVE THE STRING SENT
                Send(handler, content);
            } else {
                // Not all data received. Get more.
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
            }
        }
    }

    private static void Send(Socket handler, String data) {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        handler.BeginSend(byteData, 0, byteData.Length, 0,
            new AsyncCallback(SendCallback), handler);
    }

    private static void SendCallback(IAsyncResult ar) {
        try {
            // Retrieve the socket from the state object.
            Socket handler = (Socket) ar.AsyncState;

            // Complete sending the data to the remote device.
            int bytesSent = handler.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to client.", bytesSent);

            handler.Shutdown(SocketShutdown.Both);
            handler.Close();

        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }

    public static int Main(String[] args) {
        StartListening();
        // I want to make string here that has the result from ReadCallback so I can then perform other logic on the string.
        return 0;
    }
}

Comment: Since your source and destination use the `String` data type, which is for text in the UTF-16 encoding of the Unicode character set, consider using one of the Unicode encodings for the transfer. UTF-8 (`Encoding.UTF8`) is common for streams and files. UTF-16 (`Encoding.Unicode`) is common (.NET, Java, JavaScript, …) for in-memory text. Otherwise, conversion from Unicode  to ASCII is potentially lossy. For a non-Unicode encoding, you could use an `Encoder` with an [`EncoderExceptionFallback`](https://msdn.microsoft.com/en-us/library/system.text.encoderexceptionfallback(v=vs.110).aspx).
Answer: Your followed the example quite right. You just need to wait for the input. Put a Console.ReadLine(); before the return statement:
public static int Main(String[] args)
{
    StartListening();
    // I want to make string here that has the result from ReadCallback so I can then perform other logic on the string.

    Console.ReadLine();
    return 0;
}

If you want to print out the input. Just use Console.WriteLine() after you decoded the received bytesin the ReadCallback method:
if (bytesRead > 0) {

    // There  might be more data, so store the data received so far.
    state.sb.Append(Encoding.ASCII.GetString(
        state.buffer,0,bytesRead));

    // Check for end-of-file tag. If it is not there, read
    // more data.
    content = state.sb.ToString();

    // print the stuff to the console
    Console.WriteLine(content);

If you want to have the content and do something with it you can declare it as a static class variable and you will be able to access it in the main method:
public class AsynchronousSocketListener
{
    public static string content = "";

public static int Main(String[] args)
{
    StartListening();
    // I want to make string here that has the result from ReadCallback so I can then perform other logic on the string.

    Console.ReadLine();

    // wait until the message has arrive and press enter to jump to this line
    Console.WriteLine("Now I can do what ever I want with the incoming message: " + content);
    // just to be able to read it one more time before the program ends ;)
    Console.ReadLine();
    return 0;
}

Of course you have to remove the declaration from the ReadCallback.
You have to be aware that it is asynchronous and hence you will have to wait for the message to arrive. But you can see it in the console if you print it there. The rest is up to you
Comment: I will give this a shot in a little bit, but thank you for the idea.
Comment: you are welcome. If problems come up just drop a comment. I tried this asyncronous stuff the first time in a WinForms project. it is easier to wait for the received message, since it does not run through the main and finishes right away. A good practice is to write a chat program.


Finding the basis for the row space of matrix $A$

Question: Given $A = \begin{bmatrix}0&0&1&-3&2\\2&-1&4&2&1\\4&-2&9&1&4\\2&-1&5&-1&5\end{bmatrix}$, after I perform row-reduction, I get $U=\begin{bmatrix}2&-1&4&2&1\\0&0&1&-3&2\\0&0&0&0&2\\0&0&0&0&0\end{bmatrix}$
I can see that there are pivots in rows 1, 2 and 3 of $U$. So I thought the basis for the row space of $A$ would be ${(2, -1, 4, 2, 1), (0, 0, 1, -3, 2), (0, 0, 0, 0, 2)}$
Because I had to exchange the rows of $A$ using $P=\begin{bmatrix}0&1&0&0\\1&0&0&0\\0&0&0&1\\0&0&1&0\end{bmatrix}$to obtain $U$, the pivots are not in rows 1, 2, and 3 of $A$ but instead in rows 1, 2 and 4. So the basis for the row space would be $(0, 0, 1, -3, 2), (2, -1, 4, 2,1), (2, -1, 5, -1, 5)$
So now I have 2 sets of bases, and my question is which set is correct? Or are both correct?
Answer: You have $$(2,-1,5,-1,5)=(2,−1,4,2,1)+(0,0,1,−3,2)+(0,0,0,0,2),$$ and conversely $$(0,0,0,0,2)=(2,-1,5,-1,5)-(2,−1,4,2,1)-(0,0,1,−3,2)$$ so both sets span the same vector space.
Comment: So if I put down either set of basis on the test it would be correct?
Comment: Yes. If your row reduction was correct of course.
Comment: @Adrian it is customary to accept an answer if you're satisfied with it. If you need more help, please ask.


Delete zip folder in android

Question: Map<String, String> zip_properties = new HashMap<>();
zip_properties.put("create", "false");
URI zip_disk = URI.create(name);

/* Create ZIP file System */
try (FileSystem zipfs = FileSystems.newFileSystem(zip_disk, zip_properties))
{
   Path pathInZipfile = zipfs.getPath(name);
   // System.out.println("About to delete an entry from ZIP File" +
     pathInZipfile.toUri() );
   Files.delete(pathInZipfile);
   //System.out.println("File successfully deleted");
} catch (IOException e) {
    e.printStackTrace();
}

I have create zip folder for multiple images in internal storage.Now i want to delete Zip files from the location and recreate same name zip folder in android.
Perform above code for delete zip folder but its not working
Please help me if anyone have solution
Thanks in advance..

Comment: Possible duplicate of [How do I delete files programmatically on Android?](https://stackoverflow.com/questions/24659704/how-do-i-delete-files-programmatically-on-android)
Comment: @RanjanDas I try your code but it deletes only content of zip files but not delete zip files.
Comment: give path of zip file, not contents of it.
Comment: Zip_Folder_Path :: /storage/emulated/0/PhotoResizer/PhotoResizer_1533707372194.zip

I use above path for deleting zip folder, but only content of zip folder is deleted not zip file.
Comment: Only do arraylist.clear(); in my case when recreate zipfile.
its solve my problem.

Thanks.
Answer: after using delete() method in your File.
filePath is a String containing the path to your zip file.
File file = new File(filePath);

//must check if deleted is true. It is true if the file was successfully deleted
boolean deleted = file.delete();

Answer: File file = new File(deleteFilePath);
boolean deleted = = file.deleted();
deleteFilePath is a String containing the path to your zip file.
if deleted is true. It is true if the file was successfully deleted.
Answer:  Use below method

     /**
     * Clear/Delete all the contents in file/Directory
     *
     * @param file file/folder
     * @return true on successfull deletion of all content
     * Make sure file it is not null
     */
    public boolean clearDirectory(@NonNull File file) {
        boolean success = false;
        if (file.isDirectory())
            for (File child : file.listFiles())
                clearDirectory(child);
        success = file.delete();
        return success;
    }

Answer: Give this a try!
public static final String ZIP_FILES_DIR = "Download/FolderNAME";

File directoryPath = new File(Environment.getExternalStorageDirectory()+ File.separator + ZIP_FILES_DIR);
    if (directoryPath.delete()) {
        //do whatever you want
      }

Delete zip folder in android


How to distance and to MDS-plot objects according their complex shape

Question: Suppose I have four basal forms of signal (blue, purple, red, green). I also have created transition forms between each other. If you carefully look on the picture below, you can see that for example blue signal (A1) slowly transforms into purple  (A5) - horizontally, or into red (E1) - vertically.  Taken in general, the closer is the difference between any two signals the more similar they are.
I am looking for some method/algorithm/technique which is able to:

Extract as much information as possible about complexity of signals
Map signals into 2D (or 3D) according to their similarity

Link to source data: each signal is coded into JPG image (25 jpg files, each 100x180 pixels)
https://www.dropbox.com/sh/ynidcsjdymrh85f/AAAHVtYSG0GUvX3CEdDWWG42a

I have spent some time trying to solve this issue, so here I add my approach, which does no yield desired result:
At first, I've set working directory, load all 25 jpg-files into a R list...
setwd("add directory where you downloaded jpg-files here")

# required libraries
library(jpeg)
library(raster)
library(asbio)

sgnl.vctr<-c("A1.jpg","A2.jpg","A3.jpg","A4.jpg","A5.jpg",
             "B1.jpg","B2.jpg","B3.jpg","B4.jpg","B5.jpg",
             "C1.jpg","C2.jpg","C3.jpg","C4.jpg","C5.jpg",
             "D1.jpg","D2.jpg","D3.jpg","D4.jpg","D5.jpg",
             "E1.jpg","E2.jpg","E3.jpg","E4.jpg","E5.jpg")

sgnl.list <- list()      # sgnl.list contains all 25 signals
for (i in 1:length(sgnl.vctr)){
sgnl.list[[i]] <- readJPEG(sgnl.vctr[i])
}

I had some problems with pixel values (range from 0 to 1), therefore I recclassify them into binary. (either 0 or 1).
# reclassification of values
for (i in 1:25) {
sgnl.list[[i]][1:100,1:180,1][sgnl.list[[i]][1:100,1:180,1] > 0.5]<- 2
sgnl.list[[i]][1:100,1:180,1][sgnl.list[[i]][1:100,1:180,1] <= 0.5]<- 1
sgnl.list[[i]][1:100,1:180,1][sgnl.list[[i]][1:100,1:180,1] == 2]<- 0
}

Then, I've extracted binary (0-1) vectors from each jpeg-file. If someone know how to shorten procedure bellow, please edit the R-code.
# A row
A1<-as.vector(sgnl.list[[1]][1:100,1:180,1])
A2<-as.vector(sgnl.list[[2]][1:100,1:180,1])
A3<-as.vector(sgnl.list[[3]][1:100,1:180,1])
A4<-as.vector(sgnl.list[[4]][1:100,1:180,1])
A5<-as.vector(sgnl.list[[5]][1:100,1:180,1])
# B row
B1<-as.vector(sgnl.list[[6]][1:100,1:180,1])
B2<-as.vector(sgnl.list[[7]][1:100,1:180,1])
B3<-as.vector(sgnl.list[[8]][1:100,1:180,1])
B4<-as.vector(sgnl.list[[9]][1:100,1:180,1])
B5<-as.vector(sgnl.list[[10]][1:100,1:180,1])
# C row
C1<-as.vector(sgnl.list[[11]][1:100,1:180,1])
C2<-as.vector(sgnl.list[[12]][1:100,1:180,1])
C3<-as.vector(sgnl.list[[13]][1:100,1:180,1])
C4<-as.vector(sgnl.list[[14]][1:100,1:180,1])
C5<-as.vector(sgnl.list[[15]][1:100,1:180,1])
# D row
D1<-as.vector(sgnl.list[[16]][1:100,1:180,1])
D2<-as.vector(sgnl.list[[17]][1:100,1:180,1])
D3<-as.vector(sgnl.list[[18]][1:100,1:180,1])
D4<-as.vector(sgnl.list[[19]][1:100,1:180,1])
D5<-as.vector(sgnl.list[[20]][1:100,1:180,1])
# E row
E1<-as.vector(sgnl.list[[21]][1:100,1:180,1])
E2<-as.vector(sgnl.list[[22]][1:100,1:180,1])
E3<-as.vector(sgnl.list[[23]][1:100,1:180,1])
E4<-as.vector(sgnl.list[[24]][1:100,1:180,1])
E5<-as.vector(sgnl.list[[25]][1:100,1:180,1])

Vectors were compared by Kappa function to obtain total agreement value. See this link:
https://stackoverflow.com/questions/24534192/how-to-compare-all-possible-combinations-of-objects-in-r-by-loop/24534794#comment37992299_24534794
(Many thanks to @digEmAll)
# looping of:
#            Kappa(sgnl.list[[1]][1:100,1:180,1],
#                  sgnl.list[[2]][1:100,1:180,1])$ttl_agreement
M <- rbind(A1,A2,A3,A4,A5,
           B1,B2,B3,B4,B5,
           C1,C2,C3,C4,C5,
           D1,D2,D3,D4,D5,
           E1,E2,E3,E4,E5)

res <- outer(1:nrow(M),
             1:nrow(M),
             FUN=function(i,j){
               # i and j are 2 vectors of same length containing
               # the combinations of the row indexes.
               # e.g. (i[1] = 1, j[1] = 1) (i[2] = 1, j[2] = 2)) etc...
               sapply(1:length(i),
                      FUN=function(x) Kappa(M[i[x],],M[j[x],])$ttl_agreement )
             })

row.names(res) <- c("A1","A2","A3","A4","A5",
                    "B1","B2","B3","B4","B5",
                    "C1","C2","C3","C4","C5",
                    "D1","D2","D3","D4","D5",
                    "E1","E2","E3","E4","E5")
colnames(res) <- c("A1","A2","A3","A4","A5",
                   "B1","B2","B3","B4","B5",
                   "C1","C2","C3","C4","C5",
                   "D1","D2","D3","D4","D5",
                   "E1","E2","E3","E4","E5")

Finally, similarity matrix (res object) was used for multidimensional scaling...
# mds based on ttl_agreement matrix
d <- as.dist(res)
mds.coor <- cmdscale(d)
plot(mds.coor[,1], mds.coor[,2], type="n", xlab="", ylab="")
text(jitter(mds.coor[,1]), jitter(mds.coor[,2]),
     rownames(mds.coor), cex=0.8)
abline(h=0,v=0,col="gray75")

However, as you can see (left plot), four basal signals were not separated as I expected. Does anybody know better solution which would lead to desired outcome (right plot)?
Comment: It seems to me that you didn't use clustering. You used multidimensional scaling (mds). So, was the whole question about mds, i.e. about plotting the distances between the 25 shapes in euclidean space?
Comment: @whuber should you want to blow my answer out of the water (:)), If I understand you correctly what you suggest can perhaps most conveniently be achieved in R with smacofConstraint in smacof. There is an option external that allows fitting onto a simplex of given dimensions. E.g. with `simpl <- smacofConstraint(res,constraint="unique",external=list("simplex",4),ndim=2); plot(simpl)`. The result doesn't look like what the OP needs, but I suppose to fix the basal points to the vertices of the simplex one needs to define a user-defined specified `constraint`.
Comment: If yes, then two question arise. First, why did you expect that 2d map will be sufficient? Or is 2d was the strict requirement of yours? Given that you have 4 focal propotypes, they may well require 3d space. Second, the problem may be with the chosen proximity measure. Did you consider more alternative measures, not just "kappa"? Selecting proximity measure is crucial.
Comment: Hi @ttnphns! Yes, I would like to plot the distances between the 25 shapes in euclidean space. 2D map is not strict requirement. I would just prefer it over hierarchical clustering (tree branches). Do you know any better proximity measures than Kappa?
Comment: I never analyzed images, and I'm not `R` user. Did I understand it right, that all images, of equal pixial size, you take as X-Y coordinates data, binary (0 for white pixel, 1 for black pixel). Then you unwrap X-Y into a single column (vector) and compute some proximity measure (called 'kappa") between each pair of vectors (i.e. images).
Comment: Yes @ttnphns. That is exaclty what I have done.
Comment: One crucial moment. Can shapes be improperly aligned wrt each other? Shitf by just one pixel will be devastating. Consider two identical vectors `0101`. If the alignment is shifted, such as `-0101` vs `0101-`, the similarity is 0!
Comment: I am aware of this possibility, however it is highly unlikely to cause problems with this particular dataset. I was very careful when creating JPG's - the alignment is NOT shifted. (minimal agreement via Kappa is approx. 74%)
Comment: If you are sure that the alignment is fully the same, that saves much effort... OK. I'd compute [Dice](http://stats.stackexchange.com/a/55802/3277) coefficient instead of Simple matching coefficient (which you call "kappa"). Matrices of all such _binary matching coefficients_ can be [efficiently computed](http://stats.stackexchange.com/a/49477/3277) via matrix algebra. Then I'd input `1-Dice` (called Bray-Curtis distance) into MDS program and tried 2d and 3d metric and nonmetric solutions.
Comment: P.S. Why Dice and not Simple matching? Well, `0-0` (i.e. white-white) match is of no importance for you, it only interfere. Also, `1-1` match is the same importance as _either_ `1-0` and `0-1`, no matter what of those. That's why. (Sorry I won't go chatting, I have to go now.)
Comment: In any way, comparing such shapes by binary matching coefficients based on pixel data is not the only and not the best approach. One could compare the shapes as histograms are compared, for example...
Comment: As far as I can see--I did not read through the code--your four "basal forms" can be represented as high-dimensional vectors and the "transitions" lie in their convex hull, which is a three-dimensional simplex. Doesn't your question (2) boil down to projecting any arbitrary signal onto that simplex?  This is easily done with the least squares solution (constraining the coefficients to be positive and sum to unity). Then you will need to decide an appropriate map of that simplex into 2D or 3D; I don't see that you provided any criteria for uniquely determining such a map.
Comment: Hi @whuber! Thank you for reaction. As soon as I understand to your comment, I will respond. :D
Comment: @whuber, You're saying interesting things. May you wish to post a full answer?
Answer: This may be only a partial answer because I don't think the plot that you expect is really what is in the data, especially the "parallelity and continuity" of the intermediate signals. I will speculate on reasons for that below.
But I think I was able to get to what you look for in terms of the four basal signals A1, A5, E1, E5. Namely that they lie on the edge of the embedded manifold, that opposite signals lie more or less diametrical to each other (that is A1, E5 and E1, A5 respectively) and that neighbouring signals are preserved (so A1, A5 and E1, E5 respectively).
Generally, I think standard (i.e. with an input weight matrix consiting of only 1's) MDS doesn't really give you what you want because you are actually looking for nonlinear dimension reduction that has some localization feature, namely that larger "distances" should not be preserved but local distances should. There are a number of algorithms that do that. A rather popular one that is often used for cases like yours is called t-SNE for t-Distributed Stochastic Neighbor Embedding. On the linked homepage you will find quite some information.
I calculated the t-SNE embedding for your kappa distance. Note that I use a high perplexity to force a shaping that looks like the one you aim for. It can be obtained by
set.seed(1)
library(tsne)
tsne.coor1 <- tsne(res,perplexity=25)
rownames(tsne.coor1) <- c("A1","A2","A3","A4","A5",
                   "B1","B2","B3","B4","B5",
                   "C1","C2","C3","C4","C5",
                   "D1","D2","D3","D4","D5",
                   "E1","E2","E3","E4","E5")
plot(tsne.coor1[,1], tsne.coor1[,2], type="n", xlab="", ylab="")
text(tsne.coor1[,1], tsne.coor1[,2],
     labels=row.names(tsne.coor1), cex=0.8)
abline(h=0,v=0,col="gray75")

and looks like this

The basic signals are labeled in red. As you can see, the similarity structure as captured by your preprocessing and distance measure does not suggest that the intermediate signals are actually at all as you expect them to be. For example, the path from A1 to E1 has intermediate signals E4, D5, A3 and not B1 through D1. But this is what your data tell you! So, the similarity between the signals that are within the convex hull of the embedded manifold suggests that the clear-cut pattern is not preserved.
There are two obvious explanations:

Some information gets lost in mapping to low-D. The information that gets lost might actually be the information you were looking for.
The distance measure might not capture what you actually care for. I agree with @ttnphns on this one.

[\Edit] (thanks @ttnphns!)
To investigate the last point, I tried other measures of similarity for binary matrices. For this high perplexity it led to no discernably different results in the shape, but it did so in the arrangements (I used a gravity model similarity and an asymmetric binary similarity, the one returned by dist(x,method="binary")). For lower perplexity the effects on the visualisation the kappa distance is small, but for the other distances it is not. To illustrate for the asymmetric distances the results are:
res <- dist(M,method="binary")
set.seed(1)
tsne.coor2 <- tsne(res,perplexity=25)
tsne.coor3 <- tsne(res,perplexity=3)
rownames(tsne.coor2)<-rownames(tsne.coor3) <- c("A1","A2","A3","A4","A5",
                   "B1","B2","B3","B4","B5",
                   "C1","C2","C3","C4","C5",
                   "D1","D2","D3","D4","D5",
                   "E1","E2","E3","E4","E5")
par(mfrow=c(1,2))
plot(tsne.coor2[,1], tsne.coor2[,2], type="n", xlab="", ylab="")
text(tsne.coor2[,1], tsne.coor2[,2],
     labels=row.names(tsne.coor3), cex=0.8)
abline(h=0,v=0,col="gray75")
plot(tsne.coor3[,1], tsne.coor3[,2], type="n", xlab="", ylab="")
text(tsne.coor3[,1], tsne.coor3[,2],
     labels=row.names(tsne.coor2), cex=0.8)
abline(h=0,v=0,col="gray75")

and here's the results

So, for high perplexity the difference in the shape of the projection of the signals is rather similar for both distance measures. For lower perplexity, the results change. Note that while it is looking different than what you originally intended when using the asymmetric binary distance, the transition from basis signal through the other states seems to be better preserved in the low perplexity plot, particularly column-wise! . This makes the speculation 2 of using kappa being a not very suitable distance measure more likely. You may try the distances dist(x, method="binary") or cluster::daisy(x, metric= "gower")) (which is the dice coefficient, I think).
[\end Edit]
Note the t-SNE has random initializations, so it might look a bit different at your end --- not sure whether set.seed has an effect in the R implementation. The random initialization is actually something that might get you closer to what you need anyway. As the authors put it:

In contrast to, e.g., PCA, t-SNE has a non-convex objective function. The objective function is minimized using a gradient descent optimization that is initiated randomly. As a result, it is possible that different runs give you different solutions. Notice that it is perfectly fine to run t-SNE a number of times (with the same data and parameters), and to select the visualization with the lowest value of the objective function as your final visualization.

You may play around with the above mentioned distances and some of the parameters, especially perplexity, to perhaps get you closer to what you need into one direction or the other. Hope this helps as a first start.
Comment: +1. For `has some localization feature, namely that larger "distances" should not be preserved but local distances should`, however, one could note that MDS - good implementations - provide option to weight input distances. So, one can put more weight (importance) for small ones. But, in any case, a good distance function must be crucial. I was somewhat upset that t-SNE (which's new to me) `led to no discernable different results`.
Comment: @ttnphns Re: Input weights-this is a good point. I edited the answer accordingly. Re: no discernably differences of t-SNE with different distances. I found that curious too. Maybe I made a mistake somewhere, I didn't investigate it further. But I set the perplexity parameter quite high here (to 25) to force this type of shape. If one uses smaller perplexity, the results are different for different distances, see the edit.


How can I disable the Windows Game DVR from the command line?

Question: I need to disable the Windows Game DVR for a collection of Windows computers that will be running student exam / testing software, so that students can't use the Game DVR hotkeys to record the test questions and choices.
These computers are not Windows 10 Home edition so group policy can be used, but they are also not managed by Active Directory, SCCM, or Azure Endpoint Manager. Is there a way to do it from the command line?
Answer: One way to disable the Game DVR from the command line is by using REG.EXE at an elevated command prompt like this:
reg.exe add "HKLM\Software\Policies\Microsoft\Windows\GameDVR" /v "AllowGameDVR" /t REG_DWORD /d 0

If you want to overwrite any previous value, add /f at the end of this command to force the change without prompting.
Explanation:
Microsoft group policy documentation at https://docs.microsoft.com/en-us/windows/client-management/mdm/policy-csp-applicationmanagement#applicationmanagement-allowgamedvr
Says that this policy is found in C:\Windows\PolicyDefinitions\GameDVR.admx
On my Windows 10 21H2 the policy looks like this:
<policy name="AllowGameDVR" class="Machine"
displayName="$(string.GameDVRMode)"
explainText="$(string.GameDVRMode_Help)"
key="Software\Policies\Microsoft\Windows\GameDVR"
valueName="AllowGameDVR">
  <parentCategory ref="GAMEDVR" />
  <supportedOn ref="windows:SUPPORTED_Windows_10_0_NOSERVER" />
  <enabledValue>
    <decimal value="1" />
  </enabledValue>
  <disabledValue>
    <decimal value="0" />
  </disabledValue>
</policy>

It is policy class Machine so it is in the HKEY_LOCAL_MACHINE or HKLM registry hive.
The registry path is Software\Policies\Microsoft\Windows\GameDVR
To disable it, you create the key name AllowGameDVR with a decimal value (or DWORD) of 0


How to add a Facebook "Like" button with full functionality?

Question: I'm trying to add a Facebook "Like" button and I'm using a free extension for it but it's giving me an error as they are not compatible with Magento version 1.5.
I'm trying to do it manually but a little help which I found was to get a Facebook developer code and paste in static URL etc.
...but I didn't understand that.
So can you kindly tell me how to do what I want? From where do I get which code and where to paste please?
Answer:
Go to http://developers.facebook.com/docs/reference/plugins/like/ and obtain the proper code for your site. (It will generate iframe HTML code that you need to copy)
Determine where you want to show the like button, options are: all pages, product view, category view, etc...(your choice)
For example if you want it on product page, then you need to add the previously generated HTML to the catalog/product/view.phtml template.
If you want the url that needs to be liked to be fixed:

If you want the url to be the current one:

<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo $this->helper('core/url')->getCurrentUrl(); ?>?other_params_go_here">
Answer: you need login Facebook account panel & create your own code for your website
then you can paste code in any block template .
if you can not template you can login magento admin panel to enable development mode
Answer: It is always advisable to use an module.
There is a 3-in-one module available for Social sharing. i.e. Google+1 Button, Facebook LIke and Twitter Share.
you can check it at magento connect
http://www.magentocommerce.com/magento-connect/Modulesoft/extension/7258/google_1_plus_button_with_facebook_and_tweet
Hope the information is helpful
Answer:

Answer: I added a Facebook plugin at a front page, see it here: http://www.boardcorner.se on the right side.
By adding a piece of code in the TinyMCE javascript it allows the Facebook iframe to be inserted by a standard copy & paste.
You'll find the piece of code needed here: Magento - How to allow certain tags (iframe, embed) in Magento's CMS editor?
Answer: Try this for product detail page

<fb:like href="<?php echo $_product->getProductUrl() ?>" send="false" show_faces="false"></fb:like>


Curve : should I use the mean or all values?

Question: In my experiments, I measure glycemiae at 7 different times to then draw a curve with R or Excel.
For more precision, I duplicate my measures, so for each time I have 2 glycemiae.
For now, curves data are the means of each time glycemiae, but I tried to enter each single point and R² is not the same.
I'm not sure I'm clear, so here's an example :

t ---gly1---  gly2
  ----------------- 0  ---10   ---12 30   ---13   ---15

I can either enter datas (t, gly) as {(0,10), (0,12), (30,13), (30,15)} or as {(0,11), (30,14)}.
In which situation should I use one way or the other ?
Answer: $R^2$ will certainly be different if you enter means of replicates instead of all the individual values.
If I were in this position, I'd use the individual values; for example, it allows one to better assess lack of fit and correctness of the variance specification.
In some circumstances other considerations might impact the choice, but in most cases, that's what I'd suggest.
Comment: There may be a number of situations - I can't guess at all the circumstances that might lead to that choice -- but for example if I had really large numbers of replicates (many hundreds say) and many distinct points (enough that I felt I could see lack of fit even just with the means, for example) and were not as concerned about testing, prediction intervals and the like, I might consider using the mean. However, these days it would be a relatively rare situation. It's not like even millions of data points is difficult to deal with.
Comment: Yeah, I kinda agree. And when should I use the mean ?


selenium change firefox proxy to autoDetect c#

Question: I search to change the default proxy of firefox on firefoxDriver call.
I work in c#.
I know in java you do :
FirefoxProfile ff = new FirefoxProfile();
ff.setPreference("network.proxy.type", ProxyType.AUTODETECT.ordinal());
FirefoxDriver ffD = new FirefoxDriver(ff);

I tried :
FirefoxProfile ff = new FirefoxProfile();
ff.SetPreference ("network.proxy.type",ProxyKind.AutoDetect.ToString ());
var driver = new FirefoxDriver(ff);

Answer: I just forgot whats ordinal. After that.
ff.SetPreference ("network.proxy.type",(int)ProxyKind.AutoDetect);


crontab won't work on mac 10.6.7

Question: i create a simple cron job by editing /etc/crontab as following:
*/2     *       *       *       *       *       php /Users/min/Documents/testcron.php

and the testcron.php  is simple as:
<?php

$fd = fopen("/Users/min/Documents/testcron.txt", 'a');
fwrite($fd, "test--cron--\n");
fclose($fd);
?>

then simply save the crontab file and hope magic happen, but nothing happened. i even run the command manually and it worked.
php /Users/min/Documents/testcron.php

anyone have any idea? Thanks
Answer: Just a quick note, on some systems you have to do sudo crontab -e  , and sudo crontab -l because otherwise you won't have the proper permissions to create or view crontabs
Answer: Not certain, but I bet your file is not being read. Perhaps you have to do
$ crontab -e

to edit, and then it gets read properly after you save?
You could probably test this theory by doing
$ crontab -l

to list the table to see if it is working already.
Comment: ok, i ran crontab -e to rewrote the file, though i m sick of vi, then ran crontab -l, now it complained:crontab: no crontab for min, does it matter where i ran the crontab -e?
Comment: @ohana: It does not matter from where you run `crontab -e`. But you have to be logged in as the user with whose rights the cronjob shall run. Did `crontab -e` give an output like "Installing new crontab for min" when you saved the crontab and closed vi? Btw.: You can avoid to use vi by setting the `EDITOR` environment variable to something else.
Answer: I think there's one column too much. You have 6 time specification columns - it should be 5: minute, hour, day of month, month, day of week:
*/2 * * * * php /Users/min/Documents/testcron.php

Comment: that are 5 columns: */2 means every 2 min.
Comment: i mistyped here with one more column, but in my file it is 5 columns.
Comment: @ohana: So it seems to be a different problem. Do you see anything in e.g. `/var/log/messages`?

crontab won't work on mac 10.6.7


Export content to pdf angular using jspdf

Question: I am trying to create a pdf using jspdf. However I'm getting error cannot create property 'header' on string 'Details'.I went through this question How to fix: Cannot create property 'header' on string but couldn't find a solution.Please Help.Thanks in advance.
Here is my convert function
convert() {

    var doc = new jsPDF();
    var col = ["Details", "Values"];
    var rows = [];

    /* The following array of object as response from the API req  */

    var itemNew = [
      { id: 'Case Number', name: '101111111' },
      { id: 'Patient Name', name: 'UAT DR' },
      { id: 'Hospital Name', name: 'Dr Abcd' }
    ];

    itemNew.forEach(element => {
      var temp = [element.id, element.name];
      rows.push(temp);

    });

    doc.autoTable(col, rows);
    doc.save('Test.pdf');
  }

StackBLitz: https://stackblitz.com/edit/angular-jspdf-xgoetc?file=app/app.component.ts
Comment: Can you share in stackbiltz
Comment: @AdritaSharma added stackblitz link
Answer: The problem is in the autoTable() function where you specifyhead and body.
var col = [["Details", "Values"]];

alter autoTable() like
 doc.autoTable({
        head: col,
        body: rows
    });

Updated Snippet:
convert() {

    var doc = new jsPDF();
    var col = [["Details", "Values"]];
    var rows = [];

    /* The following array of object as response from the API req  */

    var itemNew = [
      { id: 'Case Number', name: '101111111' },
      { id: 'Patient Name', name: 'UAT DR' },
      { id: 'Hospital Name', name: 'Dr Abcd' }
    ];

    itemNew.forEach(element => {
      var temp = [element.id, element.name];
      rows.push(temp);

    });

    //doc.autoTable(col, rows);
    doc.autoTable({
        head: col,
        body: rows
    });
    doc.save('Test.pdf');
  }

PDF Preview (Test.pdf):

Refer to the jsPDF-AutoTable Documentation for more info.
Comment: @rock11 Glad to help. Could you please mark the answer as useful. Thank you


Representations of compact groups on hilbert spaces

Question: Let $G$ be a compact group.
I know that every finite dimensional representation of $G$ is unitarizable (start with an artbitrary inner product and average it along $G$).
Now, let $\mathcal{H}$ be a Hilbert space on which $G$ acts continuously and linearly. The averaging process still seems to work, but does the new inner product define the same topology on $\mathcal{H}$ as the old one?
What I'd really like to know is "is every representation of a compact group on a Hilbert space unitarizable", and the above would answer this question.
Answer: Let $\langle\cdot,\cdot\rangle$ be the original scalar product on $\mathcal H$. So, you have defined a new scalar product by$$(v,w)=\frac1{|G|}\sum_{g\in G}\bigl\langle g.v,g.w\bigr\rangle.$$Then this scalar product induces a norm $\|\cdot\|_G$ defined by$$\|v\|_G=\sqrt{\frac1{|G|}\sum_{g\in G}\|g.v\|^2},$$where $\|\cdot\|$ is the norm induced by $\langle\cdot,\cdot\rangle$. So, obviously$$(\forall v\in V):\|v\|_G\geqslant\sqrt{\frac{\|v\|^2}{|G|}}=\frac{\|v\|}{\sqrt{|G|}}.$$On the other hand, if, for each $g\in G$, $\|g\|$ is the norm of the linear map $v\mapsto g.v$, then$$(\forall v\in V):\|v\|_G\leqslant\sqrt{\frac1{|G|}\sum_{g\in G}\|g\|^2.\|v\|^2}=\sqrt{\frac1{|G|}\sum_{g\in G}\|g\|^2}\,\|v\|$$So, the norms $\|\cdot\|_G$ and $\|\cdot\|$ are equivalent and therefore they induce the same topology.
Comment: @JoLasker Right.
Comment: I haven't read it all yet, but just to make sure, those sums are actually integrals, right?
Comment: @JoLasker Sure. I thought that you had asked a question about *finite* groups. But all that I wrote remains valid if you use an integral. Sorry about my confusion.
Comment: Thanks. Your answer is very clear. Your proof also shows that a sequence is Cauchy w.r.t to new norm if and only if it is Cauchy w.r.t. the original norm. So, together with the fact that they give the same topology, this means that if the original norm was complete, so is the new one, right?


How to affect contents of a div

Question: HTML

4
<?php echo $location; ?>
Night

CSS
.Box {
white-space: nowrap;
padding: 0px 20px;
font-size: 110%;
color: blue;}

.list {
height: 30px;
width: 30px;
line-height: 30px;
-moz-border-radius: 15px; /* or 50% */
border-radius: 15px; /* or 50% */
text-align: center;
display: inline-block;
background-color: orange;
color: blue;}

.locations{
text-transform: uppercase;
color: blue;}

.type {
text-transform: uppercase;
color: blue;}

I want the .active span to change the font color of .list , .locations and .type to dark blue or any other color
I'm no expert at CSS and looking online hasn't given me any answers.
Apologies if I am posting this wrong or am asking stupid questions.
Comment: where is div in your code??
Comment: sorry, i don't have it yet but was thinking of changing span "active" to div "active" if that makes any difference
Comment: Edit the question to and remove the php tag . before it gets voted down
Answer: .active .list,
.active .locations,
.active .type {
    color: darkBlue;
}

Example...

.Box {
white-space: nowrap;
padding: 0px 20px;
font-size: 110%;
color: blue;}

.list {
height: 30px;
width: 30px;
line-height: 30px;
-moz-border-radius: 15px; /* or 50% */
border-radius: 15px; /* or 50% */
text-align: center;
display: inline-block;
background-color: orange;
color: blue;}

.locations{
text-transform: uppercase;
color: blue;}

.type {
text-transform: uppercase;
color: blue;}

.active .list,
.active .locations,
.active .type {
    color: darkBlue;
}

4
<?php echo $location; ?>
Night

Comment: this was way too easy haha, don't know how i didn't think of that. Thanks
Answer: Add this -:
a {
    color :red; // your color here
  }

and remove the attribute color from the other selector.

How to affect contents of a div


How do I access image files

Question: So I was trying to open image files in google collab. My target is to apply FFT for image processing. Here i have files labelled as array values. How exactly would I access an image instead of the numerical values.
!nvidia-smi
!nvidia-smi
!nvidia-smi
!pip install tensorflow-gpu
!pip install tensorflow_hub
from __future__ import absolute_import, division, print_function, unicode_literals
import matplotlib.pylab as plt
import tensorflow as tf
import tensorflow_hub as hub
import numpy as np
import pandas as pd
import os
import cv2

from google.colab import drive
drive.mount('/content/drive')

data_root='/content/drive/My Drive/ML/AlpDatabase/DATASET'

import numpy as np
from matplotlib import pyplot as plt

data = tf.keras.utils.image_dataset_from_directory('/content/drive/My Drive/ML/AlpDatabase/DATASET')

data_iterator = data.as_numpy_iterator()

batch = data_iterator.next()

batch[0].shape

fig, ax = plt.subplots(ncols=4, figsize=(20,20))
    for idx, img in enumerate(batch[0][:4]):
      ax[idx].imshow(img.astype(int))
      ax[idx].title.set_text(batch[1][idx])

so if I had to print a certain image from data set how would I accomplish that as my goal is to send the image files to my FFT algorithm and then create a new dataset after processing. My goal here was to basically read image files from my drive folder maintain classes.
My drive folder has DATASET folder containing A,B,C,D.... etc folders each with many images. Basically an image dataset of alphabets.
Answer: If I understood correctly - You want to basically read image files from the drive folder maintain classes.
The code mentioned above is working fine to do the same when I tried replicating the issue. Please check this gist for your reference.
You also can use the below code to display images after fetching from the directory where class_names will be your DATASET inside folder names (A,B,C,D...).
data = tf.keras.utils.image_dataset_from_directory('/content/drive/My Drive/MY WORK/dataset/flowers')

class_names = data.class_names
print(class_names)

Output:
['daisy', 'dandelion', 'rose', 'sunflower', 'tulip'] #in your case ['A', 'B', 'C', 'D'...

To display images:
import matplotlib.pyplot as plt

plt.figure(figsize=(10, 10))
for images, labels in data.take(1):
  for i in range(9):
    ax = plt.subplot(3, 3, i + 1)
    plt.imshow(images[i].numpy().astype("uint8"))
    plt.title(class_names[labels[i]])
    plt.axis("off")

Output:

How do I access image files


É possível um Switch dentro de um Else?

Question: Eu estou tentando fazer um site onde o jogador pode calcular os status de seu personagem automaticamente para agilizar na hora da ficha,criação de personagem e não haver erros.
Então eu fiz o seguinte código (utilizando jQuery), dependendo do valor digitado, já calcula automaticamente o mod (modificador) e o rank da sua habilidade.
Porém, eu não estou conseguindo fazer isso funcionar, só funciona o meu primeiro if() e apenas o Default que eu defini no switch(), eu gostaria de saber o motivo de não estar funcionando.

$('#str').on('input', function() {
  let modificador = $('.str-mod');
  let rank = $('.str-rank');

  if (this.value == '' || this.value <= 0) {
    rank.text('F');
    modificador.text('-10 ');
  } else {

    let modificadorStatusBase = -5;
    let modificadorBase = Math.floor(this.value / 2) + modificadorStatusBase;

    modificador.text((modificadorBase < 0 ? '' : '+') + modificadorBase + ' ');

    switch (this.value) {
      case this.value >= 4 && this.value <= 9:
        rank.text('D');
        break;
      case this.value >= 10 && this.value <= 15:
        rank.text('C');
        break;
      case this.value >= 16 && this.value <= 21:
        rank.text('B');
      default:
        rank.text('E');
        break;
    }
  }
});

  <fieldset>
    <legend>Status</legend>
    <form class="form-pontos">

        <input type="text" nome="str" id="str" placeholder="Força" value="22" maxlength="3">

        [
          +6
          A ] Str (Força)

    </form>
  </fieldset>

https://jsfiddle.net/9obtwds1/1/
Answer: Citando a resposta do stackoverflow inglês -> https://stackoverflow.com/a/2697105/10577440
O switch funciona comparando o que está no switch() com o que está em cada case:
switch (valor) {
    case 1: ....
    case 2: ....
    case 3: ....
}

Portanto não se pode ter lógica dentro dos case.
Um código como esse:
switch (valor) {
    case (valor >= 10 && valor <= 20): ...
}

é equivalente a esse:
if (valor === (valor >= 10 && valor <= 20)) ...

Nesse caso é recomendado usar if-else :)
Comment: Vale lembrar que, por não utilizar a [comparação frouxa](https://pt.stackoverflow.com/q/7/5878), mas sim `===`, o resultado da expressão `(valor === (valor >= 10 && valor <= 20))` jamais será verdadeira se o tipo de `valor` **não for** booleano. Na verdade, ela será válida **apenas se** `valor = false`, o que não faz sentido algum neste caso - o que explica sempre entrar no `default` quando utilizado `switch(valor)`.
Answer: Seu switch está errado, para que possa usar um between no switch deve usar uma estrutura como essa:
switch (true) {
  case (this.value >= 4 && this.value <= 9):
    rank.text('D');
    break;
  case (this.value >= 10 && this.value <= 15):
    rank.text('C');
    break;
  case (this.value >= 16 && this.value <= 21):
    rank.text('B');
  default:
    rank.text('E');
    break;
}

Ou simplesmente um if/else:
if (this.value >= 4 && this.value <= 9) {
  rank.text('D');
} else if (this.value >= 10 && this.value <= 15) {
  rank.text('C');
} ...

Como muito bem lembrado pelo AndersonCarlosWoss nos comentários: "se existe a condição value <= 9, não será necessário fazer a comparação value >= 10 posteriormente, dado que a condição anterior já garante que o valor é maior que 9". Logo é possível criar uma estrutura como essa:
switch (true) {
  case (this.value <= 3):
    rank.text('E');
    break;
  case (this.value <= 9):
    rank.text('D');
    break;
  case (this.value <= 15):
    rank.text('C');
    break;
  case (this.value <= 21):
    rank.text('B');
    break;
  default:
    rank.text('E');
    break;
}

Ou, com if/else
if (this.value <= 3) {
  rank.text('E');
} else if (this.value <= 9) {
  rank.text('D');
} else if (this.value <= 15) {
  rank.text('C');
} ...

Comment: Nesse caso eu usaria if/else if. Pra que um switch em cima de nada?
Comment: Só lembrando que em muitos casos as condições podem ser simplificadas. Por exemplo, se existe a condição `value <= 9`, não será necessário fazer a comparação `value >= 10` posteriormente, dado que a condição anterior já garante que o valor é maior que 9.
Comment: O operador `switch` é para comparar igualdades. Internamente ele utiliza o comparador `===`. O correto é usar a estrutura lógica `if  else` para resolver o problema.
Comment: @VictorCarnaval na minha resposta ele compara `true` com o resultado da comparação de cada caso, é um modo de se usar o switch para esse fim
Comment: @bfavaretto concordo, mas se o perguntador quer usar o switch, seja porque está estudando ou porque acha mais legível, essa é a forma
Comment: @AndersonCarlosWoss muito bem lembrado, editei a resposta com uma solução melhor
Answer: Realmente usar um switch acho desnecessário nesse caso. Você pode fazer uma sequência de if else e por último um else (quando nenhuma das condições dos if else anteriores foram atendidas). Inclusive pode simplificar o código, fazendo as alterações nos textos no final, tudo de uma vez.
Pode guardar o valor do campo numa variável, sem precisar repetir this.value diversas vezes:
let val = parseInt(this.value.trim());

Primeiro eliminei espaços nas bordas com .trim(). Isso significa que se for digitado apenas espaços no campo, o valor será vazio. Depois converti para número inteiro com parseInt(), para que ele converta o valor em número em vez de string. Isso faz diferença no 0, porque 0 tipo número é diferente de 0 tipo string, que será usado no if.
O código ficaria assim:

$('#str').on('input', function() {

   let modificador = $('.str-mod');
   let rank = $('.str-rank');
   let val = parseInt(this.value.trim());
   var rtxt, mtxt;

   if (!val || isNaN(val) || val < 0) {
      rtxt = 'F';
      mtxt = '-10 ';
   } else if (val >= 4 && val <=9) {
      rtxt = 'D';
   } else if (val >= 10 && val <= 15) {
      rtxt = 'C';
   } else if (val >= 16 && val <= 21) {
      rtxt = 'B';
   } else {
      rtxt = 'E';
   }

   if(rtxt != "F"){
      let modificadorStatusBase = -5;
      let modificadorBase = Math.floor(val / 2) + modificadorStatusBase;
      mtxt = (modificadorBase < 0 ? '' : '+') + modificadorBase + ' ';
   }

   rank.text(rtxt);
   modificador.text(mtxt);

});

  <fieldset>
    <legend>Status</legend>
    <form class="form-pontos">

        <input type="text" nome="str" id="str" placeholder="Força" value="22" maxlength="3">

        [
          +6
          A ] Str (Força)

    </form>
  </fieldset>

No primeiro if:
if (!val || isNaN(val) || val < 0) {

verifica:
!val       -> se o valor é vazio ou igual a 0
isNaN(val) -> não é um número (no caso de se digitar algo que não seja número)
val < 0    -> se for um número negativo

Após os if else coloquei mais um if:
if(rtxt != "F"){

Como apenas a primeira condição do primeiro if modifica o texto do elemento da variável modificador de forma diferente das outras condições, eu verifiquei se o valor da variável rtxt (que será o texto do elemento da variável rank) é diferente de F.

É possível um Switch dentro de um Else?


Module of exponential function

Question: In the Fourier transform $\hat{f}=\int_{\mathbb{R}^n}f(x)\exp(-2\pi j w x)$. What is a value of $|\exp(-2\pi j w x)|$?
Answer: If $w\in\mathbb{R}^n$ and $j$ is the imaginary unit (what I ussually call $i$), then $|e^{-2\,\pi\,j\,w\cdot x}|=1$.
Comment: @Juan Almost, by Euler you know that this is equal to $|\cos(-2\pi wx) + j\sin(-2\pi wx)| = (\cos^2 + \sin^2)^{1/2}\ldots$.
Comment: but, What are the intermediary steps please
Comment: by indentity of Euler I know that expresion is equal to $|\cos(-2\pi j w x)+\sin(-2\pi j w x)|$
Comment: ok, understand thanks

Module of exponential function


Rehearsal marks

Question: I'm looking for a good way to mark sections of music piece. Using simple letters such A, B, C doesn't make a lot of sense in "modern" music pieces. Is it still ok to use markings like Verse, Bridge, Intro when there are no vocal parts in the music? Or is there a better way? What are some good practices to do this?
Comment: Speaking as someone who's played in large ensembles such as symphony orchestras for 45 years, let me tell you that you should put in both letter/number rehearsal marks,  **and** measure numbers at the start of each line.
Answer: I would recommend against using terms like "Verse," "Bridge," "Intro," etc. unless the piece is clearly referencing that stylistic norm.
Why don't you think A, B, C, etc. make a lot of sense in "modern" music pieces? I've certainly seen it done this way.
Otherwise, plenty of scores simply give the measure number in a large box, thus serving two roles as both a measure locator and an easy landmark by which to lead rehearsals (hence the term "rehearsal" mark).
Answer: The reason for using letters (or numbers) is that they are in sequence. If the conductor says "letter D" and the player can see letter B or F, he/she knows whether he/she needs to look before or after that point to find letter D.
A set of terms like "verse", "chorus", "bridge" could be in any random order, unless you are only concerned with a very specific and "formulaic" genre of music.
Answer: The letters are the rehearsal marks. Simply naming a section verse, chorus, bridge, ect. is not using rehearsal marks. The purpose of rehearsal marks are to have "a checkpoint" when rehearsing the piece. You are not actually name the section A, B, C, ect., but you are referencing an absolute position on the score to pick up playing the piece in rehearsal.
If you are just talking about labeling sections, you can label the sections however you want. If it doesn't make sense to call them verse, chorus, ect. then don't. It will be up to you at the end of the day.

Rehearsal marks


Add values from API call to dropdown Angular

Question: I'm facing a problem while I want to display some values which I got from a API call in a dropdown in the fronted.
I call my endpoint like this:
component.ts
ngOnInit() {
  const values = this.backendService.getAllValues().subscribe()
}

The call works, I get the following output:
0: {name: "Data Visualisation",…}
 name: "Data Visualisation"
1: {name: "Watchning TV",…}
 name: "Watchning TV"

Now, I d'like to display those values in my dropdowon:
component.html
<scs-dropdown>
   <scs-dropdown-item *ngFor="let value of values" [value]="value.name">
   </scs-dropdown-item>
</scs-dropdown>

But nothing is displayed in the dropdown, what do I wrong?
Comment: can you create a stackblitz for the same
Answer: That's not how you should set the values attribute. It should be like this:
values = [];

ngOnInit() {
    this.backendService.getAllValues().subscribe(response => {
        this.values = [];
        for (const item in response) {
            this.values.push(item);
        }
    });
}

Look that values is a class attribute, not a variable defined in ngOnInit
Comment: Thanks for your answer. Unfortunately it doesn't work. I got this error message: `Type 'Object' is not assignable to type 'never[]'.
  The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?ts(2322)`
Comment: This is because your response is not an array. You should convert to an array before assign to this.values
Comment: where should I define the `item`?
Comment: With this solution I got the error: `Argument of type 'string' is not assignable to parameter of type 'never'`
Comment: Can you tell me what shows when you add console.log(response) at the beginning?
Answer: The Values you get from the API Must be mapped into an Array using the ' .map => ' operator then once mapped you can loop through the values on the interface
Comment: I think that your answer is wrong. The return type of the api call is an array.. This return type is an Subscription:    this.backendService.getAllValues().subscribe()
Answer: Please try this and show us the console output:
values = [];

ngOnInit() {
  this.backendService.getAllValues().subscribe( arr => {
      console.info(JSON.stringify(arr, null, 4));
      values = arr
  });
}

<scs-dropdown>
   <scs-dropdown-item *ngFor="let value of values" [value]="value.name">
      {{value.label}} :-)
   </scs-dropdown-item>
</scs-dropdown>

See: https://angular.io/guide/observables-in-angular
Don't forget to unsubscribe.
Comment: Thanks for your answer. Unfortunately it doesn't work. I got this error message: Type 'Object' is not assignable to type 'never[]'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?ts(2322)


What NoSQL database is good for developing a Wiki?

Question: What NoSQL database do you recommend for developing a Wiki-like application?
I need documents to have many sub-section texts, and each can be versioned controlled, and yet normalized.
Think of a Wikipedia page. It has many sections, and being a Wiki, it has version control for the document. However, I do not want a new document to be created (or the document being entirely duplicated) everytime a paragraph is changed. I only want that particular paragraph (or section) to have a new version, so it won't waste space on storage.
Any recommendation on the database or the design strategy?
Answer: Currently no NoSQL database provides what you want here (as far as I know). The closest to what you want is the CouchDB which keeps document revision history on every update. The disk space is cheap so generally it's not a problem.
But if versioning is the key to your business and one of the business requirements you should choose a tool that is built specifically to solve this problem - Git. Git does exactly what you want and does a lot of heavy lifting for your wiki app (like version diffs, easy blame in other words who did what changes, has hooks etc.).
A great example is GitHub wiki pages. Their wiki engine built on git (Gollum) is open-sourced.
To conclude, here are your options:

use git
CouchDB that does revision tracking for you, but as far as I
know saves a copy of the document
implement the revision logic in
your app, any NoSQL db would fit nicely.
Comment: "You cannot rely on document revisions for any other purpose than concurrency control.

Due to compaction, revisions may disappear at any time. You cannot use them for a client revision system." - https://wiki.apache.org/couchdb/Document_revisions


Three equilateral triangles

Question: Can you provide a proof for the following claim:

Claim. Given an arbitrary equilateral triangles $\triangle ABC$ and $\triangle BDE$ with common vertex $B$ . The points $H$ and $I$  divide line segments $CE$ and $AD$ respectively in the ratio $2 : 1$ . Let $G_1$ be the centroid of triangle $\triangle ABC$ . Then triangle $\triangle G_1IH$ is an equilateral triangle as well.

GeoGebra applet that demonstrates this claim can be found here.
So far I have managed to prove that $|AE|=|CD|$ and that line segments $AE$ and $CD$ intersect each other at angle of $60^{\circ}$ , but I dont know if this can be of any use. Also, can we apply the fundamental theorem of similarity in some way?
Comment: What you've proven is enough! All that needs to be done is a simple modification and you will have your result. I'll elaborate.
Answer: Use complex numbers. Put $G_1=0$, $B=1$ and $BD=z$ (so $BE=ze^{i\pi/3}$). Then, letting $w=e^{i\pi/3}$,
$$H=\frac13(w^2+2(1+zw))=\frac13(w^2+2zw+2)$$
$$I=\frac13(w^4+2(1+z))=\frac13(w^4+2z+2)$$
But $w^2+2=w(w^4+2)$, so
$$H=w\cdot\frac13(w^4+2z+2)=wI$$
Since $|w|=1$ and $\arg w=60^\circ$, $G_1H=G_1I$ and $\angle HG_1I=60^\circ$, so $\triangle HG_1I$ is equilateral.
Comment: A somewhat similar issue was posted [here](https://math.stackexchange.com/q/3992520) shortly after this one and I had, like you, the idea to use complex numbers...
Answer: Here's a synthetic solution. You have already proven the required facts.
Let $X, Y$ be the midpoints of $\overline{BC}, \overline{BA}$, respectively. Then $\triangle XBY$ is equilateral. Apply your results to $\triangle XBY$ and $\triangle EBD$ to obtain

$\angle(\overline{XD}, \overline{YE}) = 60^{\circ}$.
$XD = YE$.

Now here's the critical point of the argument: $\triangle CYE \sim \triangle CG_1H$ and $\triangle AXD \sim \triangle AG_1I$. Thus $\overline{YE} \parallel \overline{G_1H}$ and $\overline{XD} \parallel \overline{G_1I}$. Furthermore, $G_1H = \lambda YE$ and $G_1I = \lambda XD$ for a scaling factor $\lambda = 2/3$. This, all together, shows

$\angle(\overline{G_1I}, \overline{G_1H}) = 60^{\circ}$.
$G_1H = G_1I$.

We're done.
Answer:
Let $L$ and $M$ be the midpoints of side $AB$ and $BC$ respectively. Draw medians $AM$ and $CL$.The point at which they intersect will be the centroid of $\triangle ABC$, point $G$. Draw $GH$, $LE$, $GI$ and $MD$. Let the points at which $GH$ and $LE$ intersect $MD$ be $P$ and $Q$ respectively.Let the point at which $GI$ intersect $LE$ be $R$. Draw $BQ$.
Observe that, $\triangle MDB\cong \triangle LBE$. $\Rightarrow LE=MD$
Also, observe that, since $\frac {CG}{GL}=\frac {CH}{HE}=\frac {2}{1}$, $GH\parallel LE$ and $GH=\frac 23LE$. Similarly, $GI\parallel MD$ and $GI=\frac 23MD$.
$LE=MD$ $\Rightarrow GH=GI$
Quadrilateral $GPQR$ is a parallelogram since its opposite sides are parallel.
$\Rightarrow \angle HGI=\angle PGR=\angle PQR=\angle EQD$
Notice that, in quadrilateral $QEDB$, $\angle QEB=\angle LEB=\angle MDB=\angle QDB$; Hence, $\angle EQD=\angle EBD=60^{\circ}$.
$\Rightarrow \angle HGI=\angle EQD=60^{\circ}$
$HG=GI$ and $\angle HGI=60^{\circ}$ ; Therefore, $\triangle HGI$ is equilateral.

Three equilateral triangles


Como imprimir um valor específico de um JSON em PHP

Question: Tenho o seguinte arquivo JSON e gostaria de imprimir somente o valor do campo nome, que está dentro de contato. Estou utilizando linguagem PHP.
C:\wamp64\www\macmind\client-search.php:31:
array (size=1)
  'retorno' =>
    array (size=3)
      'status_processamento' => string '3' (length=1)
      'status' => string 'OK' (length=2)
      'contato' =>
        array (size=41)
          'id' => string '393021930' (length=9)
          'codigo' => string '21656' (length=5)
          'nome' => string '  REST SIDER DE VOLTA REDONDA COMERCIO DE ALIMENTOS LTDA ME' (length=59)
          'fantasia' => string 'GIRAFFAS' (length=8)
          'tipo_pessoa' => string 'J' (length=1)
          'cpf_cnpj' => string '08.348.956/0001-90' (length=18)
          'ie' => string '  78.191.830' (length=12)
          'rg' => string '' (length=0)
          'im' => string '' (length=0)
          'tipo_negocio' => string '' (length=0)
          'endereco' => string 'RUA DOZE,300 ' (length=13)
          'numero' => string '300' (length=3)
          'complemento' => string 'Loja 309' (length=8)
          'bairro' => string 'Vila Santa Cecília' (length=19)
          'cep' => string '27260-315' (length=9)
          'cidade' => string 'Volta Redonda' (length=13)
          'uf' => string 'RJ' (length=2)
          'pais' => string '' (length=0)
          'endereco_cobranca' => string '' (length=0)
          'numero_cobranca' => string '' (length=0)
          'complemento_cobranca' => string '' (length=0)
          'bairro_cobranca' => string '' (length=0)
          'cep_cobranca' => string '' (length=0)
          'cidade_cobranca' => string '' (length=0)
          'uf_cobranca' => string '' (length=0)
          'contatos' => string '' (length=0)
          'fone' => string '(24) 7836-5440' (length=14)
          'fax' => string '' (length=0)
          'celular' => string '(24) 7836-5442' (length=14)
          'email' => string 'firstname.lastname@example.com' (length=26)
          'email_nfe' => string '' (length=0)
          'site' => string '' (length=0)
          'limite_credito' => int 0
          'situacao' => string 'A' (length=1)
          'obs' => string '' (length=0)
          'id_lista_preco' => int 0
          'id_vendedor' => string '0' (length=1)
          'nome_vendedor' => string '' (length=0)
          'data_criacao' => string '13/11/2017 09:02:21' (length=19)
          'tipos_contato' =>
            array (size=1)
              ...
          'pessoas_contato' =>
            array (size=0)
              ...

Comment: Utilize `$obj = json_decode('seu-json'); var_dump( $obj->retorno->contato->nome );`
Answer: Já deu uma olhada no site da  API sobre json_encode do PHP? Você só precisa pegar dentro do seu array especificamente qual o valor que deseja que seja retornado para o usuário.
Exemplo:
$objectJson= [
  'nome'=>$seuArray['retorno']['contato']['nome']
];
json_encode($objetoJson);
// A saída deve ser: {"nome":"Nome pego do array"}

Answer: $obj = json_decode($json);

echo($obj->contato>nome);


What is the parameter $instance_id in the function Block::setVisibilityConfig?

Question: I need to programatically set the visibility of a block. I've loaded the block, and I know I need to use the Block::setVisibilityConfig method, but I don't know what the $instance_id variable is.
Does anyone know what to pass here to the function?
Comment: It's [documented](https://api.drupal.org/api/drupal/core!modules!block!src!Entity!Block.php/function/Block%3A%3AsetVisibilityConfig/8.2.x). You pass an instance of a visibility condition object (which implements [ConditionInterface](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Condition%21ConditionInterface.php/interface/ConditionInterface/8.2.x))
Comment: Hi @Clive, thanks for your reply, but I don't understand it. I have the following code: use Drupal\block\Entity\Block;
$block = Block::load('sitebranding');
$block->setRegion('content');
$block->save(); What can I add to call that function?
Answer: I got it. Example:
use Drupal\block\Entity\Block;

function mytheme_preprocess_html(&$variables)
{
    $block = Block::load('sitebranding');
    $block->setRegion('content');

    $visibility = $block->getVisibility();

    if (isset($visibility['request_path']['pages']))
    {
       unset($visibility['request_path']['pages']);
       $visibility['request_path']['negate'] = 0;
       // $visibility['request_path']['pages'] = '/node/2';
       $visibility['request_path']['pages'] = \Drupal::config('mymodule.settings')->get('services_block_path_visibility');
       $block->setVisibilityConfig('request_path', $visibility['request_path']);
       $block->save();
    }
}