Qual mais seguro, aplicação Web ou Web API?

Question: Tenho um projeto no qual haverá uma web API para se "comunicar" com aplicativos moveis. Este, só é para consulta. Além deste, haverá a administração no qual se resume na inclusão dos dados.
A dúvida seria na parte da administração, é mais seguro utilizar uma aplicação web com acesso "direto" com o BD ou, utilizar os recursos da web API? Levando em conta a segurança necessária aplicada em ambos os casos.
Comment: Nenhum dos dois, Sua aplicação web pode acessar uma api e ainda assim não ser segura da mesma forma ** "direto" com o BD **, você precisar entender o conceito de web e api, e segurança que é algo bem diferente. você precisa implementar a segurança nos dois casos.
Comment: Agradeço a atenção, em questão de segurança, sou o básico do básico. Mas refazendo a pergunta, neste ambiente que citei, o que você recomendaria ? Utilizar a API para todas as operações (CRUD) ou compartilhar estas operações (consulta) com um aplicação web (CRUD) com acesso direto ao BD ?
Comment: Recomendaria o uso do DDD, em qualquer que seja a aplicação.
Answer: Aquele que for bem feito e por alguém que entenda de segurança. Ou seja, qualquer um dos dois, se for bem feito.
Se qualquer uma delas tivesse menos segurança nem deveria usar. Se encontrar algum problema de segurança deveria ser um bug a ser corrigido.
Se não entender o que está fazendo e todas as implicações de tudo o que faz então ambos são inseguros, não porque eles foram construídos assim, mas porque quem fez não tem condições de fazer ser seguro.
A insegurança é explorada por pessoas quem entendem muito do que fazem contra o que foi feito por pessoas que entendem pouco ou nada.
E para aprender o que faz não é aprender receitas de bolo, é aprender todos os fundamentos com profundidade, só assim entenderá tudo o que pode ocorrer e mitigá-los. Ou seja, para fazer seguro tem que conhecer tanto quandt quem explora as falhas de segurança.
Se tem uma área que não dá para fingir que sabe, que não dá para seguir receitas é a segurança, até porque as maiores inseguranças ainda não possuem receitas.
Claro, a maioria dos sistemas, principalmente web, são extremamente vulneráveis porque são feitos porque sequer tem noção do básico e cometem erros bem básicos já solucionados há décadas.
Quando os sistemas não eram web eram mais seguros pelo simples fato que poucas pessoas podiam acessar. Agora todo mundo pode, não pode confiar em nada externo, tem que se proteger de tudo o que se conhece e o que não conhece. E hoje se tem a ideia de que qualquer pessoa pode programar, quando na verdade ficou muito mais difícil. Por isso hoje a esmagadora maioria das aplicações são inseguras e vulneráveis e a vasta maioria dos servidores estão ou estarão operando à serviço de crackers, alguns por anos ou décadas sem a pessoa saber.
Se levar em conta que o programador fez tudo direito, ambas são seguras iguais.
Mesmo que uma fosse mais segura, de que adianta usá-la se o que precisa usar é a outra?
Eu não recomendaria o uso de DDD em nenhuma aplicação. A não ser, é claro, se ela for muito adequada para aquela aplicação, você dominar totalmente o assunto, e tenha uma boa implementação dela (e vou dar uma dica, nem o criador do termo fez uma boa, o que gera atrocidades). Não sei o que isso faz aqui, mas achei melhor não passar em branco sobre esse mito, e que de alguma forma isso ajudaria a segurança, pelo contrário, pelo que vejo por aí as pessoas aplicando DDD errado, criando mecanismos próprios duvidosos para substituir o que já existe que é considerado como seguro, a segurança só tende a piorar, ainda mais porque as pessoas não enxergam que está ocorrendo. Na verdade qualquer coisa que seja aplicada em tudo já está errado por definição. Até os maiores defensores de DDD não o usam em tudo.
Um exemplo de como as pessoas não entendem de segurança é que votaram para fechar a pergunta como baseado em opiniões. Segurança existe ou não existe. É mensurável e mesmo sem medir é de conhecimento público sobre a condição das tecnologias, e os inerentemente inseguros são considerados obsoletos e só usa quem não lê documentação (o que poucos fazem, e não nem pra começar conversar sobre segurança com quem faz isto, uns 80, 90%). Ok, eu entendo que alguém pode ter votado por algum tipo de bias ou desatenção, mas é importante saber disso também.
Resumo
Ambos são seguros, segurança é dada pela qualidade do programador, use o que atende sua necessidade, e se proponha ser um profissional completo ou passe para quem pode ajudar na questão e não compre mitos. Aceite que não entende de segurança, é o que eu faço, e pesquise para pelo menos não cometer os erros básicos que a maioria faz e nem percebe.
Os que entendem isso e agem de acordo fazem sistemas mais seguros, os que acham que fazem sistemas seguros sem observar isso estão se iludindo, e muita gente experiente faz assim.
Espero que aproveite bem as dicas.
Comment: Novamente, agradeço a explicação. Optei por dividir as operações entre a aplicação web e a web api para não ficar "todos os ovos na mesma cesta".


communicating vessel formulas

Question: i having trouble with this formula
$$
Z1(t) = Ze+(\sqrt{Z1-Ze}-\frac{2S0}{S1}\sqrt{2g(1+\frac{S1}{S2})}.t)²
$$
Z1 and Z2 are the heights of the vessels.
S1 and S2 are the sections of the vessels.
S0 is the section of the tube between them (for the exchange).
Ze is the final height of the two vessels.
Z1(t) is the height at t
but i only get incorrect values and don't know if the formula is wrong of if its me.
for testing is use Z1 = 45
Z2 = 5
S0=2$\pi$0.3=1.884
S1=2$\pi$10=62.8
S2=2$\pi$10=62.8
$Ze = \frac {S1.Z1 + S2.Z2} {S1+S2}=\frac {62.8.45 + 62.8.5} {62.8+62.8}=25$
thanks
Comment: If you're wondering whether this is the right formula, I think the right place for this would be physics.SE. If you're wondering whether you're doing something wrong in substituting values, then you'll need to give us some of your results, since so far there's nothing for us to check in what you've written.
Comment: If by the period in the formula you mean multiplication, then this formula must be wrong, since it would make the height go off to infinity, whereas what one would expect would be some form of oscillation around the equilibrium value $Z_e$.
Comment: @joriki, didn't know physics.Se, i ll ask there . In fact i found this formula on a site and the notice isn't very clear  :  http://www.univ-lemans.fr/enseignements/physique/02/divers/vasescom.html , it's in french
Comment: First of all, there isn't any $Z_2$ in your formula for $Z_1(t)$, so what difference does the value of $Z_2$ make? Second, your computation of $Z_e$ seems to depend on a formula you haven't given us. Third, you haven't told us what $t$ is, so how can we figure out any values of $Z_1(t)$? And fourth, how do you know that you are getting incorrect values? Do you have some independent way of getting correct values? What is it? You have to do a lot of work on the presentation to turn this into a question anyone can help you with.
Answer: I'm thinking S0, S1, and S2 should be the cross sectional areas of the connecting tube and the two cylinders.  The calculation above seems to be calculating the circumferences of the cylinders and connecting tube.
Comment: Indeed, it's the $S$ of [superficies](http://en.wiktionary.org/wiki/superficies#Latin).
Comment: Thanks ,here the result : http://www.wolframalpha.com/input/?i=plot+25%2B%28Sqrt%5B45-25%5D-%282Pi0.3%C2%B2%29%2F%28Pi10%C2%B2%29Sqrt%5B2*980%281%2B1%29%5Dt%29%C2%B2+from+0+to+37

communicating vessel formulas


What is the color number of the 3D space, if we allow only convex regions?

Question: I am thinking on the analogy of the well-known 2D coloring problem for the 3D space (with the trivial geometry & topology).
As this reference says, simply increasing the dimensions by one doesn't work. It would elevate the color number to infinite, because:

In this case, however, once you go to three dimensions, you can make
partitions of space into regions for which you need N colors to color
the regions in order that no two adjacent regions will have  the same
color for any N.
You can make an example by starting with one ball.
Now, add a ball to the picture and connect it with a thin tube to the
first ball.
Now, add a third ball to the picture and connect this ball with two
thin tubes to the two balls already in the picture.
You can keep adding balls and connecting them to all the other balls
like this because there is enough space in three dimensions to work
with.
If the balls represent regions, since each ball is touching every
other ball, you need at least as many colors as there are balls to
color them.

I think it would be useful if we would add a restriction: all of the regions should be convex. Also I think not I am the first one who thought on this possibility.
Is it possible? How to even start to think on such a problem?
What could be the result?
Comment: I guess the result with convex bodies is still infinite, though it would take some more fiddling around to achieve.
Comment: @IvanNeretin Thanks. I've fiddled a lot around it and I couldn't construct a really infinite one. I hit mainly similar walls as I tried naively to construct not 4-colorable 2d regions.
Answer: I actually considered this very problem some years ago and managed to convince myself that the answer should be finite if we restricted to convex regions (I thought it would be less than 20).
Unfortunately, it seems that even when we restrict to convex regions, the 'colour number' can still be arbitrarily large. There are two references which I've found online which claim to prove this, specifically when we restrict to just using cuboid regions.
Painting the Office by Reed and Allwright.
Colouring Rectangular Blocks in 3-space by Magnant and Martin
The first paper also has references to earlier works where it was proved that the colour number is unbounded for convex regions.
Comment: On the third page of your second link, there is a very clear explanation. :-( Sad...


Show a different view mode depending on role

Question: Using the Group module, when a user views a group, I want to use a different view mode depending on whether the user is a member of the group or not.
Conceptually, this is almost identical to showing a different view mode of a node depending on the user role.
I'd have thought it was easy, but I'm struggling. What I know:

The route is entity.group.canonical
I can modify the result of that route using alterRoutes() in a route subcriber
protected function alterRoutes(RouteCollection $collection) {
  if ($route = $collection->get('entity.group.canonical')) {
    // Do something.
  }
}

I'm not sure how to modify the route. Swapping in a whole new custom controller seems extreme.
Answer: Turns out, there's a hook for that.
function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {

  // For nodes, change the view mode when it is teaser.
  if ($entity->getEntityTypeId() == 'node' && $view_mode == 'teaser') {
    $view_mode = 'my_custom_view_mode';
  }
}


Remover conjunto específico do final do array com regex

Question: OBJETIVO
Estou tentando remover de todos os elementos do array o conteúdo ":PM" com regex, porém está me retornando erro.
DETALHES
O array sempre irá conter ":PM", e é somente essa parte que desejo remover dos elementos do array.
SCRIPT
import re

array = ['SOLDADO1:PM','SOLDADO2','SOLDADO3:PM','SOLDADO4','SOLDADO5:PM']

regex = r"^...-(.*)"
re.match(regex, array)

for linha in array:
    print(linha)

OUTPUT

Traceback (most recent call last):   File "regex.py", line 6, in

      re.match(regex, array)   File "C:\Python27\lib\re.py", line 141, in match
      return _compile(pattern, flags).match(string) TypeError: expected string or buffer
Answer: Se o trecho ":PM" está sempre no final da string, basta fazer:
import re

array = ['SOLDADO1:PM','SOLDADO2','SOLDADO3:PM','SOLDADO4','SOLDADO5:PM']
regex = re.compile(r':PM$')
for texto in array:
    print(regex.sub('', texto))

Eu uso o marcador $ para indicar o final da string.
Depois, para cada elemento do array, uso o método sub para substituir o trecho correspondente pela string vazia (''), que é o mesmo que remover o trecho.
Saída:
SOLDADO1
SOLDADO2
SOLDADO3
SOLDADO4
SOLDADO5

Se quiser gerar outra lista com as strings sem o trecho, basta fazer:
outra_lista = [ regex.sub('', texto) for texto in array ]

O resultado é a lista ['SOLDADO1', 'SOLDADO2', 'SOLDADO3', 'SOLDADO4', 'SOLDADO5'].

Sobre a sua regex: ^...-(.*), ela não funcionou porque ela tem o seguinte:

^: marcador de início da string
...-: 3 caracteres seguido de hífen
(.*): zero ou mais caracteres

Ou seja, bem longe de ser o que você precisa. Além disso, o método match recebe uma string, não uma lista. Por isso fazemos o loop e aplicamos a regex para cada elemento da lista.
Comment: Opa, muito obrigado, ficou perfeita sua didática, parabéns!
Answer: Sei que a outra resposta já foi aceita, mas acho que vale a pena acrescentar para quem estiver lendo essa pergunta no futuro:
Não use regexp para isso, a operação nesse caso é simples demais para valer a pena usar regexp; Você terá um código mais simples e que funciona melhor usando o método endswith e fatiando a string:
outra_lista = [texto[:-3] if texto.endswith(':PM') else texto for texto in array]


How to disable updating of structure.sql in rails?

Question: Is there a config option that would let us disable updating of the structure.sql?
It constantly updates everytime we run a migration and we don't need it to update.
We just need it for legacy tables.
Answer: You can disable that in your config/application.rb:
config.active_record.dump_schema_after_migration = false

See the configuration guide here.
Comment: Cool. Thats the best. You wouldn't happen to know of a way for rails 3? :)
Comment: Ohh, I see. We had to monkey-patch that, unfortunately.


Is there a nice recurrence relation for $n^n$

Question: I know there is a nice equation for $n!$, but is there one for $n^n$? I was thinking you could get it with the fact $n^n=a^{n\log_an}$ but I can't seem to make the needed jump.
Edit: It was suggested by goblin to use the fact that $(n+1)^{n+1} = (n+1)(n+1)^n$ and expand with the binomial theorem. This gives $a_{n+1} = (n+1)\sum_{i=0}^n \binom n {n-i} n^i$
Which is still a little more complicated then I'd like. I'd love to have something of the form $a_{n+1}=a_nb^{f(n,b)}$ for every $b$
Comment: Real life seldom is... :-$)$ There is no *meaningful* recursive relation between $n^n$ and $(n-1)^{n-1}$.
Comment: $a_n=\Big(\sqrt[n-1]{a_{n-1}}+1\Big)^n.$
Comment: Not quite what I'm looking for.
Comment: Is there any way to prove that? If so please post it as an answer.
Answer: Using the $W$ Lambert function (the inverse of $x\mapsto xe^x$) we get:
$$a_n=n^n$$
$$\ln a_n=n\ln n=\ln n e^{\ln n}$$
$$W(\ln a_n)=\ln n$$
Therefore
$$a_{n+1}=[e^{W(\ln a_n)}+1]^{e^{W(\ln a_n)}+1}$$
On the other hand, from your equation
$$(n+1)^{n+1}=n^n\,b^{f(b,n)}$$
we get
$$f(b,n)=\log_b\frac{(n+1)^{n+1}}{n^n}=\log_b(n+1)+n\log_b\left(1+\frac{1}{n}\right)$$
Comment: So basically it simplifies to $a_{n+1} = a_n(n+1)b^{n\log_b\left(1+\frac{1}{n}\right)}$. Quite elegant. Especially since if my memory serves me correctly the last term converges to $e$.


How to set content transfer encoding using MimeKit/MailKit?

Question: I try to send text in attachment. That works well only right now i have  encoding problems in the builder.ToMessageBody() statement (see code below) Itry to send an email with text "my text = my subject and Version=1.0" as attachment , but when you open the email the text has been altered to "my text =3D my subject and Version=3D1.0". As you can see the = sign has been encoded to =3D Is there a way to change the encoding?
Thanks
var message = new MimeMessage();
var builder = new BodyBuilder();

builder.TextBody = "";
var xmltext ="my text = my subject and Version=1.0" ;

builder.Attachments.Add("12345.txt", Encoding.ASCII.GetBytes(xmltext), new ContentType("text", "plain"));

message.Body = builder.ToMessageBody();

Answer: The Add method actually returns the MimeEntity that it creates, allowing you to make changes to it.
To force the encoding to base64, for example, you can do this:
var attachment = (MimePart) builder.Attachments.Add("12345.txt", Encoding.ASCII.GetBytes(xmltext), new ContentType("text", "plain"));
attachment.ContentTransferEncoding = ContentENcoding.Base64;


Find closed-form solution to the SDE $dX_t = dt + 2 \sqrt{X_t} \, dW_t$

Question: I've been tasked to solve the following SDE:
$dX_t = dt + 2\sqrt{X_t}dW_t, \ \ \ t \in \mathbb{R}_+$
where $W_t$ is a standard Brownian motion and $X_0=x$.
I need a closed form solution.
What is the best approach?
Is it to write in in "integral" form: $X_t = x + t + 2\int_0^t\sqrt{X_u}dW_u$ and solve the stochastic integral term? If so, I can't find a function $f$ to use in Ito's lemma so that I get a good-enough solution.
Any advice would be appreciated as I am pretty much a bigger to stochastic calculus. Thanks
Edit: Note: I am allowed to assume X stays non-negative all the time
Answer: Hints:

Suppose that $(X_t)_{t \geq 0}$ is a solution to the SDE. Using Itô's formula show that $Y_t := \sqrt{X_t}$ satisfies $$dY_t = dW_t.$$ (See the second part of this answer  to get a better understanding how to choose a suitable transform.)
Conclude from step 1 that $X_t := (\sqrt{x}+W_t)^2$ is a candidate for the solution.
Use Itô's formula to show that $(X_t)_{t \geq 0}$ from step 2 is indeed a solution to the given SDE.
Comment: @VladimirNabokov You are welcome.
Comment: Is it too naive to ask why $dY_t = dW_t$ in step 1? I am a complete beginner in stochastic calculus. Although I know Ito's formula, I don't understand how to apply it to get the above SDE.
Comment: If we naively take $dY_t = \frac{1}{2\sqrt{X_t}}dX_t$, we get that $dY_t = dW_t + \frac{1}{2Y_t}dt$. I suspect $dY_t = \frac{1}{2\sqrt{X_t}}dX_t$ is not a valid inference.
Comment: I just learned that if $f$ is a smooth real-valued function over the reals, then $df(X_t) = f'(X_t)dX_t + \frac{1}{2}f''(X_t)d[X]_t$ ([source](https://math.stackexchange.com/a/3583369/948760)). I also learned that if $dX_t = \sigma(X_t,t) dW_t +  \mu(X_t,t) dt$, then $d[X]_t = \sigma(X_t,t)^2 dt$ ([source](https://quant.stackexchange.com/a/51574/70451)). I think that it's best to not delete my naive thoughts above because it might help other confused beginning learners of stochastic calculus in the future.


Static File Serving with Extensionless MVC3 on IIS6

Question: I have a MVC3 site in .Net 4.0 running on IIS6 with extensionless manner successfully.
One function og the site is the generate static files for user to download. One type of file is CSV, I generated files on server which is accessible via http://DevServer:1234/StaticFile/1.csv which works fine.
However the requirement is changed, client wants file extension to be ".rpt" instead of ".csv" and all the content of file leaves the same. The code has been adjusted accordingly, I have verified the new file is generated properly at correct path. But when I tried to load it via http://DevServer:1234/StaticFile/1.rpt web server returns 404 error code. If I simply rename the file extension back to CSV on server I have no problem loading it.
Sounds like IIS6 is not able to server tthe request properly.
Any idea what is wrong?
Comment: To get your site working, did you setup MVC as a Wild Card mapping in IIS?
Comment: No i did not setup wildcard mapping.
Answer: You need to add a custom MIME type to IIS to tell it to serve up .rpt files.

Open up your IIS management console and find the site you want this to work with.
Right click on your site and choose properties and choose the "HTTP Headers" tab
Press the "mime types" button
In the dialog, under extension type ".rpt" (without the quotes) and under mime type: type "text/csv" (without the quotes)
Comment: Glad it worked for you. You noted that you're outputting these static files to the disk. IIS will only serve up known MIME types. Does this answer your question?
Comment: It works for me. But what does MIME to do with MVC3 project here?


How to learn to play 'out of phase' with yourself?

Question: There's a Piano piece by Steve Reich called piano phase, in which the same notes are played on 2 pianos (usually by different people), but over time, they shift out of phase with each other.
Here's a video of it being done by one guy on youtube:

I imagine it's extremely difficult, but how would you go about learning to play out of phase in such a way?
Comment: That is an INCREDIBLE video!!!
Comment: My suggestion would be to record one hand, then practice listening to it while playing the other hand. Then you can begin to hear what it should sound like. I know this suggestion has nothing to do with hand independency, but it's where I would start if I were to attempt anything even remotely like this.
Comment: I know virtuoso pianists who will back you up on your estimation of the difficulty -- a lot of so-called minimalist music is extraordinarily difficult to play.
Comment: Jon Hiseman (drums,percussion) does a similar thing, starting with a drum roll on snare, with a slow bass drum pulse. As the roll slows down, so the bass drums (double) speed up, so that in the middle of the number, the snare is slow single beating, whilst the bass drums are rolling. Then it all slowly swaps over to the original.Impressive over 4/5 mins.
Comment: There is another cool piece by Reich call "Clapping Music", and it has [this neat video](http://www.youtube.com/watch?v=lzkOFJMI5i8&feature=youtu.be) that goes along with it, to kind of demonstrate a "simpler" version of this phasing thing.  Thanks to my brother ([Stephen](http://music.stackexchange.com/users/1075/stephen)) for pointing this video out to me.
Answer: What make's Reich's piece difficult, is how he specifies the phasing.  For example, there are portions of the score where you need to be exactly 1/16th note out of phase with yourself.
Self-phasing is something I have practiced for quite some time, and indeed, it does take a while to learn.  However, such practice / skill allows you great freedom through improvisation as well as some very interesting syncopation.
If you're starting from the absolute beginning, then I would suggest becoming very smooth at transitioning between rhythmic durations.  For example, put on a metronome at 44bpm or something equivalently slow.  Next, begin with a whole note (four beats) and repeat a few times, then move to half-notes, triplet quarters, quarter-notes, eighth, triplet-eighth, sixteenth, quintuplets, etc etc.  Practice moving between them staying exactly with the beat.
Once you have mastered that, apply the same technique while keeping one hand constant with the metronome while you accelerate with your other hand exactly with the beat.  Next alternate hands.
Really, the trick is being able to multitask.
Quite simply, when you have mastered speeding up and slowing down with the beat, do it over or independently of the beat.  If there were measures, you could think of it as being "over the barline." Obviously, alternate hands.
Once you have mastered this task, take it a step further by only tapping on beats 1, 3 or 2, 4 (I'm a fan of 2, 4 personally for jazz reasons.)  Once you can arhythmically swing on 2, 4, then you know you can have some fun.
If you want to slow down / speed up at a specific rate, then that will need to be practiced specially - the difficulty really lies in how well you understand conceptually what needs to occur kinesthetically in order for your hands to create the desired phasing effect.
Comment: A lot of people are misunderstanding the nature of the piece. The Reich piece never asked you to play out of phase with yourself, the actual piece calls for 2 pianists. This performer is attempting to do it all by himself. You're right that sometimes 1 part is ahead by a 16th; it's systematic, next it's an 8th ahead, then a dotted-8th, etc. And that's hard enough, but all it requires is practice of all the different line ups. It's the in-between part, where you transition from 1 lineup to the next, that's so difficult--especially by yourself.
Comment: @jjMusicNotes Another fantastic answer as always jj!
Comment: @PatMuchmore - you are correct that Reich never actually asks perfomers to phase in and out with them selves, and I apologize if my answer's wording appear to imply that the piece was originally written for one person. Though the phasing is metrically systematic, a *phasing* effect is after all what the composer is going for.


Can you use a Pack200 file without first unpacking it?

Question: Is it possible to load classes on-the-fly (in memory) from a pack.gz file created by Pack200 without unpacking it back into a jar first? All of the examples that I can find just show me how to unpack it into a .jar file and then load the classes from the .jar file.
Comment: Yes, and this is routinely done with JWS.
Answer: Yes, it's possible.  The Pack200.Unpacker.unpack method writes to a JarOutputStream;  if you do that in a background thread, you can connect a new JarOutputStream to a JarInputStream using a pipe, and read from that.
public JarInputStream readPackFile(Path packGzFile)
throws IOException {

    PipedInputStream pipeIn = new PipedInputStream();
    PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Void> unpacker = new Callable<Void>() {
        @Override
        public Void call()
        throws IOException {
            try (InputStream file =
                    new GZIPInputStream(
                        new BufferedInputStream(
                            Files.newInputStream(packGzFile)));
                 JarOutputStream jarOutput = new JarOutputStream(pipeOut)) {

                Pack200.newUnpacker().unpack(file, jarOutput);
                return null;
            } finally {
                executor.shutdown();
            }
        }
    };
    executor.submit(unpacker);

    return new JarInputStream(pipeIn);
}

That should be sufficient.  However, there are still two issues:

If there's an error with the unpack operation, you'll never know about it, since ExecutorServices suppress their taskṣ' exceptions.
JarInputStream and JarOutputStream (more specifically, their superclasses, InflaterInputStream and DeflaterOutputStream) don't work well with pipes.  This is because closing the JarOutputStream forces a call to its finish() method, but the JarInputStream on the other side of the pipe will never read that data.  This means the JarInputStream will almost certainly be closed before finish() is called, causing finish() to generate an IOException due to a broken pipe.

To resolve the first problem, we can override the JarInputStream's close method to account for any failure in the unpack operation.  To resolve the second, we can override finish() in the JarOutputStream to do nothing:
public JarInputStream readPackFile(Path packGzFile)
throws IOException {

    PipedInputStream pipeIn = new PipedInputStream();
    PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);

    class NonFinishingJarOutputStream
    extends JarOutputStream {
        NonFinishingJarOutputStream(OutputStream out)
        throws IOException {
            super(out);
        }

        @Override
        public void finish()
        throws IOException {
            // Deliberately empty.
        }
    }

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Void> unpacker = new Callable<Void>() {
        @Override
        public Void call()
        throws IOException {
            try (InputStream file =
                    new GZIPInputStream(
                        new BufferedInputStream(
                            Files.newInputStream(packGzFile)));
                 JarOutputStream jarOutput =
                    new NonFinishingJarOutputStream(pipeOut)) {

                Pack200.newUnpacker().unpack(file, jarOutput);
                return null;
            } finally {
                executor.shutdown();
            }
        }
    };
    Future<?> unpackerTask = executor.submit(unpacker);

    return new JarInputStream(pipeIn) {
        @Override
        public void close()
        throws IOException {
            super.close();
            try {
                // If the unpack generated an exception, propagate it here.
                unpackerTask.get();
            } catch (ExecutionException e) {
                throw new IOException(e);
            } catch (InterruptedException e) {
                InterruptedIOException iie = new InterruptedIOException();
                iie.initCause(e);
                throw iie;
            }
        }
    };
}

Comment: All JarFile constructors require a file.  I'm pretty sure there is no way to use the JarFile class without one.
Comment: That gives me a JarInputStream, not a JarFile. https://stackoverflow.com/questions/16602668/creating-a-classloader-to-load-a-jar-file-from-a-byte-array seems to indicate that it's difficult at best to actually do much with a JarInputStream.


Is there anything like a small version of TFS?

Question: Is there anything that has features of TFS(Like Source Control, Debug, Testing,...) that we can use in a workgroup with a small team(say 1-6 persons)?
BTW: we are using VS 2008 Team Suit
Answer: Do you particularly need it all in one package? Various open source projects only do one thing, but integrate nicely with others. For instance:

Subversion for source control
Trac for bug tracking
Cruise Control .NET for continuous builds
NAnt for build management
Comment: Using all of them in a single package is much easier.
Comment: Open source does not mean free. Its usually harder to configure and setup, integrates poorly, and time-consuming to maintain. TFS is free for 5 users and also is Visual Studio Online.
Comment: @MrHinsh: I don't think it was in 2008. And I wouldn't assume it's easier to install and configure commercial software, either. Hopefully it's better now, but last time I installed TFS it was a horrible experience.
Comment: @MrHinsh: You don't have to install with GitHub, BitBucket etc either, do you? (And heck, there's a Git client in Visual Studio...)
Comment:   and there is Git in VSO, so why limit myself to mear GitHub or Bitbucket? http://nakedalm.com/why-should-i-use-visual-studio-alm-whether-tfs-or-vso/
Comment: @MrHinsh: You seem to be shifting your argument. You were arguing against using open source options because they were hard to set up. With GitHub - and yes, VSO - that issue goes away. So why would I want to use TFS (as you were advocating) rather than one of the far-more-commonly used tools such as Git or Mercurial? My experiences with TFS  have been almost entirely negative - and talking to various people over the years, that doesn't sound uncommon.
Comment: TFS and Git are not an apples to apples comparison. TFS does way more than Git. Do you maybe mean TFVC vs Git? Because I create all my team projects with Git rather than TFVC. But I get enterprise grade Git
Comment: @MrHinsh: I really don't see what you're trying to accomplish in this discussion, on a question over 6 years old which wouldn't even stay open on SO these days (and which I've now voted to close, with an eye to deleting). The question was asking for alternatives to TFS, which I provided options for. If you want to provide your own answer (which I doubt many people will read). What benefit do you think you're providing here?
Comment: Not trying to accomplish anything... I got a notification of a reply and am replying... If noone cares then don't reply
Answer: Use the Team foundation workgroup edition but be warned.  Under no circumstances think of source safe.
There are many other very good alternatives for all you seek.  To many to mention, so will leave particular recommendations to others.
Comment: Where can I find Workgroup edition? I googled for about 1 hours but didn't find anything.
Comment: Team Suite should come with Team Foundation Server Workgroup edition.  Check your DVDs or download from MSDN.  You'll need to install Team Explorer from the TFS DVD on each client workstation as well.  TFS workgroup edition is good for up to 5 developers.
Comment: Is there anything else that I should install to use it completely?
Answer: SourceGear Fortress?  Encompassing SourceGear Vault, work item / bug tracking, and integration with CruiseControl for build.
Is there something in particular you dislike about TFS?
Is there a particulare feature you feel is missing?
If you are using Team Suite, why not use TFS (even workgroup edition)?
Comment: The problem with the TFS is that it requires a dedicated server with a lot of resources.
Comment: TFS can run on 2GB of RAM in a VM using SQL Express so I don't know where 'lots of resources' comes from. If you have issue anyway then use Visual Studio Online...
Answer: If you want to go with OpenSource, use CodePlex. So, you'll get TFS with all features for free :)
If not, please check TFS Wiki page for alternatives.
Answer: Team Foundation Server is FREE if you have an MSDN licence. Even if you don't it is only $500 for a retail licence that allows 5 users.
if you have paied for Team Suit (now Visual Studio Ultimate) then you loose one hell of a lot of features if you do not use TFS.
Comment: But the license isn't to develop for it?, I mean, you get access to TFS but as a developer for it (plugins), not like user...
Comment: Sure, however you already have that to have tfs. So its free to upgrade to the latest version.
Comment: You get 5 users for free and every developer with ab MSDN has access as a user to TFS at no cost. There is NO cost to develop for TFS.
Comment: You get 5 users for the TFS Express edition, not from the MSDN edition. Read carefully the terms, we have several MSDN licences here and our licensing manager explained this to us, we had to purchase it.
Answer: I was in the same boat as you. I even asked a question about it here at SO. We had the budget for TFS, and even the hardware to put it on, but with our team only being 5 people, going through the work to get TFS up and running didn't seem worth it. There was also a high training cost for a TFS administrator to take care of it all. Don't get me wrong: I love TFS, but for this team it was like using the space shuttle to cross the street.
As my question says, I looked at the Subversion stack. I liked it a lot. But at the end of the day, my customer wanted something that was vendor-supported.
We went with SourceGear Fortress. It has the familiarity of SourceSafe but with the heavy-duty SCM features found in SVN and TFS. It was also significantly cheaper than TFS. In the end, Fortress was the balance my team needed.
I set up Fortress to use CruiseControl.NET for integrated builds, moved our VSS repository with the import tool, and was up and running in about a day.
I will admit that I miss TFS and wish I had some of its features, like the very tight integration with Visual Studio (Fortress has VSS style integration; bug- and issue-tracking are web-based).
Comment: You should look at Visual Studio Online. Its TFS in the cloud and its free for 5 users. In addition anyone with an MSDN licence gets access included in their MSDN...


Consulta sql SELECT

Question: Qual comando select me mostra apenas aqueles comentários de um único usuário?
Por exemplo: tenho uma tabela Post onde guarda os comentários de cada usuário (usuario_1, usuario_2, usuario_3), porém gostaria de mostrar apenas os comentários do usuario_1.
Tabela de comentários se chama Post:
ID_POST
ID_USER (chave estrangeira para a tabela Users, campo ID_USER)
mensagem
data

Tabela de usuários se chama Users:
ID_USER
username
avatar

Answer: Conforme as informações fornecidas:
SELECT comentario FROM comentario WHERE usuario = "usuario_1"

Deduzindo que o nome da coluna que armazena os comentários é comentario, que o nome da sua tabela é comentario e que a coluna que armazena os usuários é usuario.
EDIT - Devido à novos dados posteriormente informados
SELECT mensagem
FROM Post
INNER JOIN Users ON Users.ID_USER = Post.ID_USER
WHERE Users.username = "usuario_1"

Comment: Caraka mano realmente era isso que estava procurando flw abraço..
Comment: acho que eu deveria ser mais especifico kkkk, tenho uma tabela users e outra tabela post, a tabela post tem coluna = id_post, coluna = chave estrangeira id_user que é o id_user da tabela users, tem coluna mensagem, coluna = data_poste, agora a tabela users tem coluna = id_user, coluna = username, coluna = avatar
Comment: SHOW FULL COLUMNS FROM nomeDaSuaTabela (se for Mysql). Acredito que não possa ter um SELECT exclusivo para um campo.
Answer: Pelo que entendi da sua pergunta, seria isso:
/*Buscando pelo nome do usuário*/
SELECT * FROM Post
WHERE ID_USER = (
    SELECT ID_USER FROM Users
    WHERE Login LIKE '%Texto_da_Busca_Pelo_Login_do_Usuario%'
)

/*Buscando pelo id do usuário*/
SELECT * FROM Post
WHERE ID_USER = 'ID_Digitado_Pelo_Usuario'

Consulta sql SELECT


AWK field substitution based on lookup table

Question: I am trying to replace values in column 1 of file1 using a lookup table. A sample (tab separated):
chr1 1243 A T 0.14
chr5 1432 G C 0.0006
chr10 731 T C 0.9421
chr11 98234 T G .000032
chr12 1284 A T 0.93428
chr17 941 G T 0.1111
chr19 134325 T C 0.00001
chr21  9824 T C 0.9

Lookup table:
chr1 NC_000001.11
chr2 NC_000002.12
chr3 NC_000003.12
chr4 NC_000004.12
chr5 NC_000005.10
chr6 NC_000006.12
chr7 NC_000007.14
chr8 NC_000008.11
chr9 NC_000009.12
chr10 NC_000010.11
chr11 NC_000011.10
chr12 NC_000012.12
chr13 NC_000013.11
chr14 NC_000014.9
chr15 NC_000015.10
chr16 NC_000016.10
chr17 NC_000017.11
chr18 NC_000018.10
chr19 NC_000019.10
chr20 NC_000020.11
chr21 NC_000021.9
chr22 NC_000022.11

script being used:
awk 'FNR==NR{a[$1]=$2;next} {for (i in a)sub(i,a[i]);print' lookup.txt file1 > new_table.txt

output with comment on which line is correct/incorrect (with right answer in brackets):
NC_000001.11 1243 A T 0.14 #correct
NC_000005.10 1432 G C 0.0006 #correct
NC_000001.110 731 T C 0.9421 #incorrect (NC_000010.11)
NC_000001.111 98234 T G .000032 #incorrect (NC_000011.10)
NC_000012.12 1284 A T 0.93428 #correct
NC_000001.117 941 G T 0.1111 #incorrect (NC_000017.11)
NC_000001.119 134325 T C 0.00001 #incorrect (NC_000019.10)
NC_000021.9 9824 T C 0.9 #correct

I don't understand the pattern of why it isn't working and would welcome any help with the awk script. I thought it was just those with double digits e.g. chr17 but then chr21 seems to work fine.
Many thanks
Comment: Do you have DOS carriage returns in one or both files?
Comment: Could you please correct your samples as `NC_000005.101432` is not at all in your shown sample files, kindly correct the sample of input and expected output in your question and let us know then.
Comment: @tripleee I don't think so. These files are only from linux and I have reformatted them all to be tab seperated using the column -t function
Answer: Shouldn't it be:
awk 'FNR==NR{a[$1]=$2;next}{$1=a[$1]}1' lookup.txt file1

?
Output:
NC_000001.11 1243 A T 0.14
NC_000005.10 1432 G C 0.0006
NC_000010.11 731 T C 0.9421
NC_000011.10 98234 T G .000032
NC_000012.12 1284 A T 0.93428
NC_000017.11 941 G T 0.1111
NC_000019.10 134325 T C 0.00001
NC_000021.9 9824 T C 0.9

Explanation:
# true as long as we are reading the first file, lookup.txt
FNR==NR {
    # create a lookup array 'a' indexed by field 1 of lookup txt
    a[$1]=$2
    # don't process further actions
    next
}

# because of the 'next' statement above, this will be only executed
# when we are processing the second file, file1
{
    # translate field 1. use the value from the lookup array
    $1=a[$1]
}

# always true. print the line
1

PS: If there's the possibility that entries can't be found in the lookup table, you could use a special text for them:
awk 'FNR==NR{a[$1]=$2;next}{$1=($1 in a)?a[$1]:"NOT FOUND "$1}1' lookup.txt file1

Answer: I believe sub could be the problem in OP's attempt, not checked thoroughly, this could be done simply by:
awk 'FNR==NR{arr[$1]=$2;next} ($1 in arr){first=$1;$1="";print arr[first],$0}' lookup_table Input_file

Problem with OP's attempt(Only for understanding purposes NOT to be run to get shown samples results): Though OP's code shown one doesn't look like complete one to dig it out why its giving wrong output as per OP's question, I have written it as follows.
awk 'FNR==NR{a[$1]=$2;next} {for (i in a){line=$0;if(sub(i,a[i])){print (Previous line)line">>>(array key)"i"....(array value)"a[i]"............(new line)"$0}}}' lookup_table Input_file
So whenever a proper substitution happens then only its printing the line as follows, where we could see whats going wrong with OP's code.
chr1 1243 A T 0.14 chr1 1243 A T 0.14 >>>(array key)chr1....(array value)NC_000001.11............(new line)NC_000001.11 1243 A T 0.14
chr5 1432 G C 0.0006chr5 1432 G C 0.0006>>>(array key)chr5....(array value)NC_000005.10............(new line)NC_000005.10 1432 G C 0.0006
chr10 731 T C 0.9421chr10 731 T C 0.9421>>>(array key)chr1....(array value)NC_000001.11............(new line)NC_000001.110 731 T C 0.9421
chr11 98234 T G .000032chr11 98234 T G .000032>>>(array key)chr1....(array value)NC_000001.11............(new line)NC_000001.111 98234 T G .000032
chr12 1284 A T 0.93428chr12 1284 A T 0.93428>>>(array key)chr12....(array value)NC_000012.12............(new line)NC_000012.12 1284 A T 0.93428
chr17 941 G T 0.1111chr17 941 G T 0.1111>>>(array key)chr1....(array value)NC_000001.11............(new line)NC_000001.117 941 G T 0.1111
chr19 134325 T C 0.00001chr19 134325 T C 0.00001>>>(array key)chr1....(array value)NC_000001.11............(new line)NC_000001.119 134325 T C 0.00001
chr21  9824 T C 0.9chr21  9824 T C 0.9>>>(array key)chr21....(array value)NC_000021.9............(new line)NC_000021.9  9824 T C 0.9

Where we could easily see
old line from chr1 1243 A T 0.14 chr1 1243 A T 0.14 to becomes like NC_000001.11 1243 A T 0.14 that's because array key(chr1) get substituted with array value (NC_000001.11) If you see output shown above for understanding purposes.
Answer: Looks like sub is causing the issue and so simply prepend the value for the index specified by $1 to the line with a space and print the line with short hand 1 and so:
awk 'FNR==NR{a[$1]=$2;next} {$0=a[$1]" "$0 }1' lookup.txt file1 > new_table.txt

Comment: what is the need to modify the entire record `$0`?
Comment: We are printing $0 for every line with short hand "1" at the end of the statement
Comment: That's not my question, though. Why not just `$1=a[$1]`?
Comment: Because we are not replacing $1 with a[$1] with are prepending $1 with a[$1] and then a space. I guess the other was is to do $1=a[$1]" "$1


Javascript regular expression

Question: string = 'Hello 1234_ world 4567_ trap 456';

I need to capture all digits followed by underscore. Following code will do.
string.match(/(\d+?)(_)/gi);

However I tested following code and it worked except that underscore was also being captured.
(\d+)_

So I decided to give underscore its own capture group like this
(\d+)(_)
But it did not work. I am getting digits with trailing underscore. I do not want underscore.
Comment: How are you using the regex? What is the rest of the code?
Comment: I am using this site http://regex.larsolavtorvik.com/#js
Answer: The match method returns a string containing the characters that matched regardless of whether or not they were part of a (capturing or non-capturing) group.
The (?=_) group is a lookahead. A lookahead is a zero-width match and therefore it doesn't match any characters. It matches the empty string, but only if the character immediately afterwards is an underscore.
The groups are not really the important thing here. When you use a zero-width match, the result won't include any extra characters.
Comment: That's `/\d+(?=_)/g`. Not sure why it isn't written.
Comment: Kobi: That was already part of the question, but he edited it out.
Comment: As I mentioned my code works with look ahead strategy. My main question was why the capturing of underscore is not working in the last solution. Thanks.
Comment: @dorelal: Updated answer. Any better?
Answer: Try
var regex = /(\d+?)(_)/

Javascript regular expression


WaitForSingleObject With timeout=0

Question: I have a mutex created in non signaled state
HANDLE hmutex= CreateMutex(NULL,FALSE,"");---1

Now I am calling
DWORD dw = WaitForSingleObject(hmutex,0); ---2

Since hmutex is not signaled, WaitForSingleObject will return immediately but will state of hmutex will change to signaled??
If another thread calls this second statement what will happen?
Comment: Don't do that (use an empty name), it's begging for a collision.  If you don't want a name, pass NULL and receive an unnamed mutex.
Comment: You are creating a named mutex with an empty name. Is this intentional?
Comment: yes , its intentional
Comment: @Ben: Thanks for advice , will take care of that
Answer: No, it won't change to signaled.
The following invariants are true about that call:

It returns immediately regardless of the mutex state.
The mutex becomes owned (non-signaled) regardless of its previous state.
The return value tells you whether you gained ownership or failed due to contention.

In all cases, someone owns the mutex.  However, if another thread was owner, it could release the mutex at any time, so by the time the function returns several processor cycles later, it might be released (signalled).
Answer: Don't think of mutex objects as being signaled or non-signaled.  Instead, think about them as being owned or unowned.
The second parameter in the call below says that the mutex is initially unowned.
HANDLE hmutex= CreateMutex(NULL,FALSE,"");

The very first time the call below is made, the calling thread will take ownership of the mutex.  If another thread makes the same call while the mutex is owned by the first thread, the return value will be WAIT_TIMEOUT (258 decimal, 102 hex).
DWORD dw = WaitForSingleObject(hmutex,0);

Here are some guidelines to follow.  Use mutexes if you need to restrict access to a resource shared by multiple processes.  If you are restricting access to a resource within a single process, use CRITICAL_SECTION instead.  If you are wanting an object that one thread can use to signal another thread, use events.
Comment: and then there were semaphores.  And condition variables.

WaitForSingleObject With timeout=0


WPF ListItem Template - Button to Fade In

Question: I have a ListBox with an ItemTemplate (shown below) that when the mouse is over an item, a button is displayed that will fire a Delete Command.
This works, but what I'd like is for the button to "fade in" after the mouse has been over the listitem for a couple of seconds. How can I achieve this?
<code>        <ListBox.ItemTemplate>
            <DataTemplate d:DesignSource="{d:DesignInstance quizCompanion:Question}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="40"></ColumnDefinition>
                        <ColumnDefinition Width="16"></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding Path=Number}"></TextBlock>
                    <Button
                        Content="x" Grid.Column="1"
                        Command=MyDeleteCommand>
                        <Button.Style>
                            <Style TargetType="Button">
                                <Setter Property="Visibility" Value="Hidden"></Setter>
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsMouseOver}" Value="True">
                                        <Setter Property="Visibility" Value="Visible" />
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </Button.Style>
                    </Button>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
</code>
Answer: Try using a DataTrigger with a RelativeSource for the Binding.
Here's a sample ... mouse over anywhere on the StackPanel for 2 seconds or more and the hidden button will fade in. It'll disappear when the mouse is moved off. Hopefully it'll work within your ListBox ItemTemplate:
<code><Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <Grid>
      <StackPanel Height="100" Background="Yellow">
         <TextBlock Text="Mouse over the yellow area to see the button"/>
         <Button Width="250" Height="50" HorizontalAlignment="Left" Opacity="0">
            <Button.Style>
               <Style>
                  <Style.Triggers>
                     <DataTrigger Binding="{Binding Path=IsMouseOver, RelativeSource={RelativeSource AncestorType={x:Type StackPanel}}}" Value="True">
                        <DataTrigger.EnterActions>
                           <BeginStoryboard Name="Fade">
                              <Storyboard>
                                 <DoubleAnimationUsingKeyFrames Duration="0:0:3" Storyboard.TargetProperty="Opacity">
                                    <LinearDoubleKeyFrame KeyTime="0:0:2" Value="0"/>
                                    <LinearDoubleKeyFrame KeyTime="0:0:3" Value="1"/>
                                 </DoubleAnimationUsingKeyFrames>
                              </Storyboard>
                           </BeginStoryboard>
                        </DataTrigger.EnterActions>
                        <DataTrigger.ExitActions>
                           <StopStoryboard BeginStoryboardName="Fade"/>
                        </DataTrigger.ExitActions>
                     </DataTrigger>
                  </Style.Triggers>
               </Style>
            </Button.Style>
         </Button>
      </StackPanel>
   </Grid>
</Page>
</code>
Comment: This trigger is when the mouse is over the button, I really need to trigger when the mouse is over the listitem that the button is on
Comment: Updated answer. That's what happens when you answer after a long day. Let me know how it works out for you.
Comment: Sorry for not getting back but I've been working on other things. Thanks for the help


Android banding artifact

Question: When using a dark semitransparent view, the banding over an underlying bitmap seems unmanageable. The background is just a blurred image, which I think makes more visible the artifact.
I think the image explains everything
Code:
<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <View
        android:background="@drawable/blur"
        android:id="@+id/view1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
    <View
        android:background="#D000"
        android:id="@+id/view2"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</android.support.constraint.ConstraintLayout>
</code>
Answer: Solved: On a real device, the banding artifact dissapears.

Android banding artifact


Linkedin API to get user Posts

Question: I am trying to get a user posts or reposts by using their access token via linkedin apis, but I am unable to get any data from api. Here is the api:
https://api.linkedin.com/v2/shares?q=owners&owners=urn:li:person:vO2dw56SKV
Headers contains : my access_token as Authorization: Bearer <ACCESS_TOEKN> and **X-Restli-Protocol-Version:2.0.0
**
.THE response which I am getting is
{
"serviceErrorCode": 0,
"message": "Invalid query parameters passed to request",
"status": 400
}
Can anyone help me out with what is wrong with Syntax in API or am I even using correct api according to my requirement.
I am trying to find examples but unable to find from their docummentation
Answer: I haven't managed to do it with the v2 of the API as I'm currently upgrading ours to the new API (their documentation is currently a bit mixed on whether v2 is expiring in February 2023, but I believe that it is).
I've managed to get it working using the 202301 version of their API (which is apparently required to get a list of posts). Which seems incredibly limiting given their new posts API (released middle of last year) doesn't provide the Id of a post when you create one.
This is particularly odd given LinkedIn used to provide the Id on creation, as do Facebook and Twitter. Also means that you're making an additional API call, to try and find the post you just made, and they modify the text you sent, so you can't match it on that to make sure you have the right one. I'll be raising a support ticket regarding this with LinkedIn, but here's the documentation I used:
https://learn.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/posts-api?view=li-lms-2022-06&tabs=curl#sample-request-2
This is the GET Url: https://api.linkedin.com/rest/posts?author=urn%3Ali%3Aorganization%3A{ORGIDHERE}&q=author&count=5
This is part of the response I received back:
Comment: Hi, the OP says that need to get posts of a person. This works with organization but doesn't work on person post on this API.
Comment: Turns out they sometimes include an id in the Response Header, other times elsewhere, in this case they do give the id in the Response Header, so you can grab it from there. Similar when uploading images to their new Image end points.

Linkedin API to get user Posts


How can i create an animation like this in css

Question: I'm trying to create an animated text like bellow using css, how can i do this?

I already tried this:

span1 {
  display: inline-block;
  color: #e74c3c;
  position: relative;
  white-space: nowrap;
  top: 0;
  left: 0;
  -webkit-animation: move 5s;
  -webkit-animation-iteration-count: infinite;
  -webkit-animation-delay: 1s;
}

@keyframes move {
  0% {
    top: 0px;
  }
  20% {
    top: -50px;
  }
  40% {
    top: -100px;
  }
  60% {
    top: -150px;
  }
  80% {
    top: -200px;
  }
  100% {
    top: -300px;
  }
}
<span1>
  web developer
 css cowboy
 self-facilitating media node
 box inside a box
 part of the problem
</span1>

but it has a delay after last text that i need to remove!
Comment: could you share enough code tat shows your issue and what you tried so far ? It can be done in HTML/CSS indeed, but what do you have ?
Comment: What have you tried so far coding wise?
Comment: @ehsan no problem! i need the style!
Comment: @GCyrillus I did.
Answer: See This:

*{
  box-sizing: border-box;
}

body {
  background-color: skyblue;
}

div {
  overflow: hidden;
  color: #fff;
  text-align: center;
  font-size: 20px;
  position: relative;
  height: 100px;
  margin-top: 100px;

}

div p {
  height: 100px;
  animation: move  7s infinite linear;
  position: relative;
  bottom: -100px;
  font-size: 36px;
  margin: 0;
}

@keyframes move {
0% {bottom: -100px;}
10%, 20% {bottom: 0px}
40%,50% {bottom: 100px;}
70%,80% {bottom: 200px;}
100% {bottom: 300px}
}

50% OFF

Some Text

Write by: Ehsan Taghdisi

Comment: It's cool.tnx, what should i change if i want to make it three item?
Comment: nothings changed! can you please update your answer with three  tag.
Comment: if you want for dynamic elements,you must use of javascript.
Comment: what if its just for 3 items not different elements , i'm not so good in css and i just wanna do it the fast way possible.
Comment: thanx, your awsome!
Comment: Thanks buddy, you definitely saved my day! :*
Answer:

.anim1 {
  animation: anim1 1.5s infinite;
}

.anim2 {
  animation: anim2 1.5s infinite;
}

@keyframes anim1 {
  0% {
    transform: translateY(-10px);
  }
  50% {
    transform: translateY(-80px);
  }
  100% {
    transform: translateY(-10px);
  }
}

@keyframes anim2 {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-80px);
  }
  100% {
    transform: translateY(0px);
  }
}

Hello animation 1

Hello animation 2

Comment: @MahboobehMohammadi It just demonstrate basic animation as you've not mentioned specific issue or any other try out.
Comment: i added a gif, and also i add some code. i tried this animation you made before, but i want the texts to go up and start over again from the first text. like see Hello animation 1 goes up then a delay then Hello animation 2 will be shown like before and the it repeats from begining.
Comment: @MahboobehMohammadi Did you mean you want just some delay while text is shown and then move fast to up/down?
Comment: i want to show first text, then movie it up and show the second then move the second up and show first and go on like this.


How to animate points being added to a plot in a certain amount of time?

Question: I have a df containing 10000 data points that I want to add to a plot one by one using gganimate. So the data is:
df = data.frame(x = runif(10000),
                y = runif(10000),
                z = 1:10000) # z column is needed for transition_states()

I created the animation using:
library(ggplot2)
library(gganimate)

ggplot(df, aes(x, y)) +
        geom_point() +
        transition_states(z) +
        shadow_mark() +
        labs(title = "Point num: {closest_state}")

But I struggle to get all of my points shown in the animation. For example, I would like to show the points from 1 to 10000 to be added in the animation in about 60-100 seconds.
Answer: You can use the duration parameter in the animate function.
anim <- ggplot(df, aes(x, y)) +
  geom_point() +
  transition_states(z, state_length = 0) +
  shadow_mark() +
  labs(title = "Point num: {closest_state}"

animate(anim, duration = 80, fps = 10000/80, renderer = gifski_renderer())

Since you have a lot of points in your dataset, I would suggest to group your point so that you don't end up with 10,000 frames, which takes a lot of time to compute!
Comment: This did not work for me. It only shows up to ~4000 points added, and it is for some reason much longer than 80 seconds.


Como utilizar o PyOpenGL no pycharm

Question: Fiz as instalações corretas do PyOpenGL e do Acellerate. Consigo usar as bibliotecas tranquilamente na IDLE do python 3.7.2, entretanto quando vou tentar fazer um import delas usando a IDE Pycharm não consigo utilizar as bibliotecas. Oque devo fazer? Provavelmente devo copiar alguma pasta para algum diretorio do Pycharm, mas não sei em qual ;/
Answer: Verifique suas configurações de execução e depuração: run/debug configurations (em inglês)
Veja se o caminho para o interpretador (Python interpreter), é o mesmo onde você instalou os pacotes ou usa em outra ferramenta.

Como utilizar o PyOpenGL no pycharm


Somar date com int

Question: Estou tentando fazer uma soma de dias, informados em um campo int,com um campo date usando SQL. Testei da forma abaixo, mas ele soma o dia, mas ignora mês e ano. Existe alguma forma de fazer essa soma?
SELECT DATE_FORMAT(ocorrencias.dt_fechamento, '%d-%m-%Y')+50 as calendario from ocorrencias

Comment: Segue um tutorial que talvez possa te ajudar! link [http://www.devmedia.com.br/funcoes-de-manipulacao-de-data-do-mysql-5-5/25539](http://www.devmedia.com.br/funcoes-de-manipulacao-de-data-do-mysql-5-5/25539)
Answer: Tenta utilizar o comando DATE_ADD(ocorrencias.dt_fechamento, INTERVAL 50 DAY)
Exemplo: SELECT DATE_FORMAT(DATE_ADD(expiry_date,INTERVAL 3 DAY), '%d %m %Y' )
Comment: Valeu! Era isso ai!
Answer: Use a função date_add() do MySQL
SELECT DATE_FORMAT(date_add(ocorrencias.dt_fechamento, INTERVAL 50 day), '%d-%m-%Y')
       as calendario FROM ocorrencias

Exemplo simples:
SELECT  date_add(now(), INTERVAL 50 day)

Comment: @Diego isso mesmo, aproveite e anote a função que faz subtração em datas, `date_sub()` :D
Comment: boa! vou anotar no caderno essa. Valeu!

Somar date com int


Validate if Date1 > Date2

Question: If I have 2 date fields in a content type: Event Start Date and Action Start Date.
Is there a way to validate that Action Start Date is later/greater than Event Start Date while creating the content?
Answer: If you use the Date module you can create one field and configure it to use a start and end date. Then the module will validate the end date is greater than start date automatically for you.
Comment: Thanks for your answer but actually I want both to be separate as I want to name them differently. You can consider both of them as start date but one should be after the another. May be I should rephrase my question.
Answer: Use Date restrictions module. This is how to achieve what youre looking for:

Enable Date Restrictions Min/Max and Date Restrictions Host Entity modules.
Edit your target field (Action Start Date).
Expand More settings and values » Restrictions » Minimun date.
Choose option "Host entity: get fixed date from a field in the host entity" and select your source field (Event Start Date).

This will restrict the minimum value for the target field to the value of the source field.
If you're using date popup, it will restrict available days in the target field's popup, also if the source field changes, the target will be updated via ajax to reflect the new restriction.
Comment: It looks to be the one I need but I use drupal 6, is backporting to version 6 possible?
Comment: Backporting Date Restrictions (or the portion involved here) is probably fasible but it seems hard, and a no rewarding task to do. You better look for another solution.
Answer: How about this

hook_form_alter your content type.
Add custom validation handler to it.
In the validation callback try using date diff as below.

<code>   // Pass the date field value while instantiating date object.
   $event_start = new DateTime('2013-01-26');
   $action_start  = new DateTime('2013-07-26');
   $date_diff = $event_start->diff($action_start);
   $date_diff->format('%R'); // use for point out relation: smaller/greater
   $date_diff->days;
</code>
if action date is larger/greater then $date_diff->format('%R'); will return '+' else it will return '-'.
Comment: It is far to hard to read this:
Why not using simple comparison operators?
https://stackoverflow.com/questions/961074/how-do-i-compare-two-datetime-objects-in-php-5-2-8

Validate if Date1 > Date2


Testing statistical independence before using ICA

Question: First a little bit of background.
I'm interested in exploring the performance of Independent Component Analysis (ICA) in the context of disentangling intracranial EEG signals. These signals are measures of voltage along time at different points in space. If we understand intracranial EEG as a mixture of different signals generated by different neural elements, say, different neuronal populations, ¿would be possible to recover these components (representing different neuronal elements) from the mixture using ICA?  At the core of this idea is the assumption that components are statistically independents, maybe pretty unrealistic since a natural consequence of neuronal connectivity is the correlated neuronal activity.
So, my question is. I have some benchmark signals that have been generated in a realistic computational model of the cerebral cortex microcircuit. Each signal is a temporal series representing the activity of a neuronal population. Before mixing the signals and apply ICA, I would like test about the independence assumption. Then, I'm looking for methods (and software) to test the independence between these signals: measures of mutual information, linear and non-linear correlations, whatever (I suppose). Any way to support or reject the assumption of independence.
I'm sorry for the lack of mathematical formality, and maybe accuracy, in the question. I'm not an expert. Feel free to correct me if I've made an error above.
Thank you in advance!
Comment: To my understanding, there is no requirement of independence per se in the incoming signals themselves (otherwise what would be the point of the ICA?). Its the results that are independent.

What is important for the ICA is that the data are "full rank". That is, none of the input signals can be completely defined by some combination of the other signals.

For example if the average reference was also an input signal. Note that the AR would not have to correlate particular well with any other channel.

Matlab has the function "rank" for this. Which EEGLAB uses to check prior to ICA.
Answer: Partially answered in comments:

To my understanding, there is no requirement of independence per se in
the incoming signals themselves (otherwise what would be the point of
the ICA?). Its the results that are independent. What is important for
the ICA is that the data are "full rank". That is, none of the input
signals can be completely defined by some combination of the other
signals. For example if the average reference was also an input
signal. Note that the AR would not have to correlate particular well
with any other channel. Matlab has the function "rank" for this. Which
EEGLAB uses to check prior to ICA.

– Mensen


Snowflake dbt connectin Fail on github

Question: Using this cicd yml file in github.
name: dbt Build and Push

on:
  push:
    branches:
      - main

permissions:
  contents: write

jobs:
  build:
    runs-on: ubuntu-20.04

    container:
      image: xemuliam/dbt:1.5

    steps:
      - name: Check out code
        uses: actions/checkout@v3

        run: |
          dbt debug
          dbt seed
          dbt docs generate

Few days back cicd was working fine. Got this in console.
04:26:28  Connection:
04:26:28    account: myaccount
04:26:28    user: ***
04:26:28    database: mydb
04:26:28    schema: dev
04:26:28    warehouse: DBT
04:26:28    role: SYSADMIN
04:26:28    client_session_keep_alive: False
04:26:28    query_tag: None
04:26:28  Registered adapter: snowflake=1.5.2
04:26:29    Connection test: [OK connection ok]

But now it gives me this
Connection test: [ERROR]
09:06:46  dbt was unable to connect to the specified database.
The database returned the following error:

  >Database Error
  Error detecting the version of libcrypto

Also when I tried "dbt debug" locally it is working fine. It also works fine on gitlab cicd.
I have changed nothing in code or any config but connection is failing.
Comment: Possibly related: https://github.com/wbond/oscrypto/issues/78#issuecomment-1741032472
Answer: The issue seems to come from the python package oscrypto:
https://github.com/wbond/oscrypto/issues/78
Replacing the oscrypto requirement by pointing on the particular commit d5f3437 corrects the issue. Once a new release is pushed 1.3.1 you need to use this one.
Answer: I solved the issue with:
poetry add oscrypto@git+https://github.com/wbond/oscrypto.git@d5f3437ed24257895ae1edd9e503cfb352e635a8

Snowflake dbt connectin Fail on github


Create link with node id parameter

Question: When I create a new content type, I want to prefill a link field following this format :
/my/specific/link?node_id=<CURRENT_NODE_ID>

Is it possible to access the node id before his creation? Or a specific id to refer to this new content type??
[EDIT]
More details :
I want to add a content type, which is a job offer. In this content type, there is a Link field, that refer to a web form to apply to the job offer. So I need to prefill the link field, with the node ID to know the job you are applying for.
Answer: You do not need a link field for that. You can generate link at theme level for example. Or even better in hook_node_view:

The module may add elements to $node->content prior to rendering. This hook will be called after hook_view(). The structure of $node->content is a renderable array as expected by drupal_render().

Last but not least, if you really want it to be a field, use Computed Field and have it calculated at save.

Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it.
Comment: Thanks a lot!
I'm using computed field but it doesn't work (Display Code (PHP)):
global $node;
$display_output = l("Apply", "apply_form?job_offer=".$node->nid);
Comment: @Bibix your comment above probably should be a separate question.

Create link with node id parameter


How can I execute PostgreSQL stored procedure

Question: I have following question. I've created a stored procedure in PostgreSQL and I have can not execute it, I've tried to use exec , but I get wierd error.
Here is my stored function:
<code>  DROP PROCEDURE IF EXISTS checkName();
CREATE PROCEDURE checkName(c_Name varchar)
      LANGUAGE plpgsql
AS $$
declare notify_msg text := 0;
  BEGIN
    if(LENGTH(c_Name) > 41) THEN
         notify_msg = 'Restaurant name can not be longer than 41 characters.';
        END IF;
  END;
$$;

COMMENT ON PROCEDURE checkName IS 'This procedure checks if the restaurant name is longer than 40 characters';
</code>
And this is how I tried to execute it:
<code>exec checkName('ThisIsTest');
</code>
This is the error I'm getting:
<code> ERROR: FEHLER:  Funktion »checkname« existiert bereits mit den selben Argumenttypen
</code>
Is there a different way to execute stored procedure in PostgreSQL.
Comment: https://www.postgresql.org/docs/current/sql-call.html
Comment: @a_horse_with_no_name May I  ask you one more thing ?
Answer: According to documentation you have to use
$ Call functioname
https://www.postgresql.org/docs/11/sql-createprocedure.html


What is law of random variable $ S_n = X_1 + \cdots + X_n $

Question: We consider a sequence $ (X_n)_{n \leq 1} $ of mutually independent random variables defined on a probability space $ (\Omega, \mathcal{A}, \mathbb{P}) $  with value in $\{-1,1\}$ and such that, for all $ k \geq 1$ $$ \mathbb{P} (X_k = -1) = \mathbb{P} (X_k = 1) = \frac{1}{2} $$ For all $ n \geq 1 $, we set $ S_n = X_1 + \cdots + X_n $
Problem
What is law of random  variable $S_n$?
An idea please.
Comment: $X= 2Y-1$ where $Y$ has the distribution $P(Y=0)=P(Y=1)=\frac{1}{2}.$ The distribution of the sum of $Y$'s is well-known.
Answer: Ignoring order, all drawings with $p$ positives are equiprobable with probability $\dfrac1{2^p}\dfrac1{2^{n-p}}=\dfrac1{2^n}$, and the values sum to $p-(n-p)=2p-n$. Observe that all sums are distinct, hence a function of $p$.
Now if we restore order, the $p$ positives can appear in $\displaystyle\binom np$ different ways, and this gives us the distribution:
$$\mathbb P(S_n=2p-n)=\binom np\frac1{2^n}$$ for $p=0,1,\cdots n$.
Answer: Hint: The Count for values of $+1$ among the sequence of ${(X_k)}_{k=1}^n$ shall be the count for successes among $n$ independent Bernoulli trials with an identical success rate.


Assembly Syscalls in 64-bit Windows

Question: I am on windows 10, with Cygwin installed. I have been using Cygwin for the compilation/assembly of c and assembly programs using Cygwin-installed "gcc" and "nasm". From what I know, nasm has a -f win64 mode, so it can assemble 64-bit programs. Now, for x64 assembly programming on windows, it seems youtube has a lack of tutorials. Most assembly programming tutorials on youtube are either for x64 linux or x32 windows, and I need to be able to print a string to the console on x64 windows, without the use of any external functions such as C's "printf".
StackOverflow links that didn't work for me:
64-bit windows assembler
As far as I know, nasm does support 64-bit windows using the -f win64 extension. Also, the answers have nothing to do with how to write an actual program in assembly on x64 bit windows
How to write hello world in assembler under Windows?
All answers that give code give only code for outdated windows versions (32-bit), except one. The one answer that works for 64 bit I tried, but the command to link the object file gave an error for me, that the system could not find the path specified.
windows x64 assembler?
This site does not contain any code, which is what I need. Also, I am trying to write the Hello World program in nasm.
64 bit assembly, when to use smaller size registers
The question actually contains code for a hello world program, but when executed under cygwin on windows 10 (my device), I get a segmentation fault.
Why does Windows64 use a different calling convention from all other OSes on x86-64?
I have tried disassembling a C Hello World Program with objdump -d, but this calls printf, a prebuilt C function, and I am trying to avoid using external functions.
I have tried other external functions (such as Messagebox), but they return errors because something does not recognize the functions. Also, I am trying not to use any extern functions if possible, only syscall, sysenter, or interrupts.
CODE:
Attempt #1:
    section .data
    msg db "Hello, World!", 10, 0
    section .text
    mov rax, 1
    mov rdi, 1
    mov rsi, msg
    mov rdx, 14
    syscall
    mov rax, 60
    mov rdi, 0
    syscall

Problem: Assembles and links properly, but throws a segmentation fault when run.
Attempt #2:
    section .text
    mov ah, 0eh
    mov al, '!', 0
    mov bh, 0
    mov bl, 0
    int 10h

Problem: Does not assemble properly; says "test.asm:3: error: invalid combination of opcode and operands"
Attempt #3:
    section .text
    msg db 'test', 10, 0
    mov rdi, 1
    mov rsi, 1
    mov rdx, msg
    mov rcx, 5
    syscall
    mov rdi, 60
    mov rsi, 0
    syscall

Problem: Assembles and links properly, but throws a segmentation fault when run.
Attempt #4:
    section .text
    mov ah, 0eh
    mov al, '!'
    mov bh, 0
    mov bl, 0
    int 10h

Problem: Assembles and links properly, but throws a segmentation fault when run.
I just need an example of a hello world assembly program that works on 64-bit Windows 10. 32-bit programs seem to return errors when I run them. If it is not possible to print a string to the console without using external functions, an example of a program that uses external functions and works on 64-bit Windows 10 would be nice.
I heard that syscalls in windows have far different addresses than those in linux.
Comment: [This MASMForum link](http://masm32.com/board/index.php?topic=6486.0) will help you. It is the key to the best MASM64 Windows source available.
Comment: Attempt 2 is 16bit DOS code, will not work as windows executable, and `mov al,imm8` instruction can contain only single 8 bit immediate value, so you have to pick if you want number `'!'` (`33` IIRC ASCII table) or number `0`, you can't assign to register `al` both at the same time. Attemp 3: unless you specify with some label where the code starts, it may start at the beginning of `.text` section, executing string data "test" as instructions (too lazy to check what kind of instructions they form). Labels like `_start:` are often used in cooperation with linker to specify entry point into code
Comment: Attemp 4 is again 16 bit DOS code (using BIOS interrupt `int 10h`), so you can use this one under some DOS emulator/VM, like dosbox. .. (and I guess attempt 1 and 3 are using linux or OSX syscalls, but I don't know how windows 64b system calls work, so I wouldn't recognize even correct way, I use only linux for last decade and sometimes DOS in dosbox)
Comment: Is there a special flag to set with ld to specify where the start of the program is? I tried putting _start in there and putting the message within section .data and it still says "Illegal instruction", so I am assuming that ld still doesn't know where to start.
Comment: This question looks a little like [this](https://stackoverflow.com/a/41622071/2189500).
Comment: Oh, can someone give an example of using external functions then or a system dll to perform the operation of a simple syscall like write? Interesting that microsoft doesn't publish its own syscalls.
Answer:
Attempt #1:
Attempt #2:

Internally Windows uses either interrupts or system calls. However they are not officially documented and they may change anytime Microsoft wants to change them:
Only a few .dll files directly use the system call instructions; all programs are directly or indirectly accessing these .dll files.
A certain sequence (for example mov rax, 5, syscall) might have the meaning "print out a text" before a Windows update and Microsoft might change the meaning of this sequence to "delete a file" after a Windows update.
To do this Microsoft simply has to replace the kernel and the .dll files which are officially "allowed" to use the syscall instruction.
The only way to call Windows operating system functions in a way that it is guaranteed that your program is still working after the next Windows update is to call the functions in the .dll files - just the same way you would do this in a C program.
Example (32-bit code):
push 1
push msg
push 14
call _write
mov dword [esp], 0
call _exit

Comment: The author requested 64 bit code. Is the C-level Windows API in x86_64 still a 32 bit interface? Which DLL's provide `_write` and `_exit`?
Comment: Been a while since I posted this, but I figured out which dll files to use and how to include them. C:\\Windows\\System32\\msvcrt.dll seems to provide the entire C standard library, and all you have to do is say "extern [whatever C function]" and link msvcrt.dll with your object file. It doesn't use syscalls, but considering what you said about syscalls in windows being unstable, I'm okay with using C's standard library in assembly. That's likely the only way to make it platform independent anyhow.
Comment: Just 1 question: do you know if there are in fact lower level dll files I could be using in place of msvcrt.dll? The fact that sizeof in C varies from implementation to implementation somewhat concerns me. I found user32.dll and kernel32.dll in System32, do these provide the windows library?
Comment: solved my own problem. there's a thing that comes with Visual Studio called dumpbin that, with /exports, allows you to see all functions that come with a .dll file. And it turns out that kernel32.dll does indeed provide the windows api.
Comment: @mcandre The main aspect of my answer was the "platform independent" part: Directly using system calls will not work. The x86_32 example code is only there to make the last part of the answer clearer and not to give a "valid" example of code.
Comment: Syscalls numbers indeed change: https://hfiref0x.github.io/syscalls.html but the question is an excersise in reverse engineering and not normal code.
Answer: Take a look at ReactOS source code. This Program is using Native API to print Hello, world!\n to console.
const char *Message = "Hello, world!\n";
HANDLE hStdOut = NtCurrentPeb()->ProcessParameter->StandardOutput;
IO_STATUS_BLOCK IoStatusBlock;
NtWriteFile(hStdout,
            NULL,
            NULL,
            NULL,
            &IoStatusBlock,
            (PVOID)Message,
            sizeof(Message),
            NULL,
            NULL);
// NtTerminateProcess(NtCurrentProcess(), STATUS_SUCCESS);
RtlExitUserProcess(STATUS_SUCCESS);

extern NtWriteFile
; extern NtTerminateProcess
extern RtlExitUserProcess

%define NtCurrentPeb() gs:[0x60]
%define ProcessParameter 32
%define StandardOutput 40
%define NtCurrentProcess() -1

section .rdata
        Message db `Hello, world!\n\0`
        Length equ $-Message
section .text
        global main
main:
        sub rsp, 88
        mov rcx, NtCurrentPeb()
        mov rcx, ProcessParameter[rcx]
        mov rcx, StandardOutput[rcx]
        xor edx, edx
        xor r8d, r8d
        xor r9d, r9d
        lea rax, 72[rsp] ; IoStatusBlock
        mov qword 32[rsp], rax
        mov qword 40[rsp], Message
        mov qword 48[rsp], Length
        mov qword 56[rsp], 0
        mov qword 64[rsp], 0
        call NtWriteFile

        // mov rcx, NtCurrentProcess()
        // xor edx, edx
        // call NtTerminateProcess
        xor ecx, ecx
        call RtlExitUserProcess
        int3

Explanation
First we extract StandardOutput handle by accessing _RTL_USER_PARAMETERS from PEB.
This is hStdout returned from GetStdHandle(STD_OUTPUT_HANDLE);
call NtWriteFile to write into StandardOutput handle.WriteFile call NtWriteFile.
WriteConsole* call NtDeviceIoControlFile.
the NtDeviceIoControlFile is more complex than NtWriteFile calls.
call RtlExitUserProcess to exit.
Actually we can just do TerminateProcess(GetCurrentProcess(), ERROR_SUCCESS); rather than ExitProcess(ERROR_SUCCESS);.
The second one is much safer, it does cleanup before Terminate self process.  Rtl is not system call, it stands for RunTimeLibrary.
It's extended C lib. It calls NtTerminateProcess inside that similar to kill(), Nt never had exit_group() similar system call.
Calling Convention
syscall instruction clobber R11for rflags  and RCX for RIP so the first argument is on R10.

System Call Number
Arg0
Arg1
Arg2
Arg3

RAX
R10
RDX
R8
R9

About the stack argument, it's started from 40[rsp] due to shadow store (32 bytes), and 8 bytes from call instruction.
So if you want libc-free program. You can change from RCX to R10, pass the stack argument from 40[rsp], and call NtXxx to mov eax, SYSCALL_NR.
This program is stil depends on ntdll.dll because NT never had a stable system call number.
Compability
May work from Windows 8 and above. See https://www.mandiant.com/resources/blog/monitoring-windows-console-activity-part-one
Comment: The `syscall` instruction itself clobbers RCX, but the DLL interface like `call NtWriteFile` still follows the function-calling convention, with the first arg in RCX.  That's what your example shows.  (The DLL function probably does `mov eax, call_number` / `mov r10, rcx` / `syscall` / `ret` and maybe some other library shenanigans, same as on Linux with libc wrapper functions for system calls.)  So you'd only need to care about the special calling convention if you were inlining `syscall` manually, with the unstable call number from https://j00ru.vexillium.org/syscalls/nt/64/
Comment: Ah thanks, edited. Also Windows Internals structure may changed on alter version. see https://ntdiff.github.io/

Assembly Syscalls in 64-bit Windows


Como subir uma aplicação web (html e css) pra um servidor local?

Question: Afim de usar o Livestyle (ferramenta que atualiza o css em tempo real no browser), preciso subir minha aplicação web (html + css) pra um servidor local, mas como posso fazer isso?
Sempre usei o Tomcat pra minhas aplicações PHP e JAVA, mas nunca pra html puro.
Obrigado!
Comment: Use o servidor embutido do php dentro da pasta do projeto. https://www.php.net/manual/pt_BR/features.commandline.webserver.php
Answer: o HTML, CSS e até mesmo JAVASCRIPT (utilizado no front-end) são compilados por seu navegador (ex.: Chrome, Firefox, Edge...); então você pode simplesmente arrastar seu arquivo HTML para o navegador que ele irá abrir e os respectivos caminhos serão respeitados.
Ao arrastar você verá o caminho físico de sua máquina na URL.
Caso seja necessário ter o caminho 127.0.0.1 você pode usar diversas soluções, como o Wamp: https://sourceforge.net/projects/wampserver/ (supondo que você use Linux)
Comment: entendo, porem para eu ver a mudança no css eu preciso atualizar a pagina, e com o Livestyle essa mudança acontece assim que eu modifico o css, porem apenas se estiver num servidor local (127.0.0.1 por exemplo)
Comment: Entendi, eu uso o Wamp, coloquei o link na resposta, funciona bem legal


Como posso criar um visual de Cartela de Apostas de 20 números no Jframe

Question: É um jogo onde sua aposta estará concorrendo a Sena, Quina e Quadra, por isso cada aposta só pode ter 6 números, eu preciso que usuário selecione 6 números dentre esses 20 e depois eu pego esses 6 selecionados e faço a aposta dele. Mas eu só preciso dessa Cartela de Apostas.
Então Como posso criar uma Cartela de Apostas de 20 números onde você selecionará apenas 6 deles clicando nele, depois pegar os números que foram selecionados. A parte de comparação e criar números randomicamente já está pronta e funcionando, eu estou usando 6 JComboBox de 1 a 20 para que o usuário escolha os 6 números, mas seria mais prático se ele clicasse nos números espalhados na tela, eu também queria uma bola atrás de cada número pra dar uma ideia de Bingo.
Obrigado pela atenção!
Comment: É um jogo onde sua aposta estará concorrendo a Sena, Quina e Quadra, por isso cada aposta só pode ter 6 números, eu preciso que usuário selecione 6 números dentre esses 20 e depois eu pego esses 6 selecionados e faço a aposta dele.
Comment: Ok vou preparar uma resposta para ver se te ajuda, contudo havias de reformular a tua pergunta está um pouco confusa
Comment: ok obrigado, farei isso.
Answer: Verifica o código, penso que assim fica mais pratico do que selecionar os números por uma combobox, falta implementar a regra de só deixar selecionar 5 números, mas isso penso que agora consigas fazer.
Código:
public class Matrizz extends javax.swing.JFrame {
private List<JToggleButton> listTogglebu = new ArrayList<JToggleButton>(20);
/**
 * Creates new form Matrizz
 */
public Matrizz() {
    initComponents();
    JPanel jPanel1 = new JPanel();
    JPanel jPanel2 = new JPanel();
    this.setLayout(new GridLayout(2,0));
    jPanel1.setBorder(new EmptyBorder(5, 5, 5, 5));
    this.setSize(500,300);
    this.add(jPanel1);
    this.add(jPanel2);
    jPanel1.setLayout(new GridLayout(2, 10));

    for (int y = 0; y < 20; y++) {
        listTogglebu.add(new JToggleButton("" + (y + 1)));
        jPanel1.add(listTogglebu.get(y));
    }
    JButton ver = new JButton("Selecionados");

    jPanel2.add(ver);
     ver.addActionListener( new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                      printSelecionado();
                 }

        });

}
  private void printSelecionado() {
            for (JToggleButton jToggleButton : listTogglebu) {
                if(jToggleButton.isSelected())System.out.println(" numero:"+jToggleButton.getText());

      }
        }

resultado:

output:
run:
numero:3
numero:4
numero:6
numero:12
numero:15
numero:17

Comment: Ficou legal J Santos, eu irei implementar desse jeito mesmo, ficou mais prático, era exatamente isso que eu queria, Obrigado!


expected ')' before '(' token when using NULL macro in C

Question: This is my code for a program that creates an environment to run a Java .jar file. I am using the _execl function and am programming on Windows:
#include <stdlib.h>
#include <stdio.h>
#include <process.h>

int setenv(const char *name, const char *value, int overwrite);

int main()
{
    setenv("JAVA_HOME2", "path\\to\\java.exe", 1);
    char *var, *param, *path;

    var = getenv("JAVA_HOME2");
    param = ("-jar");
    path = ("path\\to\\foo.jar");

    intptr_t _execl(var, param, path, NULL);
}

int setenv(const char *name, const char *value, int overwrite)
{
    int errcode = 0;
    if(!overwrite) {
        size_t envsize = 0;
        errcode = getenv_s(&envsize, NULL, 0, name);
        if(errcode || envsize) return errcode;
    }
    return _putenv_s(name, value);
}

However, VS Code returns the error: expected ')' before '(' token on line 16, which is intptr_t _execl(var, param, path, NULL);.
Does anyone have any solutions?
Comment: `intptr_t _execl(var, param, path, NULL);` is nonsense. that `intptr_t` has no business being there. It seems you either forgot the `var = ` or copy/pasted a prototype, then filled in the blanks without trimming the return type. And fyi, I removed the `java` tag you had linked to this post; clearly this has *nothing* to do with Java when its a C compilation error.
Comment: save the compilation after the preprocessor sometimes helps to understand a vague error message, look in your compiler docs what the CLI option is.
Answer: You're getting an error here:
intptr_t _execl(var, param, path, NULL);

Because this is not a function call but a declaration of a function.
By putting a type name before the function, you're declaring that _execl is a function whose return value is of that type.  The parameters given to the function are then taken as the names of those parameters, and since NULL is not a valid identifier for a parameter you get an error.
If you look at the several other places you call a function such as setenv and getenv you're not putting a type name first.  So remove it:
_execl(var, param, path, NULL);

And now you have a function call.
This still won't call the function properly, however.  The first argument is the path to the executable, and the remaining arguments are command line arguments to the program, and the first command line argument is the name of the program being run.  So you actually want to call it like this:
_execl(var, var, param, path, NULL);

Or this:
_execl(var, "java", param, path, NULL);

Also, there's no need for parenthesis around a string constant when you assign it to something.  So this:
param = ("-jar");
path = ("path\\to\\foo.jar");

Can be replaced with:
param = "-jar";
path = "path\\to\\foo.jar";

Or you can get rid of these temporaries entirely and pass the strings directly to _execl:
_execl(var, "java", "-jar", "path\\to\\foo.jar", NULL);


What does "128 / 256 bit SSL and 2048 bit CSR encryption" mean in practical terms?

Question: One of the SSL certificates mentioned here says "128 / 256 bit SSL and 2048 bit CSR encryption". Does that mean that the generating the certificate is very secure but the communications handled by the certificate are not?
Or is "CSR encryption"?!? used to enhance the standard SSL?
Are all 2048 bit certificates as above or are there others which are 2048 bit CSR and 2048 bit SSL?
In short, if I want a very secure certificate, what exactly am I looking for?
Comment: A CSR is a Certificate Signing Request; it is, in theory, used to indicate the name you want in a certificate as well as to prove that you have possession of the public-key you want attached to that name.
Answer: SSL uses several encrypt algorithmic at different points.
Typically it will use a asymmetric cryptography authenticate the hosts and establish trust between the client and server.  Then a random key will be generated and shared between the hosts and a symmetric cryptography algorthim will be used for the actual payload.
Typically the asymmetric key will be RSA with key sizes of 1024, 2048, or 4096.  The key size doesn't really affect the symmetric that is used for the payload.  These days most certificate vendors will sign a 2048 or 4096 certificate request, key sizes of 1024 are pretty weak.  While most CA keys are 2048 bits, many will sign larger keys, so you don't have to limit your private key to 2048 bits.
The symmetric algorithim that is used will depend on the client and server.  The client and server will select the most secure option available.  If you are using apache then you use the SSLCipherSuite to select which symmetric ciphers you will permit.
Asymmetric cryptography is has the large sizes of the keys(2048,4096), and it is very slow.  That is why it is only used during the initial phase.  Once the connection is established, communication happens over the relatively fast symmetric cryptography which uses the smaller key sizes (128,256).
Comment: Encryption is actually optional in SSL/TLS. Normally SSL is used to authenticate the server, or both the server and the client; then, depending on the configuration of the client and server, it may use the asymmetric keys used for authentication in the initial negotiation steps to generate a (temporary) Master encryption key which is then used to generate (even more temporary) encryption keys.
Comment: the bulk encryption key is used for a while, the client or server will decide it is time to generate a new bulk encryption key every oft and again, they use the master secret key. Wikipedia has a [decent walk through](http://en.wikipedia.org/wiki/Transport_Layer_Security#Simple_TLS_handshake) if you're curious on the topic.
Comment: @Zoredache Thank you for the very detailed answer. Can I then clarify - the smaller keys used for the payload - are they unique per packet? That is to say if you broke the asymmetric bit, you'd get the random key which would allow you to calculate the symmetric keys for each packet but breaking a single packet by brute force won't expose anything other than that packet?
Comment: They are not unique per packet, they are unique per connection.  But I believe SSL can periodically change the session key and does for some applications.
Comment: @Ram and Zoredache thanks both of you - perfect answer :)


Como retirar dtype de linha do dataframe?

Question: Rodando o código:
def novacoluna(df):
  coluna_adicionada = {}
  coluna_adicionada['retorno_diario']= df['quota_value']/df['quota_deslocada']
  return pd.Series(coluna_adicionada, index=['retorno_diario'])

agrupamento_por_fundo = df.groupby([df['fund_name'], df['date']]).apply(novacoluna)

Para adicionar uma nova coluna ao dataframe agrupado, quando rodo agrupamento_por_fundo.head() os dados aparecem dessa forma:

Como faço pra poder adicionar na coluna apenas os resultados da conta, sem 10397 antes e o dtype depois?
Comment: pq vc criou uma função para adicionar coluna? Tenta criar a coluna diretamente
Answer: Criar uma coluna como resultado de outras duas é mais simple do que parece
Crie o DataFrame
import pandas as pd

>>> df = pd.DataFrame({'quota_value': [10.10, 20.0, 15.50, 50.0], 'quota_deslocada': [2, 2, 5, 5]})

>>> df
   quota_value  quota_deslocada
0         10.1                2
1         20.0                2
2         15.5                5
3         50.0                5

Crie a nova coluna baseada nas outras duas
>>> df['retorno_diario'] = df['quota_value']/df['quota_deslocada']

>>> df
   quota_value  quota_deslocada  retorno_diario
0         10.1                2            5.05
1         20.0                2           10.00
2         15.5                5            3.10
3         50.0                5           10.00

Espero que ajude
Answer: O problma é que a sua função cria uma série com os dados que você precisa,
e na sequência você cria um dataframe  contendo a série, na linha que tem o "return".  Na resposta o conteúdo de cada célula é ele mesmo uma série completa, e a representação da série inclui a informação de 'dtype'.
Sua função poderia ser só:
def novacoluna(df):

  coluna_adicionada = df['quota_value']/df['quota_deslocada']
  coluna_adicionada.name = 'retorno_diario'
  return coluna_adicionada


How to read notes with an "ornate X" notehead for guitar?

Question: I am not sure how to read notes with noteheads that look like a double-sharp (see the image below for an example). So far, I have dicovered that this notehead might be called "ornate X notehead" and can be found in the SMuFL specification.
At first, I thought this might be another style of writing ghost notes (usually with a simple X as notehead). However an arrangement of "Sweet Home Alabama" in one of my songbooks contains such ghost notes with a simple X as notehead while the chorus has these ornate X noteheads. So the latter cannot also stand for ghost notes. By the way, alongside standard notation the songbook contains tabulatur where these noteheads appear too, without a stem of course. So, how do you play these notes on guitar?

Update: Adding examples from the songbook as requested in comments. First image shows the use of use of convential x-noteheads for muted notes in the intro. Second image shows the ornate x noteheads in the chorus.
Comment: Thank you. I've updated the question to include samples from the mentioned book.
Comment: Usually such note heads are written to notate percussion instruments, that's why I assumed this must be just a rhythm beat on the guitar body. But now I'm sure these must be the 2 stopped (muted) notes you can hear in this video. (in an overview of 200 music sheets with this title (s. *google images*) I couldn't find these note heads.  It would be kind if you'd poste a copy of your sheet.
Comment: One could be palm muting and the other dead notes. But you might check the book's front matter to see if they have included an explanatory chart, as many publishers will when using idiosyncratic notation. You could even see who the editor is (likely a professor somewhere) and send them an email.
Comment: @Max Sadly the book doesn't contain any hints, despite they claim it is for beginners. The author doesn't have a public e-mail nor is he a professor.
Answer: So this must be dead notes:
I've found this description in a german wiki:
A dead note or ghost note on a guitar is a tone that does not have a precisely defined pitch, but is more like a dull clack.
A dead note is generated by not pressing the string down on the fingerboard of the instrument when striking it, but only touching it with the index finger, middle finger or the entire palm of the hand and thereby dampening it.  The string is struck in the normal way by plucking, playing the plectrum or slapping the electric bass.
Dead notes are marked with an "x" on the staff or tab and are often e.g. with the electric bass on the line on which the open string would normally stand.  However, it is still considered as a counting time.
Source: https://de.wikipedia.org/wiki/Dead-Note
For more information:
https://www.ultimate-guitar.com/en/wiki/Dead_note
A dead note effect is achieved by resting your fretting hand across the strings without actually pressing the strings against the fret. A dead note (also called muted note or silenced note) adds more percussion than pitch.
Comment: Thank you. I understand that bit. But I still don't know why there are two different kind of noteheads for ghost notes in the same song.
Answer: The 2 eighth notes on beat 1 and 3 are immediately muted as you can see in this video:

When he sings mute mute strum he explains how he holds his right hand on the strings **muting ** them by the hand. These muted notes are your notes with the x-heads.
also this guy explains he is stopping the 2 notes with the plec:
Answer: Meanwhile I've bought the book "Behind Bars" by Elaine Gould and found the answer:
"The double-sharp sign is sometimes used for crossed noteheads, but is best reserved for use as an accidental symbol."
The book also confirms our assumption, that double-sharp noteheads may indicate "finger damping" amongst other uses, which are not relevant for this case. However, it is a completely confusing inconsistency to use both the crossed noteheads and double-sharp noteheads for the exact same function in one score, like we have seen above. The arranger simply made a mistake.