$\vec{AC}$ is the angle bisector of the angle between $\vec{AB}$ and $\vec{AD}$ which is $\frac{2\pi}{3}$,$15|\vec{AC}|=3|\vec{AB}|=5|\vec{AD}|$

Question: In a quadrilateral $ABCD$,$\vec{AC}$ is the angle bisector of the angle between $\vec{AB}$ and $\vec{AD}$ which is $\frac{2\pi}{3}$,$15|\vec{AC}|=3|\vec{AB}|=5|\vec{AD}|$.If $\theta$ is the angle between $\vec{BA}$ and $\vec{CD}$,then prove that $\cos\theta=\frac{2}{\sqrt7}$

My Attempt:
In quadrilateral $ABCD$,$\angle BAC=\angle CAD=\theta=\frac{\pi}{3}$
In triangle $ABC,$apply cosine law,
$\cos\angle BAC=\frac{AC^2+AB^2-BC^2}{2AC\times AB}$

Putting $\frac{AC}{AB}=\frac{1}{5}$ and $\cos\angle BAC=\frac{1}{2}$
We get $\frac{BC}{AB}=\frac{\sqrt{21}}{5}$
Similarly applying cosine law in triangle $CAD$,we get
$\frac{DC}{AC}=\sqrt7$
But then i got stuck,please help me.Thanks.
Answer: I have expresses every angle in degrees,since i am more comfortable with that.
Now I continue where you got stuck,so:
If you consider $\Delta ADC$ we have by Law of Sines that: $$\cfrac{DC}{ \sin 60^\circ }=\cfrac {AC}{\sin \angle ADC} $$
Since we know that $DC/AC=\sqrt 7$ ,we have that $DC=\sqrt{7} \cdot AC$
Hence,applying this to our previous equality ,we get:
$$\cfrac{ \sqrt {7} \cdot AC}{ \sin 60^\circ}=\cfrac {AC}{ \sin \angle ADC}$$
Simplifying this and rearranging for $\sin \angle ADC$,we have :
$$\sin\angle ADC =\cfrac { \sqrt {21}}{14}$$
$$\angle ADC =  \sin^{-1} \cfrac{ \sqrt {21}}{14}$$
Now ,if you consider $\Delta AXD $ where $X$ is the point of intersection of lines $AB$ and $DC$ (hence the angle intercepted by these lines  is your $\theta$ ),we have that $$\angle DAX + \angle ADC + \theta = 180^\circ$$
$$\theta =60^\circ - \angle ADC=60^\circ - \sin^{-1} \cfrac{ \sqrt {21}}{14}$$
$$\cos \theta = \cos (60^\circ - {\sin^{-1} \cfrac {\sqrt {21}}{14}})=0,755928946...=\cfrac{2}{\sqrt{7}}$$


How to find the cumulative probability of a multinomial?

Question: Suppose I want to know the probability that when rolling a fair 3-sided die (faces labeled 1-3) 12 times 1 comes up 4 times, 2 comes up 6 times, and 3 comes up twice. This is straightforward enough using the multinomial formula, but suppose I want to know the probability of "at least" scenarios? For example, what is the probability that after 12 rolls the die shows 3 at least twice, shows 2 at least twice, and shows 1 at least 3 times?
I don't think it's simply a matter of adding probabilities using the standard formula, because "at least" constrains the number of possibilities, and I haven't been able to find any formula or algorithm which shows how to do it correctly.
Answer: I suspect there's no simple equation to give you what you need, but a brute force algorithm is pretty easy to implement.
Python Solution
<code>import collections
import fractions
import itertools as it

def enumerate_rolls(faces, count):
    for elems in it.product(range(1, faces + 1), repeat=count):
        yield collections.Counter(elems)

def count_successes(count, faces, success_test):

    successes, failures = 0, 0

    for elems in enumerate_rolls(faces=faces, count=count):
        if success_test(elems):
            successes += 1
        else:
            failures += 1

    return fractions.Fraction(successes, successes + failures)

if __name__ == '__main__':
    print(
        count_successes(12, 3, lambda s: s[3] >= 2 and s[2] >= 2 and s[1] >= 3)
    )
</code>
Theory
Suppose you have $N$ count of dice each with $F$ number of faces. The domain of all possible rolls can be modeled as a set of multisets where cardinality equals $N$ and the domain is $\mathbb{Z}_F$. The goal is to find a subdomain $S$ meeting your condition.


An encoding of non - empty sequence of strings

Question: An exercise problem $:$
Let $\Sigma = \left\{a, b, c, d, e\right\}$ be an alphabet. We define an encoding scheme as follows:
$g(a) = 3, g(b) = 5, g(c) = 7, g(d) = 9, g(e) = 11$.
Let $p_i$ denote the i-th prime number $\left(p_1 = 2\right)$.
For a non-empty string $s=a_1 \dots a_n$, where each $a_i \in \Sigma$, define $f(s)= \Pi^n_{i=1}P_i^{g(a_i)}$.
For a non-empty sequence$\left \langle s_i, \dots,s_n\right \rangle$ of stings from $\Sigma^+$, define $h\left(\left \langle s_i \dots s_n\right \rangle\right)=\Pi^n_{i=1}P_i^{f\left(s_i\right)}$
Which of the following numbers is the encoding, $h$, of a non-empty sequence of strings?

$2^73^75^7$
$2^83^85^8$
$2^93^95^9$
$2^{10}3^{10}5^{10}$

My attempt :
Given , For a non-empty string $s=a_1 \dots a_n$, and length of $s$ is $3$(in all option)
So , $s=aaa$ , $f(aaa)= \Pi^3_{i=1}2^{3}$
and
$h\left(\left \langle s_i \dots s_n\right\rangle\right)=
h\left(\left \langle aaa\right\rangle\right)=\Pi^n_{i=1}P_i^{f\left(s_i\right)}= \Pi^3_{i=1}P_i^{2^3} = 2^83^85^8$

Can you please explain better than me .
Answer: From $2^j\cdot3^j\cdot5^j = \prod_{i=1}^3p_i^{f(s_i)}$ we deduce by the uniqueness of the prime decomposition that $f(s_i) = j$ for $i=1,2,3$.
If $j=7$ we have for example $f(s_1)=7^1$ and since $1 \notin \{3,5,7,9,11\}$ we conclude that it is not a sequence of words with the above encoding scheme.
If $j=8$ we have for example $f(s_1)=2^3$ and since $3 \in \{3,5,7,11\}$ we conclude that is a sequence of words with the above encoding scheme.
If $j=10$ we have for example $f(s_1)=2^1\cdot5^1$ and since $1 \notin \{3,5,7,9,11\}$ we conclude that it is not a sequence of words with the above encoding scheme.
Similarly with $j=9$ you can conclude that it is not an encoding.
Comment: Please , can you fix the typo , 3∈{3,5,7,9,11}.
Comment: No problem. This is not a typo: 3 is contained in the set {3,5,7,9,11}.


How to solve this Inverse Laplace Transform $\frac{s}{s^2-s+\frac{17}{4}}$

Question: How would I solve this Inverse Laplace transform?
$$\mathscr{L}_s^{-1} \left\{ \frac{s}{s^2-s+\frac{17}{4}} \right\}$$
The solution is
$$f(t) = (1/4 )e^{t/2} (\sin(2 t)+4 \cos(2 t))$$
I know I need to break up $F(s)$ into more common Laplace transforms, but I'm not quite sure how to begin.
Comment: Partial fractions, completing the square, or both.
Comment: Use the derivative property of Laplace transform to get the final result after partial fractions
Comment: Like Chappers said, complete the square in the numerator. You get

$$\frac{s}{(s - \frac{1}{2})^{2} + 4}$$

which hopefully looks familiar to you.
Comment: That was it! I can't believe I didn't see it. Thank you.
Comment: @Mattos, do you mean "denominator"?
Comment: @JoelReyesNoche Yeah I did.
Answer: $$\begin{align}
F(s)&=\frac{s}{(s - \frac{1}{2})^{2} + 4}\\
&=\frac{\frac{1}{2}}{(s - \frac{1}{2})^{2} + 4} + \frac{s-\frac{1}{2}}{(s - \frac{1}{2})^{2}+ 4}\\ \\
f(t) &= (1/4)e^{t/2} (\sin(2 t) + 4\cos(2 t))
\end{align}
$$
Credit to Chappers, Oliver, and Mattos for guiding me to the above solution
Comment: ...accept yourself!


express.js multiple file upload callback

Question: I'm new to node.js & express.js, so... I want to upload multiple files, and later work with them.
But i need to send a response (ok or error status) after all my files have been saved on disk, or if one failed - then send an error callback.
Now I have such code:
var express = require('express');
var router = express.Router();

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();

var fs = require('fs');

router.post('/upload', multipartMiddleware, function(req, res) {
  var reqBody = req.body;
  var reqFiles = req.files;

  saveFile(reqFiles, 'main.xlsx', function(err) {
    if (err) {
      res.status(404).send('');
      return;
    }

    res.send('Multi-File File uploaded');
  }
});

function saveFile(file, name, callback) {
  fs.writeFile('./uploads/' + name, file, callback);
}

but how can i change my code to parse this:
router.post('/upload', multipartMiddleware, function(req, res) {
  var reqBody = req.body;
  var reqFiles = req.files;

  saveFile(reqFiles['files'][0], 'main.xlsx', function(err) {
    if (err) {
      res.status(404).send('');
      return;
    }
  }
  saveFile(reqFiles['files'][1], 'second.xlsx', function(err) {
    if (err) {
      res.status(404).send('');
      return;
    }
  }

  res.send(''); // only after first two fileUploaders have finished
});

function saveFile(file, name, callback) {
  fs.writeFile('./uploads/' + name, file, callback);
}

Answer: You need to iterate through req.files.  You can use async library.
For example:
async.each(req.files, function(file, callback) {
  saveFile(file, file.name, callback)
}, function(err) {
  res.send('')
})

Comment: where should i respond with `ok` status?
Comment: In the callback for the `async` function. Where i have `res.send('')`
Comment: Basically what it's doing is there's the initial callback with `(file, callback)` this is called for each file.  Once all files are processed, your final callback with `res.send('')` will be called, you can handle your errors in the final callback as well.
Comment: `var express = require('express');
var router = express.Router();

var multiparty = require('multiparty');

var fs = require('fs');
var async = require("async");`
Comment: `router.post('/upload', function(req, res) {
  var form = new multiparty.Form();

  form.parse(req, function(err, fields, files) {
    async.each(files, function(file, callback) {

      saveFile(file[0], file[0].originalFilename, function(err) {
        if (err) {
          res.status(404).send('File not uploaded');
          return;
        }
      });
    }, function(err) {
      res.send('');
    })
  });
});

function saveFile(file, name, callback) {
  fs.writeFile('./' + name, file, callback);
}
` should be like this?
Answer:
The module recommends not using this. Use the multiparty module directly.
When you have the list of files they will also have file names. you can loop through those and save each file asynchronously. Then respond. Take a peek here
Comment: Exactly. The module says don't use this module.
Comment: `router.post('/upload', function(req, res) {
  var form = new multiparty.Form();

  form.parse(req, function(err, fields, files) {
    async.each(files, function(file, callback) {

      saveFile(file[0], file[0].originalFilename, function(err) {
        if (err) {
          res.status(404).send('File not uploaded');
          return;
        }
      });
    }, function(err) {
      res.send('');
    })
  });
});

function saveFile(file, name, callback) {
  fs.writeFile('./' + name, file, callback);
}
` should be like this?
Comment: `var express = require('express');
var router = express.Router();

var multiparty = require('multiparty');

var fs = require('fs');
var async = require("async");`
Comment: You would need to build the middleware yourself but multiparty is pretty straightforward.


Uipath try/catch problem - throwing system exception

Question: Having some trouble with try/catch in UiPath:
Got two different projects with their own workflows, with try catch implementations exactly the same in both.
However, one of the try/catch is working absolutely fine, whereas the other one is giving troubles with the following error when I Throw an exception, and then the steps defined in the catch block doesn't even trap it and execute.
Thoughts/Suggestions will be much appreciated - Thanks!
<code>RemoteException wrapping System.Exception: <My user defined message>

   at System.Activities.Statements.Throw.Execute(CodeActivityContext context)

   at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)

   at System.Activities.ActivityInstance.Execute(ActivityExecutor executor, BookmarkManager bookmarkManager)

   at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)
</code>
Comment: Hi Ash. It may be hard to help because of missing information. Please try to explain in more detail, what your workflow do. Regardless, here are some hints: Compare dependencies in both projects. (Are they really the same?) Compare inputs and every activity including they parameters. (There must be some "small hidden" difference easy to overlook, I guess.) Regards.
Answer: If you have been using the Try Catch with the general Exception, it should be working in the same way in any project.
I believe you was a bit confused by the running mode.
So I assume in one project you fired the project in the debug mode. This stops on the exception when it occurs. If happening you need to hit the continue button.
But if you run the project with the Run button, it will ignore the exception handling as breakpoint and will continue now without any break.
So make sure in a live test you always run it with the run button and not with the usual debug button.


Blacklist IPs with iptables behind a Reverse Proxy

Question: I have a Ubuntu Server 16 and I use iptables as firewall. HTTP and HTTPS traffic is behind a Reverse Proxy that I cannot control, but I have X-Forwarded-For field activated.
Is it possible to filter out traffic at the iptables stage instead of adding rules in Apache?
If not what is the best way to implement black list in Apache?
Answer: iptables is not able to inspect that deeply into packets. Even if it could, it would only be able to inspect HTTP traffic, not HTTPS. In apache, you can blacklist using the Limit directive.
Comment: From the TCP/IP network model layer 2 (Internet layer) you have the IP header, and can filter on things commonly in that, but iptables can also filter based on some details from the TCP/IP layer 3 (transport layer) details for some protocols like tcp/udp.
Comment: `iptables` is limited to layer 2, is that correct?
Answer: It actually is quite possible, though it may require a kernel patch depending on your distrubution. There is the string netfilter extension that let's you match specific packets based on if a string is contained within them. We have used it in the past for handling DDOS traffic.
An untested example is here:
# iptables -A INPUT -m string --string 'X-Forwarded-For: badIP' -j DROP
Keep in mind that this is a rather blunt instrument and can result in traffic being unexpectedly dropped- make sure you craft your rules carefully and explicitly. As EEAA stated as well, it will not work on encrypted traffic.
More information is here: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-3.html#ss3.18
Comment: How is it not suitable for your needs? It literally answers your question: `Is it possible to filter out traffic at the iptables stage instead of adding rules in Apache?`
Comment: Thank you for sharing this, but not suitable for my needs
Comment: Most of my traffic is HTTPS unfortunately
Comment: The link you provide me also explicitly discourage using it for this purpose, thank you anyway
Comment: Ah yes - if you are using HTTPS, you will have to do it where the HTTPS connection is terminated.

The article only says don't use it for broad things like GET/POST (as they may be strings used in other messages) - using it for explicitly written blocks works very well.
Comment: Yes, I have learnt something useful with your answer, thank you
Comment: Just so others may know: I've had some problems applying this filter, and find out later that the headers where written in lowercase: 'x-forwarded-for'. you can search string with case insensitive option as well using the --icase option. (http://ipset.netfilter.org/iptables-extensions.man.html)


Java single pipeline operator (expression | expression)

Question: I was looking at the android source code today and I found this:
if (mLeftDragger.continueSettling(true) | mRightDragger.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(this);
}

The return type of both these methods is boolean.
What is the purpose of this operator and what happens there actually?
Comment: Described [here][1].
The difference between | and || is that the former is not short-circuit... so even if the first operand is true, the rest will still be evaluated. I believe this is not described in the linked question...?

  [1]: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.2
Comment: It means "or", similar to `||`, but *both* operands will be evaluated.  This means that `continueSettling` is called on both objects, no matter whether it returns `true` or `false` for `mLeftDragger`.  The result is `true` if either method returns `true`.
Comment: I feel like [this question](http://stackoverflow.com/q/7101992/1079354) is a suitable duplicate to this.  It deals directly with booleans.
Comment: @Hot Licks--Correct, in C++.  Java does not have a `bool` type, and its `boolean` type is not simply an integer (and cannot be converted to or from one with a cast), although there is an obvious relation between booleans and the subset {0,1} of integers.  So because of that, I don't really consider the _originally_ linked question to be a duplicate since it doesn't deal with `true` and `false` at all.  (The duplicate question has changed since my first comment.)
Comment: I'm not sure that is really a duplicate, because the linked question answers the question of what `|` does for integer operands, but not for boolean operands.
Comment: It is bitwise OR for integer arguments, or non-short-circuit OR for boolean arguments.
Comment: @Makoto Use your hammer!
Comment: How was I supposed to search for this question by the single-character string of "|". Give me a break :)
Comment: @SotiriosDelimanolis:  I wanted to wait for a relatively simple quorum on the matter.
Comment: You know, you could actually look it up in a Java reference.
Comment: @ajb -  A bool is simply a 1-bit integer.
Comment: @ajb - The reason that boolean is treated a little differently in Java is so that it's easy to require only a boolean value in an `if` statement or for the "logical" operators.  This, among other things, allows the compiler to diagnose `if (a = b)` as an error.
Answer: || short circuits where as | does not.  Short circuiting is when the right hand expression does not get evaluated if there is no need for it to be evaluated.  | will calculate all Boolean expressions (left to right).  Check out this answer.
Comment: Not that I am downvoter, but if you know that answer has already been given then you should vote to close (or flag) question as duplicate rather than reposting answer.
Comment: Oh, the gracious down vote (and even more gracious missing explanation).


403 Forbidden Error on Tomcat 7 When using POST or PUT

Question: I have an AngularJS front end that receives data from a Java web service. Both of these live on a Tomcat 7 server. My application performs GET operations correctly. However, when I am trying to save a new object or update an object, my POST and PUT operations return a 403 Forbidden error.
From searching around, I found that Tomcat has PUT disabled and that it has to be turned on. So I modified the web.xml file in the conf folder in the Tomcat directory and added the following code under the DefaultServlet:
<code><init-param>
    <param-name>readonly</param-name>
    <param-value>false</param-value>
</init-param>
</code>
After this, the server was restarted. But I am still receiving the 403 error.
Please let me know what other information I can include to help find what I am doing wrong.
Answer: The answer to my issue was discovered this morning. This was not a tomcat configuration error. Rather it was an authentication issue. We use openam to authenticate on the servers and the PUT and POST options were not marked. Once those were checked, my web services worked correctly.


Rests in classical guitar notation

Question: I'm reading a book by David Braid — Play Classical Guitar.
Everything is going smoothly until I get to the part on rests, here's the part that confuses me:

Let me first explain what I understand:
Exr-26

When we bind a semibreve rest to a note, that note becomes separate in time for 4 beats (regarding to other notes coming, this notes keeps ringing in the background).

If a crotchet note is binded to a minim rest, it will be separate in time for 2 beats (this note keeps ringing in the background for 2 beats (minim rest)).

The small curved line means the note keeps ringing — don't rest you thumb for infinite time — just don't rest.

(Please correct me if I am wrong)
Exr-27

In the first bar I can't understand the meaning of having a semibreve note binded with a crotchet rest and attached to the small curve, could you please explain this to me?

Questions:

What does "separate in time" really mean?

Is the term "keeps ringing" identical to "separate in time"?
Comment: Don't know the book, but it probably isn't the best. The way it explains could be better - and I expect English is not your first language. The last minim ought to be written the other way (upside down) too, and there's absolutely no need for the smiley bits to tell the notes last long. The notes themselves do that!. See if there are other tutor books out there; sorry to be so negative!
Answer: I can barely understand what you're talking about, honestly.  Whatever it is, I think you need to forget the word "bind".
In both exercises, there are two separate lines.  In the first, there's a top line that goes:

    (rest)  | E E E    | (rest)  | (rest) E

and a bottom line that goes:

    A A A   | (rest)   | A   E E | A

The second example follows similarly.  In the first, the two separate voices seem pretty unnecessary, but the writer is just trying to create a simple example to prepare you for the next one.
The curved line after the notes is a tie connecting to nowhere, which is the common notation to "let ring", meaning don't dampen the note and just let it continue to sound until it dies away on its own.
Comment: Not playing an A sounds the same as not playing a D. ;^) I think that convention is to hang or place the rest symbol on the centre line of the stave but since there are two parts superimposed on the one stave the lower part rest is signified on the first ledger line.
Comment: Well,  the explanation given by the book is rather nonsensical too. What does it mean "to keep the parts separate in time"? Anyway your explanation is quite good, I would just stress that the two lines should sound as independent as possible, as if played by two different players (and that, it seems to me, is the main purpose of the exercise).
Comment: Short and simple thank you! (thanks to @joseem too for the comment) One more simple question: Is the position of the rest is soo important ? Since it's a silent note, can I just move it up and down randomly (Eg: from A to D ) without the affecting the whole piece?

Rests in classical guitar notation


É possível chamar por OnClick de TextView uma nova Activity?

Question: Olá, estou tentando chamar um activity novo por meio de OnClick num TextView, mas ao executar a aplicação gera um crash.
Eis a activity de a partir que estou tentando passar:
public class sdActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "TesteGigaservicesAPP";

//list view dos produtos
public ListView lv;

//list view adapter
ArrayAdapter<String> adapter;

//barra de busca
AutoCompleteTextView inputSearch;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sd);

    //produtos da busca
   String[] produtos = {
           "Produto 1",
           "Produto 2",
           "Produto 3",
           "Produto 4",
           "Produto 5"
   };

   lv = (ListView)findViewById(R.id.listaDProdutos);
   inputSearch = (AutoCompleteTextView)findViewById(R.id.barradepesquisa);

   //popula a lista
   adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, produtos);
   lv.setAdapter(adapter);

    //

   //aciona a barra de buscas

    inputSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

        }

        @Override
        public void beforeTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        sdActivity.this.adapter.getFilter().filter(cs);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    /*problemas de implementação*/

    TextView ver = (TextView)findViewById(R.id.product_name);

    ver.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(sdActivity.this, ProdutoActivity.class));
            //teste para passar sob o elemento de uma view de layout
        }
    });

    //botão que volta a página anterior
    Button btVoltarUm = (Button)findViewById(R.id.btVoltarUm);

    btVoltarUm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(sdActivity.this, MainActivity.class));
        }
    });
}
}

O item product_name fica em um arquivo de layout separado que está como list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/product_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:textSize="16dip"
        android:textStyle="bold" />

</LinearLayout>

Esse é meu arquivo de manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testegigaservices.testegigaservices">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".sdActivity"
        android:label="@string/pgBusca"
        android:windowSoftInputMode="stateHidden"></activity>
    <activity android:name=".produtoActivity"></activity>
</application>

Comment: "ao executar a aplicação gera um crash" - O primeiro passo neste caso é consultar o *Log* para ver qual a mensagem de erro e qual a linha em que deu erro. Deve pegar nessa mensagem de erro e colocar na pergunta
Comment: ok, das consultas no logcat inserirei os logs na próxima tentativa.
Answer: Em primeiro lugar caso essa não seja a solução, cole o LOG para que possamos analisar.
Verifique se o nome de sua activity no AndroidManifest está coerente com sua classe, percebi que você está declarando uma activity no manifesto e quando tentar startar a nova activity passa uma referência  com letra maiúscula.
<activity android:name=".ProdutoActivity"></activity>

Answer: O que você precisa observar é o seguinte:
1º O findViewById() dentro da activity está diretamente ligado ao seu respectivo layout, nesse caso:
setContentView(R.layout.activity_sd);
2º O erro provavelmente acontece justamente porque o findViewById() está procurando pelo TextView que na verdade está em um outro layout (list_item.xml), consequentemente ele não vai achar:
3º Sempre poste a mensagem de erro, para que fique mais fácil lhe ajudar.
4º Solução para reconhecer o click em um dos items da lista:
private OnItemClickListener quandoOhItemForClicado = new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View v, int position, long id) {
           startActivity(new Intent(sdActivity.this, ProdutoActivity.class));
    }
};

listView.setOnItemClickListener(quandoOhItemForClicado);

Comment: ok, entendi a lógica.


Why when I am using file.peek() in C++ do I get a number rather than the char?

Question: In most of my code, the in.peek() works as getting whatever the next char is supposed to be. However, when it is reading some symbols, it returns a number rather than the char, and I am not sure how to fix it to get the symbol I want.
The text file reads:

print "Good morning!!";

but during the " char I use file.peek() to read the next symbol is a ; to change the state of my switch, but it comes out as a number instead of the symbol.
This is how I am trying to print, I even created a temp char and set it to in.peek(), but that just comes out as a blank space.
char temp = in.peek();
cout<<"hit  " << ch << " "<< in.peek()<<" "<<temp << endl;

The output is: "hit  " 10 "
With the last bit being a blank space. Does anyone know how I can fix this so I get the ;?
Comment: according to the docs I see, it returns an int. That int may typically be displayed as a char in some places, presumably ascii?
Comment: Same reason why getchar and friends return int [Difference between int and char in getchar/fgetc and putchar/fputc?](https://stackoverflow.com/q/35356322/10147399)
Answer: peek returns an int (to account for possibility of eof()). To make sure cout recognizes it as a char, you can cast it (though this will produce incorrect values if you did hit EOF), e.g.:
cout << "hit  " << ch << " " << static_cast<char>(in.peek()) << " " << temp << endl;

Comment: Worked! Thanks so much, didn't know that.


Linq FirstOrDefault ordering when OrderBy or OrderByDescending are not supplied?

Question: If we have an EF entity with basic structure of
public class Entity
{
   public int Id {get; set;}
   public string name {get; set;}
   public DateTime lastUpdated {get; set;}
}

And a collection of them with 4 entities:
entities = new List<Entity>{
   new { Id = 0, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 1, 0, 0, 0,)},
   new { Id = 1, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 4, 0, 0, 0,)},
   new { Id = 2, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 3, 0, 0, 0,)},
   new { Id = 3, Name = "Thing One", LastUpdated = new DateTime(2020, 10, 2, 0, 0, 0,)}
};

If we use Linq to select the FirstOrDefault by the Name property.
   var selectedEntity = entities.FirstOrDefault(e => e.Name == "Thing One");

What is this going to return?
This is causing issues in a piece of code that I'm reviewing; which will be fixed by only allowing unique entities and using SingleOrDefault, but I'm curious at to what the FirstOrDefault is going to return by default when there is no OrderBy clause.
Comment: it's just undefined. in programming there's many such cases. in my opinion useless to study the behaviour.
Answer: The first item matching this condition is returned, if there are multiple items matching the result is unpredictable/undefined. If you want to ensure a specifc item you need to apply an OrderBy:
var selectedEntity = entities
   .Where(e => e.Name == "Thing One")
   .OrderByDescending(e => e.LastUpdated)
   .FirstOrDefault();

What is returned by the database depends on the vendor. This related qustion might help: When no 'Order by' is specified, what order does a query choose for your record set?
Comment: cheers! the articles in the linked answer are very interesting. Relying on a FirstOrDefault with no ordering is certainly going to turn up in bug somewhere :-)
Comment: @RossHalliday: You're welcome. Yes, especially the first article is worth reading: https://web.archive.org/web/20160808070425/https://blogs.msdn.microsoft.com/conor_cunningham_msft/2008/08/27/no-seatbelt-expecting-order-without-order-by/


Turning text in a tableview to capitals?

Question: I'm working on an RSS feed and need to turn the title and subtitle into capitals, is there an easy way to do this?

Thanks.
Answer: in the cellForRow AtIndexPath
<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

NSString *string1 = @"The quicK brOwn fox jumpeD";

cell.textLabel.text = [string1 uppercaseString];

....
</code>
Answer: <code>NSString* str = @"abcd abcd abcd abcd";
[str capitalizedString];    //  = Abcd Abcd Abcd Abcd
[str uppercaseString];      //  = ABCD ABCD ABCD ABCD
</code>
Answer: uppercaseString, method of NSString ?
Answer: You can do it from the storyboard under Text Field Properties.
Change the Capitalization drop down to All Characters. Test it on your device or make sure the Keyboard is toggled on. If you type from the physical keyboard it will override the Upper Case arrow on simulator keyboard.


How to prove (A ⊆ B) ∧ (B ⊆ C) ⇒ (A ⊆ C)

Question: How would I go about proving that, given A, B, C are sets;
$[(A⊆B)∧(B⊆C)]⇒(A⊆C)$
Thanks for the help.
Comment: What's the definition of "being a subset of"?
Comment: Yes, just wondering if it is enough proof to say that: If there is an $x$ in B such that, for every $x$ in B, $x$ is in C and there exists an $x$ in A such that, for every $x$ in A, $x$ is in B. Thus, for every $x$ in A, $x$ is also in C, and therefore A is a subset of C.
Comment: You're doing it in a rather confuse way; what do you mean by "there is an $x\in B$ such that, for every $x\in B$, …"?
Comment: "If there is an x in B such that, for every x in B" is already meaningless, because you have chosen x twice -- first with an existential quantifier, and then again with a universal quantifier.
Comment: Sorry wasn't sure if you could use $\in$ in the comments. Would have been easier to write.
Answer: Hint:
You want to start with $a\in A$, and try to use the assumptions you're given to show that $a\in C$.
Answer: Suppose that $(A\subseteq B)\wedge (B\subseteq C)$ is true. Then both $A\subseteq B$ and $B\subseteq C$ are true.  Let $x\in A$ be chosen arbitrarily.  Since $A\subseteq B$, we conclude that $x\in B$.  Since $B\subseteq C$, we conclude that $x\in C$.  Since $x$ was chosen arbitrarily, we conclude that $A\subseteq C$.
Based on the hypothesis $(A\subseteq B)\wedge (B\subseteq C)$, we have concluded $(A\subseteq C)$.  Hence we have proved that $(A\subseteq B)\wedge (B\subseteq C)\to (A\subseteq C)$
Answer: Suppose that it is not true.
So we have:
$A\subseteq B \land B\subseteq C \land (\lnot  A\subseteq C)$
$ (x\in A \implies x\in B) \land (x\in B \implies x\in C) \land x\in A \land x\notin C $
and :
$( (x\in A \implies x\in B) \land x\in A ) \implies x \in B$
so:
$ x \in B \land (x\in B \implies x\in C) \land x\in A \land x\notin C $
then:
$((x∈B⟹x∈C)∧x∈A)⟹x∈C$
ans we have:
$ x \in B \land x∈C \land x\in A \land x\notin C $
$  x∈C \land  x\notin C $ isn't true,
so $\lnot$ [(A ⊆ B)∧(B ⊆ C) → (A⊆C)] is false
and (A ⊆ B)∧(B ⊆ C) → (A⊆C) is true
Answer: For any $x\in A$, since $A\subset B$, we have that $x\in B$. Note that $B\subset C$, then we can derive that $x\in C$. This shows that $A\subset C$.


ERROR ORA-00933: SQL command not properly ended

Question: <code>PROCEDURE PR_TRIAL_BAL_BULKWITHOUTCUR IS

VAR_OF_TYP_TBL TYP_TBL;

BEGIN
SELECT * BULK COLLECT INTO VAR_OF_TYP_TBL
  FROM (SELECT NAME, SUM(CREDIT) AS CREDIT, SUM(DEBIT) AS DEBIT
          FROM (SELECT (SELECT GL_NAME
                          FROM QM_GL
                         WHERE QM_GL.GL_ID = QT_ACCOUNTING.GL_ID) AS NAME,
                       DECODE(QT_ACCOUNTING.TRANS_TYPE,
                              'CR',
                              (QT_ACCOUNTING.TRANS_AMOUNT),
                              0.00) AS CREDIT,
                       DECODE(QT_ACCOUNTING.TRANS_TYPE,
                              'DR',
                              (QT_ACCOUNTING.TRANS_AMOUNT),
                              0.00) AS DEBIT

                  FROM QT_ACCOUNTING, QM_ACCOUNTING_PERIOD

                 WHERE QT_ACCOUNTING.VALUE_DATE BETWEEN
                       QM_ACCOUNTING_PERIOD.PERIODFROM AND
                       QM_ACCOUNTING_PERIOD.PERIODTO
                   AND QM_ACCOUNTING_PERIOD.STATUS = 'O')
         GROUP BY NAME)
         );

FOR I IN 1 .. VAR_OF_TYP_TBL.COUNT LOOP

  IF (VAR_OF_TYP_TBL(I).CREDIT - VAR_OF_TYP_TBL(I).DEBIT) > 0 THEN
    INSERT INTO TBL_TRIAL_BALANCE_REPORT
    VALUES
      (VAR_OF_TYP_TBL(I).NAME,
       (VAR_OF_TYP_TBL(I).CREDIT - VAR_OF_TYP_TBL(I).DEBIT),
       0);
  END IF;
  IF (VAR_OF_TYP_TBL(I).DEBIT - VAR_OF_TYP_TBL(I).CREDIT) > 0 THEN
    INSERT INTO TBL_TRIAL_BALANCE_REPORT
    VALUES
      (VAR_OF_TYP_TBL(I).NAME,
       0,
       (VAR_OF_TYP_TBL(I).DEBIT - VAR_OF_TYP_TBL(I).CREDIT));
  END IF;

END LOOP;
VAR_OF_TYP_TBL.DELETE;

EXCEPTION
  WHEN OTHERS THEN
  DBMS_OUTPUT.PUT_LINE(SQLERRM);
  BEGIN
    VAR_OF_TYP_TBL.DELETE;
  EXCEPTION
    WHEN OTHERS THEN
      NULL;
  END;
END;
</code>
Can anyone help me, where are following errors in above code and how can it be removed?

ORA-00933: SQL command not properly ended
Error: PL/SQL: SQL Statement ignored

(errors are in select query, only)
Comment: DON'T SHOUT ON US. [Did'n you learn from your previous question?](http://stackoverflow.com/q/12793389/1369235)
Answer: <code>    SELECT   *
      BULK   COLLECT
      INTO   VAR_OF_TYP_TBL
      FROM   (  SELECT   NAME, SUM (CREDIT) AS CREDIT, SUM (DEBIT) AS DEBIT
                  FROM   (SELECT   (SELECT   GL_NAME
                                      FROM   QM_GL
                                     WHERE   QM_GL.GL_ID = QT_ACCOUNTING.GL_ID)
                                      AS NAME,
                                   DECODE (QT_ACCOUNTING.TRANS_TYPE,
                                           'CR', (QT_ACCOUNTING.TRANS_AMOUNT),
                                           0.00)
                                      AS CREDIT,
                                   DECODE (QT_ACCOUNTING.TRANS_TYPE,
                                           'DR', (QT_ACCOUNTING.TRANS_AMOUNT),
                                           0.00)
                                      AS DEBIT
                            FROM   QT_ACCOUNTING, QM_ACCOUNTING_PERIOD
                           WHERE   QT_ACCOUNTING.VALUE_DATE BETWEEN QM_ACCOUNTING_PERIOD.PERIODFROM
                                                                AND  QM_ACCOUNTING_PERIOD.PERIODTO
                                   AND QM_ACCOUNTING_PERIOD.STATUS = 'O')
              GROUP BY   NAME);
          -- );       remove this from your code
</code>
Comment: @priyanka:You need to be careful about how you put your braces ,if you already know that ,you have some problem with the query post only the query .
Comment: thanks gaurav.
this was the only silly mistake which i was doing.


how Seperate a string in java without using functions like split & stringtokenizer?

Question: I want to separate a string without using split .can anybody help with my problem I am tried but I cannot find the exact logic. I did separated string with split function and stringtokenizer .
I solved later..
`package File;
import java.util.Scanner;
public class Java_String_separating {
public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();

    for(int i = 0; i <str.length();i++) {
        if(str.charAt(i)==' ') {
            System.out.println();
            continue;
        }
        System.out.print(str.charAt(i));
    }
    sc.close();
}

}`
Comment: Could you post your approach that you tried (the one without the split and stringtokenizer)?
Comment: Thanks for your reply i solved later.
Comment: i wanted to solved in this way
  for(int i = 0; i <str.length();i++) {
   if(str.charAt(i)==' ') {
    System.out.println();
    continue;
   }
  System.out.print(str.charAt(i));
Answer: I wanted to separate string in this way..
package labFile;

import java.util.Scanner;

public class Java_String_separating {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();

        for(int i = 0; i <str.length();i++) {
            if(str.charAt(i)==' ') {
                System.out.println();
                continue;
            }
            System.out.print(str.charAt(i));
        }
        sc.close();
    }

}

Answer: You can use a mixture of String.indexOf() and String.substring() and iterate over the input while looking for delimiter:
String input = "Hello World";
char delimiter = 'o';

var result = new ArrayList<>();
int i, start = 0;
while ((i = input.indexOf(delimiter, start)) > -1) {
  result.add(input.substring(start, i));
  idx = i + 1;
}
if (start != s.length()) {
  result.add(input.substring(start));
}

System.out.println(result); // [Hell,  W, rld]

Answer: If you know the length of the sections of string, you could run a for loop and substring it. So you header would look sometjing like:
    for(int i = 0; i < str.length(); i += lenOfSubStrDesired)
You could theb substring by
    str.substring(i, i+lenOfSubStrDesired);
However, if the length of string desired is unknown and you want to split by a delimiter, it gets harder. You could do something with regular expressions, but at that point your just emulating String.split.
Hope this helps, let me know if you need better examples, I am on mobile and my ability to give example code currently is limited.


Silverlight: Difficult with Data Binding

Question: Apparently I don't understand something about binding ListBox controls to data.
Here is a ListBox that binds to a property in the code-behind:
        <ListBox ItemsSource="FavoriteFilters"
                 x:Name="favoriteFiltersList"
                 Visibility="{Binding FavoriteFilters.IsEmpty, Converter={StaticResource visibilityConverter}}">

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <my:FavoriteFilterLink />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

When I do this, the ListBox appears with a single element populated with fallback values, even though the items source is empty. This happens no matter what I set ItemsSource to, like ItemsSource="TotallyInvalidProperty". However, if ItemsSource is empty, the ListBox disappears.
The code behind:
    public ObservableCollection<FavoriteFilter> FavoriteFilters
    {
        get
        {
            return PlumData.FavoriteFilters;
        }
    }

PlumData:
    private static ObservableCollection<FavoriteFilter> _favoriteFilters = new ObservableCollection<FavoriteFilter>();
    public static ObservableCollection<FavoriteFilter> FavoriteFilters
    {
        get
        {
            return _favoriteFilters;
        }
    }

I don't understand why this isn't working. However, when I do it in the code-behind, it works fine:
    void BottomFavoritesBar_Loaded(object sender, RoutedEventArgs e)
    {
        favoriteFiltersList.ItemsSource = FavoriteFilters;
    }

What am I doing wrong? I'm using SL4.
Answer: off the top of my head, don't you need to set the binding like this:
<ListBox ItemsSource="{Binding FavoriteFilters}"
             x:Name="favoriteFiltersList"
             Visibility="{Binding FavoriteFilters.IsEmpty, Converter={StaticResource visibilityConverter}}">

note the Binding keyword.


Why can't Openstack VM reach itself via it's Floating IP?

Question: I set up an OpenStack Folsom (2012.2) multi-node, single-network infrastructure.
Everything runs fine, instances are running good on any compute node, private network works like a charm and all instances are reachable via Floating IPs from the outside and can reach the outside.
But when trying to perform a network request from a VM to itself via it's Floating IP it fails.
Neither ping nor ssh are working.
Security Groups are all open.
Ping works via Floating IPs from one VM to another but SSH don't.
Some data for one example

10.0.0.0/24 is the private network
10.0.0.1 is the controller
10.1.100.0/24 is the Floating IP network
the VM with 10.0.0.13 has the Floating IP 10.1.100.4

iptables entries (regarding 10.1.100.4/10.0.0.13) on the controller (all services including network):
<code>-A nova-network-2.7-OUTPUT -d 10.1.100.4/32 -j DNAT --to-destination 10.0.0.13
-A nova-network-2.7-PREROUTING -d 10.1.100.4/32 -j DNAT --to-destination 10.0.0.13
-A nova-network-2.7-float-snat -s 10.0.0.13/32 -o eth0 -j SNAT --to-source 10.1.100.4
</code>
iptables entries on the compute node:
regarding 10.1.100.4/10.0.0.13:
<code>-A nova-compute-2.7-local -d 10.0.0.13/32 -j nova-compute-2.7-inst-143
</code>
regarding nova-compute-2.7-inst-143:
<code>-N nova-compute-2.7-inst-143
-A nova-compute-2.7-inst-143 -m state --state INVALID -j DROP
-A nova-compute-2.7-inst-143 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A nova-compute-2.7-inst-143 -j nova-compute-2.7-provider
-A nova-compute-2.7-inst-143 -s 10.0.0.1/32 -p udp -m udp --sport 67 --dport 68 -j ACCEPT
-A nova-compute-2.7-inst-143 -s 10.0.0.0/24 -j ACCEPT
-A nova-compute-2.7-inst-143 -p tcp -m tcp --dport 22 -j ACCEPT
-A nova-compute-2.7-inst-143 -p tcp -m tcp --dport 3389 -j ACCEPT
-A nova-compute-2.7-inst-143 -p tcp -m multiport --dports 1:65535 -j ACCEPT
-A nova-compute-2.7-inst-143 -p udp -m multiport --dports 1:65535 -j ACCEPT
-A nova-compute-2.7-inst-143 -p icmp -j ACCEPT
-A nova-compute-2.7-inst-143 -j nova-compute-2.7-sg-fallback
</code>
Any suggestions where to search for the problem are welcome.
Of course I will provide any necessary data to solve the problem. Currently I am not quite sure which data would help.
Comment: You can try to change the configuration of compute node to solve the `iptables` rules problem by: $ echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables
Answer: Okay, I have found the problem:
All packets to Floating IPs (10.1.100.0/24 in my case) are DNATed to private network destination (10.0.0.0/24 in my case). The ssh packets go round via the controller and come right back to the VM. The ssh server answers but sends the packet with it's private address as source (of course - it has no other). So the ssh client gets a packet from 10.0.0.13 as answer to a request to 10.1.100.4 which it ignores.
Well, so when sending packets from Private to Floating IPs not only the destination has to be NATed but the source, too. But that's not straight forward because the DNAT is in PREROUTE while the SNAT is in POSTROUTE. It can be done using the connection tracking module:
<code>iptables -t nat -A nova-network-2.7-float-snat -s 10.0.0.13/32 -d 10.0.0.0/24 -j SNAT --to-source 10.1.100.4 -m conntrack --ctstate DNAT
</code>
This did the trick for me (for every single Floating IP of course). It mangles every packet from private to private which was already DNATed (then it should go to Floating IP), to make it seem to come from a Floating IP.
In my ssh scenario now happens the following:

client sends from 10.0.0.13 to 10.1.100.4
packet is DNATed to 10.0.0.13
packet is SNATed to 10.1.100.4
server answers packet to 10.1.100.4
packet is DNATed to 10.0.0.13
packet is SNATed to 10.1.100.4
client gets answer from 10.1.100.4 and is happy

This works as well for ping and also for traffic between different VMs.
Looks like I have to patch the nova-network code and submit it to the openstack project :-/.
Comment: Okay, but do you know if quantum has such issue?
Comment: nova-network is frozen at this point.  quantum should be taking over and the deprecated nova-network project will eventually be removed.
Answer: Tilo,
This is captured pretty well in https://bugs.launchpad.net/nova/+bug/1096259, and patches are currently in progress for nova (https://review.openstack.org/#/c/19139/) as of today (Jan 7th, 2013).
The full fix also goes with bug 1096987 (https://bugs.launchpad.net/nova/+bug/1096987) and 1096985 (https://bugs.launchpad.net/nova/+bug/1096987) to cover the more common deployment scenarios where you are using either a predefined external gateway or taking advantage of the nova-network linux/iptables networking public bridge setup.


Git rebase inside github actions

Question: I have set up a GitHub action that is supposed to change the commit it was started on.
This looks something like
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Do some computations
        run: |
          # Create some new files that should be added to the commit
          dvc repro
      - name: Commit Results
        run: |
          git config --local user.email "firstname.lastname@example.com"
          git config --local user.name "GitHub Action"

          git add .
          git commit --amend --no-edit

          git push --force

This works fine, when there are no updates to the branch while the action is running.
It becomes more complicated when I try to have multiple actions running with some small offset and try to use the following to combine the results:
- name: Commit Results
        run: |
          git config --local user.email "email@example.com"
          git config --local user.name "GitHub Action"

          CIREVISION=$(git rev-parse HEAD)

          # stash changes
          git add .
          git stash

          # update for new commit
          git pull --rebase

          # start rebase only on the commit of this CI run
          GIT_SEQUENCE_EDITOR="sed -i -re '0,/pick/{s/pick/edit/}'" git rebase -i "$CIREVISION^"

          # update files and commit
          git stash pop
          git add .
          git commit --amend --no-edit

          # finish rebase <- this fails with a merge conflict
          git rebase --continue

          git push --force

which in the case of a single changed file metrics.json fails with
Auto-merging metrics.json
CONFLICT (content): Merge conflict in metrics.json
Rebasing (2/3)
error: could not apply ABCD123... TEST01
hint: Resolve all conflicts manually, mark them as resolved with

I tried to use something like git status | grep both | awk '{print $3}' | xargs git checkout --ours . to not merge but always accept the version of the file present in the current branch, but I could not resolve the merge conflict.
A little more context:
I am using Github CI together with cml.dev to version control and allow for full reproducibility of research data. I update a parameter file, this triggers some computation and the results of these computations are saved externally, but some small metrics should be stored via git together with the correct parameters. Having one commit with the updated parameters but the old metrics is not feasable, therefore I must change the original commit.
I am aware of the consequences it has, to force push to a repository and I am willing to take the risk.
I usually use git for software development and have not looked into changing an existing git structure, because I usually don't want to do this.
Comment: @PythonF cml has the `cml pr` command to be able to create a pr against the experiment branch. You could use `gh pr merge` if you would like to try to merge it automatically... not recommended either in my opinion
Comment: The problem seems due to running jobs in parallel. Wouldn't it be an option to run them in sequence?
Comment: It would require not running the jobs in sequence but I would have to block pushing to the branch while the action is running, because otherwise I would loose a commit through force push.
Comment: You can eventually add a push step in a specific job at the end of all jobs execution (using the `needs` field). But even like this I think you will have the metrics file conflict (as many jobs will update the same file). Did you try this to check?
Comment: I have not yet - I will look into it though. Shouldn't it somehow be possible in each rebase to force accept the new file and not try to merge it?
Comment: I'm not sure. From what I understand, as your jobs in parallel upload the same file almost at the same time, I think the `git pull --rebase` should maybe happen before the `git add .` to avoid conflict. But I'm not sure how it will behave in the workflow.
Answer: If all you need is to commit the current state regardless of upstream changes, then fetch and reset:
BRANCH=experiment
git fetch --all
git reset --mixed origin/$BRANCH
git add .
git commit -m "a new experiment"
git push origin HEAD:$BRANCH

Naturally the push may fail so the whole thing should be in a retry loop.
This avoids the scariness of CI doing --force pushes.

Git rebase inside github actions


Finding a global solution for the IVP

Question: im trying to find the global solution for the following IVP. In general, I know how to check if theres a global solution but I dont know how to calculate it.
PROBLEM:
The IVP is $\dot x = t^{2}|x|^{2/3}$, $x(t_{0})=x_{0}$.
Let $(t_{0},x_{0})=(1,1)$. How can I build a global solution? And whats the process to see if it is locally unique or globally unique?
Any help would be incredibly appreciated, thanks so much.
My only work in this problem was to find the explicit solution for the IVP(the easy part)
$\int _{1}^{t} \frac{\dot x }{|x|^{2/3}} = \int _{1}^{t} t^{2}dt$, now changing variables and integrating we get to:
$3|x(t)|^{1/3} - 3 = \frac{t^{3}}{3} -\frac{1}{3}$
$|x(t)|= (\frac{t^{3}}{9}+\frac{8}{9})^{3}$
Comment: So, what's your solution?
Comment: I got $+\frac 89$ instead of $-\frac 89$.
Comment: Separate variables
Comment: Yeah, but once I solve it how do I build the global solution D:
Comment: And well, I know it must have a global solution cause $\frac{\partial f(t,x)}{\partial x}$ is bounded
Comment: You should first show us how you solved it. Efforts by the ones that ask is highly appreciated here.
Comment: But my problem is that I dont know how to solve that, :/. I could show how I got to the explicit solution but I havent done any other work cause I dont know what Im suppose to do D:
Comment: I posted it sir :)
Comment: So, this solution is valid for $t\ge t_1 = -2$ (and $x_1=0$). Now, start again with the initial value $(t_1,x_1)$ and for $x\le 0$ so that $|x|^{2/3} = (-x)^{2/3}$.
Comment: Hmm, I don't see another way than extending the function on $(-\infty,-2)$ by zero. Then you have your global solution.
Answer: The function
$$
x(t) =
\begin{cases}
\frac 1{9^3}(t^3+8)^3 &\text{for $t\ge-2$}\\
0 &\text{otherwise}
\end{cases}
$$
is a global solution.

Finding a global solution for the IVP


É possível ocultar a barra de link apresentada no canto inferior dos navegadores?

Question: Gostaria de saber se existe alguma forma de ocultar a barra de link apresentada no canto inferior esquerdo (ou direito conforme a posição do link) do navegador. É possível?
Google

Imagem de exemplo:
Comment: Não é possível fazer isto.
Comment: @qmechanik é possível sim fazer isto. O próprio [Stack Overflow](http://pt.stackoverflow.com/help) utiliza isso no "banner" de boas-vindas. Se você passar o mouse sobre qualquer um dos icons da secção `Veja como funciona` no banner da **Central de ajuda**, você irá ver que esta barra de link não aparece. Você pode também ver um exemplo disso na minha [resposta abaixo](http://pt.stackoverflow.com/a/69181/11886).
Comment: @Chun Boa resposta a tua. Interpretei a pergunta no sentido de desativar o recurso do navegador, acho que isso não deve ser possível como mencionado pelo Victor Stafusa por razões de segurança.
Comment: Olá!
Pode esconder sim!
Vejam aí a resposta: http://allinworld99.blogspot.pt/2015/02/hide-url-hover-over-link-hide-link-from.html Testei e funciona!
Answer: Essa barra de link existe como um recurso de segurança e foi inventada para mitigar problemas decorrentes de phishing. Se ela pudesse ser ocultada ou desativada, então todos os sites que promovem phishing iriam desativá-la, e como resultado tal recurso perderia o sentido de existir. Por essa razão, esta barra foi projetada de forma a não poder ser removida e nem desativada, não havendo portanto meio de ocultá-la.
Comment: Acho que essa informação é errônea pois acredito que ele se refere a barra de status do browser. É possível ocultar sim a status bar.
Comment: Eu não diria que está errado, nos navegadores modernos uma tag `a` com o atributo `href` sempre vai exibir o endereço, geralmente no canto inferior esquerdo da página, quando se coloca o mouse em cima do mesmo. Para não aparecer só usando alguma outra tag ou não usando o atributo `href`, porém seria necessário usar `javascript` para isso, o que faz com que isto não seja muito prático.
Answer: Isto não é possível ser feito apenas usando puro HTML, mas sim isto é possível ser feito usando JavaScript da seguinte maneira:
Ir para a página

$("#anchorID").click(function() {
    window.open(
    'http://www.google.com',
    '_blank' // <- Isto faz o link ser aberto numa nova janela.
    );
});

#anchorID{cursor:pointer;}

Eis um exemplo online no jsFiddle - http://jsfiddle.net/fummw6wp/1


How to display webform results under the webform with contextual filters?

Question: I created a view listing webform fields
New View » Webform Submissions » Unformatted list of Rendered submissions
It gives me all the submitted data of all the webforms of the website.
I'm looking for a way to have under each webform its results.
So when i visit : website.com/webform/id678
under the form, i would like to have a block showing the previously submitted data i'll be using a pager to only display the 5 latest submissions and be able to browse through submissions if i want to.
This is possible with the contextual filter of Views but i can't seem to figure out how to configure it correctly
thanks
I'm using Drupal 7.56 and webform 4.16
Answer: 1. create a views block display of your view
configure the view as you wish
but you have to add contextual filter by content:nid as shown below with setting: raw value from URL, path compoment 2

We have to specify validation criteria content: webform as shown below

2. add the views block in a block region
Now if you visit a webform will show under it the relevant submissions
Comment: Wonderful! Exactly what i needed. Drupal is amazing and the community is even better. Thanks


Is there an "algorithm" for the time duration of a repeating rhythm?

Question: Is there a way to determine the amount of additional rest time required after a rhythmic figure in order to ensure that the entire phrase loops seamlessly within a defined time signature? I want to measure the amount of time in seconds.
For example, I used a stopwatch to tap a rhythm. I measured how much time separated each tap (and I assumed the taps themselves don't consume any time). I did this twice: the first time, I included a rest at the end of the phrase. The second time, I didn't include a rest at the end of the phrase. The following numbers give the duration (in seconds) between successive taps. For example, the first item, "1. (tap) 0.274," indicates that the amount of time between the first tap and the second tap is 0.274 seconds. Here's scenario 1, which includes the final rest at the end of the phrase:

(tap) 0.274 s
(tap) 0.257 s
(tap) 0.262 s
(tap) 0.249 s
(tap) 0.468 s
(tap) 0.504 s
(tap) 0.237 s
(tap) 0.251 s
(tap) 0.466 s
(tap) 0.978 s

There were 10 taps in this rhythm, as shown. After completing duration no. 10, the rhythm would start again, so that the 11th tap would be the start of the second loop. The total time for this phrase is 3.946 seconds. The number of taps per minute is 167.26.
However, if I were to remove the final 0.978 s duration after the 10th tap, (scenario 2), then the total time for the phrase is 2.968 s, and the number of taps per minute is 202.16. In this second instance, the loop would rush into the beginning and would eventually sound like another rhythm. In other words, the loop was too short when I skipped this final 0.978 s duration.
I am trying to understand how would someone take scenario 2 and determine from the values that, in order to have a seamless loop, they would need an extra duration of 0.978 seconds at the end. How can this be determined? This is a 4/4 rhythm.
Comment: In your "scenario 2" you can add any number of "beats" you like as a rest at the end of the pattern. For example I'm currently working on a 20th-century "classical" piece where most of the music is in alternating "bars" with 23 and 15 beats! You can't "determine mathematically" how the music is *intended* to sound. There are even pieces which have a fraction of a beat at the end of each bar (e.g. 2 beats + 2/3 of a beat per bar - though you could think of that as "8 beats divided into 3+3+2".)
Comment: I don't really understand what you are trying to do, but it looks to me as if your "beats" 5 6 and 9 are really two beats each, and "beat" 10 is four, which gives a 16-beat pattern. Also, if you use free software like Audacity (or many other alternatives) you can measure the "beats" much more consistently than by "using a stop watch".
Comment: Before understanding rhythm and beats in a mathematical way, have you made sure you understand them very well in a musical way? Can you tell us what time signature the example rhythm could be in? Is it a 4/4 rhythm or 6/8 or what? Understand the musical aspects of rhythm will make the mathematical aspects much easier.
Comment: Sigh -__-. I had a feeling that my question was a mess. I do apologise for this.  I'm trying to understand rest times in a mathematical way. For example, in software like FL studios where the user plays a beat and presses play to hear it back, the software plays back a loop of the user's rhythm. The software would have looked at factors from that rhythm -including rest times- to know how to playback that rhythm in a loop. Even if the user's input was rhythmless, the playback would still be a loop of that input. i'm trying to figure out how the software does that. Does this make better sense?
Comment: I feel that I do understand in a musical way. Although, of course, please let me know what else I am missing in question. It would be 4/4
Comment: So what you really need to do is algorithmically determine two "hits" that are on the beat, calculate the time between those two hits, and then multiply that time by four to get the length of time for a measure.
Comment: @ToddWilcox I will admit that I do not quite understand what you mean by two hits on a single beat. Would you be able to explain that for me, please?
Comment: Also, @alephzero  thank you for pointing out at the pattern. Although I don't quite know what to do with the information, it does help my  understanding.
Comment: Not on a single beat. On adjacent beats. So a hit on beat 1 and a hit on beat 2 are separated from each other by 1/4 of the amount of time that an entire measure should last (in 4/4 time).
Comment: @Madra, I've edited your post to improve clarity. You were using the word ["beat"](https://en.wikipedia.org/wiki/Beat_(music)) when referring to a "tap." I've fixed this, because a "beat" refers to something else. Please check to confirm that the post is still accurate and is true to your original question and idea. The only content I changed is that there are 10 taps in the phrase (not 11). I believe the 11th tap is the start of the second loop. See my answer below for an example of how this calculation can be done.
Comment: I think you are vastly overcomplicating this by looking at rhythms strictly as units of time instead of as abstract divisions of a measure with limits defined by a metre. Your example rhythm is an exceedingly simple phrase when expressed in abstract terms; it can be expressed as two bars of 4/4 and would be expected to repeat because it fills two bars succinctly and two bar phrases are common. Sure, you could express that in entirely absolute terms but it's much easier (and much more useful) to figure it out musically. In short: Investigate some musical literature on basic rhytm and phrasing.
Comment: @Fugu, I can see why it looks like I'm over complicating things, but I wouldn't use this in a scenario where I was playing an actual instrument. In that case, I would use my ear. I wanted this understanding for cases like music production software where a beat is an important component of the production. Specifically, using Sonic Pi the user is expected to calculate the "sleep" times to create beats. I kept having issues figuring how much time was need after a sequence to sound right. I hope I'm making sense.
Comment: Sure, but the process of going from abstract musical values to concrete units of time is fairly simple from a mathematical perspective. Determining how long a quarter note lasts at a given tempo is merely a matter of arithmetic. You would be hard-pressed, however, to make the logic of rhythm presentable using absolute values.
Comment: You might want to look at the autocorrelation algorithm. With autocorrelation, you sucessively shift a "signal" (in this case time stamps of beats) by some small amount of time (the "hop size"). When the correlation value starts to exceed some threshold (where 1.0 is a perfect correlation), you can assume that the beats have folded back on themselves and can establish a periodicity of the music. With that you can make a good guess at the BPM which I think would allow you to make your loop seamless.
Answer: General Method
There is a way to figure it out. First, let's establish the fundamental unit of your rhythm. 1, 2, 3, 4, 7, and 8 all have the duration of one fundamental unit. This fundamental unit is called a "beat." So duration 5, duration 6, and duration 9 all last two beats each. Duration 10 lasts four beats.
Using this as the fundamental unit, one beat lasts 0.25±0.01 s. (±0.01 s is the standard deviation based on the fluctuation in your counting of the fundamental unit.) If we have 0.25s/beat, we can take the reciprocal to get:

So your pattern has a tempo of 240 bpm. Since we're working in 4/4 time, each beat is a quarter note (that's what the denominator of 4/4 indicates). Here's your rhythm:

Using this example as a guide, here's the general approach:

determine the key signature (X/Y, e.g., 3/4)
determine the duration of one beat (Y represents the duration of a beat; normally we refer to the duration as a quarter note or eighth note, but you're referring to it as an amount of time in seconds)
multiply the beat duration (Y) by the number of beats (X) to get the time duration of a single measure--the duration that you must repeat/loop
optional: multiply the value from step 3 by 4, because music is often written in 4-bar phrases

First Example
For example, in your case, we would have:

the key signature is 4/4
one beat lasts for a time duration of 0.25 s
multiplying 0.25 s by 4, we get 1.0 s as the time duration of one measure
optional: multiplying the value from step 3 (1.0 s) by 4 gives 4.0 s

And so, in your example, each phrase that you loop must be 4.0 s long. (This assumes you'll be using a 4-bar phrase, which is true in the case of the example you provided.) When we add up the duration of 1-10, we get a total of 3.946 s, which almost perfectly matches are ideal value of 4.0 s. In the second case you describe, the time is only 2.968 s, which means you need to add a final 1.032 s of "rest" to bring the total phrase up to 4.0 s (2.968 s + 1.032 s = 4.000 s.) This additional "rest" duration of 1.032 s is almost exactly the same as the value you found to work: 0.978 s. The difference is simply a result of imprecision.

Second Example
Here's a second way to do the calculation. Let's say you have these values, and we're working in a 4/4 time signature again:

(tap) 0.173 s ≈ 0.2 s
(tap) 0.182 s ≈ 0.2 s
(tap) 0.390 s ≈ 0.4 s
(tap) 0.599 s ≈ 0.6 s
(tap) 0.397 s ≈ 0.4 s
(tap) 0.186 s ≈ 0.2 s
(tap) 0.425 s ≈ 0.4 s

You can see I've rounded the values. The reason is that it's extremely reasonable for the taps to be off by ~0.03 s. All of the original values above are all within that tolerance, and so it's fine to standardize the numbers by rounding to the nearest tenth of a second.
As we can see from the list above, the smallest unit (the duration of 1 beat) is 0.2 s. Let's convert each time (above) into a number of beats. We divide every time value by the duration of 1 beat to get the number of beats that each tap counts for:

(tap) 0.2 s / 0.2 s = 1 beat(s)
(tap) 0.2 s / 0.2 s = 1 beat(s)
(tap) 0.4 s / 0.2 s = 2 beat(s)
(tap) 0.6 s / 0.2 s = 3 beat(s)
(tap) 0.4 s / 0.2 s = 2 beat(s)
(tap) 0.2 s / 0.2 s = 1 beat(s)
(tap) 0.4 s / 0.2 s = 2 beat(s)

Adding up all of the beats gives a total of 12 beats. In 4/4 time, one measure contains 4 quarter-note beats, or four 0.2-s-long beats. So 12 beats would be 3 measures, and 16 beats would be 4 measures. To extend the current phrase to a 4-bar phrase, you need to add 4 more beats, each of which would last 0.2 s. So the time you need to add is 4 x 0.2 s = 0.8 s. This might sound even more natural. Here's what that could look like:

(tap) 0.2 s / 0.2 s = 1 beat(s)
(tap) 0.2 s / 0.2 s = 1 beat(s)
(tap) 0.4 s / 0.2 s = 2 beat(s)
(tap) 0.6 s / 0.2 s = 3 beat(s)
(tap) 0.4 s / 0.2 s = 2 beat(s)
(tap) 0.2 s / 0.2 s = 1 beat(s)
(tap) 0.4 s / 0.2 s = 2 beat(s)
(tap) 0.4 s / 0.2 s = 2 beat(s)
(tap) 0.4 s / 0.2 s = 2 beat(s)

or

(tap) 0.2 s / 0.2 s = 1 beat(s)
(tap) 0.2 s / 0.2 s = 1 beat(s)
(tap) 0.4 s / 0.2 s = 2 beat(s)
(tap) 0.6 s / 0.2 s = 3 beat(s)
(tap) 0.4 s / 0.2 s = 2 beat(s)
(tap) 0.2 s / 0.2 s = 1 beat(s)
(tap) 0.4 s / 0.2 s = 2 beat(s)
(tap) 0.2 s / 0.2 s = 1 beat(s)
(tap) 0.2 s / 0.2 s = 1 beat(s)
(tap) 0.4 s / 0.2 s = 2 beat(s)

where the added portion has been bolded.
Comment: Thank you for cleaning up my question. You were right to replace beat with tap. I have been going through your explanation and am trying to make a single formula out of it - let me know what you think. 1. get the mean of the rest times - this will be the duration of one beat ±1, 2. multiply this value by the number of beats, 3. i.e. for 3/4 you multiply by 3 and for 2/4 by 2. How does this look?
Comment: I feel silly to still be asking questions even after such a thorough explanation. However, when I attempt to apply it to a different rhythm and test it out in some software (Sonic Pi), it just doesn't seem to sound right. Is it possible for you to do the example as mathematical solution so that each line of your explanation is working out the scenario in maths? Please let me know if this is pushing it, thanks
Comment: @Madra, I've tried to make the edit you requested. See the 4 steps at the bottom of my answer. Would you post the new beats in a comment?
Comment: Thank you for taking the time to explain further. These are the new taps:
1: 0.173
2: 0.182
3: 0.390
4: 0.599
5: 0.397
6: 0.186
7: 0.425
4/4 time signature again, total time 2.352, 8 taps, approx 11 beats (Can't tell if I should count the 0.599 as 2 or 3 beats) and 7 "rests", they have a bpm of 204. Mean 2.352/11, 0.21*4 = 0.84 or 0.8. It sounds good. I'm going to keep trying it out. Thank you very much for your help
Comment: @Madra, I've edited my answer above to include this second example. I would round the time values to: 0.2, 0.2, 0.4, 0.6, 0.4, 0.2, 0.4. The smallest unit is 0.2 s. So the first duration lasts 1 beat, the second duration lasts 1 beat, the third duration lasts 2 beats, etc. We can rewrite it this way: 1 beat, 1 beat, 2 beats, 3 beats, 2 beats, 1 beat, 2 beats. This adds to 12 beats total, which is 3 measures in 4/4 time. If you want 4 measures in 4/4 time, then you need 16 beats total, so you must add 4 more beats, or 4 x 0.2 = 0.8 s of time. I've edited this solution into my answer, above.
Comment: Thank you. I am also realising that another reason things didn't sound right is because I am automatically assuming that all the rhythms are 4/4, when this won't always be the case. I will need to look into finding a way to calculate what the time signature is for rhythm that way when it comes to the last step (multiplying), I am multiplying by the correct number.
Comment: @Madra, that's trickier, because you can't determine how long a measure lasts until you know the time signature. So the correct length of the phrase will be indeterminate until you decide upon a time signature. My recommendation is to tap out the rhythm and count along. If you find yourself counting "1 2 3 1 2 3" then you've got 3/4 time. If you find yourself counting "1 2 3 4 1 2 3 4" then you've got 4/4 time. Or you could decide, at the onset, to compose a song in 3/4 vs. 4/4.


C++ inherited operator '<<' on templated class

Question: I have the following C++ code, which demonstrate my problem.
My goal is to override the stream operator in inherited class in order to allow me to print specific stream depending on object type:
#include <iostream>
#include <unordered_set>

using namespace std;

template <typename T>
class Base {
    public:
        Base(){}
        Base(T n): value_(n){}

        friend inline ostream &operator<<(ostream &os, const Base &b) {
            b.to_str(os);
            return os;
        }

    protected:

        T value_;

        // All object should implement this function
        virtual void to_str(ostream& os) const {
            os << value_;
        }
};

template <typename T>
class Child: public Base<T> {
    public:
        Child(T n): Base<T>(n){}

    protected:
        void to_str(ostream& os) const override {
         os << "{";
            for (auto v = this->value_.begin(); v != this->value_.end(); v++) {
                if(v != this->value_.begin())
                    os << ",";
                os << (*v);
            }
            os << "}";
        }
};

int main()
{
    Base<string> b("base");
    Child<unordered_set<string>> c({"child"});
    cout << "b: " << b << endl;
    cout << "c: " << c << endl;

    return 0;
}

For now the code is not compiling:

main.cpp:31:16: error: no match for 'operator<<' (operand types are
'std::ostream {aka std::basic_ostream}' and 'const std::unordered_set
>')

It seem that the virtual method to_str() from base is used by the compiler instead of the overrided one for the Child class.
If I comment the body of the base to_str() function then it compile and print the correct result for unordered_set Child class but then it print nothing with the base implementation.
So the override is working, but why it do not compile when base to_str() have a body?
How can I force the compiler to use the one from the derived one (Child)?
Regards
Comment: It will always use the `Child` version of `to_str()`. But the comiler still wants to generate the function `Base::to_string()` for `std::unordered_set` which is reasonable as it can still potentially be called (and the address is needed during the construction of Base to correctly build the V-Table (assuming the implementation uses V-Tables). A solution is to make `to_str()` pure virtual in the Base. Then have to derived implementation for Child and a new class StandardStremable.
Comment: You didn't copy your error message properly.  There are pieces missing.
Comment: @MartinYork Thank you for your hint, was thinking about a solution like the one you propose. I will post the modified code.
Answer: The base to_str gets compiled even if it is never run.
So
    virtual void to_str(ostream& os) const {
        os << value_;
    }

fails to compile.
When you create a type with a vtable, its entries are (well, I believe the standard says "can be") populated even if they aren't called.  This is different than a "normal" template class, where unused methods have thier bodies "skipped".
It is possible you want the CRTP for compile-time polymorphism.
template <class T, class D_in=void>
class Base {
    using D=std::conditional_t< std::is_same<D_in,void>{}, Base, D_in >;
    public:
        Base(){}
        Base(T n): value_(n){}

        friend inline ostream &operator<<(ostream &os, const Base &b) {
            static_cast<D const&>(b).to_str(os);
            return os;
        }

    protected:

        T value_;

        // All object should implement this function
        void to_str(ostream& os) const {
            os << value_;
        }
};

template <typename T>
class Child: public Base<T, Child<T>> {
    friend class Base<T, Child<T>>;
    public:
        Child(T n): Base<T>(n){}

    protected:
        void to_str(ostream& os) const {
         os << "{";
            for (auto v = this->value_.begin(); v != this->value_.end(); v++) {
                if(v != this->value_.begin())
                    os << ",";
                os << (*v);
            }
            os << "}";
        }
};

or somesuch.
Comment: Whaoo good to know that this exist!!! I will implment the pure virtual solution since it seem more clear to me. Thank you anyway
Answer: The virtual call actually does happen.  You can see that by changing the code to
template <typename T>
class Base {
    public:
        Base(){}
        Base(T n): value_(n){}

        friend inline ostream &operator<<(ostream &os, const Base &b) {
            b.to_str(os);
            return os;
        }

    protected:

        T value_;

        virtual void to_str(ostream& os) const = 0;
};

template <typename T>
class Child: public Base<T> {
    public:
        Child(T n): Base<T>(n){}

    protected:
        void to_str(ostream& os) const override {
         os << "{";
            for (auto v = this->value_.begin(); v != this->value_.end(); v++) {
                if(v != this->value_.begin())
                    os << ",";
                os << (*v);
            }
            os << "}";
        }
};

int main()
{
    Child<unordered_set<string>> c({"child"});
    cout << "c: " << c << endl;
    return 0;
}

What is actually happening is that in Base the compiler is going to stamp out
Base<unordered_set<string>>::to_str

and that function is invalid since os << value_ is not defined.  As you can see you need to either make it pure virtual, or put in a stub that will compile no matter what value_ is.
Comment: Thank you for your answer, I will post a solution with pure virtual implementation
Answer: This is what I finally implemented by using the "pure virtual solution",
Tested with some more basic type:
#include <iostream>
#include <unordered_set>

using namespace std;

template <typename T>
class Base_ {

    public:
        Base_(){}
        Base_(T n): value_(n){}

        friend inline ostream &operator<<(ostream &os, const Base_ &b) {
            b.to_str(os);
            return os;
        }

    protected:
        T value_;

        // All object should implement this function
        virtual void to_str(ostream& os) const = 0;
};

template <typename T>
class Base: public Base_<T> {
    public:
        Base(){}
        Base(T n): Base_<T>(n){}

    protected:

        // All object should implement this function
        void to_str(ostream& os) const override {
            os << this->value_;
        }
};

template <typename T>
class Child: public Base_<T> {
    public:
        Child(T n): Base_<T>(n){}

    protected:
        void to_str(ostream& os) const override {
         os << "{";
            for (auto v = this->value_.begin(); v != this->value_.end(); v++) {
                if(v != this->value_.begin())
                    os << ",";
                os << (*v);
            }
            os << "}";
        }
};

template <typename T>
class Boolean: public Base_<T> {
    public:
        Boolean(T n): Base_<T>(n){}

    protected:
        void to_str(ostream& os) const override {
         os << (this->value_ ? "true" : "false");
        }
};

int main()
{
    Base<string> s("string");
    Base<int> i(42);
    Boolean<bool> b(true);
    Child<unordered_set<string>> u({"child1", "child2"});
    cout << "s: " << s << endl;
    cout << "i: " << i << endl;
    cout << "b: " << b << endl;
    cout << "u: " << u << endl;

    return 0;
}

Result:

s: string
  i: 42
  b: true
  u: {child2,child1}


django send_mail with SMTP backend cannot send out email

Question: I am deploying a Django project on an ubuntu stack with a postfix SMTP mail server, hosted on Amazon's EC2. I can send out email from the server using the Linux mail program. But when I try to send email using django.core.mail.send_mail, the email is never received.
Here are my settings:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
I left everything else as default.
I tried
python manage.py shell
Then in the shell, I did
from django.core.mail import *
send_mail(
    'TEST',
    'THIS IS A TEST',
    'email@example.com',
    ['firstname.lastname@example.com'],
    fail_silently=False,
    )

This returns 1, but I never received any message at the destination ('firstname.lastname@example.com' in the example).
Is there a tutorial on how to configure a SMTP server to work with Django's mail system? Thanks.
Comment: I assume that you did specify your EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER and EMAIL_HOST_PASSWORD in your settings.py right? And for the email port, you did open your port for smtp under ec2's security group? Smtp port usually defaults to 25     if you left it as default during your postfix configuration.
Answer: I assume that you did specify your EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER and EMAIL_HOST_PASSWORD in your settings.py right?
A detailed explanation of how the default django.core.mail.backends.smtp.EmailBackend works is explained -
https://docs.djangoproject.com/en/dev/topics/email/
https://docs.djangoproject.com/en/dev/topics/email/#smtp-backend
And specifically for your email port, you did open your port for smtp under EC2's security group? SMTP port usually defaults to 25 if you left it as default during your postfix configuration and it is important that you have opened up that port when you created your EC2 instance.


Increasing the number of sides of a polygon by $k$ increases the number of diagonals by $6k$

Question: For reference:

In a certain polygon when increasing the number of sides in $k$, the number of diagonals increases by $6k$. How many polygons meet this condition? (Answer: $5$)

My progress:
$\frac{n(n-3)}{2}+ 6k = \frac{(n+k)(n+k-3)}{2}\rightarrow\\
{\frac{n^2}{2}}-{\frac{3n}{2}}+6k = \frac{k^2}{2}+kn-\frac{3k}{2}+{\frac{n^2}{2}}-{\frac{3n}{2}}\rightarrow\\
\frac{k^2}{2}+kn-\frac{15k}{2}\rightarrow{k = 0} ~or ~k =15 -2n \implies n = \frac{15-k}{2}\\
n \ is \ integer \geq3 \therefore n={7, 6, 5, 4, 3}\rightarrow 5~polygons$
Is my resolution correct?
Comment: Looks correct to me.
Answer: $\frac{n(n-3)}{2}+ 6k = \frac{(n+k)(n+k-3)}{2}\rightarrow\\
{\frac{n^2}{2}}-{\frac{3n}{2}}+6k = \frac{k^2}{2}+kn-\frac{3k}{2}+{\frac{n^2}{2}}-{\frac{3n}{2}}\rightarrow\\
\frac{k^2}{2}+kn-\frac{15k}{2}\rightarrow{k = 0} ~or ~k =15 -2n \implies n = \frac{15-k}{2}\\
n \ is \ integer \geq3 \therefore n={7, 6, 5, 4, 3}\rightarrow 5~polygons$


Erro ao instalar React

Question: Estou tentando instalar reagir mas quando eu digito o comando:

npm install -g criar-reagir-app

ele me retorna um erro Por favor me ajude a entender o motivo que eu recebo esse erro
Comment: Você tem o NPM instalado? O comando não seria `npm install -g create-react-app`? Ajudaria se você postasse qual erro está recebendo.
Comment: Seu comando está em português
Answer: O comando que você digitou está em português, tente novamente, porém em inglês:
<code>npm i -g create-react-app
</code>

Erro ao instalar React


Mostrar fotografia de um listbox item dá me erro Out Of Memory

Question: Estou a fazer uma ferramenta que transforma uma foto feita upload pelo utilizador em bytes array depois compara esses bites com as fotos existentes na base de dados
Consegui fazer o código funcionar mas quando no fim ele detectou alguma igual ou parecida então mostra essa do utilizado no picturebox1 e a encontrada na base de dados que neste caso e inserida em uma listbox quando o programa faz load.
Quando termina a operação depois de encontrar um match ele dá me erro.
O meu erro é:

Out Of Memory esta na função timer1

O meu código é:
Public Class Form3
Dim totalbytes As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Using fo As New OpenFileDialog
        If fo.ShowDialog = DialogResult.OK Then
            Dim fs As New IO.FileStream(fo.FileName, IO.FileMode.Open)
            Dim br As New IO.BinaryReader(fs)
            Dim byteArea As Byte()
            byteArea = br.ReadBytes(CInt(fs.Length))
            totalbytes = fs.Length
            br.Close()
            'just to show the sample without a fileread error
            'be aware not to use a dispose or using here
            'it gives a GDI+ error as the stream (not the name) is reused.
            Dim ms As New IO.MemoryStream(byteArea)
            PictureBox1.Image = Image.FromStream(ms)
        End If
    End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim byteArea As Byte()
    Using msX As New IO.MemoryStream
        PictureBox1.Image.Save(msX, Imaging.ImageFormat.Bmp)
        byteArea = msX.ToArray()
    End Using
    Using ms2 As New IO.MemoryStream(byteArea)
        Me.PictureBox2.Image = Image.FromStream(ms2)
    End Using
    Me.PictureBox1.Image = Nothing
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim finfo As New IO.DirectoryInfo("C:\flora")
    For Each fi In finfo.GetFiles
        ListBox1.Items.Add(fi.FullName)
    Next
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    ListBox1.SelectedIndex = Me.ListBox1.SelectedIndex + 1

    ''PictureBox1.Image = Image.FromFile(Me.ListBox1.SelectedItem.ToString())
    Dim ffs As New IO.FileStream(ListBox1.SelectedItem, IO.FileMode.Open)
    Dim bbr As New IO.BinaryReader(ffs)
    Dim byteArea As Byte()
    byteArea = bbr.ReadBytes(CInt(ffs.Length))
    If ffs.Length = totalbytes Then
        Timer1.Stop()
        Dim pict2 As String = ListBox1.SelectedItem.ToString
        PictureBox2.Image = Image.FromFile(pict2)

        MsgBox("Resultados Encontrado " + ListBox1.SelectedItem)

    End If

    ''MessageBox.Show(fs.Length)
    bbr.Close()
    'just to show the sample without a fileread error
    'be aware not to use a dispose or using here
    'it gives a GDI+ error as the stream (not the name) is reused.
    Dim ms As New IO.MemoryStream(byteArea)
    PictureBox1.Image = Image.FromStream(ms)

    ''MessageBox.Show(ms.ReadByte)

    ListBox1.SelectedIndex = Me.ListBox1.SelectedIndex + 1
End Sub
End Class

Answer: O código não está liberando o fs, nem o ms, embora este último não sei se poderia. Não há garantia que o br será liberado assim. Tem outras variáveis que seguram objetos mais que o necessário. E pelo que dá para ver no código pode ter outros problemas em outros pontos.
Se sabe usar o Using, conforme mostrado no código, faça uso dele para resolver estes problemas. Se o problema persistir tem problemas em outras partes.


"Invalid Signature, code object not signed at all" error

Question: I've been browsing Stack for hours in an attempt to try and fix this error, and I've tried everything I can find/think of. I'm submitting an update to an existing app to the App Store, and upon submitting my build, I keep receiving this error:

Invalid signature. Code object is not signed at all. Make sure you
  have signed your application with a distribution certificate, not an
  ad hoc certificate or a development certificate. Verify that the code
  signing settings in Xcode are correct at the target level (which
  override any values at the project level. Additionally, make sure the
  bundle you are uploading was built using a Release target in Xcode,
  not a simulator target.

My app is undoubtedly signed with a distribution certificate, the correct provisioning profile is installed and selected, the profile contains the correct certificate, I've deleted the profile and created a new one in attempt to fix the error, I've reinstalled certificates, restarted Xcode... cleaned the project multiple times, even restarted my system; I'm stumped.
Also: When I do attempt to export the build, even though I've selected to use my provisioning profile and it appears to build with my selected profile, it says it's using "XC [Name of my Profile Here]" provisioning profile. When I check the portal, there's now the profile I created, and a separate profile with the same title with the XC in front of it. Even once I delete this profile on the developer portal, it's recreated? Could this be causing the submission error?
Please help.
Comment: I hit into a similar issue and the first solution in this question solved it for me: http://stackoverflow.com/questions/29788601/error-itms-90035-xcode   Any form of executable script (.sh, .py etc) can cause the issue. In my case I had a few python scripts that were causing the error.
Comment: Do you make use of any third party libraries? It also had issues with files that were contained within third party libraries that I was using.
Comment: @IainMcManus There are no .sh or .py files in my Copy Bundle Resources :/ Though I did upgrade Xcode recently. Not sure why it's giving me grief all of a sudden O_O
Comment: @Brittany Have you fix this? What was your solution? Thanks
Comment: @LiborZapletal I have yet to fix this problem (I needed to fix it to submit an app update to the app store, I have yet to do so lol). I built my app prior to iOS8 (not sure why the store is giving me a hard time with submitting the update, or if that has anything to do with it) - if you stumble across a fix, let me know.
Comment: Hey I had the same issue. I found ended up working around it. I posted the details here
Answer: Here is the way I found a script file in the app which caused the error:

Archive the app
Open the archive folder from terminal
Execute the following command grep -r '#!/' *
Review all the files which are returned from the command
Delete all the scripts from Copy Bundle Resources build phase
Profit
Comment: This has helped me identify my issue. All the faulty files belonged to a cocoapod that I wasn't supposed to be shipping to production, so I disabled it :)
Comment: Review all the files means ? There are some couple of files returned from the command.
Answer: I had the same issue. In my case I am including my own frameworks, which has some script files, I removed those script files from the frameworks targets, and the issue went away.
Answer: Now-a-days Xcode has a "Show Log" button.

Tap that and it'll shine some light on the offending framework / script.

In my case, I sometimes forget to remove some debugging Frameworks before making my production build.
Comment: That was my case. I forgot to set Release type for Archive scheme (it was set to Debug)
Answer: This issue occurred for me when one of my Cocoapods incorrectly specified the resources in it's podspec so that scripts were inappropriately included.
Updating the suspected podspec to only include resource file types resolved the issue. In this case, I added xcassets to the spec.
s.resources = '<path>/**/*.xcassets'