Cloudstack- Unable to delete secondary storage

Question: I am working on a model of cloudstack framework to analyse the feasibility of Cloudstack with my organization's product.
I was trying to delete secondary storage from the cloudstack's UI but it was failing due to the error "Cannot delete image store with active templates backup!". I later went through several blogs on Internet for this and did several modification in the mysql database (in tables such as template_host_ref, vm_template, etc) without taking any prior backup of the database.
Is there any default database backup imported during installation of cloudstack which can help me to restore modified database? I mean, which could lead to restore initial configuration.
If not then what is the possible solution to get back to the initial state?
Please suggest as I am very new in this.
Thanks in advance.
Comment: How was this problem resolved?
Answer: The error message seems reasonable.  CloudStack should stop you from deleting secondary storage if the zone is in use.  Secondary storage holds all template disk images including system VMs that CloudStack uses to operate the zone.  If the zone is enabled, deleting secondary storage would cause it to fail.  Therefore, CloudStack should stop you from deleting secondary storage.
For non-production deployments of CloudStack, you are probably better off re-installing the system.  Note that for certain hypervisor types, CloudStack will delete existing VMs.
Direct further questions to the 'users' group on the apache cloudstack mailing list.


Apache Spark: broadcast join behaviour: filtering of joined tables and temp tables

Question: I need to join 2 tables in spark.
But instead of joining 2 tables completely, I first filter out a part of second table:
spark.sql("select * from a join b on a.key=b.key where b.value='xxx' ")

I want to use broadcast join in this case.
Spark has a parameter which defines max table size for broadcast join: spark.sql.autoBroadcastJoinThreshold:

Configures the maximum size in bytes for a table that will be
broadcast to all worker nodes when performing a join. By setting this
value to -1 broadcasting can be disabled. Note that currently
statistics are only supported for Hive Metastore tables where the
command ANALYZE TABLE  COMPUTE STATISTICS noscan has been
run. http://spark.apache.org/docs/2.4.0/sql-performance-tuning.html

I have following questions about this setup:

which table size spark will compare with autoBroadcastJoinThreshold's value: FULL size, or size AFTER applying where clause?
I am assuming that spark will apply where clause BEFORE broadcasting, correct?
the doc says I need to run Hive's Analyze Table command beforehand. How it will work in a case when I am using temp view as a table? As far as I understand I cannot run Analyze Table command against spark's temp view created via dataFrame.createorReplaceTempView("b"). Can I broadcast temp view contents?
Answer: Understanding for option 2 is correct.
You can not analyze a TEMP table in spark . Read here
In case you want to take the lead and want to specify the dataframe which you want to broadcast, instead spark decides, can use below snippet-
df = df1.join(F.broadcast(df2),df1.some_col == df2.some_col, "left")

Answer: I went ahead and did some small experiments to answer your 1st question.
Question 1 :

created a dataframe a with 3 rows [key,df_a_column]
created a dataframe b with 10 rows [key,value]
ran: spark.sql("SELECT * FROM a JOIN b ON a.key = b.key").explain()

== Physical Plan ==
*(1) BroadcastHashJoin [key#122], [key#111], Inner, BuildLeft, false
:- BroadcastExchange HashedRelationBroadcastMode(List(cast(input[0, int, false] as bigint)),false), [id=#168]
:  +- LocalTableScan [key#122, df_a_column#123]
+- *(1) LocalTableScan [key#111, value#112]

As expected the Smaller df a with 3 rows is broadcasted.

Ran : spark.sql("SELECT * FROM a JOIN b ON a.key = b.key where b.value=\"bat\"").explain()

== Physical Plan ==
*(1) BroadcastHashJoin [key#122], [key#111], Inner, BuildRight, false
:- *(1) LocalTableScan [key#122, df_a_column#123]
+- BroadcastExchange HashedRelationBroadcastMode(List(cast(input[0, int, false] as bigint)),false), [id=#152]
   +- LocalTableScan [key#111, value#112]

Here you can notice the dataframe b is Broadcasted ! meaning spark evaluates the size AFTER applying where for choosing which one to broadcast.
Question 2 :
Yes you are right. It's evident from the previous output it applies where first.
Question 3 :
No you cannot analyse but you can broadcast tempView table by hinting spark about it even in SQL. ref
Example : spark.sql("SELECT /*+ BROADCAST(b) */ * FROM a JOIN b ON a.key = b.key")
And if you see explain now :
== Physical Plan ==
*(1) BroadcastHashJoin [key#122], [key#111], Inner, BuildRight, false
:- *(1) LocalTableScan [key#122, df_a_column#123]
+- BroadcastExchange HashedRelationBroadcastMode(List(cast(input[0, int, false] as bigint)),false), [id=#184]
   +- LocalTableScan [key#111, value#112]

Now if you see, dataframe b is broadcasted even though it has 10 rows.
In question 1, without the hint , a was broadcasted .
Note: Broadcast hint in SQL spark is available for 2.2

Tips to understand the physical plan :

Figure out the dataframe from the LocalTableScan[ list of columns ]
The dataframe present under the sub tree/list of BroadcastExchange is being broadcasted.


Prevent PHP from reading own source files

Question: For simplicity consider the following example: We have a file secret.php that runs our back end code and it includes a file custom.php somewhere a long the line. Obviously the apache-user must be able to read both files to work, but can you prevent using something like file_get_contents('secret.php') to get the source code?
We do have some control over custom.php before it is loaded, so it's possible to use a coding solution with white and/or blacklist on php functions, but that adds a major layer of complexity I'd rather not use.
Can you setup apache / php / ubuntu in a way that allows execution of php files but not reading them?
Answer: While there are lots of ways to restrict file access via the operating system, none of these can differentiate between PHP scripts run by the same executable process, by the same user, in the same context, on the same host.
However you can enforce constraints within PHP itself via open_basedir - this can be set on a per path basis (or via other criteria) in the webserver config. e.g.
<Directory /var/www/html>
        php_admin_value open_basedir "/usr/share/php"
</Directory>
<Directory /var/www/html/privileged_scripts>
        php_admin_value open_basedir "/usr/share/php:/usr/share/restricted"
</Directory>

However if an attacker can get their code running on your webserver, this is not going to provide much protection.
As implemented above, this is applied to the PHP script mapped directly to the URL - scripts it subsequently includes inherit this value.
Comment: Thank you for the open_basedir suggestion. This might be enough for our goal and we'll definitely set up a test case to see if we can get it to work.
Answer:
Obviously the apache-user must be able to read both files to work, but can you prevent using something like file_get_contents('secret.php') to get the source code?

No. On UNIX-alike systems (like your Ubuntu Linux), file access permissions are handed out on a process-basis. So, if the process needs to be able to read a file, you will have to grant the process the ability to read it – for any purpose.
You can do much more advanced things using seccomp whilst modifying your PHP source code (and possibly even the PHP interpreter) to disable reading the file after a certain point in time, but that's going to be cooperative.
If you need a security boundary between secret.php and custom.php, you should probably at least separate their processes – and make them communicate, e.g. via a domain socket, or POSIX shared memory, or actual network sockets, or simply through pipes. Mind you, PHP has no great representation for "code running in other process working on the same data structures as this process", much less for nicely represented RPC, so this will all incur a significant serialization/deserialization overhead.
You might want to consider migrating away from PHP if you can't trust code that you run (which, by the way, is the nr.1 reason for wordpress instances getting hijacked: untrustworthy code run in themes that should only modify the HTML output but do sinister things).
Comment: @symcbean I didn't say "based on", I intentionally chose the wording "handed out": the thing that decides whether a `read()` can be done is the process'es privileges. These are *not purely* based on the effective User/group of that process (as in Unix in the 70s), but you need to take Linux capabilites, namespaces, and things like compsec into account! But yeah, same process, no help. As said, a bit in the spirit of BSD `pledge` and similar mechanisms, your process can voluntarily lose privileges (and if its just by setting a different effective UID; but that would require root to begin with).
Comment: erm, no. Unix permissions are based on users/groups not processes. MAC does allow for behaviours based on the process, but in this scenario its still the same process so that doesn't help.
Comment: Thanks for the input. This is in no way intended to be foul proof, but more a discouragement for freelancers working on our system from downloading the core software. They are bound by law with an NDA, but it doesn't hurt to have something extra in place.
Comment: @HugoDelsing I'd strongly recommend stopping to hope that happens. The source code they are not supposed to download is quite probably still there in the process that runs their code. They can get it. If you can't trust your freelancers, don't let them run their code. And especially don't let them run their code in your process. And especially don't let them run their code in your PHP process.
Comment: @HugoDelsing You just literally gave us four big red flags regarding your system's architectural security: untrustworthy code in non-sandbox environment, untrustworthy code in same process, attempt to ignore trust problem with superficial non-fixes, and thinking plugging PHP could stop them. It is time for a software re-design, to be honest! Isolate the non-trustworthy code to a VM, to a container, or at the very least to its own process. Define interfaces for your code with which the freelancer code can interact – and don't implement a "read my code" interface. Implement harsh restrictions…
Comment: … on the untrustworthy code-running instances. What you're trying to do here is like asking about which mop to bring to a dam breach; the answer is none, you need something that can stop flood waters, not a mop up a puddle.
Comment: @MarcusMüller Your making many assumptions without knowing most details. The only person you can trust is yourself, but if you need to expand your business you need more developers. It doesn't matter how you call them; employee; freelancer; interim; whatever; they will be able to access source code. You prevent them from sharing it with an NDA. One extra step to prevent them from direct access to some parts of the code isn't a security flaw. It's like a padlock. You don't stop malicious intent but you do prevent a curious bystander.
Comment: @MarcusMüller and there is nothing in my question about a sandbox environment or not. There is, but a sandbox environment also needs all parts of the code to run. And whether their code ends up in production isn't any part of this question either. It won't, it will be checked. But that doesn't stop them from taking a peak before releasing the final code for testing. And obviously having a separated process is best, but who would develop the core that enables this? Right, other developers.
Comment: yes, but these other developers would be the ones that you trust as much as the ones currently developing your core that these freelancers you don't trust aren't supposed to read. All in all, while you're right, I was making a security problem out of a confidentiality problem, it still sounds like you'd massively benefit from a clearer separation of concerns, even, and especially, on a legal basis: For example, if one of the developers who you trust less copies some AGPL code into their code. Suddenly, a competitor comes on and says, "hey, that whole system is AGPL, you gave me access to the
Comment: part the lesser-trusted freelancer wrote, so now I'm entitled to the full source code of your system!" They'd be right. If you can't trust people to not read your source code, you cannot trust them to not introduce funky code, and then you need to introduce clean separation. Just a thing to think about. Personally, if you can't give your code to your freelancers, freely, and in full,, your code must either be very very bad, or you really really shouldn't be contracting with these freelancers. That's my 2ct as FOSS maintainer *and* Freelancer.


Question regarding dimensions of vector spaces

Question: How can one prove the following ?
Let $U,V$ be two vector spaces.
$$\dim (U + V) + \dim (U \cap V) = \dim U + \dim V
$$
Comment: Chose a basis of $U\cap V$ and extend the same basis to two different bases for $U$ and $V$ resp. Finally show that the union of these bases is a basis for $U + V$. Note that $U\cap V$ is a linear subspace of both $U$ and $V$ so the first step is valid.
Answer: Hint
Let $\mathcal B$ be a basis for the linear subspace $U\cap V$ of both $U$ and $V$. We can extend this basis such that $\mathcal B_U = \mathcal B \cup \mathcal U$ is a basis of $U$ where $\mathcal U$ is a basis for $(U\cap V)^\perp$ in $U$ and to a basis $\mathcal B_V = \mathcal B \cup \mathcal V$ where $\mathcal V$ is a basis for $(U\cap V)^\perp$ in $V$.
$\mathcal B \cup \mathcal V\cup \mathcal U$ must now be a basis for $U+V$ (why?) and thus by inclusion-exclusion principle
$$\dim (U+V) + \dim (U\cap V) = |\mathcal B \cup \mathcal U \cup \mathcal V| + |\mathcal B| = |\mathcal B| + |\mathcal U| + |\mathcal B| + |\mathcal V| = \dim U + \dim V$$
Comment: What is $(U\cap V)^\bot$?
Answer: A more abstract approach:
Consider the map
$$
\Phi : U \times V \to U+V, (u,v) \mapsto u+v.
$$
Show that this is a (well-defined) linear map with ${\rm ker}(\Phi) = U\cap V$.
EDIT: Ok, the kernel of $\Phi$ is not really $U\cap V$, but it is
$$
{\rm ker}(\Phi)=\{(u,-u)\mid u \in U\cap V\},
$$
which is isomorphic to $U\cap V$ via $U \cap V \to {\rm ker}(\Phi), u \mapsto (u,-u)$, so both spaces have the same dimension.
By the first isomorphism  theorem, this yields
$$
U+V \cong (U \times V) / {\rm Ker}(\Phi).
$$
Now it is easy to see $\dim(U\times V) = \dim(U) + \dim(V)$.
The only thing you have to know now (which is useful in general) is that
$$
\dim(X/Y) = \dim(X) - \dim(Y),
$$
if $Y$ is a subspace of $X$.
But this follows by choosing a basis $(y_1, \dots, y_k)$ for $Y$, extending it to a basis $(y_1, \dots, y_k, x_1, \dots, x_\ell)$ of $X$ and noting that $(x_1 + Y, \dots, x_\ell + Y)$ is a basis of $X/Y$.
Comment: $\ker(\Phi) \ne U \cap V$ You need to find a different map!
Comment: way too complicated.
Comment: @AlexR: You are right. I corrected the post. The kernel of $\Phi$ is not $U\cap V$, but it is isomorphic to this space. This is all we need.


Edição inline vuejs

Question: Quando fazer click na coluna nota todas as inputs aparecera  mostrado. Queria que cada input aparecera quando for clicada na linha correspondente.

 new Vue({
      el: '#app',
      data: {

        nota:'nota',
        edit: '',
        myclass: 'before',
        pincel: 'before',
        list: [
            {
                "id": 0,
                "Firstname": "Humberto",
                "Lastname": "Lopes",
                "Email": "email@example.com",
                "Nota": "xxxx"

            },
            {
                "id": 1,
                "Firstname": "Luis Humberto",
                "Lastname": "Lopes",
                "Email": "email@example.com",
                "Nota": "xxxx"

            },
            {
                "id": 2,
                "Firstname": "Lino",
                "Lastname": "Moniz",
                "Email": "firstname.lastname@example.com",
                "Nota": "xxxx"

            },
            {
                "id": 3,
                "Firstname": "Jorge",
                "Lastname": "Cabral",
                "Email": "email@example.com",
                "Nota": "xxxx"
            }
        ],

      },
      methods: {

        whenclick(item) {

        console.log(item);
          this.edit = true;
         },
         whenedited(nota) {

          this.nota = nota;
          this.edit = false;

         },

    change() {
      console.log('rato em cima');
      this.myclass = 'after';
      this.pincel = 'after';
    }

      }
    })

Inline edition

                      Name
                      Apelido
                      Email
                      Nota

                      {{item.Firstname}}
                      {{item.Lastname}}
                      {{item.Email}}

                      {{item.Nota}}

                      <input  v-model="item.Nota" v-on:keyup.enter="whenedited(item.Nota)" v-on:blur="whenedited(item.Nota)" v-if="edit" type="text" class="form-control" id="exampleInputName2" placeholder="">

Answer: Tentei isto abaixo:

new Vue({
      el: '#app',
      data: {

        nota:'nota',
        edit: '',
        myclass: 'before',
        pincel: 'before',
        list: [
            {
                "id": 0,
                "Firstname": "Humberto",
                "Lastname": "Lopes",
                "Email": "firstname.lastname@example.com",
                "Nota": "xxxx",
                Editable: false

            },
            {
                "id": 1,
                "Firstname": "Luis Humberto",
                "Lastname": "Lopes",
                "Email": "firstname.lastname@example.com",
                "Nota": "xxxx",
                Editable: false

            },
            {
                "id": 2,
                "Firstname": "Lino",
                "Lastname": "Moniz",
                "Email": "email@example.com",
                "Nota": "xxxx",
                Editable: false

            },
            {
                "id": 3,
                "Firstname": "Jorge",
                "Lastname": "Cabral",
                "Email": "firstname.lastname@example.com",
                "Nota": "xxxx",
                Editable: false
            }
        ],

      },
      methods: {

        whenclick(item) {

        console.log(item, ':item');
          item.Editable = true;
         },
         whenedited(nota) {

          this.nota = nota;
          this.edit = false;

         },

    change() {
      console.log('rato em cima');
      this.myclass = 'after';
      this.pincel = 'after';
    }

      }
    })

Inline edition

                      Name
                      Apelido
                      Email
                      Nota

                      {{item.Firstname}}
                      {{item.Lastname}}
                      {{item.Email}}

                      {{item.Nota}}

                      <input  v-model="item.Nota" v-on:keyup.enter="whenedited(item.Nota)" v-on:blur="whenedited(item.Nota)" v-if="item.Editable" type="text" class="form-control" id="exampleInputName2" placeholder="">

Coloquei um novo atributo Editable em seus objetos e seto este atributo para cada objeto, ao invés de uma variável global.

Edição inline vuejs


Is there any software to program accompaniment quickly without electronic keyboard?

Question: Is there any software where I can select a style and mention the chord names to be played?
I used to do it with my yamaha keyboard where I could select a nice style and create chord progressions but I fried my keyboard and I am waiting for a new one.
I want a software where I can select a style like pop ballad or rock and add the chords to be played. And I can listen to it just by hitting play and then edit the style and chords just by mentioning it's name and not by adding every single key of the chord.
Thanks.
Comment: Finale series programs can do it with "Band in a Box" if you have a score.  I think others can do it too. But this looks like a software recommendation to me, and those are off topic here.
Answer: You want Band-in-a-Box. It is extremely rich and powerful for generating accompaniment tracks.
If you are on Android tablet, iPad or iPhone or Mac OS X, there is also iReal Pro. It is very simple to use, but its results are not as good as those created by Band-in-a-Box. iReal Pro also has thousands of song charts of jazz and pop standards available for downloading from their website after you purchase the program.
Answer: This is Chorrdbot application for Android and Iphones. It is simple to use. It allows the user to customize the style. It can export the chord sequence as MIDI format as well as WAV format which you can import to garage band.
Answer: Any reasonable digital audio workbench should allow you to input notes with a computer keyboard and mouse.
Assuming I didn't misinterpret your question completely, I could probably set up something like that in GarageBand with minimal effort.


Não consigo fazer o dataBinding AndroidStudioKotlin

Question:

Simplesmente não consigo fazer o binding funcionar e quando boto o mouse por cima aparece o seguinte erro : Unresolved reference: CrieSeuPersonagemBinding
Just cant make the binding work and when i put the mouse over it shows the following error : Unresolved reference: CrieSeuPersonagemBinding
Answer: Quando você cria uma activity, existe a opção de criá-la junto com o layout, ai o binding é automático. Depois de criar é só botar id nos componentes desse layout e utilizá-los no código da própria activity, por exemplo:
Se no seu xml existe um Button com id "btnSalvar", na sua activity é só escrever esse btnSalvar dentro de algum método (pode ser do onCreate) e botar por exemplo:
btnSalvar.setOnClickListener{ coisa que vc quer que o botão faça ao ser clicado }. Depois o nome btnSalvar vai estar em vermelho pra importar, ai é só apertar Alt Enter pra importar.
A mesma coisa vale pra um TextView, que seria pelo .text, conseguindo assim pegar o texto que está dentro dele.
<code>class Main2Activity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main2)

    btnSalvar.setOnClickListener{
         var destreza = editDestreza.text
         var inteligencia = editInteligencia.text
         var sabedoria = editSabedoria.text
         var forca = editForca.text
    }
  }
}
</code>
editDestreza, editInteligencia, editSabedoria e editForca são os ids de cada EditText no layout xml
Comment: Onde fica essa opção de criá-la junto com o layout?
Comment: quando vc cria a activity aparece a opção Generate Layout File
Comment: Mas esse layout já foi gerado assim.
Comment: Sim, mas a activity por padrão já se comunica com o layout através do setContentView, que no seu código está removido e estaria na linha do val binding :CrieSeuPersonagem. Vou editar minha resposta para clarear o que está acontecendo
Comment: Outra coisa, dentro do seu xml tem que ter um tools:context=".nomeDaSuaActivity" para ocorrer o binding, senão o aplicativo vai crashar.
Esse tools:context=".nomeDaSuaActivity" seria uma propriedade do componente Layout, pode ficar embaixo do android:layout_height="match_parent" só que antes da setinha ">"
Comment: val editDestreza : EditText = findViewById(R.id.editDestreza)
Se eu quiser referenciar o editText editDestreza eu preciso fazer isso, caso contrário dá Unresolved Reference.
Comment: Sim, ocorre porque não existe um setContentView da própria activity, como está escrito no meu código.
Comment: No meu código por exemplo eu não precisei utilizar o findViewById(R.id.btnSalvar), eu apenas utilizei o btnSalvar solto, o que acontece é que esse btnSalvar vai ficar pintado de vermelho, pois não foi importado ainda o layout, ai é só clicar no btnSalvar e apertar Alt Enter que importa o layout automaticamente
Comment: Cara, se eu fosse você criava outro projeto do zero com uma empty activity, depois disso é só botar um EditText no layout e dentro dele botar um id, que seria assim

android:id="@+id/edt_Destreza"

Ai depois escreve "edt_Destreza" dentro da sua activity no onCreate . Só isso já vai identificar automaticamente o componente. Esse edt_Destreza que vc acabou de escrever vai ficar escrito em vermelho, ai é só botar o mouse em cima e escolher a opção de importar
Answer: Elias, tentei fazer dessa forma mas as opções não contêm importar
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val destreza = editDestreza.text.toString().toInt()
}
}
nas opções do alt enter não há nada sobre importar.


Defining physicsbody for a curved object

Question: How can I define the physics body of an curved or not rectangle object
I know for a rectangle I use ( rectangle of : width,height)
And for a circle I use (circle of radius: )
But how can I do this for a different object like this one
Comment: You can use `UIBezierpath` to define a path, which can be converted into a `physicsBody` object.
Comment: Can you show me the code
Answer: You can use a CGPath like this:
let path = CGMutablePath()
path.addLine(to: CGPoint(x: 10, y: 10))
path.addArc(center: CGPoint(x: 20, y: 20), radius: 50, startAngle: 20, endAngle: 60, clockwise: true)
node?.physicsBody = SKPhysicsBody(edgeLoopFrom: path)

You can show the bodies of SKView with:
view.showsPhysics = true

The complete example are here: GameScene.swift
Comment: Can you please implement it on this project
Comment: on physics body p1
Comment: https://www.dropbox.com/sh/nch0xjxnammop11/AADB_TG1BghZA_wiZbCZtGjba?dl=0


Jquery Dialog Box and Pulling content from a Database

Question: Good Afternoon All,
I am working on part of a site that will read data from a table in a database and display the data sequentially with a click of the previous and next buttons, in a JQuery Dialog box. I am really not that good with Javascript or Jquery for that matter and need a little guidance here.
I can get the the content on the first page of the dialog, but it pulls each id body column for the specific value. I want it to pull one instance with the given id, click next and get the next and so on.
The code is below.
Here is the script

Here is the code on my View Page
<% IQueryable<#######.#####.######.######> tutorials =  gr.GetEntriesByStream(13); %>

This is dialog box for the tutorial data.

        <%foreach (var item in tutorials)
          { %>
          <%if (item.seOrder == 0)
            {%>
              <%: item.seBody %>
          <%} %>
        <%} %>

Go To Tutorial

Answer: If i understood correctly, you want to traverse the tutorials based on your Previous and Next buttons. Instead what's happening is that the entire content get displayed in the jQuery dialog in one go.
There's more than one way to do this, and I think a simple method would be to have view page generate each tutorial inside a div element with an Id that is suffixed with an index, for instance, here's what it would look like

This is dialog box for the tutorial data.

        <%foreach (var item in tutorials)
          { %>
          <%if (item.seOrder == 0)
            {%>
              <div id='tutorial<%:tutorials.indexOf(item) + 1 %>'>
              <%: item.seBody %>

          <%} %>
        <%} %>

This would generate an HTML like so

tutorial1Content1

tutorial1Content2

tutorial1Content3

You could then modify your prev and next functions as below
"<< Prev": function () {
    $("#tutorial" + currentTutorialIndex).hide();
    currentTutorialIndex --;
    $("#tutorial" + currentTutorialIndex).show();

 },
 "Next >>": function () {
     $("#tutorial" + currentTutorialIndex).hide();
    currentTutorialIndex ++;
    $("#tutorial" + currentTutorialIndex).show();
 }

where currentTutorialIndex is a globally/appropriately scoped variable that is accessible from within prev and next functions.
*please excuse syntax errors since this is an untested code


Tensor products and monomorphisms of $A$-modules.

Question: This problem addresses the same question that has been asked in $A^m\hookrightarrow A^n$ implies $m\leq n$ for a ring $A\neq 0$, which is exercise 2.11 of Atiyah and Macdonald's Introduction to Commutative Algebra. The reason I am posting this again is because although the other threads provided a complete answer, there are additional questions that arise from the problem that are of concern to me. Specifically, I would like to know whether the following is true:
Problem. Let $f:A^m\rightarrow A^n$ be a monomorphism of $A$-modules with $A$ a non-zero commutative ring. Let $I\subset A$ be a maximal ideal in $A$. Is the following map injective
$$f\otimes 1:A^m\otimes_A(A/I)\rightarrow A^n\otimes_A(A/I),\enspace (f\otimes 1)(a\otimes \bar{b})=f(a)\otimes \bar{b}\ ? $$
Discussion\Solution:
 Manos has pointed out the error in my proof, see the EDIT section below for additional discussion
I know that in general tensor products are right exact, and so if we replace monomorphism by epimorphism then then statement always holds. Unfortunately we cannot use exactness here since the tensor product is not in general left exact (if $A/I$ is a flat module, we can use exactness). The reason I am considering the above homomorphism is because it is a $A/I$-linear transformation of $A/I$ -vector spaces, and thus if the result holds then $m\leq n$ since no injective linear transformation sends a vector space of higher dimension to one of lower dimension.
Set $k=A/I$. For $r=m,n$ we have that  $A^r\otimes_A k$ is a $k$-vector space with basis $\{e_i\otimes 1: 1\leq i \leq r\}$. I will denote elements in $k$ by $[a]$ with $a\in A$.
Suppose that $\sum_{i=1}^m[\lambda_i](e_i\otimes 1)\in Ker(f\otimes 1)$. Then:
\begin{align}
(f\otimes 1)\left(\sum_{i=1}^m[\lambda_i](e_i\otimes 1) \right)&=(f\otimes 1)\left(\sum_{i=1}^m(e_i\otimes [\lambda_i]) \right)\\
     &=\sum_{i=1}^m(f(e_i)\otimes [\lambda_i])\enspace (*)\\
\end{align}
For each $i$, $f(e_i)\otimes [\lambda_i]=f(e_i)\otimes \lambda_i\cdot [1]=\lambda_i f(e_i)\otimes 1=f(\lambda_ie_i)\otimes 1$ since $f$ is a homomorphism of $A$-modules (and by how the $A$ module structure on $A/I$ is defined). Then we have:
$$(*)=\sum_{i=1}^m(f(\lambda_ie_i)\otimes 1)=\left(\sum_{i=1}^m f(\lambda_ie_i) \right)\otimes 1 =f\left(\sum_{i=1}^m \lambda_ie_i \right)\otimes 1 $$
Again, this holds since $f$ is a homomorphism of $A$-modules. Since
our initial assumption was that $\sum_{i=1}^m[\lambda_i](e_i\otimes 1)\in Ker(f\otimes 1)$,
$$f\left(\sum_{i=1}^m \lambda_ie_i \right)\otimes 1 =0 $$
From this it would be nice to conclude that each $\lambda_i\in I$ which then implies that $\sum_{i=1}^m[\lambda_i](e_i\otimes 1)=0$. This is the part I am not sure about. Clearly by the injectivity of $f$,
$$f\left(\sum_{i=1}^m \lambda_ie_i \right)=0\iff \lambda_i=0\enspace \forall i $$
So we can omit this case. Thus $f\left(\sum_{i=1}^m \lambda_ie_i \right)=a\neq 0 \in A^n$. The only other time I can see the tensor $a\otimes 1$ being zero is if $a\in I\cdot A^n$, which should then imply that $ \sum_{i=1}^m \lambda_ie_i \in I\cdot A^m\implies \lambda_i\in I$ for all $i$. But I am not sure about this last statement or that this is the only time an element of this $k$-vector space is $0$.
If someone could read through this and help me out that would be great!
EDIT. I am really just trying to come up with a proof that doesn't use Cayley-Hamilton for modules or determinants/linear algebra for modules (we have not discussed either in this class). We have covered basically the first two Chapters of Atiyah and Macdonald, but we skipped the Cayley-Hamilton theorem for modules and have not done any computations involving the matrix theory of modules. As Martin Brandenburg has kindly mentioned, it is possible that this question was given to us with the assumption that Cayley-Hamilton would be covered, which seems to seem very possible. The proofs in
http://www.mathoverflow.net/questions/136, http://www.mathoverflow.net/questions/30860 or http://www.math.stackexchange.com/questions/106786 are very well done and I in particular like the Cayley-Hamilton one, but I was hoping to come up with a proof that only used concepts that have been covered in class, such as the basic properties of tensor products, exact sequences, modules (excluding Cayley-Hamilton and matrix theory) and rings.
Comment: Have you seen Keith Conrad's proof using exterior powers? It is Cor. 5.11 in http://www.math.uconn.edu/~kconrad/blurbs/linmultialg/extmod.pdf. The main ingredient is Thm. 5.10, which is a consequence of Thm. 4.2., which is just the usual basis of the exterior power of a free module. Notice that this is a coordinate-free version of the proof using minors and matrices. In my opinion this is the most elegant proof.
Comment: Tensor $2 : \mathbb{Z} \to \mathbb{Z}$ with $\mathbb{F}_2$, it gets zero. General advice: Think about examples and structural arguments before diving into long element calculations  ...
Comment: It is also possible that your professor / assistant didn't realize before if the exercise is solvable with the methods you have covered so far. Some assistants (not sure if this is the right word in english; I mean the one who helps to create the exercises and works together with the professor) just copy exercises from books.
Comment: can you elaborate on your comment? I am not sure I understand what you are saying. Edit: Nevermind I see it. I don't see where the proof goes wrong though, that is what I am interested in finding out.
Comment: Okay thanks I see now that it just goes wrong in that last step. I am still interested in a proof that does not use Cayley-Hamilton or matrix theory though
Comment: You can find dozens of proofs in the linked question, as well as in the linked MO thread there. And yes, also many which do not use matrices or Cayley Hamilton. For example,
Georges Elencwajg has presented a nice proof reducing to the case of artinian rings and then using the additivity of the length of a module.
Comment: There is only one proof listed among all those proofs that I can see does not use Cayley hamilton or matrix theory that is the proof in Lam- which depends on the notion of stably finite and noetherian rings among other things (this is the closest thing to a proof I have found that is accesible at our point in the class). So I don't really see what these "many" arguments are. I was hoping to construct an alternative proof- I suspected since it was a homework question and that we have not covered these additional things in class that would be possible.
Comment: Then please ask a new question including details what your professor has covered (and what **not**) so far in the lecture. I will certainly try to help then.
Comment: It would also be good if you include specific reasons why none of the proofs in http://mathoverflow.net/questions/136 , http://mathoverflow.net/questions/30860 or http://math.stackexchange.com/questions/106786/ satisfy you (also in order to prevent potential close votes!).
Comment: I think you could be correct Martin that this question was perhaps given in the false pretence that we had covered Cayley-Hamilton. I'll send the professor an email, in the meantime I have taken your advice and added some edits to my OP.
Comment: Yes, I actually really like the argument and Have dealt a bit with Exterior algebras in a Lie theory graduate course I did last year- but only in the case of dealing with vector spaces over fields. Thanks though, it is a nice argument.
Answer: Let me reproduce the proof given by Keith Conrad in his notes on  exterior powers. I will present it in a self-contained way. We really only need the definition of the exterior power $$\Lambda^n M := M^{\otimes n} / \langle m_1 \otimes \dotsc \otimes m_n : m_i = m_j \text{ for some } i \neq j \rangle.$$

Theorem: Let $M,N$ be free $A$-modules, and $\phi : M \to N$ be an injective homomorphism. Then for every $n \geq 0$ also $\Lambda^n \phi : \Lambda^n M \to \Lambda^n N$ is an injective homomorphism.

This implies that $A^n$ does not embed into $A^m$ for $n>m$, since otherwise$^\textbf{1}$ $A \cong \Lambda^n A^n $ embeds into $\Lambda^n A^m = 0$.
Proof of the Theorem. Since free modules are flat, we see by induction that $\phi^{\otimes n} : M^{\otimes n} \to N^{\otimes n}$ is injective. The map $M^n \to M^{\otimes n}$ which maps $(m_1,\dotsc,m_n)$ to $\sum_{\sigma \in \mathfrak{S}_n} \mathrm{sgn}(\sigma) \cdot m_{\sigma(1)} \otimes \dotsc \otimes m_{\sigma(n)}$ is multilinear alternating (check this!), hence lifts to a linear map $\alpha_M : \Lambda^n M \to M^{\otimes n}$. The diagram
$$\begin{array}{c} \Lambda^n M & \xrightarrow{\alpha_M} & M^{\otimes n} \\ \downarrow && \downarrow \\ \Lambda^n N & \xrightarrow{\alpha_N} & N^{\otimes n} \end{array}$$
is commutative. Therefore, it suffices to prove that $\alpha_M$ is injective (because then also $\phi^{\otimes n} \circ \alpha_M = \alpha_N \circ  \Lambda^n \phi$ and therefore $\Lambda^n \phi$ is injective).
For this choose an ordered basis $B$ of $M$. Then clearly $\{b_1 \wedge \dotsc \wedge b_n : b_1 < \dotsc < b_n \text{ in } B\}$ is a generating set$^\textbf{1}$ of $\Lambda^n M$. Let $\omega = \sum_{b_1 < \dotsc <  b_n} \lambda(b_1,\dotsc,b_n) \cdot (b_1 \wedge \dotsc \wedge b_n)$ be an element in the kernel of $\alpha_M$. Then in $M^{\otimes n}$ we have
$$0 = \sum_{\sigma \in \mathfrak{S}_n} \sum_{b_1 < \dotsc <  b_n}  \lambda(b_1,\dotsc,b_n) \cdot \mathrm{sgn}(\sigma) \cdot b_{\sigma(1)} \otimes \dotsc \otimes b_{\sigma(n)}.$$
Since $\{b_{\sigma(1)} \otimes \dotsc \otimes b_{\sigma(n)} : \sigma \in \mathfrak{S}_n, b_1 < \dotsc < b_n \}$ is a subset of the basis $\{b_1 \otimes \dotsc \otimes b_n : b_i \in B\}$  of $M^{\otimes n}$, we conclude that $\lambda(b_1,\dotsc,b_n) \cdot \mathrm{sgn}(\sigma)$ and hence $\lambda(b_1,\dotsc,b_n)$ vanishes for all $b_1<\dotsc<b_n$. Thus, $\omega=0$. $\square$
$^\textbf{1}$ This argument actually shows that $\{b_1 \wedge \dotsc \wedge b_n : b_1 < \dotsc < b_n \text{ in } B\}$ is a basis of $\Lambda^n M$. In particular $A \cong \Lambda^n A^n$ and $0 = \Lambda^n A^m$ for $n>m$.
Comment: Very nicely put- I think this is my favourite argument so far and you have made it more clear.
Comment: Beautiful argument Martin using exterior powers!
Answer: If $f(\sum_{i=1}^m \lambda_i e_i) \otimes 1 =0$, then indeed we must have that $f(\sum_{i=1}^m \lambda_i e_i) \in I A^n$. The error in your proof is that this last relation does not imply that $\lambda_i \in I$.
Answer: One can see the error also in another way. Since $A^n$ is projective, hence flat, we have $\def\Tor{\operatorname{Tor}}\Tor^A_1(A^n,X)=0$ for all modules $X$; similarly, $\Tor^A_1(X,A)=0$. If you tensor by $A/I$ the exact sequence
$$
0\to A^m\to A^n\to C\to 0
$$
where $C$ is the cokernel of your map, you get the exact sequence
$$
0=\Tor^A_1(A^n,A/I)\to\Tor^A_1(C,A/I)\to A^m\otimes A/I\to A^n\otimes A/I
\to C\otimes A/I\to 0
$$
You can compute $\Tor^A_1(C,A/I)$ by tensoring by $C$ the exact sequence $0\to I\to A\to A/I\to 0$, which gives
$$
0=\Tor^A_1(C,A)\to\Tor^A_1(C,A/I)\to C\otimes I\to C\otimes A\to C\otimes A/I\to 0
$$
Now you see that
$$
\Tor^A_1(C,A/I)=\ker(C\otimes I\to CI)
$$
because the epimorphism $C\otimes A\to C\otimes A/I$ is the canonical projection $C\to C/CI$ under cover, so its kernel is isomorphic to $CI$. The morphism $C\otimes I\to CI$ is not necessarily injective.
Comment: Oh, when I started to read the answer, I was hoping to find an alternative proof using Tor functors. :)
Comment: @MartinBrandenburg Only if one is able to find a suitable maximal ideal $I$ such that $\operatorname{Tor}^A_1(C,A/I)=0$. This *might* be possible.


How to scan a List

Question: I'm trying to make a method in java that will use a scanner to read a List String. I want the program to divide the array word by word using the delineator "//s". I already got each array by the names of the people in the text file, I am just trying to divide the array further so that way i can sort them by there information (Ex. if they have f for female I would be able to call that specific part of the array using arrayList.get(index) and sort it by gender that way) Here is my code:
Sorry for being unclear, here is my full code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class Filereader {

public static void replaceSlash(List<String> array) {

    for (int i = 0; i < array.size(); i++)
      {
        if (array.get(i).contains("-"))
        {
            array.set(i, array.get(i).replace("-", "/"));
        }
      }

}

public static void split( List<String> array ) {

    Scanner scanner = new Scanner().useDelimiter("\\s");
    for (int i= 0; i < array.size(); i++) {
        while (scanner.hasNext()) {
            array.set(i, scanner.next());
        }

    }

}

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

    System.out.println("Please type the name of the file you wish to sort: ");
    //get the name of the file
    Scanner scanner = new Scanner(System.in);
    File fileName = new File(scanner.nextLine());

    scanner = new Scanner(fileName).useDelimiter("\\s");
    List<String> annaK = new ArrayList<String>();
    List<String> martinaH = new ArrayList<String>();
    List<String> monicaS = new ArrayList<String>();

    while (scanner.hasNextLine()) {

        annaK.add(scanner.nextLine());
        martinaH.add(scanner.nextLine());
        monicaS.add(scanner.nextLine());

    }

    replaceSlash(annaK);
    replaceSlash(martinaH);
    replaceSlash(monicaS);

    split(annaK);

    System.out.println(annaK);
    System.out.println(martinaH);
    System.out.println(monicaS);

}
}

Comment: Your list should **already be** "divided words"
Comment: Can you give us valid inputs and outputs?  I think you're going about this incorrectly.
Comment: It's very unclear what you're trying to do. Please elaborate.
Answer: You can make one scanner for every string within the list, then loop over that
for (String a : array) {
     Scanner scanner = new Scanner(a).useDelimiter("\\s");
    while (scanner.hasNext()) {
        System.out.println(scanner.next());
    }

}

However, a.split()  or StringTokenizer make more sense than a Scanner here
Besides that, array.set won't work because you're assigning the same i value for multiple words within each individual a value... Which will result in only the last value in the scanned string to be assigned to that index of the list
If you're trying to splits all words within a list into a new list, then you'll actually need to create and append values to a separate list object (don't modify your parameters, and don't have methods with side effects)

How to scan a List


FATAL EXCEPTION: Timer-0 java.lang.NullPointerException

Question: I'm having a timer in the oncreate() like:
final Timer timer1 = new Timer();
timer1.schedule(new TimerTask() {
    public void run() {
        sendSMS();
    }
}, 20000);

The methode sendSMS() is like:
private void sendSMS(){
    float test2;
    test2 = reallocation.getAccuracy(); //-> This is the line where logcat says.... NullPointerException
    ....
}

The logcat says:
05-30 18:32:26.962: W/dalvikvm(741): threadid=9: thread exiting with uncaught exception (group=0x4001d5a0)
05-30 18:32:26.972: E/AndroidRuntime(741): FATAL EXCEPTION: Timer-0
05-30 18:32:26.972: E/AndroidRuntime(741): java.lang.NullPointerException
05-30 18:32:26.972: E/AndroidRuntime(741):  at com.eljoom.df.ActionGPS.sendSMS(ActionGPS.java:280)

Well after searching the net I believe I need a handler for the timer... but I have no clue how to implement it.
Does anybody can put me on the right track?!
Comment: what is ur reallocation data type, have u initialized it?
Comment: I set reallocation as Location: Location reallocation=null;
Comment: Then you just answered your question, as assylias said, reallocation is null. You can't call reallocation.getAccuracy() because ... reallocation is null :).
Answer:
I set reallocation as Location: Location reallocation=null; –
  user1404924 3 mins ago

you set reallocation =null. you can not invoke reallocation's method reallocation.getAccuracy(); because you dont have a instance of the obj yet.
I suggest you to take a look at LocationManager class. You can request location from there with a specific location source
http://developer.android.com/reference/android/location/LocationManager.html
Comment: well I have... but I forgot to do: reallocation= lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); Thanks I'm at the right track!! :D Thanks
Answer: reallocation is uninitialized, so its taking the null value, the default one for object.
Comment: correct that was the problem, I solved it :D ...thanks I close the question.


Ember - is "location: none" the only change needed to make a single-page app?

Question:
   I had been investigating ways to make my app a single-page app, and was considering using StateManager when I was told in one other question I posted in StackOverFlow that the Router approach is the latest Ember style. After lots of attempts, I stumbled upon "location: none" option in Router definition and using that my app's screens are no longer directly accessible. I am still using routes because of Router, but  is it true to assume that my app has indeed become single-page Ember app due to this one change alone? Or what other attributes of single-page do I need to configure to make it truly single-page Ember app?
Thanks,
Paddy
Answer: Let's define what a Single Page Application (SPA) is. In the days when PHP and ASP.NET ruled the internet, web servers would dish out static pages that had static contents. If a user wanted to navigate to a different page, then they would have to ask the server for a completely different page to get the different content.
In the age of Javascript and modern browsers, we don't need our web servers to dish out a different page every time we want to view new content. Content is dynamic, and Javascript allows us to replace parts of a page without the server ever doing anything. That's the key with an SPA, there's no rules and bits of code that defines it. It's a single page that a server gives the user initially, and then the user asks for the content rather than a different page.
So, if your application only serves a single page, and the content is injected or taken away without requesting another page from the server, then you can consider it a SPA. In most projects that use this design you will see that they have only an 'index.html' page, and everything else is javascript files and template files. That's all it means to be a SPA.
Answer: Short answer: it doesn't really matter; using the router to manage client side state will make any Ember app a 'single page app'
Almost by definition an Ember.js app using the router is 'single page' -- like what Deif said, 'single page' basically means there's one initial request for the request (html + js + css), the javascript Ember app is then initialized client side, and navigating around in the Ember app will cause different views to render / states to change / data to be displayed (the server returns data to be displayed by the client-side EmberJS app, instead of content wrapped in HTML), but it's all in the same initial page.
This might be confusing with the location setting. By default, Ember appends a /# to the URI, followed with the route path. You'll notice that when you're navigating around (via route transitions), the fragment after the # will change -- but this is still all on the same page so it counts as "single page app."
So what happens when you click the 'back' button? When each request is returns a new HTML page form the server, it's obvious: clicking 'back' takes your browser to the previous page  by repeating the GET request. But what about in a javascript app? Traditional JS single page apps can 'break' the back button -- you might navigate around, changing the state on the client side, but hitting the back button returns you to the previous website instead of instead of the previous 'page' of your single page app!
Ember gets around the broken back button problem with the router + history location implementation -- setting location offers different behaviors. I think location:none completely disables history -- I will try it later.
See: EmberJS History Location
and What should my Rails routes look like to work with pushState Ember.js routes?  and EmberJS Routing Guide
Comment: I have two questions regarding 'location: history' in Ember.js:  '1. Why do I have to specify "rootURL" in Router - otherwise the first page is not rendered? Worse still, I had to hard-code the app-name to make this work? Am I missing something or is this a drawback of Ember.js history feature? It simply said the / URL is undefined, if I did not specify 'rootURL : /' in Router.reopen?' 2
Comment: Could you provide a jsFiddle / example / code sample of the behavior you're seeing?
Comment: I tried a jsFiddle [here](http://jsfiddle.net/tv_sathish/A8Qwb/10/), but it is not giving me any output? I am new to JSFiddle, not sure what mistake I am making, also I have not pasted my app, as is, just put the parts resembling my code and relevant to my issue at hand, please help. Please note that in the jsFiddle, I have not set rootURL to show the issue.
Comment: https://github.com/emberjs/ember.js/blob/master/CONTRIBUTING.md has some good instructions for setting up a JSfiddle with ember -- give that a shot? (See the "Reporting a bug" section")
Comment: Please refer [here](http://jsbin.com/ucanam/37/edit) for a sample, the rootURL feature is forcing to hard code the app URL and secondly every transition is a separate URL that is not bookmark-able as it results in a 404 page.
Comment: The reason Ember needs the rootURL attribute is because you're using `location: history` and JSBin is serving the result in an iframe with a root url Ember isn't expecting. For instance, I had to change `rootURL` in your sample to `'/_display/'` to get it to work in [jsFiddle](http://jsfiddle.net/GkMAP/1/). I don't have much experience with `location: history` beyond that, so I can't say how this corresponds to its behavior in a production environment.
Answer: Sherwin Yu and Deif are both correct. To add to what's already been stated, the reason why the default implementation of location (namely HashLocation) maintains your application as a SPA is due to a particular property of fragment identifiers, which is well summed up in section 4 of this blog post. (Ironically, that post doesn't utilize fragment ids, so I can't link you directly to the section in question.)
Take a look around this jsFiddle. You might notice one of the major advantages of using the hash implementation:
third template

Bookmark-able links directly to specific routes in your application work without any fuss.
I think what may be going on here is this: a lot of SPA frameworks out there don't offer anything like Ember's router location. With them, once you load the page, the url never changes. Thus, when Ember starts playing with the browser history and you see the url changing, it's natural to question whether this thing you've built is still an SPA. (It threw me off at first, too!) Rest assured it is an SPA. If it makes you more comfortable, use location: 'none' to keep that single page aesthetic; Ember won't care, but your users might. ;)


Construct an isosceles based tetrahedron

Question: I've searched the forum and didn't find any answer to my question, I need to construct a Tetrahedron with an isosceles triangle for the base.
$AB = AC = 10.5$ cm
$BC = 17.5$ cm
and I need the height of the tetrahedron from its gravity point to be $4.5$ cm.
Doing some basic Pythagore from the BC segment I found the length of the two projected segments to be $10.26$ cm but I'm not even sure that's right.
Since I can't find a rectangular triangle with two known lengths from $AB $ or $AC$ I don't know how to get the other length.
Thank you :)
Comment: What exactly do you mean by "the height of the tetrahedron from it's gravity point"? Do you mean that the the projection of the forth vertex onto the base plane is the [centroid](https://en.wikipedia.org/wiki/Centroid) of $\triangle ABC$? What values do you need for the construction of the tetrahedron?
Comment: Oh yes sorry used the wrong word, I meant the centroid. What do you mean by what values do I need ? The one I gave are insufficient ?
Comment: Quite opposite. I think that the given values are completely sufficient for constructing the tetrahedron. But you apparently have a different opinion. The question is: what additional parameters do *you* need for construction of the tetrahedron? Where did you stuck?
Answer: The centroid $C$ always lies on $1/3$ of the medians, you can read about it on Wikipedia. Since your triangle is isosceles, the median that connects $A$ to $BC$ intersects $BC$ exactly in the middle $M$, which results in right-angled triangles $AMB$, $AMC$. I am not sure what measurements you are searching for, but here are some formulas. Let's call the top point $H$.
\begin{align}
\overline{BM} &= \frac{1}{2}\overline{BC} \\
\overline{AM} ^2 &= \overline{AB}^2+\overline{BM}^2 \\
\overline{AC} &= \frac{2}{3} \overline{AM} \\
\overline{CM} &= \frac{1}{3} \overline{AM} \\
\overline{BC}^2 &= \overline{BM}^2 + \overline{CM}^2 \\
\overline{AH}^2 &= \overline{AC}^2 + \overline{CH}^2 \\
\overline{BH}^2 &= \overline{BC}^2 + \overline{CH}^2
\end{align}


How to create a custom intent and calling helper intent using Actionsdk?

Question: Please find my action.json file content
{
  "actions": [
    {
      "description": "Default Welcome Intent",
      "name": "MAIN",
      "fulfillment": {
        "conversationName": "testapp"
      },
      "intent": {
        "name": "actions.intent.MAIN",
        "trigger": {
          "queryPatterns": [
            "talk to Developer"
          ]
        }
      }
    },
    {
      "name": "BUY",
      "intent": {
        "name": "com.example.sekai.BUY",
        "parameters": [{
          "name": "color",
          "type": "SchemaOrg_Color"
        }],
        "trigger": {
          "queryPatterns": [
            "find some $SchemaOrg_Color:color sneakers",
            "buy some blue suede shoes",
            "get running shoes"
          ]
        }
        },
        "fulfillment": {
          "conversationName": "testapp"
      }
    }
  ],
  "conversations": {
    "testapp": {
      "name": "testapp",
      "url": "https://us-central1-samplejs2-id.cloudfunctions.net/testApp",
      "fulfillmentApiVersion": 2,
      "inDialogIntents": [
        {
          "name": "actions.intent.CANCEL"
        }
      ]
    }
  },
  "locale": "en"
}

Please find my index.js file content
'use strict';
const functions = require('firebase-functions');
const admin     = require('firebase-admin');
const {actionssdk} = require('actions-on-google');
const app = actionssdk({debug: true});

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
app.intent('com.example.sekai.BUY', (conv, input) => {
  console.log("Inside custom intent");
    conv.ask('<speak>Hi! <break time="1"/> ' +
   ' The color you typed is' +
   `<say-as >${input}</say-as>.</speak>`);
 });
 app.intent('actions.intent.MAIN', (conv, input) => {
    conv.ask('<speak>Hi! <break time="1"/> ' +
    'You are entering into samplejs application by typing ' +
     `<say-as >${input}</say-as>.</speak>`);
});
app.intent('actions.intent.CANCEL', (conv) => {
    conv.close(`Okay, let's try this again later.`);
  });
app.intent('actions.intent.TEXT', (conv, input) => {
    if (input === 'bye') {
    return conv.close('Goodbye!');
  }
   conv.ask('<speak>You said, ' +
    `<say-as >${input}</say-as>.</speak>`);
});
//exports.app  = app;
console.log("global----------->",global);
 exports.testApp = functions.https.onRequest(app);

Whenever I call the custom intent "BUY" using any color, instead of calling my custom intent it is calling "intent.Text". How to fix this issue?
While creating cloud function I have select JavaScript option.
For creating a custom intent, is these much updates is need in action.json?
Is there any option for creating custom intent?
How to call this helper content in the js file?
app.intent('ask_for_place', (conv) => {

     conv.ask(new Place(options));

});

Answer: Custom intents are only triggered as welcome intents for "deep linking". Once the conversation has started, all conversational intents will be reported as TEXT.
So for the intent com.example.sekai.BUY you defined in your actions.json file, and if your Action was named something like "super store", then the following invocation would trigger that intent:

Hey Google, ask super store to find some blue sneakers

but once the conversation had started, asking "find some blue sneakers" would trigger a TEXT intent.
The Actions SDK with actions.json is primarily intended for use by systems that provide the natural language processing and just want to get the text after it has been converted from speech.
If you want more sophisticated natural language processing, where each phrase in the conversation will trigger a user-defined Intent, take a look at Dialogflow.
Comment: These are two different questions you were asking - go ahead and ask another StackOverflow question to address this one.
Comment: how to use or call the intent      "app.intent('ask_for_place', (conv) => {

     conv.ask(new Place(options));"         in js


Integral approximation

Question: I have the following integral
$$I=-\frac{1}{\varepsilon^{4}}\int_{0}^{\infty}dx\left(  \sqrt{x^{4}%
+2\varepsilon^{4}}-x^{2}\right)  e^{-2x}$$
where $\varepsilon\ll1$. This integral is solvable exactly in terms of MeijerG function, and is part of a bigger integral whose integrand has been broken into sums (one of those being the one I'm presenting here).
Because $\varepsilon$ is very small, I'm interested in the first powers of the solution. Because it is summed with other integrals, the final solution, in power series of $\varepsilon$, has its leading term equal to $-\frac{4\sqrt{2}}{9}\varepsilon^2$. This term comes from $I$, and only from the integration interval $\left[0,1\right]$. I know this because I analyzed similar situations and they all come from this "part" of the bigger integral.
So, instead of solving the whole thing (several integrals) exactly and then expanding the solution in powers of $\varepsilon$ to obtain the leading term, I want to expand the integrand of the integral from which the leading term comes (i.e. in this case $I$), and solve only the term proportional to $\varepsilon^2$. Reducing the interval from $\left[0,\infty\right]$ to $\left[0,1\right]$ would make it even easier to find the proper expansion of the integrand and solving it.
The thing is, if I expand the integrand  around $x=0$ I get
$$-\frac{1}{\varepsilon^{4}}\left(  \sqrt{x^{4}%
+2\varepsilon^{4}}-x^{2}\right)\approx-\frac{\sqrt{2}}{\varepsilon^2}+\frac{x^2}{\varepsilon^4}-...,$$
and increasing powers of $\frac{1}{\varepsilon}$, and thus don't recognize the $\varepsilon^2$ term. If I, however, expand the same integrand around $\varepsilon=0$ I get,
$$-\frac{1}{\varepsilon^{4}}\left(  \sqrt{x^{4}%
+2\varepsilon^{4}}-x^{2}\right)\approx-\frac{1}{x^2}+\frac{\varepsilon^4}{2x^6}-\frac{\varepsilon^8}{2x^{10}}+...,$$
where not only I don't get any $\varepsilon^2$ term but also get divergent integrals at the lower limit $x=0$.
I guess that, in the first expansion, I lose the information with which the limit $\varepsilon\rightarrow0$ is well defined, and, in the second expansion, the information in which the limit $x\rightarrow0$ is well defined.
Which aspect of the integrand, and their possible expansion, is causing this behavior? And what would be a better approach for getting the $\varepsilon^2$ term without solving the whole integral?
Thanks
Answer: The analysis here is a bit loose, but time is not on my side today.
Consider the following function
$$I\left( a \right)=-\frac{1}{{{a}^{4}}}\int\limits_{0}^{\infty }{\left( \sqrt{{{x}^{4}}+2{{a}^{4}}}-{{x}^{2}} \right){{e}^{-2x}}dx}$$
Which we can write as
$$I=-\frac{1}{{{a}^{2}}}\int\limits_{0}^{\infty }{\left( \sqrt{\frac{{{x}^{4}}}{{{a}^{4}}}+2}-\frac{{{x}^{2}}}{{{a}^{2}}} \right){{e}^{-2x}}dx}$$
Now  use $u=x/a\Rightarrow du=\frac{1}{a}dx$
$$I=-\frac{1}{a}\int\limits_{0}^{\infty }{\left( \sqrt{{{u}^{4}}+2}-{{u}^{2}} \right){{e}^{-2ua}}du}$$
Observe
$$\int\limits_{0}^{\infty }{\left( \sqrt{{{u}^{4}}+2}-{{u}^{2}} \right)du}=\beta \simeq 2.07878...$$
This integral apparently has an expression in terms of elliptic functions (which I suppose isn't too hard to guess).  Mathematica yields the following exact result
$$\int\limits_{0}^{\infty }{\left( \sqrt{{{u}^{4}}+2}-{{u}^{2}} \right)du}=-\frac{2}{3}\left( -2 \right){}^{3/4}K\left( 2 \right)+\frac{{{\left( -2 \right)}^{1/4}}}{3\sqrt{\pi }}\Gamma {{\left( \tfrac{1}{4} \right)}^{2}}$$
Where K is the complete elliptic integral of the first kind and $\Gamma $ is the gamma function.   Observe that $\left| I\left( a \right) \right|\le \frac{\beta }{a}$, and for very small a, the 1/a term dominates, hence $I\simeq -\frac{\beta }{a}$.
It's actually not quite as simple as that.  For note that if we expand the exponential then we obtain
$$I=-\int\limits_{0}^{\infty }{\left( \sqrt{{{u}^{4}}+2}-{{u}^{2}} \right)\left( \frac{1}{a}-2u+O\left( a \right) \right)du}$$
The $O\left( a \right)$terms disappear as $a\to 0$ and so we are left with something that behaves like 1/a, and something that becomes infinite.  Note however that
$$\left( \sqrt{{{u}^{4}}+2}-{{u}^{2}} \right)u=\frac{1}{u}+O\left( {{u}^{-2}} \right)\Rightarrow \int{\left( \sqrt{{{u}^{4}}+2}-{{u}^{2}} \right)u\simeq \ln \left( u \right)+O\left( 1 \right)}$$
for large u.  Hence we have two terms $I\simeq -\frac{\beta }{a}+\ln \left( b \right)+O\left( 1 \right)$, where b is large and a is small.  We may, however justify all this a tad more by first partitioning the integral into two parts, namely
$$I=-\int\limits_{0}^{1/a}{{}}-\int\limits_{1/a}^{\infty }{{}}$$
Doing this then essentially yields for small a
$$I\simeq -\frac{\beta }{a}-\ln \left( a \right)$$ plus terms that are $O\left( 1 \right)$.
If we numerically evaluate the integral (blue curve) and compare it to the above approximation (yellow curve) for small a, then we have the following graphs
Answer: As you wrote, assuming $a>0$, $$J=\int_{0}^{\infty}\left(  \sqrt{x^{4}%
+2a^{4}}-x^{2}\right)  e^{-2x}\,dx$$ has the nice expression (thanks to a CAS)
$$J=-\frac{1}{4}-\frac{2\ 2^{3/4}}{\pi ^2 a^3}\,G_{1,5}^{5,1}\left(\frac{a^4}{8}|
\begin{array}{c}
 \frac{9}{4} \\
 \frac{3}{4},\frac{3}{2},\frac{7}{4},2,\frac{9}{4}
\end{array}
\right)$$ Developed as a series (thanks to a CAS), this gives
$$J=-\frac{2^{3/4} \pi ^{3/2} }{\Gamma \left(-\frac{1}{4}\right) \Gamma
   \left(\frac{7}{4}\right)}\,a^3+\frac{1}{2}  (4 \log (a)+4 \gamma -5+\log
   (8))\,a^4-\frac{\sqrt[4]{2} \pi ^{3/2} }{\Gamma \left(\frac{1}{4}\right) \Gamma
   \left(\frac{9}{4}\right)}\,a^5+O\left(a^6\right)$$ and then $$I=-\frac J {a^4}= \left(\frac{5}{2}-2 \gamma -\frac{3 \log (2)}{2}\right)-2\log(a)+\frac{2^{3/4} \pi ^{3/2}}{ \Gamma \left(-\frac{1}{4}\right) \Gamma
   \left(\frac{7}{4}\right)}\frac 1a+\frac{\sqrt[4]{2} \pi ^{3/2} }{\Gamma \left(\frac{1}{4}\right) \Gamma
   \left(\frac{9}{4}\right)}a$$ For a few values of $a$, we get the following values for $I=-a^{-4}\, J$
$$\left(
\begin{array}{ccc}
 a & \text{exact} & \text{approximation}\\
  0.100 & -15.7215 & -15.7156 \\
 0.095 & -16.7205 & -16.7151 \\
 0.090 & -17.8356 & -17.8307 \\
 0.085 & -19.0875 & -19.0832 \\
 0.080 & -20.5023 & -20.4985 \\
 0.075 & -22.1132 & -22.1098 \\
 0.070 & -23.9626 & -23.9596 \\
 0.065 & -26.1064 & -26.1039 \\
 0.060 & -28.6191 & -28.6169 \\
 0.055 & -31.6025 & -31.6006 \\
 0.050 & -35.1992 & -35.1977 \\
 0.045 & -39.6158 & -39.6145 \\
 0.040 & -45.1624 & -45.1614 \\
 0.035 & -52.3274 & -52.3266 \\
 0.030 & -61.9259 & -61.9253 \\
 0.025 & -75.4277 & -75.4273 \\
 0.020 & -95.7771 & -95.7768 \\
 0.015 & -129.856 & -129.856 \\
 0.010 & -198.346 & -198.346
\end{array}
\right)$$

Integral approximation


Form API: How to add arbitrary render element after specific field?

Question: I've got an input field in an entity form which needs quite a bit of extra documentation. This documentation is long and needs computed, contextual information, so a simple field description or #field_suffix just doesn't do it. I also want to keep the ability to move fields around in field UI. I'm trying to create a form_alter hook to inject a render element with my docs right after that field.
I already have a working prototype:
function MYMODULE_form_ENITY_FORMMODE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $fieldToEnhance = 'field_foo';
  if (!isset($form[$fieldToEnhance])) {
    return;
  }
  $computedDocumentationVariables = mymodule_get_infos();
  $renderElementToAppend[$fieldToEnhance . '_append'] = [
    '#type' => 'inline_template',
    '#template' => '
This is a very shortened and simplified placeholder.
',
    '#context' => $computedDocumentationVariables,
    '#parents' => $form[$fieldToEnhance]['#parents'] ?? [],
    '#weight' => isset($form[$fieldToEnhance]['#weight']) ? $form[$fieldToEnhance]['#weight'] + 1 : NULL,
  ];
  $positionOfField = array_search($fieldToEnhance, array_keys($form));
  // inject the render element right after the field in the form array
  $form = array_merge(
    array_merge(
      array_slice($form, 0, $positionOfField+1),
      $renderElementToAppend
    ),
    $form
  );
}

This works as exptected for a very plain form.
But as soon as I move my field inside a container from Field group module, the positioning doesn't work as expected. When viewing it in a debugger, I can see that my custom render element is at the correct position inside the $form array. But on screen it is not rendered at the correct position. (My documentation render element is on root level. I want it inside the container, right after the field.)
How do I make my hook aware of potential nesting containers from Field Group module?
Comment: *a simple field description doesn't do it* ... I don't think there is a limitation on what you can put in `#description`. This variable is printed in the field wrapper template below the field. You can change the position in the template, but I wouldn't change the form array structure if you want the form to work with other modules.
Comment: I can't inject a render array neither in field descriptions nor the suffix. My desired solution is a render array containing multiple inline templates inside collapsible details elements.
Answer: #suffix and #description are very different. The first one is a Render API standard property common to all render elements and is handled by the Renderer service. The second one is handled as a normal template variable with no restrictions on the number of render elements or nesting levels. You only have to ensure it is printed the way you set it. Check Twig Debug to see which template is used. The standard form-element.html.twig is rendering a subkey content. Some input elements use their own wrapper template/preprocessing and don't have this subkey. You can also define a custom wrapper template with your own set of variables.
Comment: Still, #suffix and #description are handled very differently. Only the second one is subjected to preprocessing and is printed as a template variable. I've tried to make the wording more clear.
Comment: I was overthinking this. In my initial tests I simply was on the wrong "level" in the render array, "going deeper" in the render array of the field solved all my issues.
Comment: `#description` is a form element property too, described in [`FormElement`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21FormElement.php/class/FormElement/9) (which does not list the properties in common with other render elements, listed in [`RenderElement`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21RenderElement.php/class/RenderElement/9)). It is also used by most of the form elements.
Comment: [form-element.html.twig](https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21form-element.html.twig/9) gets both `suffix` and `description`. The difference is that the value of `#description` is available as `description.content` while the content of `#suffix` is available as `suffix`. Indeed, they are handled differently, but they are both available to preprocessing and to the template file.
Comment: No, the content of `#field_suffix` is available as `suffix`. Then this is a normal template variable and can print nested render arrays. Strange they use the name of the reserved Render API property `#suffix`, which by the way still works the same as in any other template and has the restrictions I've described.


When should the "container" form element be used?

Question: The System module defines the container form element, but that form element is not documented in the Form API Reference.
When should that form element be used?
Answer: It looks like it can be used when you want to wrap a part of the form in a div, for example to be able to add some classes to it.
Some examples from core are the following:

field_default_form()
// Also aid in theming of field widgets by rendering a classified container.
$addition[$field_name] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array(
     'field-type-' . drupal_html_class($field['type']),
     'field-name-' . drupal_html_class($field_name),
     'field-widget-' . drupal_html_class($instance['widget']['type']),
    ),
  ),
  '#weight' => $instance['widget']['weight'],
);

node_filter_form()
$form['filters']['status'] = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('clearfix')),
  '#prefix' => ($i ? '
' . t('and where') . '
' : ''),
);
$form['filters']['status']['filters'] = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('filters')),
);

search_form()
$form['basic'] = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('container-inline')),
);

Forms in Drupal 6 often used #prefix and #suffix on the first/last element to do this; this is a lot better because it is easier to add additional items or move them around.
I could use this in a few places in my own contributed modules, actually. ;)
Comment: No, it does not. Only when explicitly specified as #tree => TRUE, the default is FALSE.
Comment: container type also implies a nesting level in form_state's input / values.
Comment: Ok, sorry. By casuality I was just adding a container in a field widget form and observed the nesting in $form_state. After your comment, I realized $element['tree'] comes as true. Thanks :)
Comment: Ah, yes, field widgets are always within a language and delta key, within that, they might be repeated, so #tree => TRUE is forced on them, yes.
Answer: In D6, there were often times when you would need to add a
 around a FAPI element (for example with #ahah / #ajax), so container is a more consistent solution in regards to the Forms API to this common pattern than adding a wrapper div using #prefix/#suffix.


Which statistical test to use for my data

Question: My question is whether a low calorie diet with prescribed exercise is more effective than a low calorie diet without prescribed exercise for weight loss
study design: randomised study of 2 parallel intervention groups with 30 participants. intervention required both groups to only eat a low calorie diet provided to them for 12 weeks. The exercise diet group were prescribed 30 minutes of exercise. Assessments were performed at baseline, 6 weeks, 12 weeks and 24 weeks (follow up). primary outcome measure is BMI.
What statistical test should I use in SPSS and do i compare the baseline with the rest of the data or do i consider the means of all of them?
Answer: In the absence of a control group, your inference is limited by all forms of Hawthorne effect. If the design is balanced, consider fitting a mixed model with random effects for participant and time. Transform follow-up data to a wide format, as baseline values do not randomly vary by experimental design, and either adjust for baseline BMI as a covariate or as an offset (equivalent to t-test for paired differences but with multiple outcomes).


Is there a concise way to notate 'There are exactly 482 x, such that Px...' in logical notation?

Question: My prof has taught us that we can express the proposition $⟦$there are exactly two entities characterized by $P$$⟧$ thus:

That proposition looks verbose, despite the fact that it references just two entities. It seems impractical to use such a formula to express a proposition that references a great number of entities (e.g. 482). Is there a more concise way of conveying the number of entities that a proposition references?
Comment: If you have access to the expressive resources of set theory, you can write "The cardinality of the set of all muppets is $2$," or more formally "$|\mathrm{Muppets}|=2$.
Comment: Your sentence forces the existence of precisely one object satisfying both $P$ and $Q$. Using different variable symbols does not make their interpretations different. The "professor's" version is surely a misquotation. Even after a fair bit of wine I would not write $\forall x_1\dots\exists x_1$.
Comment: For a concise version, we use everyday speech.
Comment: You could shorten it a little by saying $\exists x_i, \forall i \in$ {$1,2,3$}
Comment: There is no concise formal version. By the way, the version you have with #\exists!$ is wrong.
Comment: @AndréNicolas Thank you. It makes sense to me, but we haven't been taught how to use $\exists!$. Where did I go wrong?
Comment: @AndréNicolas Yes, I misquoted him. I've inset a clipping of one of his slides in the question.
Comment: @AndréNicolas but can you use ordinary speech with a proof system (e.g. natural deduction, truth trees)?
Answer: Let $S_P$ be the set of individuals characterized by $P$ and $S_Q$ the set of individuals characterized by $Q$, $\mid S_P \cap S_Q\mid=482$.
Where $\mid S \mid$ is the cardinality of the set $S$.
You can possibly define these sets as $S_P = \{x \mid P(x)\}$.
Comment: I have downvoted this answer: introducting set-theoretic notation only obscures issues of the first-order logic alone. The third sentence, writing a set as the extension of the concept $P$ (as logicians traditionally phrase it) is well-motivated, but the whole history of set theory is the result of that notation not being any good...
Answer: $$\exists x_1, \ldots, x_{482}\left(\bigwedge_{i \neq j \leq 482}x_i \neq x_j \wedge \forall y \left(\phi(y) \leftrightarrow (\bigvee_{i \leq 482} y = x_i)\right)\right)$$
Or, since it's not in doubt that there is such a first-order formula, create some ad-hoc shorthand and write
"$\exists^{482} x\, \phi(x)$ where $\exists^{482}x$ is a quantifier denoting the existence of exactly 482 distinct such $x$", which is kinder to your reader.
Comment: Oh look, Carl's answer says this superscripted-quantifier notation is almost . One point to note is that both $\exists!$ and $\exists\text{-exactly-}n$ quantifiers conceal a universal assertion within them: they are $\Sigma_1$ formulas, not pure existential quantifiers.
Comment: What is a $\Sigma_1$ quantifier?
Answer: The standard abbreviation for "there are at least $482$ objects $x$ satisfying $\phi(x)$" is
$$
(\exists^{482} x)\phi(x)
$$
The extra quantifiers of the form $(\exists^{n} x)$ can either be defined directly in the metatheory, or viewed as abbreviations for longer formulas.
So you could write
$$
(\exists^{482} x)\phi(x) \land \lnot(\exists^{483} x)\phi(x).
$$
There is also a notation $(\exists ! x)\phi(x)$, which means there is a unique $x$ satisfying $\phi(x)$. I have never seen the notation $(\exists !^{482} x)\phi(x)$, but you could certainly define it in your prose.
Although I have seen this notation less, an SEP article suggests
$$
(\exists_{\geq 482} x)\phi(x)
$$
and
$$
(\exists_{=482} x)\phi(x)$$


Populating a function argument with user input in Python

Question: I'm trying to create a piece of code that performs simple subtraction and prints a message based on the user's input, but I haven't been able to figure out how to get the user input to properly serve as the functions argument.
I keep getting the following error, even though I've included int along with the user input:

TypeError: '>=' not supported between instances of > 'NoneType' and 'int'

Do you have any clue what I'm missing?
The exact code I'm working on shown below:
def withdraw_money(current_balance, amount):
    if (current_balance >= amount):
        current_balance = current_balance - amount
        return current_balance

balance = withdraw_money(int(input("How much money do you have")), int(input("How much do your groceries cost")))

if (balance >= 0):
    print("You're good")
else:
    print("You're broke")

Answer: You are missing a return in else
so whenever you are broke your function is returning nothing and you are comparing nothing (None)
def withdraw_money(current_balance, amount):
    if (current_balance >= amount):
        current_balance = current_balance - amount
        return current_balance
    else: # need to return something if the above condition is False
        return current_balance - amount

balance = withdraw_money(int(input("How much money do you have")), int(input("How much do your groceries cost")))

if (balance >= 0):
    print("You're good")
else:
    print("You're broke")

PS:
if you are checking whether the person is broke or not outside the function why are you checking the difference inside the function? (Your fnc can just return the difference and then outside you can check if it's -ive or +ive)
Comment: That fixed it. Thanks, Kuldeep for providing the answer and explaining the reasoning behind also!
Comment: To answer your PS, I'm very new to programming, so I am just testing out how to use the return command.
Comment: PS, I will definitely mark it as the answer in just a moment. For whatever reason, StackOverflow is making me wait 10 minutes before I can mark it as the answer.


Projection maps non-zero element to non-zero element?

Question: The following screenshot is taken from the book 'Topics in Banach Space Theory'.

In the third line of the proof above, I don't understand why $0 \neq y \in Y \Rightarrow S_N(y)\neq0$.
Can't we have the first $N$ entries of the sequence $y$ are zero while the remaining entries can be non-zero. In this case, we have $y \neq 0$ but $S_N(y)=0$ right? Please correct me if I am wrong.
Comment: But then a scalar multiple of that $y$ would be an element of $Y$ with $\lVert y_N\Vert = 1$ and $e_k^{\ast}(y_N) = 0$ for $1 \leqslant k \leqslant N$. The assumption is that such an $y_N$ doesn't exist.
Comment: Oh yeah I forgot the assumption.
Answer: The if not refers to the negation of the statement
$\forall\, n\in\mathbb N\;\exists y_n\in Y, \|y_n\|=1 \text{ and } e_k^*(y_n)=0$ for all $k\le n$.
Hence there is $N$ such that for all $y=\sum_na_ne_n\in Y$ (with $\|y\|=1$) there is $k\in\lbrace1,\ldots,N\rbrace$ such that $a_k=e_k^*(y)\neq 0$.


Auto fill billing information in cc avenue payment

Question: I am using Commerce Cc Avenue as a payment gateway for my eCommerce site. During checkout step user enter his billing information. In the next step it verifies his/her order and redirects to Cc avenue payment gateway, there it asks user billing address again. I want to auto fill the user billing address which he/she enters in previous step. Is that possible to do?
Answer: Finally found the answer with help of this issue queue https://www.drupal.org/node/2310505
In commerce_ccavenue.module added few lines inside commerce_ccavenue_redirect_form($form, &$form_state, $order, $payment_method)
<code>$billing_address = $wrapper->commerce_customer_billing->commerce_customer_address->value();
  $order_data = array(
    'merchant_id' => $payment_method['settings']['merchant_id'],
    'amount' => $wrapper->commerce_order_total->amount->value() / 100,
    'order_id' => $order->order_id,
    'cancel_url' => url('checkout/' . $order->order_id . '/payment/back/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),
    'redirect_url' => url('checkout/' . $order->order_id . '/payment/return/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),
    'working_key' => $payment_method['settings']['working_key'],
    'access_code' => $payment_method['settings']['access_code'],
    'language' => 'EN',
    'currency' => $currency_code,
    'billing_name' => $billing_address['name_line'],
    'billing_address' => $billing_address['thoroughfare']. ' ' . $billing_address['premise'] . ' ' . $billing_address['sub_premise'],
    'billing_zip' => $billing_address['postal_code'],
    'billing_city' => $billing_address['locality'],
    'billing_state' => $billing_address['administrative_area'],
    'billing_country' => 'India',
  );
</code>
These lines are missing inside commerce_ccavenue_redirect_form($form, &$form_state, $order, $payment_method). Works fine after adding those lines.


Não consigo deletar a imagem correta passando id por jQuery via Modal

Question: Tenho um sistema que você clica na imagem e ele abre ela maior via modal, embaixo tem um botão de Deletar, se clicar em Deletar, abre outro modal perguntando se você tem certeza que quer deletar essa imagem, só confirmando o segundo modal que ela é deletada.
Porém está sempre deletando a primeira foto que mandei para a galeria, não estou conseguindo passar o ID correto via o modal.
Estou usando Django para o sistema e Pyhton.
Agradeceria uma ajuda.
modalgallery.js
    $(function() {
        $('.pop').on('click', function() {
            $('.imagepreview').attr('src', $(this).attr('data-img-url'));
            $('#imagemodal').modal('show');
        });
    });

modalconfirmedelete.js
    $(function() {
        $('.pop2').on('click', function() {

            $('#delete').modal('show');

        });
    });

views.py
def delete(request, id):
    photos = Photo.objects.get(id=id)
    photos.delete()
    return redirect('sistema_perfil')

def perfil(request):
    photos_list =  Photo.objects.filter(user=request.user.pk)
    usuario = Usuario.objects.all()
    form = UsuarioForm()
    data = {'usuario': usuario, 'form': form, 'photos': photos_list}
    return render(request, 'perfil.html', data)

perfil.html
     {% for photo in photos %}

                          <button type="button" class="close" data-dismiss="modal">×X</button>

                          Deletar

                          <button type="button" class="close" data-dismiss="modal">×X</button>

Tem certeza que deseja deletar essa foto:

                                                   Deletar

        {% endfor %}

Comment: Vc está repetindo id's no laço. Id's devem ser únicas na página.
Comment: onde amigo? acho que nao entendi
Comment: Esse `id="imagemodal"` e esse `id="delete"`
Comment: coloquei abos para imagemodal, mas dai ele nao carrega nenhum dos dois
Comment: Acho que vc não entendeu rs... não pode repetir o mesmo id na página. Um id deve ser único. Por exemplo, vc não pode ter duas divs com o mesmo id. É como um CPF, cada pessoa tem um diferente.
Comment: acho que vou desistir, tirei e dexei só o primeiro modal, e mesmo assim sem confirmar para deleter só clicando em Deletar ele deleta a primeira imagem e nao a que selecionei
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/92515/discussion-between-sam-and-mauricio-kalfelz).
Answer: É porque está repetindo as id's e seu código irá pegar sempre a primeira. Uma id deve ser única na página.
Você pode resolver isso convertendo as id's em classes:
<div class="modal fade imagemodal" tabindex="-1"...

e
<div class="modal fade delete" tabindex="-1"...

E alterar os seletores no jQuery para abrir as modais corretas utilizando as classes:
$(function() {
   $('.pop').on('click', function() {
      $('.imagepreview').attr('src', $(this).attr('data-img-url'));
      $(this).next('.imagemodal').modal('show');
   });
});

$(function() {
   $('.pop2').on('click', function() {
      $(this).closest(".imagemodal").next(".delete").modal('show');
   });
});

Comment: não tenho nem como agradecer você, perfeito, fora a aula que me deu via chat, tu é o cara


Fiz 3 slidesshow mas entre os slidesshows esta a haver um espaço

Question: O meu código:

Comment: `class="mySlides1 w3-animate-fading""` - Tem uma aspa a mais aqui.
Comment: Já ia começar a tentar simular o seu código, mas sem o link das figuras, fica difícil.
Comment: Coloca todo o HTML, inclusive o CSS e se está usando alguma biblioteca ou plugin
Comment: hmmm eu  nao  usei  css nesta parte do  slideshow
Answer: Lucas o que acontece é que você esta usando as classes do W3CSS provavelmente está importando o CDN no  da sua pagina.
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

Aqui tem a documentação de como usar o Grid do w3.css:
https://www.w3schools.com/w3css/w3css_grid.asp
E aqui a home do projeto: https://www.w3schools.com/w3css/default.asp
O seu código tem alguma coisa que não são boas práticas, seria bom que leia a documentação dos links acima.
Ajustei o código apenas para te mostrar os problemas.
Onde está
 deveria estar <div class="w3-col s4"> por exemplo. Mas usar o SlideShow dentro do Grid não é o ideal!
Segue o modelo do código que fiz para te ajudar. Coloquei uma borda vermelha para vc ver o tamanho das células do Grid. *A última Célula do Grid eu deixei errado para demostrar como fica quando usa a Classe errada...*
Clique no botão Executar para ver o código funcionando!

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">


HTML showing as text

Question: i am using below code to show content in admincontroller of my module but $filelink is show as text instead of html
i tried to show href link in $filelink but it renders and text content like below:
Resume

but i want it as
Resume
  function content() {
    $url = Url::fromRoute('bd_career_add');
    //$add_link = ;
    $add_link = '
' . \Drupal::l(t('New Submission'), $url) . '
';

    $text = array(
      '#type' => 'markup',
      '#markup' => $add_link,
    );

    // Table header.
    $header = array(
      'id' => t('Id'),
      'name' => t('Name'),
      'number' => t('Number'),
      'email' => t('Email'),
      'email' => t('Resume'),
      'operations' => t('Delete'),
    );
    $rows = array();
    foreach (BdCareerStorage::getAll() as $id => $content) {
      // Row with attributes on the row and some of its cells.
      $editUrl = Url::fromRoute('bd_career_edit', array('id' => $id));
      $deleteUrl = Url::fromRoute('bd_career_delete', array('id' => $id));

    $file = \Drupal\file\Entity\File::load($content->resumefid);
    $filelink ="getFileUri())."' target='_blank'>Resume";

      $rows[] = array(
        'data' => array(
          \Drupal::l($id, $editUrl),
          $content->name.' '.$content->lname,$content->number,$filelink,
          \Drupal::l('Delete', $deleteUrl)
        ),
      );
    }
    $table = array(
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#attributes' => array(
        'id' => 'bd-career-table',
      ),
    );
    //return $add_link . ($table);
    return array(
      $text,
      $table,
    );
  }

Comment: try this : $row[] = array( 'data' => array(    '#links' => $links), );
Comment: whats the output
Comment: i used '#links' => $filelinkin place of $filelink it show blank value
Answer: solved it using below code:
$file = \Drupal\file\Entity\File::load($content->resumefid);
$filelink = file_create_url($file->getFileUri());

$url = Url::fromUri($filelink);
$external_link = \Drupal::l(t('Download Resume'), $url);

  $rows[] = array(
    'data' => array(
      \Drupal::l($id, $editUrl),
      $content->name.' '.$content->lname,$content->number,$external_link,
      \Drupal::l('Delete', $deleteUrl)
    ),

HTML showing as text