message not written in file, what am i doing wrong?

Question: Here is the code
class Program
{
    public static TraceSource TS = new TraceSource("myTraceSrc", SourceLevels.All);
    static void Main(string[] args)
    {

        TS.TraceInformation("Hello Trace from Main");
    }
}

here is the config file
<system.diagnostics>
    <sources>
        <source name="myTraceSrc" switchName="switch1">
            <listeners>
                <add type="System.Diagnostics.TextWriterTraceListener" name="myLocalListener" initializeData="c:\Test.Log" />
                <add name="consoleListener" />
            </listeners>
        </source>
    </sources>
    <sharedListeners>
        <add type="System.Diagnostics.ConsoleTraceListener" name="consoleListener" traceOutputOptions="None" />
    </sharedListeners>
    <switches>
        <add name="switch1" value="all" />
    </switches>
</system.diagnostics>

Message is displayed on the console but nothing goes in file. What am I doing wrong?
Answer: Have you tried calling TraceSource.Flush?
Comment: so is there anyway to have trace message written instantly rather calling Flush() every single time?
Comment: @imak: I think you want `` but to be honest I haven't used trace listeners myself.
Comment: @Jon: as far as i can see autoflush is available when you are using trace. In case of tracesource, i don't see this been available for  source, listener or switch. Not sure where to set this property
Comment: @imak: Right... I'm not sure either, I'm afraid :(
Comment: @Jon actually just added the line  before  and removed Flush() call and it worked like a charm.
Answer: Try creating the TextWriterTraceListener manually like it is described here.


$f(x^2 + 1) = f(x)g(x)$ $\forall$ x $\in\mathbb{R}$ $\Rightarrow$ no. of roots of $f(x)=$?

Question: If two real polynomials $f(x)$ and $g(x)$ of degrees $m$ $(\ge2)$ and $n$ $(\ge1)$ respectively, satisfy $f(x^2 + 1) = f(x)g(x)$; for every $x \in \mathbb{R}$ , then what can be said about the root(s), if any, of $f(x)$?
Answer: Clearly, if $x$ is a root then so is $x^2+1$.
Thus if $x_0$ is the largest real root, then we need $x_0\ge x_0^2+1$, that is $x_0^2-x_0+1\le0$. But $x_0^2-x_0+1=(x_0-\frac12)^2+\frac34>0$
Answer: Hint: If $x$ is a root of $f$, then $f(x) = 0$. That means that $f(x^2 +1) = f(x)g(x) = 0$. So that means that $x^2 + 1$ is a solution. But $x < x^2 + 1$. You can see by noting that $x = x^2 +1$ doesn't have any roots and since $1^2 + 1 > 1$ you have $x < x^2 +1$ for all real numbers $x$.
So you must now have two roots, so ...
Answer: Suppose $r=r_0$ is a root. Then $r_1=r_0^2+1$ if distinct, is another, and $r_2=r_1^2+1$, if distinct, is another, and so on. Hence, either two situations arise. Which are...?
Comment: I think one situation is that we have m distinct roots like this. But what is the other one you are hinting at?
Comment: @A.Chakraborty Either $f$ is the zero polynomial, or has no roots at all. In particular $f$ cannot be of odd degree.
Answer: I guess the answer is that $f(x)$ has no roots.
Firstly we can see that degree of $f(x)$ must be even.
Why?. Using the left hand side of the definition $dgr(f(x))=2m$.
Then if we had one root $(r_0)$, we could build the increasing sequence $r_{n+1}=r_n^2+1$ of solutions. Which it's a contradiction with the fact of a finite degree of the polynomial.


Tabela Calculadora PHP

Question: Não sei programar em javascript então gostaria de uma ajuda de vocês,  de como proceder nesse caso.
  Nesse código abaixo gostaria de saber como faço uma calculadora dinâmica,
  por linha, igual ao exemplo abaixo. eu só tenho que colocar a quantidade:

        Cod
        Data
        Tipo
        Quantidade
        Valor | Desconto
        Valor Total

<?

$cmd = "SELECT * FROM cotacao";
    $produtos = mysql_query($cmd);
    $total = mysql_num_rows($produtos);
    while ($linha = mysql_fetch_array($produtos)) {

$valor = $linha['valor'];
$data_abertura = $linha['data_abertura'];
$cod = $linha['cod'];

?>

        <?echo $cod?>
        <?echo $data_abertura?>

        <?echo $p_tipo_veiculo?>
        <input type="text" name="qtd" />

         <input type="text" value="<?echo $valor?>" />

        <input type="text" name="total" value="resultado" />

        <?}?>

Answer: Podes fazer assim:
function getClosest(el, tagName) {
    while (el = el.parentNode) {
        if (el.tagName.toLowerCase() == tagName) return el;
    }
}

window.addEventListener('keyup', function (e) {
    // caso não seja o input pretendido
    if (e.target.name != 'qtd' || e.target.tagName != 'INPUT') return;

    // ir buscar o valor inserido
    var value = parseFloat(e.target.value);

    // ir buscar o outro valor dentro da mesma linha
    var tr = getClosest(e.target, 'tr');
    var valor = tr.querySelector('input[name="valor"]');

    // calcular a soma
    var sum = value + parseFloat(valor.value);

    // inserir a soma no input total da mesma linha
    tr.querySelector('input[name="total"]').value = sum;
});

Exemplo: http://jsfiddle.net/mxjfLu1x/
Deixei comentários no código. A função getClosest() é para subir no DOM e ir buscar o tr para ir buscar depois inputs que estão na mesma linha.
Repara que adicionei no HTML name="valor" no input do meio. Assim facilita e simplifica a encontrar esse input.
Coloquei o oscultador de eventos no window pois tenho a sensação que essa tabela é dinamica e saaim não tens de te preocupar com delegação.
Comment: Eu tinha feito isso mais não tinha funcionado....    Agora ta funcionando perfeitamente. Blz
Comment: Perfeito era isso mesmo que preciso, mais to com um probleminha. é que tenho que colocar o name="valor" com []  ficaria assim name="valor[]"  name="qtd[]"  name="total[]"  mais ai, para de fazer o caulculo como posso acertar isso?
Comment: @FabioHenrique nesse caso é só acrescentar `[]` nas strings do código -> http://jsfiddle.net/mxjfLu1x/1/
Comment: Parceiro...Voce saberia me informar como faço para que total apareça formatado exemplo 0.00,00 –
Comment: @FabioHenrique dá uma olhada aqui: http://pt.stackoverflow.com/q/11018/129
Answer: Ta um pouco confuso mas acho que entendi.
Primeiro, para múltiplos inputs, você coloca assim:
<input type="text" name="qtd[]" />

Depois você recupera os valores novamente dentro do seu while para somar com o que precisa:
<?

$cmd = "SELECT * FROM cotacao";
$produtos = mysql_query($cmd);
$total = mysql_num_rows($produtos);

$i = 0; //inicia o contador

while ($linha = mysql_fetch_array($produtos)) {

    $valor = $linha['valor'];
    $data_abertura = $linha['data_abertura'];
    $cod = $linha['cod'];

    $resultado = $_POST["qtd"][$i] + $valor; // aqui ta o resultado
    $i++; //incrementa o contador para pegar o próximo valor

?>

Depois você exibe o resultado:
<input type="text" name="total" value="<?echo $resultado?>" />

Comment: Ola Essa parte [] array eu sei como fazer a minha dificuldade e no calculo dinâmico quando eu colocar um numero no primeiro campo e fazer o resultado do calculo instantaneamente no ultimo campo
Comment: Entendi, então acredito que o @Sergio respondeu sua pergunta

Tabela Calculadora PHP


How to execute .load function after another function finished? See the functions in example

Question: I making a game with few scenes. Each scene have it's own javascript which i want to load asynchronously and after that to load the particular scene file into div.
Here is my html
index.html
<!DOCTYPE html>

    <title></title>

    hello

                                    <button id="submit">submit</button>

Here is two working functions.
First one
$(document).ready(function() {

    $('#submit').click(function() {

        (function() {
           var myscript = document.createElement('script');
            myscript.type = 'text/javascript';
            myscript.src = ('second.js');
            var s = document.getElementById('first');
            s.parentNode.insertBefore(myscript, s);
        })();

    });

});

And here is the second
 $( "#test" ).load('div.html');

I want the second command: $( "#test" ).load('div.html'); to be executed straight after the scripts loading finished successfully.
How can i do that?
Answer: just put the another .load() to the call back of another .load() function
$( "#targetelement" ).load('myajaxpage.php', function(){
      //call back
       $( "#targetelement" ).load('myajaxpage.html', function(){
             //call back
      })
});

as I realized the the title of your question is different on what you are asking which is

I want the second command: $( "#test" ).load('div.html'); to be
  executed straight after the scripts loading finished successfully.

you need to use a script loader that have callback functionality like the following script loaders below
http://headjs.com/
head.js("/path/to/jquery.js", "/google/analytics.js", "/js/site.js", function() {

   // your function you want to call after the scripts above is loaded

});

http://yepnopejs.com/
yepnope.injectJs("jquery.js", function () {
  // your function you want to call after the scripts above is loaded

}, {
  charset: "utf-8"
}, 5000);

well there are a lot of script loaders but the two above in my experience were really good for me
Comment: That is not an answer to my question
Comment: Actually i want to load some scripts for the scene1, and after i go to the scene2 i want to replace those scripts with others. So i have to give them an id or something (in order to replace them after)
So i prefer to use the function that i wrote. Or is it any ability to replace scripts with head.js ??
Comment: well you need to try it by yourself, you can replace scripts but replacing the variables and objects stored in the memory that came from the previous scripts cannot be replaced without manually doing it in code.. you need to put them in a single namespace so if you changed that namespace everything will be replaced (like what jquery does with their single common namespace which is the `$`)


Learning scales (skipping major scales)

Question: I dabble in the piano for half a year(+) now.
Just learned about scales through this video (

).
I guess i listen to a lot of music with minor scales, and I want to emulate that sound which clearly inspires me to play the piano.
So know I am asking my self if makes sense for me learning all the major scales.
Is there any advantges or disadvantages starting with other scales then major?
Answer: The disadvantage will be that most instructional materials will treat the major scale as the 'default' scale, and compare other scales to it. What you will also discover as you learn more music, is that the minor scale you are most likely hearing, 'natural minor', is actually the same notes as the major scale. For example, A natural minor and C major have the exact same notes (all the white keys on the piano).
This is what is called a mode. So memorizing the notes of the major scale and practicing the finger patterns will help you understand other music teaching videos, and actually teach you the natural minor scale at the same time. However, if you want to learn a particular song that is in a minor key, go right for it! You can learn a song you love first, and then learn the theory behind it later.
Answer: In almost every case, when talking about alternate scales, the intervals are always in relation to the major scale(Ionian); same as a major triad is the base reference for chords. If you are just learning scales and chords it will be pretty hard to follow someone teaching the new scales. I didn't watch the whole video but when he shows the 12 major scales near the end I think that makes it seem much harder to learn. Each one of those major scales follow the same formula and once you memorize that Single pattern you can play any of the 12 major scales without needing to know each note off the top of your head (but eventually you will know them).
The major scale formula after playing the first note is:
 W-W-H-W-W-W-H
W = Whole step | H = Half step
Learning the scale formulas will help you much faster than simply learning what notes are in each major or minor scale. I hope it opens a whole new world of music to you like it did for me
Comment: Don't agree that knowing the formula will help much faster, except finding the actual notes. Patterns will embed the scale notes better. But, a good first (I guess) answer. +1.
Comment: On guitar (which is *not* the instrument in question!) if one can play a D major scale, using only fretted notes, then Db major is the same pattern exactly, just everything one fret down. Just as Eb major is the same pattern only one fret higher. There is no need to 'know' any more than that. And on guitar, it's a little confusing with notes available either up some frets, or onto the next string and down some frets! But I take your point, and we're all different in how we reach a final conclusion.
Comment: Maybe not. I can speak of my personal experience. I played guitar for 8 years not knowing any theory (like most guitarists) and I could play G major scale and D major scale and Blues pentatonic; but ask me to play a Db major scale? I would have no clue how to play it if I didn't already know the notes or fingering. when I learned about intervals and the scale formula I could then play any major scale on any instrument. it increased my understanding of scales rapidly.
Answer: I guess there's a distinction between learning the concept of a scale and understanding how it's constructed, and doing the kind of repetitive learning exercises that get the knowledge 'into your fingers' so you can play fast using that scale.
If you want to think or communicate in traditional theory terms at all, then as the other answers have already said, knowing what the major scale is (and that it tends to be a reference point for other terminology) is essential. But again, as Timinycricket says, there's very little to learn - if you know the W-W-H-W-W-W-H pattern, you know the major scale.
But in terms of what you practice, there's no harm at all in starting with the scales you like the sound of. A lot of rock guitar books start off by teaching the blues scale on the assumption that people will want to be playing music that sounds like that, and that's absolutely fine.
Having said that, one of the aims when learning an instrument is to be able to know/hear in your mind what a note is going to sound like before you play it, and likewise, to hear a note in your mind and be able to go straight to it on the instrument. Learning various different scales will have value in building up your mental map of where all the different notes are, even if with some scales you're learning which notes to avoid in your actual playing.

Learning scales (skipping major scales)


Como enviar headers em todas as requisições HTTP ionic 3

Question: O meu código está assim, gostaria de saber como enviar um token Authorization em todas as requisições http feitas em ionic 3:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'page-categoria',
  templateUrl: 'categoria.html'
})
export class CategoriaPage {

  constructor(public nav: NavController, public httpClient: HttpClient) { }

  toTest() {

    let data = {};
    let url = 'https://localhost/gestor2.0/public/categoria/';
    let headers = new HttpHeaders({
      'Authorization': 'Bearer ' + 'TdSa4512csdgfa368747654'
    });

    this.httpClient.post(url, data, { headers: headers })
      .subscribe((result: any) => {
        console.log('sucesso ao salvar');
        console.log(result);
      },
        (error) => {
          console.log(error);
        });
  }

}

Me retorna este erro ao abrir a página categoria:

core.js:1449 ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[CategoriaPage -> HttpClient]:
    StaticInjectorError(Platform: core)[CategoriaPage -> HttpClient]:
      NullInjectorError: No provider for HttpClient!
  Error: StaticInjectorError(AppModule)[CategoriaPage -> HttpClient]:
    StaticInjectorError(Platform: core)[CategoriaPage -> HttpClient]:
      NullInjectorError: No provider for HttpClient!
      at NullInjector.get (core.js:1003)
      at resolveToken (core.js:1301)
      at tryResolveToken (core.js:1243)
      at StaticInjector.get (core.js:1111)
      at resolveToken (core.js:1301)
      at tryResolveToken (core.js:1243)
      at StaticInjector.get (core.js:1111)
      at resolveNgModuleDep (core.js:10896)
      at NgModuleRef.get (core.js:12129)
      at resolveDep (core.js:12619)
      at c (polyfills.js:3)
      at Object.reject (polyfills.js:3)
      at Tab.NavControllerBase._fireError (nav-controller-base.js:223)
      at Tab.NavControllerBase._failed (nav-controller-base.js:216)
      at nav-controller-base.js:263
      at t.invoke (polyfills.js:3)
      at Object.onInvoke (core.js:4760)
      at t.invoke (polyfills.js:3)
      at r.run (polyfills.js:3)
      at polyfills.js:3
Comment: Dá uma olhada: [Implementando Interceptor para requisições HTTP em sua aplicação Angular 4](https://medium.com/@cesarolvr/implementando-interceptor-para-requisi%C3%A7%C3%B5es-http-em-sua-aplica%C3%A7%C3%A3o-angular-4-5dba022dfcb1)
Answer: Olá!
Eu costumo a gerar um Service para abstrair os métodos HTTP:
import { environment } from '../../../environments/environment';
import {
   Http,
   RequestOptions,
   RequestOptionsArgs,
   Response,
   Request,
   Headers,
   XHRBackend
} from '@angular/http';

@Injectable()

export class HttpServices {
headers: HttpHeaders;
options: object;

constructor(private readonly http: HttpClient) { }

endpoint: string = environment.apiUrl; //pega o endereço do arquivo environments.ts

get( uri: string ) {
    return this.http.get( this.endpoint + uri ).pipe(
        tap((res: Response) => {
            this.onSuccess(res);
        }),
        retry(0),
        catchError(this.onCatch),
        finalize(() => this.onEnd())
    );
}

post(url: string, data): Observable<any> {

    return this.http.post( this.endpoint + url, data )
        .pipe(
            tap((res: Response) => {
                this.onSuccess(res);
            }),
            retry(0), // retry a failed request up to 3 times
            catchError(this.onCatch), // then handle the error
            finalize(() => this.onEnd())
        );
}

e nos services específicos como no seu caso - CategoriaService* ficaria assim:
// o caminho da abstração das chamadas HTTP
import { HttpServices } from './http.services';

CategoriaService {

  URI = '/categoria'
  // injetando o Service Http criado
  constructor( private httpCustom: HttpServices) {

  }

  salvar( data ) {
    // ja retorna uma Observable
    return this.httpCustom.post( this.URI, data )
  }
}

e na hora de usar em uma Page, pode ser usada a Service específica.
Na abstração vc pode implementar os comportamentos padrão, que forem necessários para cada chamada Http.
Espero ter ajudado.
Abraço
Comment: entendi, mas não quero usar Service entende, pq só vou precisar nesta page.
Comment: Entendi. Man, tudo leva a crer que seja alguma coisa no app.module, importar o HttpClientModule  e add no array de imports, como na resposta do @silvio-campos. Pesquisei sobre o erro e a maioria das soluções levam a essa solução.
Answer: Boa tarde, me parece que o erro apresentado é por que você não fez a importação do HttpClientModule.
Vá no seu app.module.ts e importa o module.

import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}
Comment: não é não, já fiz o import no appmodule


Node.js, Nginx and Varnish with WebSockets

Question: I'm in the process of architecting the backend of a new Node.js web app that i'd like to be pretty scalable, but not overkill. In all of my previous Node.js deployments, I have used Nginx to serve static assets such as JS/CSS and reverse proxy to Node (As i've heard Nginx does a much better job of this / express is not really production ready).
However, Nginx does not support WebSockets. I am making extensive use of Socket.IO for the first time and discovered many articles detailing this limitation. Most of them suggest using Varnish to direct the WebSockets traffic directly to node, bypassing Nginx. This is my current setup:
Varnish : Port 80 - Routing HTTP requests to Nginx and WebSockets directly to node
Nginx : Port 8080 - Serving Static Assets like CSS/JS
Node.js Express: Port 3000 - Serving the App, over HTTP + WebSockets
However, there is now the added complexity that Varnish doesn't support HTTPS, which requires Stunnel or some other solution, it's also not load balanced yet (Perhaps i will use HAProxy or something). The complexity is stacking up! I would like to keep things simpler than this if possible.
Is it still necessary to reverse proxy Node.js using Nginx when Varnish is also present?
As even if express is slow at serving static files, they should theoretically be cached by Varnish. Or are there better ways to implement this?
Comment: Haven't you tried https://github.com/yaoweibin/nginx_tcp_proxy_module ?
Comment: I've not tried it yet, the general feeling that I got was that the varnish solution was preferable. I guess the reason I haven't tried that yet is that it seems quite experimental, this could simplify things though (albeit requiring a custom Nginx build). Will experiment.
Comment: varnish can load balance https://www.varnish-cache.org/trac/wiki/LoadBalancing
Answer:
Is it still necessary to reverse proxy Node.js using Nginx when Varnish is also present?

Varnish can cache your static files from node.js app. You need to provide correct http headers (cache-control) from your app (for default VCL). Or you can tune your VCL to cache  static files based on URL or for example contenet-type.
For SSL/TLS suport  I'm using Pound with Varnish (http://www.apsis.ch/pound).
As it was noted in comments Varnish can also be load balancer.
Answer: No matter what pieces of software you'll be using, you still need these features implemented:

websocket backend
application backend
static backend
reverse proxy
content cache
http router
loadbalancer
https filter

Complexity is not about how many pieces of software you are using - it's more depending on how many configuration features you have.
It's more simple to have bigger number of dedicated software than different modules with duplicated features in play.
For other question: it's usually bad to chain-up reverse proxies, so you'd better set up varnish to use nginx only as static backend, or use node.js for this and set up caching in varnish to achieve required performance.


how do I control order of promoted pages?

Question: I have a bunch of pages I have promoted to the front page and I'm wondering how I can control the order the items appear in? This is in Drupal 7.
Answer: There is a tutorial at Custom re-ordered front page teasers. It uses the pre-packaged view Front page that comes with Views, as well as the Nodequeue module to re-order the teasers.

The Nodequeue module allows users to collect nodes in an arbitrarily
  ordered list. The order in the list can be used for a any purpose
Answer: Another possible solution is the draggable views module.
You can set up a view of promoted content ordered by the draggable views weight and then add another display to the view for reordering.
There is more detailed information on how to set this up on the draggable views documentation page.
With this you get a little contextual link on your view that will take you to the reordering page, where you can drag and drop your list of content to reorder, than save that order.
It's quite a nice user experience for reordering lists.
Answer: It can be achieved by just changing the Authored on date & time. Works very well!
Comment: Then you don't have an accurate "authored on" date.
Comment: @rooby That is correct but it works for me to re-order the "promoted on fronpage" items - and it may also for other people...


Three positive numbers a, b, c satisfy $a^2 + b^2 = c^2$; is it necessarily true that there exists a right triangle with side lengths a,b and c?

Question: If so, how could you go about constructing it? If not, why not?
I am new to proofs and I was reading a book where they posed this question. I understand that if we are given any right triangle, the relation between sides a, b, c is given by pythagorus' theorem; although, given $a^2 + b^2 = c^2$, does it necessarily imply that there exists a triangle with sides a, b, c?
Answer: Suppose you draw a right triangle such that the two legs have lengths $a$ and $b$ respectively. This is clearly possible, since one can construct line segments of any integer length and can construct right angles. Now, the hypotenuse has to have some length $c$, and this $c$ must satisfy
$$a^2+b^2=c^2$$
by the Pythagorean theorem. However, there is exactly one $c$ that satisfies this for any given $a$ and $b$.
You're right to be suspicious of the converse, but since the equation uniquely defines one parameter given the others, it turns out not to be a problem.
Answer: Yes, the triangle , $ \{ (0, 0), (0, b), (a, 0) \} $.
Comment: Maybe elaborate a bit and explain why this triangle has the given side lengths.
Answer: Yes, it does.  You can construct a pair of perpendicular lines, then measure $a$ units from the intersection down one and $b$ units down the other.  Draw the line between those two points and you have your triangle.
Answer: Take a right angle triangle with base length $a$ and height $b$. Then its hypotenuse, which we temporarily denote by $d$, should satisfy $d^2= a^2 + b^2$. Therefore, $d^2 = c^2$, which gives $d =c$ because they are both positive numbers.
Answer: If $a^2 + b^2 = c^2$, then:

$(a+b)^2-c^2 = 2ab \ge 0$ and so $c \le a+b$.
$(b-a)^2 -c^2 = -2ab \le 0$ and so $b-a \le c$, that is, $b \le a+c$.
$(a-b)^2 -c^2 = -2ab \le 0$ and so $a-b \le c$, that is, $a \le b+c$.

This proves that there exists a triangle with sides $a,b,c$.
By the law of cosines, we have $c^{2}=a^{2}+b^{2}-2ab\cos \hat c$, and so $\cos \hat c=0$, that is, $\hat c = 90^\circ$. Therefore, the triangle is a right triangle.
Answer: Yes indeed the converse for Pythagoras is also true. When such a construction is made (SSS) the relation is satisfied. The vertices lie on a semicircle, and by Thale's thm a right angle is enclosed.


Orientation Keyboard Movement

Question: Here are some great tutorials on portrait textfield movement.
One
Two
Three
My View, on the other hand, rotates to both portrait and landscape, and in both orientations the keyboard obscures the textfield...  Right now, both portrait, and One of the landscape orientations work.
So I'm wondering how I can include both landscape orientations.
Here's what I'm doing:
<code>-(void) keyboardWillShow:(NSNotification *)notif{
 if ([serverIP isFirstResponder]){
    if (isPortrait && self.view.frame.origin.y >= 0){
        [self setViewMovedVertical:YES];
    }
    else if (!isPortrait && self.view.frame.origin.x >= 0){
        [self setViewMovedHorizontal:YES];
    }
 }
}
</code>
To move the view. Here are the corrosponding methods
<code>#define PORTRAIT_KEY_OFF 216
#define LANDSCAPE_KEY_OFF 140

-(void) setViewMovedVertical:(BOOL)movedUp{
 [UIView beginAnimations:nil context:NULL];
 [UIView setAnimationDuration:0.4];

 CGRect rect = self.view.frame;

 if (movedUp){
     rect.origin.y -= PORTRAIT_KEY_OFF;
     rect.size.height += PORTRAIT_KEY_OFF;
 }
 else{
     rect.origin.y += PORTRAIT_KEY_OFF;
     rect.size.height -= PORTRAIT_KEY_OFF;
 }

 self.view.frame = rect;

 [UIView commitAnimations];
}

-(void) setViewMovedHorizontal:(BOOL)moved{
 [UIView beginAnimations:nil context:NULL];
 [UIView setAnimationDuration:0.4];

 CGRect rect = self.view.frame;

 if (moved){
     rect.origin.x -= LANDSCAPE_KEY_OFF;
     rect.size.width += LANDSCAPE_KEY_OFF;
 }
 else{
     rect.origin.x += LANDSCAPE_KEY_OFF;
     rect.size.width -= LANDSCAPE_KEY_OFF;
 }

 self.view.frame = rect;

 [UIView commitAnimations];

}
</code>
And here's the method to move it back down
<code>-(IBAction) serverIPDone: (UITextField *) sender{
if ([serverIP isFirstResponder]){
 if (self.view.frame.origin.y < 0){
    [self setViewMovedVertical:NO];
 }
 if (self.view.frame.origin.x < 0){
    [self setViewMovedHorizontal:NO];
 }
 [serverIP resignFirstResponder];
}
}
</code>
Hope you can help! If I've anti-disambiguated (see what I did there?) the question, please let me know!
Comment: not sure how both landscapes dont work..they will use the same code..interesting. good question
Comment: I figured that both would work. It's somewhat frustrating =)
Answer: FINALLY Figured it out!!!!
Here's what was wrong: The origin did indeed change between the two landscape modes. So all you have to do is detect which version of landscape you are in, and add or subtract based on that!
<code>-(IBAction) serverIPDone: (UITextField *) sender{
if ([serverIP isFirstResponder]){
        if (self.view.frame.origin.y < 0){
            [self setViewMovedVertical:NO];
        }
    if (self.view.frame.origin.x != 0){
        [self setViewMovedHorizontal:NO];
    }
    [serverIP resignFirstResponder];
}
}
</code>
The previous makes sure that the keyboard is unset.
<code>-(void) setViewMovedVertical:(BOOL)movedUp{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.4];

CGRect rect = self.view.frame;

if (movedUp){
    rect.origin.y -= PORTRAIT_KEY_OFF;
    rect.size.height += PORTRAIT_KEY_OFF;
}
else{
    rect.origin.y += PORTRAIT_KEY_OFF;
    rect.size.height -= PORTRAIT_KEY_OFF;
}

self.view.frame = rect;

[UIView commitAnimations];
}

-(void) setViewMovedHorizontal:(BOOL)moved{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.4];

CGRect rect = self.view.frame;

if (moved){
    if (leftLandscape)
        rect.origin.x -= LANDSCAPE_KEY_OFF;
    else
        rect.origin.x += LANDSCAPE_KEY_OFF;
}
else{
    if (leftLandscape)
        rect.origin.x += LANDSCAPE_KEY_OFF;
    else
        rect.origin.x -= LANDSCAPE_KEY_OFF;
    NSLog(@"after: %f",rect.origin.x);

}

self.view.frame = rect;

[UIView commitAnimations];

}
</code>
The Previous will do the actual movement of the keyboard. I got rid of the resizing, you can add it back in.
<code>- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)x
                                     duration:(NSTimeInterval)duration{

if (UIInterfaceOrientationIsPortrait(x)) {
    isPortrait = TRUE;
}
else {
    isPortrait = FALSE;
            leftLandscape = (x == UIInterfaceOrientationLandscapeLeft);
}

}
</code>
The Previous will make sure you set the variables isPortrait and leftLandscape correctly.
It took too long, but I'm finally DONE!!!

Orientation Keyboard Movement


control one sections height

Question: I am making my own fishing website:) But I am really in doubt how to structure some of my sections. The pictures below shows how I would like this section. On that specifik section I have a 100% width. But if I set a height and padding on that sections, it affects all my other col-12. So how can I set a height, padding, margin on that specifik section?
How I would like my page:

My Site:

HTML:

sdf

Home

Favorite Flies

Rated

Sea

Lake

Autaum

Summer

Winter

CSS:
    body {
        color: #797979;
        font-family: 'roboto';
        font-weight: 300;
        padding: 0px !important;
        margin: 0px !important;
        font-size: 14px;
    }
h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
        font-family: 'roboto';
        font-weight: 300;
        text-align: center;
    }
    a,
    a:hover,
    a:focus {
        text-decoration: none;
        outline: none;
    }
    ::selection {
        background: #48cfad;
        color: #fff;
    }
    ::-moz-selection {
        background: #48cfad;
        color: #fff;
    }

        #map {
                width: 100%;
                height: 300px;
              }

        .global-nav {
            overflow: hidden;
            margin-bottom: 0px;
            height: 55px;
            background: #333;
        }
        .main-header {
            background: url(../img/bg_1.jpg) no-repeat center center fixed;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            background-size: cover;
            height: 700px;
            overflow: hidden;
        }

        /* Rows */
        .row{
          margin-left:-15px;
          margin-right:-15px;
         }
        .row:after{
          content:'';
          display:block;
          clear:both
        }
        /* General properties of columns */
        .col{
          padding: 0rem;
          float:left;
        }

        /* Column Definition */
        .col-1{
          width:8.33333333%
        }

        .col-2{
          width:16.66666667%
        }

        .col-3{
          width:25%
        }

        .col-4{
          width:33.33333333%
        }

        .col-5{
          width:14.666667%
        }

        .col-6{
          width:50%;
        }

        .col-7{
          width:58.33333333%
        }

        .col-8{
          width:66.6666667%
        }

        .col-9{
          width:75%
        }

        .col-10{
          width:83.33333333%
        }

        .col-11{
          width:91.6666666%
        }
        .col-12{
          width:100%;
        }

Answer: Just add one more class or an id to the 'div' you want for which you want to set the height, padding and margin.
Then jump into your CSS and use the newly made class name or id to set the height, padding and margin.
Code :

.colPadding {
  padding: 20px;
}

Favorite Flies

Comment: Yes. An example might help too:

Favorite Flies

and the CSS:

.colPadding{
  padding:20px;
}
Comment: Ah okay. I actually tought that it was not "good coding" when you made it responsive. But then I will just throw an id on it. Maybe I have to use the same height later on also, so I can call the same id then.
Comment: There is nothing like bad coding unless you are able to get the thing done without harming anything else.If you are working in a group then you must  add comments.
don't forget to validate the answer if it's resolve your issue
Comment: I will remember that. I am always so scared of doing the coding not good enough. My friends says to me, "but if it is working, isnt it fine enough then.." Then you can always make the code better and nicer when with time when you learn more.. Thank you for the answer.
Comment: you are doing like this: col col-12 colPadding. It seems pretty smart. But why are you not using `id="colPadding" og class="colPadding"` ?
Comment: See its the same thing you could have gone with an id="colPadding"
But I personally prefer to use classes(weather you use class or an id its more of a personal choice, using a class make my life easier when i use jquery).
As far as using

' class="colPadding" '

is concerned whats the point in writing a few extra letters when you have a short hand for it.
Comment: Cool thanks a lot. I didnt knew that you could do that. I will do the same thing like you :)

control one sections height


Reentrancy on a Single-Threaded Application

Question: Writing a Winforms application over .NET 4.0 (using VB2010). It has a single form, including an ActiveX COM control asynchronously raising events. The events are handled by hook functions on form's code-file. Application does NOT start any threads (except the main one, ofcourse).
Should I guard from event-handler reentrancy?
Could Event B's hook-function be called while Event A's hook-function is being executed?
{ Searching the web has raised several conflicting answers. I'm puzzled here... }
Answer: It is not any different for ActiveX controls versus .NET controls.  Whatever you do in the event A event handler that affects the control may certainly cause another event to be raised.  Or event A may be raised again.  Another event rarely causes trouble but the latter case usually causes this site's name exception.  And you fix it the same way, a bool field that prevents re-entry.
The underlying mechanics are identical.  An ActiveX control too can fire an event in a property setter.  That doesn't have anything to do with threading or a single threaded apartment.
Comment: There is no "master switch".  An event is not much like an interrupt, you can ignore an interrupt for a while.  That's not possible for an event.  Do consider that you might be worrywarting about this too much.
Comment: Thanks much for your reply.  I added info in a comment above. Isn't there an underlying mechanism for buffering fired events while a previously intercepted event is being handled?
Back in DOS days (as well as today, on embedded systems), I could disable-interrupts when entering a function, and re-enable them before function return, and by that make the function atomic.
Is there a similar "disable-events" mechanism?
Comment: I could use the `Interlocked` class to prevent Event-reentrancy, right? Could it also be used to make sure events are handled **in the order they were fired**?
Could `SyncLock` be simply used for this purpose?
Comment: Again, this has nothing to do with threads.  No point in using Interlocked, there is never an issue about event order, everything runs on one thread.  The UI thread.  A simple bool suffices to detect re-entrancy.
Comment: Thanks. I understand. My question regards the following steps, once re-entrancy was detected: how do I deal with it such that events are NOT thrown and are handled in their firing order? Would a busy-waiting loop on that boolean be sufficient? something like `while (bWait == true);  bWait = true;  Guarded Section;  bWait = false;`
Comment: No.  Why don't you actually practice with one.  Use a TextBox, implement its TextChanged event and append a character to the Text property in the event handler.
Answer: Without knowing which ActiveX control and which events are involved the answer can only be rather general:
You should always handle any reentrancy in a graceful way.
You can either "throw away" any reentry OR you can handle them in parallel OR you can "queue" them and handle them one after the other...
Without further details I don't see a way to be more specific :-(
Comment: @Bliss there is no such mechanism... you will have to build one yourself - by using one queue per event (for example `ConcurrentQueue`) to store all event-specific information and then process the content of the queue... to build a sentinel you could utilize `Interlocked` class...
Comment: Thanks. The COM ActiveX control I'm using is actually an API to a remote server. By calling its methods, commands are sent to the remote server. The events it raises are basically data retrieved from the server. Each event-handler in my code performs a series of procedural calls (i.e. synchronous) within event-context. I must be able to make sure that while a certain event is being processed, no other event shall be intercepted by the application. I thought that a single-threaded application is not be vulnerable to reentrance, but now I understand this is not necessarily correct.
Comment: What could be done to prevent re-entrance?
If it's of any interest, the control I'm using is IB (Interactive Brokers) ActiveX API.
Comment: @Bliss your goal ist still not really clear... do you want to "throw away" any events happening while you you are processing an event OR do you want to queue for further processing ?
Comment: Events must NOT be thrown. They should be queued for later handling, preferably by any existing Windows / .NET mechanism (e.g. buffering all events fired while a previously-intercepted event is being processed).
Comment: Shall look it through. +1 for the useful tip. Thanks!
Comment: One more (important) thing regarding your "queue per event" solution: Mustn't the operation of addition to queue be atomic?? Consider a case in which while queuing a certain event (within the **Queue.Add** function), the same event-handler is reentered, causing queue structure-inconsistency.
Comment: @Bliss yes, it must... that is why I mentioned `ConcurrentQueue` which handles this correctly and efficiently.
Comment: Thank you. I think I shall 1st give a try to the Interlocked class.  :-)
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/19705/discussion-between-bliss-and-yahia)


Como fazer vários prints na mesma linha em python 3?

Question: Quero saber como fazer para os prints serem apresentados na mesma linha usando python 3. Exemplo:
print('1')
print('2')
1
2

eu queria que quando o python fosse printar o número 2, o número um fosse apagado e o 2 aparecesse na mesma linha em que o 1 estava antes.
tentei fazer com um código disponibilizado em outra pergunta aqui mesmo, mas nao obtive o resultado esperado.
import sys
import time

for x in range(11):
  print("{}%".format (x))
  sys.stdout.write("\033[F")
  time.sleep(0.1)

Comment: Por favor. não poste seus códigos como imagem. Como viu nas outras perguntas e respostas, o site possui suporte a códigos fonte. Para mais informações, faça o [tour], leia o guia de [ask] e acesse a [help].
Comment: E, por favor, verifique se o seu terminal possui suporte para tais caracteres. O mesmo código que copiou da outra pergunta funcionou perfeitamente aqui: https://i.stack.imgur.com/Ac7kw.gif
Answer: Python 3 automaticamente coloca uma quebra de linha no final do print, mas você pode sobrescrever com o que você quiser que seja adicionando o parâmetro end:
print('1', end='')
print('2')

Dessa forma o print irá terminar com uma string vazia ao invés de uma quebra de linha e o segundo print será renderizado logo em seguida.
Comment: existe algum parametro do end que apague o que foi printado anteriormente?
Comment: Edição revertida pois o novo texto alterava a resposta. Claramente é dito que é possível passar qualquer valor como `end` na função `print` e posteriormente comentado que com o caractere vazio a saída será na mesma linha. A edição reduzia as informações da resposta e adicionava redundância.


Set Theory: Symmetric Relations

Question: I was just trying to figure out this problem I came across. For a set
$X = \{1, 2, 3, 4, 5\}$ is it possible to come up with a relation on $X$ that is symmetric, but neither reflexive nor transitive?
Also, it is possible to find a relation that is transitive, but neither reflexive nor symmetric?
Thank you!
Comment: For the second part, there is a natural example: The "strictly larger than"-ordering on $X$.
Answer: For the relation $R$ to be not transitive, let $(1,2)\in R$ and $(2,3)\in R$ but $(1,3)\notin R$. If it is to be symmetric, then $(2,1)\in R$ and $(3,2)\in R$. A check shows that $R=\{(1,2),(2,3),(2,1),(3,2)\}$ satisfies the first part.
For the relation to be not symmetric, let $(1,2)\in R$ but $(2,1)\notin R$. A check shows that $R=\{(1,2)\}$ satisfies the second part.
Answer: In what follows I use $aR\,b$ as an abbreviation for $(a,b)\in R$.
To attack problems like these, start with a small relation that satisfies the positive condition. For your second problem, for instance, you could begin by letting $1 R\,2$, $2 R\,3$, and $1R\,3$; if you stop there, you have a transitive relation. Is it reflexive? Is it symmetric? Can you stop at this point?
Of course, you could have started simply with $1R\,1$, which is also transitive, but it's clearly symmetric, so that's a bad idea. The same objection rules out starting with $\varnothing$, the empty relation, in which nothing is related to anything: it's also symmetric. The next simplest way to get transitivity is the one that I actually used.
The same approach works for your first problem and yields the answer suggested by JDH: starting with $1R\,1$ isn't very helpful, but starting with $1R\,2$ and $2R\,1$ works without further modification.
Answer: Let $R$ relate $1$ to $2$ and also $2$ to $1$, but only these. That is, $R=\{(1,2),(2,1)\}$. This is clearly symmetric, but it is not reflexive, since $R$ doesn't relate any number to itself, and it isn't transitive, since $R$ relates $1$ to $2$ and $2$ to $1$, but not $1$ to $1$.
Comment: By 1 X 2 do you mean 1 ~ 2? Like, ~ is the relation marker?
Comment: I edited to clarify.
Comment: Ok thank you! That makes sense, do you have any ideas for the second part? (transitive but neither reflexive nor symmetric)

Set Theory: Symmetric Relations


AES Encryption using RijndaelManged Class: Baes64 encoding and decoding aes encryption string

Question: So, I am having an issue with decrypting the decoded base64 aes string. Is this possible? I wrote a small console program to work this out but no luck. Here is my example:

As depicted, I have successfully converted the base64 back the aes encrypted string, but when I try to decrypt it I get more junk. If a code snippet is need let me. Thank you all for your help :)
UPDATE: Code snippet for decrypting method
static void Main(string[] args)
    {
        string plainText;
        string decrypted;
        string decryptedFromB64EncodedDecoded;
        string fromBase64ToEncryptedText;
        string encryptedText;
        string encryptedTextBase64;
        byte[] encryptedBytes;

        byte[] encryptedBytes2;
        byte[] encryptedBytesBase64;

        RijndaelManaged crypto = new RijndaelManaged();

        UTF8Encoding UTF = new UTF8Encoding();

        Console.WriteLine("Please put in the text to be encrypted.");
        plainText = Console.ReadLine();

        try
        {
            encryptedBytes = encrypt(plainText, crypto.Key, crypto.IV);
            encryptedText = Encoding.ASCII.GetString(encryptedBytes);
            //encryptedBytes2 = Encoding.ASCII.GetBytes(encryptedText);

            encryptedTextBase64 = toBase64String(encryptedText);
            encryptedBytesBase64 = fromBase64String(encryptedTextBase64);

            fromBase64ToEncryptedText = Encoding.ASCII.GetString(encryptedBytesBase64);

            encryptedBytes2 = Encoding.ASCII.GetBytes(fromBase64ToEncryptedText);

            decrypted = decrypt(encryptedBytes, crypto.Key, crypto.IV);
            decryptedFromB64EncodedDecoded = decrypt(encryptedBytes2, crypto.Key, crypto.IV);

            Console.WriteLine("Start: {0}", plainText);
            Console.WriteLine("Encrypted: {0}", encryptedText);
            Console.WriteLine("Encrypted Base64: {0}", encryptedTextBase64);
            Console.WriteLine("From Base64 To AES Encypted Text: {0}", fromBase64ToEncryptedText);
            Console.WriteLine("Decrypted: {0}", decrypted);

            Console.WriteLine("Decrypted From Encode and then Decode Base64 Text: {0}", decryptedFromB64EncodedDecoded);

        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex.Message);
        }

        Console.ReadLine();
    }

public static string decrypt (byte[] textToDecrypt, byte[] key, byte[] IV)
    {
        RijndaelManaged crypto = new RijndaelManaged();
        MemoryStream stream = new MemoryStream(textToDecrypt) ;
        ICryptoTransform decryptor = null;
        CryptoStream cryptoStream = null;
        StreamReader readStream = null;

        string text = string.Empty;

        try
        {
            crypto.Key = key;
            crypto.IV = IV;
            crypto.Padding = PaddingMode.None;

            decryptor = crypto.CreateDecryptor(crypto.Key, crypto.IV);
            cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read);
            //cryptoStream.Read(textToDecrypt, 0, textToDecrypt.Length);
            readStream = new StreamReader(cryptoStream);
            text = readStream.ReadToEnd();
            cryptoStream.Close();

            byte[] decodedValue = stream.ToArray();

            return text;
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (crypto != null)
            {
                crypto.Clear();
            }
            stream.Flush();
            stream.Close();
        }
    }

public static byte[] encrypt(string text, byte[] key, byte[] IV)
    {
        RijndaelManaged crypto = null;
        MemoryStream stream = null;

        //ICryptoTransform is used to perform the actual decryption vs encryption, hash function are a version crypto transforms
        ICryptoTransform encryptor = null;
        //CryptoStream allows for encrption in memory
        CryptoStream cryptoStream = null;

        UTF8Encoding byteTransform = new UTF8Encoding();

        byte[] bytes = byteTransform.GetBytes(text);

        try
        {
            crypto = new RijndaelManaged();
            crypto.Key = key;
            crypto.IV = IV;

            stream = new MemoryStream();

            encryptor = crypto.CreateEncryptor(crypto.Key, crypto.IV);
            cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write);
            cryptoStream.Write(bytes, 0, bytes.Length);

        }
        catch (Exception)
        {

            throw;
        }
        finally
        {
            if (crypto != null)
            {
                crypto.Clear();
            }
            cryptoStream.Close();
        }

        return stream.ToArray();
    }

 public static string toBase64String(string value)
    {
        UTF8Encoding UTF = new UTF8Encoding();
        byte[] myarray =  UTF.GetBytes(value);
        return Convert.ToBase64String(myarray);
    }

    public static byte[] fromBase64String(string mystring)
    {
        //UTF8Encoding UTF = new UTF8Encoding();
        //byte[] myarray = UTF.GetBytes(value);
        return Convert.FromBase64String(mystring);
    }

Comment: I don't see your encrypt method. Am I missing something?
Comment: Let me post the real quick, accidently left that out lol.
Comment: Pretty sure your problem is in the encoding. Can you post the toBase64String and fromBase64String methods.
Comment: yeah sure give me just a sec.
Answer: I don't know how you're decrypting but before you decrypt, you should convert the base 64 string to a byte array before sending it into the decryption.
byte[] encryptedStringAsBytes = Convert.FromBase64String(base64EncodedEncryptedValue);

Then with the byte array you can pass to the CryptoStream via a MemoryStream.
UPDATE
I believe the issue is how you're setting up your streams
            using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
            {
                rijndaelManaged.Padding = paddingMode;
                rijndaelManaged.Key     = key;
                rijndaelManaged.IV      = initVector;

                MemoryStream memoryStream = null;
                try
                {
                    memoryStream = new MemoryStream(valueToDecrypt);
                    using (ICryptoTransform cryptoTransform = rijndaelManaged.CreateDecryptor())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read))
                        {
                            using (StreamReader streamReader = new StreamReader(cryptoStream))
                            {
                                return streamReader.ReadToEnd();
                            }
                        }
                    }
                }
                finally
                {
                    if (memoryStream != null)
                        memoryStream.Dispose();
                }
            }

UPDATE 2
This is how you should basically perform the steps.
To encrypt

Encode your plain text string using the Encoding.GetBytes(stringToEncrypt)
pass the byte[] into the crypto API (via memory stream, etc.)
get the bytes from the encrypted stream and encode the results as Base64

To Decrypt (do the reverse)

Convert the base64 encoded string to bytes using Convert.FromBase64String(base64EncodedEncryptedValue)
pass that byte array into your decryption function above
Comment: Hey :) That's exactly what I'm doing. I'll update with the decrypting code so you can take a look at it, I could be doing something wrong lol.
Comment: Ok cool! I'll give that a shot! I'll let you know if that works here shortly.
Comment: In actualality, I prefer to return a SecureString.or byte[]
Comment: I noticed that you did not pass the key and initialization vector into CreateDecryptor, is that not necessary?
Comment: So I just finished refactoring my streams, and I'm getting the same thing, when decoding the base64 string so that it is the original aes encrypted string and the decrypting that string it give me a bunch of junk :(
Comment: Must be the encryption side then.
Comment: I do use the key and init vector, just after the using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
Comment: Ah, so don't have to pass those into the rijndaelManaged.CreateDecryptor(), that's what was doing. Seems to work either way :)
Comment: That's exactly what I doing :) I have to missing something for this not to be working. Should be using ASCII.GetBytes or UTF8.GetBytes? As of now I'm using ASCII.GetBytes.
Answer: Try:
encryptedBytes2 = Encoding.ASCII.GetBytes(encryptedText);

Based on your comment.  The bytes are just that bytes, so in order to decrypt the ciphertext you need to undo any encoding or series of encodings you have done.
If you really want to go from Encrypted Bytes -> Base64String -> ASCII string -> then decrypt that ASCII string? you would need to base64 decode the ascii string then convert that string to bytes using
Encoding.ASCII.GetBytes(yourdecodedstring);

Note that base 64 decoding is not the same as using Convert.FromBase84String.
Comment: Yes :) but for whatever reason when i get the last step of decrypting the string give returns junk string instead of "foo bar".
Comment: Well his suggest was a lot cleaner then what I was doing, it wasn't wrong. Your answer helped solve my decoding issues. So I wanted both you guys to get credit for good answers and suggestions :)
Comment: That would defeat the purpose what I trying to accomplish, which is to encode the AES to a base64 string and then decode the base64 to the AES encrypted string and then decrypt that.
Comment: So Encrypted Bytes -> Base64String ->  ASCII string -> then decrypt that ASCII string?
Comment: In order to decrypt you need to pass the exact same bytes back.  You can't go from base64 to ASCII and then back to Base64 the way you are doing it.
Comment: For example a in ASCII, is YQ== in base 64.  If you then make the base64 string ASCII and base64 encode that you will get WVE9PQ==.  So you can't just get the bytes from WVE9PQ== and expect to decrypt it.  Does that make sense?
Comment: Ahhhhhhhh, good good. One things I noticed that the second byte[] was larger than the original. I managed to correct this using Encoding.ASCII.GetString and that gave the same number of bytes, but just because they are the same number of bytes doesn't mean the data is the same. I didn't think about.....So my question now is how get achieve this.......
Comment: Can I ask why you need to convert it to ASCII? There might be an easier solution.
Comment: I really don't need to convert to ASCII, if there is a better solution then by all means spill the beans lol :)
Comment: Then doesn't my original answer solve the problem? encryptedBytes2 = Encoding.ASCII.GetBytes(encryptedText);  You successfully encrypted and decrypted the text "foo bar". If you want those bytes stored in ASCII or base64 just convert them, but be sure to convert them back before decryption.
Comment: Yes, I totally had screwed my encryption, decryption, encoding, decoding flow. When you mentioned that I looked at my code again and was like "why am I doing that......stupid" lol. Thanks for your insight man!!! You were really helpful!
Comment: Np - why did you mark the other answer as the one that fixed your issue though?


Como criar uma FUNCTION para formatar moeda no POSTGRE?

Question: Criei uma, porém, não deu certo olha aí:
CREATE FUNCTION formatar_moeda(valor FLOAT) RETURNS VARCHAR(15) AS
$$
   DECLARE
   formatado VARCHAR(15);
BEGIN
  SET formatado = NUMBER(valor,2);
  SET formatado = REPLACE(formatado,'.','#');
  SET formatado = REPLACE(formatado,',','.');
  SET formatado = REPLACE(formatado,'#',',');
  RETURN CONCAT('R$', formatado);
END;
$$
LANGUAGE plpgsql;

Comment: Dá uma olhada aqui: http://paposql.blogspot.com.br/2012/02/funcao-para-formatar-moeda-em-reais-no.html
Answer: Podes fazer assim:
Select to_char(123.45, 'L9G999G990D99');

L - Símbolo da moeda
D - Ponto decimal
9 - Números
G - Separador de unidades
Espero ter ajudado.
Comment: Obrigado pela ajuda... vou tentar.
Answer: Acredito que seja isso que você queria:
CREATE OR REPLACE FUNCTION formatar_moeda(valor FLOAT)
  RETURNS VARCHAR(15) AS
$body$
DECLARE
--------parametros--------
    pValor        ALIAS FOR $1;
--------variaveis---------
    vValor        VARCHAR;
BEGIN
    SELECT to_char(pValor, 'L9G999G990D99') INTO vValor;
RETURN vValor;
END;
$body$
LANGUAGE plpgsql;

Daí você usa passando o valor por parâmetro assim:
SELECT formatar_moeda(123.45)

Conforme o Pedro Luzio explicou na outra resposta:
SELECT to_char(pValor, 'L9G999G990D99') INTO vValor;

L - Símbolo da moeda
D - Ponto decimal
9 - Números
G - Separador de unidades
Answer: se quiser manter a idéia original, sem mudar a definição LC_CURRENCY para pt_BR pode usar o código abaixo

CREATE OR REPLACE FUNCTION formatar_moeda(valor REAL) RETURNS VARCHAR(100) AS
$$
   DECLARE
   formatado VARCHAR(100);
BEGIN
  SELECT  to_char(valor::float, '999G999G999D99') INTO formatado;
  SELECT REPLACE(formatado,'.','#') INTO formatado;
  SELECT REPLACE(formatado,',','.') INTO formatado;
  SELECT REPLACE(formatado,'#',',') INTO formatado;
  RETURN CONCAT('R$', formatado);
END;
$$
LANGUAGE plpgsql;


Retrieving data from XMLHttpRequest on $.Ajax Error Event

Question: As the title says, i want to retrieve my Json data values from a XMLHttpRequest. I already know how to do it by using a common success $.Ajax success event, but i want to get it's values from an error event. A thing that i noticed is not simple to find all kinds of a XMLHttpRequest types.
To explain a little more, here's the scenario: after some inactivity, the user sessions expires. If he tries to do any operations using an Ajax call, he'll be redirected to the login page. I handle this session timeout error on a particular filter that implements an OnException method.
While i can do it using a sort of a hack (by setting manually the HTTP response code), i'd like to do it on "proper way", with no hacks.
OnException method code snippet
filterContext.ExceptionHandled = true;

        // If this is an ajax request, return the exception in the response
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            //If the session has expired, throws a SESSION TIMEOUT error
            if (Session["UserLogged"] == null)
            {
                //The hack mentioned before
                filterContext.HttpContext.Response.StatusCode = 502;
                filterContext.Result = new JsonResult()
                {
                    Data = new { success = false, errorType = "SESSION_TIMEOUT" ,error = filterContext.Exception.ToString() },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }

}
So, by using a simple $.Ajax Error Event, how would i retrive the data from the filterContext.Result? Specifically the errorType parameter.
Answer: You should be able to parse the JSON data out of the jqXHR responseText property in your error handler.
error: function(jqXHR, textStatus, errorThrown) {
          alert('jqXHR.responseText = ' + jqXHR.responseText);
        }

Comment: Added example to answer. From there you will need to parse the response for the json data. I'm not sure off the top of my head what the format would be.
Comment: Yep, you're right. I'll just a simple parse example to transform your answer on a full answer. But thanks anyway!


Players with 300 or more goals in top flight domestic league (European clubs)

Question: Who are the players that has more than 300 goals in top flight domestic league, combined for all the teams that they have played.
Related questions:

Players with 300 or more goals for a single team in top flight domestic league (European clubs)
Players with 400 or more goals for a single team in all competitions (European clubs)
Players with 400 or more goals in all club competitions (European clubs)
Comment: Just to clarify, you are asking about goals scored *in the same competition* or in *all domestic leagues* where the player played? For example, for [Cristiano Ronaldo](https://en.wikipedia.org/wiki/Cristiano_Ronaldo#Career_statistics) should we count together his goals in Primeira Liga, Permier League and La Liga, which yields 3+84+252=339? Or only his goal from La Liga, where he scored 252 and thus he would not qualify for this question?
Comment: All domestic league, in the case with Ronaldo La Liga + Premier League.
Comment: Some of such players could be found on [page 22](http://i.stack.imgur.com/VXixt.png) of [this book](https://books.google.com/books?id=OxswOvHm3FEC&pg=PA22).
Answer: I think this could be a reliable list, but maybe not exact, of players with more goals in the top flight domestic leagues in the world. I only consider goals in national leagues but I don´t consider goals in regional or state leagues, for example, the state championships in Brazil or the Oberliga in Germany before Bundesliga. That's why names like Pele, Romario, or Uwe Seeler with a lot of goals in regional championships are not on this list.
The list is updated to 28 May 2023.

Josef Bican 518 (Bohemia and Moravia 241, Czechoslovakia 206, Austria 71)
Ferenc Puskás 514 (Hungary 358, Spain 156)
Cristiano Ronaldo 498 (Spain 311, England 103, Italy 81, Portugal 3)
Lionel Messi 496 (Spain 474, France 22)
Imre Schlosser 417 (Hungary 411, Austria 6)
Gyula Zsengellér 416 (Hungary 387, Colombia 23, Italy 6)
Jimmy McGrory 408 (Scotland)
Gerd Müller 405 (Germany 365, USA 40)
Hugo Sánchez 400 (Spain 234, Mexico 123, USA 37, Austria 6)
Zlatan Ibrahimović 393 (340 in Europe) (Sweden 4, Netherlands 35, Italy 155, Spain 16, France 113, England 17, USA 53)
Ferenc Szusza 393 (Hungary)
Carlos Bianchi 385 (Argentina 206, France 179)
Alfredo Di Stefano 376 (Spain 227, Colombia 90, Argentina 59)
Gunnar Nordahl 374 (Italy 225, Sweden 149)
Jimmy Greaves 366 (England 357, Italy 9)
Hughie Ferguson 363 (Scotland 286, England 77)
József Takács 360 (Hungary)
Hans Krankl 354 (Austria 320, Spain 34)
Luis Suárez 353 (329 in Europe) (Uruguay 14, Netherlands 91, England 69, Spain 179)
Delio Onnis 352 (France 299, Argentina 53)
György Sárosi 351 (Hungary)
Osvaldo Castro 351 (Mexico 214, Chile 137)
Albert De Cleyn 350 (Belgium)
Victor Hugo Antelo 350 (Bolivia)
Comment: may be worth making this a wiki answer so @Lipata can update easily?
Answer: There are several players who have scored over 300 goals in top flight league.
In the current scenario they they are:
1. Cristiano Ronaldo (442 goals)
2. Lionel Messi (440 goals)
3. Zlatan Ibrahimovic (372 goals)
There are other players like Gerd Muller, Jimmy Graves, Pele and Bican.
It's very unfair of people not counting the Brazilian leagues as the top flight domestic league because in 1960s Brazilian team regularly defeated European teams with ease.
Thus Bican, Pele and then Messi and Ronaldo comes up, out of all the players Pele and Josep Bican has the highest goal ration followed by Gerd Muller, Messi and Ronaldo.
Comment: You can count the Brazilian league in. We're already counting Mexico, Argentina, etc. Feel free to edit additional players into the post above. In the Serie A Pelé only had 100 goals though.


How to Implement inbox style and bigtext style notifications in android 2.2 version?

Question: As Notification.Compact is part of android support library, they should be supported on android 4.0 and below, but I'm not able to see inbox style notification in android 4.0 as well. It works perfectly on android 4.2.
Answer: Handling compatibility
Not all notification features are available for a particular version, even though the methods to set them are in the support library class NotificationCompat.Builder. For example, action buttons, which depend on expanded notifications, only appear on Android 4.1 and higher, because expanded notifications themselves are only available on Android 4.1 and higher.
To ensure the best compatibility, create notifications with NotificationCompat and its subclasses, particularly NotificationCompat.Builder. In addition, follow this process when you implement a notification:

Provide all of the notification's functionality to all users, regardless of the version they're using. To do this, verify that all of the functionality is available from an Activity in your app. You may want to add a new Activity to do this.
For example, if you want to use addAction() to provide a control that stops and starts media playback, first implement this control in an Activity in your app.
Ensure that all users can get to the functionality in the Activity, by having it start when users click the notification. To do this, create a PendingIntent for the Activity. Call setContentIntent() to add the PendingIntent to the notification.
Now add the expanded notification features you want to use to the notification. Remember that any functionality you add also has to be available in the Activity that starts when users click the notification.

refer to this Link
Comment: Thanks @droid

Also, is there any way to combine inboxStyle and BigText Style. If there is only one notification, it should use BigTextStyle, if there is second notification then it should use inboxStyle. 'getActiveNotifications()' is available in API 18, is there any way to implement it in API 16


Accessing IIS web apps through different bindings

Question: I am hosting several web apps on IIS 7.5 on Windows Server 2008 R2. The server has a single IP address and I am using host names to differentiate the bindings to each application. The server has different DNS alias matching the host names, so all works fine within the corporate network. For example:

When I type http://intranet, "intranet" gets resolved by DNS to the server's IP and a request is made to IIS, which uses the binding with the "intranet" host name, which in turn maps to the Intranet web app.

The thing is, I also want users to be able to access the apps from outside the corporate network, by using the server's IP (which is public). This means that IIS should also recognise requests made in the form http://xxx.xxx.xxx.xxx/intranet as corresponding to the Intranet web app. The only way I have found to achieve this is to place the physical folders for all the web apps under the physical folder of the Default Web Site, and leave the default binding for this site. This means that:

When I type http://xxx.xxx.xxx.xxx/intranet, a request is made to IIS, which uses the binding with no host name, which in turn maps to the Default Web Site, and within this web site it looks into the "intranet" physical folder.

Things should work fine in theory, but I stumbled against the following problem. Most of the web apps I am hosting are ASP.NET apps, and use web.config files. When I access one of these apps directly, through the first method (i.e. using a host name), things work OK. However, when I access it using the second method, IIS complains that some settings in the web.config are at the incorrect level. I know why this happens: the request to IIS is being made to a physical folder within a higher-level web app, rather to the web app I am intending to visit, because of the way I have set up the bindings.
My question is: since this configuration strategy breaks ASP.NET web.config behaviour (and probably other things as well), is there other alternatives that I should consider to allow for both name- and IP-based access? Thank you.
EDIT. I have found a solution to this problem now; please see my own answer below.
Answer: I have found a solution to this problem.
What I am doing now is this. I have set up every web app as:

A web site on IIS, with its own binding to a specific host name such as "intranet" in my original example.
A web application under the Default Web Site, which keeps the default catch-all binding with no host name.

For example, the Intranet web app appears as a site on IIS named "Intranet" with a binding to the host name "intranet", so that people accessing the server as http://intranet/ will be directed there; and it also appears as a webb app named "Intranet" under the server's default web site, so that users accessing the server as http://xxx.xxx.xxx.xxx/intranet will be sent there as well. They are two different ways to reach the same physical folder and the same content, and it works flawlessly.
Thanks to all who have helped!
Answer: In short: don't use the second method.
In the Site Bindings for the site, just specify both intranet and yourpublicname.yourdomain.com as the host headers.
Then, assuming it's internet accessible, the same site will be served for both, with different bindings.
Translating the path to and from a site is tricky; better to keep the same site layout and just add a binding?
(Why not do this?)
Comment: I can't do this because our web server does not have a publicly-visible name. In other words, its name is on a private DNS server that works inside the corporate network, but there is no public name for it. The only way I can think of to access it from outside is by IP address, and hence the problem.
Comment: You could simply register a name with an external DNS provider, which would fix this problem. Your solution of allowing it to "fall through" to the default binding also works.


Imprimir caracteres especiais no console do windows

Question: Como imprimir caracteres especiais como 'é' e 'ç' no console do windows (printf)?
Answer: Conforme pode encontrar no site: http://linguagensdeprogramacao.wordpress.com/2011/07/16/resolvendo-problema-da-acentuacao-no-dev-c/

Para resolver este problema basta você usar o comando de
  regionalização do C para que não somente acentue as palavras
  corretamente, mas que mostre datas e horas em português, por exemplo.
Isto é feito usando o comando setlocale da biblioteca locale.h. Segue
  um exemplo de código.

#include <stdio.h>
#include <conio.h>
#include <locale.h>

int main(void)
{
    setlocale(LC_ALL, "Portuguese");
    printf("Alô mundo! \n\n");

    system("PAUSE");
    return 0;
}

----- Edit --------
Caso ainda tenha problema tenta alterar a fonte do Command:
Comment: Obrigado, mas vou aceitar a outra por ter mais detalhes.
Answer: Há três formas de se utilizar esses caracteres especiais no windows :

Passando direto o código no printf: printf("isto \x82"); //imprime isto é
(Esse código acima assume o CodePage 850 )
Criando uma função que utiliza a funcionalidade acima para imprimir os caracteres especiais
um exemplo a função oprintf que está disponível com a licensa LGPL
Ou como o Giovani disse, usando  setlocale.

Nota: sugiro que não utilize system("PAUSE"); nem a biblioteca  quando não houver necessidade. (Estão no exemplo setlocale).
Comment: E qual código de página você está levando em consideração? o \x82 não é "é" em todos os CPs
Comment: E de todo modo, o que é comum aqui pode não ser comum internacionalmente.
Comment: 850, que me parece ser um dos mais comuns.
Comment: Talvez fosse bom complementar a resposta avisando isso, pois não dá pra contar com o CP ser sempre o "comum", mesmo que esta afirmação fosse verdadeira.
Comment: @Bacco atualizei a resposta para especificar isso.
Comment: @mgibsonbr, meu computador antigo usava o Windows em Dinamarquês, meu computador atual está com Windows em Inglês (Canadá). E no computado que tenho acesso (remoto) na faculdade do Brasil coincidentemente usam o mesmo codepage. Concordo que não é universal, mas me parece que funciona para boa parte dos casos.


Windows Server 2019 Cannot Install .NET 3.5

Question: crosspost Microsoft IT Pro Tech Community
crosspost r/sysadmin

Windows Server 2019 Cannot Install .NET 3.5
I am running Windows Server 2019 (Version 1809, Build 17763.4499) and I cannot install .NET Framework 3.5. Below is the current installation status of the feature on my machine:
PS > Get-WindowsFeature -Name  NET-Framework-Features,NET-Framework-Core,NET-HTTP-Activation,NET-Non-HTTP-Activ

Display Name                                            Name                       Install State
------------                                            ----                       -------------
[X] .NET Framework 3.5 Features                         NET-Framework-Features         Installed
    [ ] .NET Framework 3.5 (includes .NET 2.0 and 3.0)  NET-Framework-Core               Removed
    [ ] HTTP Activation                                 NET-HTTP-Activation              Removed
    [ ] Non-HTTP Activation                             NET-Non-HTTP-Activ               Removed

Through hours of searching online I have not been able to discover a resolution to the issue I am seeing. I followed the installation steps in How to Install .NET Framework 3.5 on Windows 11/10 and Windows Server (Windows OS Hub) as this was the most complete guide. None of the suggested installation methods worked.

Via Server Manager: Add roles and features -> Features -> .NET
Framework 3.5 Features -> .NET Framework 3.5 (includes .NET 2.0 and
3.0 )
Using DISM: DISM /Online /Enable-Feature /FeatureName:NetFx3 /All

Using DISM: DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /Source:D:\sources\sxs /LimitAccess

With PowerShell: Install-WindowsFeature -Name NET-Framework-Core

With PowerShell: Install-WindowsFeature -Name NET-Framework-Core -Source D:\Sources\SxS

With DISM:DISM /online /Add-Package /PackagePath:D:\Sources\SxS\microsoft-windows-netfx3-ondemand-package~31bf3856ad364e35~amd64~~.cab

I also tried using the offline packages from my installation media without success. And when trying to use GPO to force installation from / prohibit installation from Windows Update (non-WSUS) I did not see any results.
Regardless which method I use, I end up getting the same 0x800f0800 error. I've only come across one other user who has received the same error code when trying to install a Windows feature, but their resolution was just rebuilding their server. This is not a viable option for my scenario. The full error from PowerShell is displayed below:
PS> Install-WindowsFeature -Name NET-Framework-Core -Source D:\Sources\SxS

Install-WindowsFeature : The request to add or remove features on the specified server failed.
Installation of one or more roles, role services, or features failed. Error: 0x800f0800
At line:1 char:1
+ Install-WindowsFeature -Name NET-Framework-Core -Source D:\Sources\SxS
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (@{Vhd=; Credent...Name=localhost}:PSObject) [Install-WindowsFeature],
    Exception
    + FullyQualifiedErrorId : DISMAPI_Error__Failed_To_Enable_Updates,Microsoft.Windows.ServerManager.Commands.AddWindowsFeatureCommand

Any help on this issue is greatly appreciated!
Comment: You will need to check the file C:\Windows\Logs\CBS\CBS.log for errors.  Sounds like something that would be damaged when a language pack is present/removed from a system.  Check this registry key for the presence of other locales: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\PackageDetect\
Answer: try
dism.exe /online /enable-feature /featurename:NetFX3ServerFeatures /Source:d:\sources\sxs /LimitAccess
Comment: Please  format that text  as "`code`" using [Markdown](https://serverfault.com/editing-help) and/or the formatting options in the edit menu to properly type-set your posts. That improves readability. Additionally some context about what that command/code is supposed to do is highly recommended.


Transform complex equation into Cartesian coordinate

Question: Here is the problem
$$$$
Show the following equation is an ellipse
$$|z-1|=3-|z-2|$$
and I tried to solve it...
Square both sides,
$$(|z-1|)^2=(3-|z-2|)^2 \\
x^2+y^2-2x+1=9-6|z-2|+x^2+y^2-4x+4$$
Rearrange them...
$$6|z-2|=12-2x \\
3|z-2|=6-x$$
Square them again, and here is the problem i met...
$$(3|z-2|)^2=(6-x)^2 \\
9(x^2+y^2-4x+4)=36-12x+x^2 \\
$$
36 in both sides is going to be cancelled out, it seems like I must did something wrong. I have spent over 2 hours on this but still get the same result..please help!
Answer: So you get $8x^2+9y^2-24x=0$, which is $8\Big(x^2-3x+\frac{9}{4}\Big)-18+9y^2=0$, which is
$$8\Big(x-\frac{3}{2}\Big)^2+9y^2 = 18$$
which is an ellipse.


Função síncrona para verificar arquivos no NodeJS?

Question: Estou criando PDF's no meu servidor NodeJS usando o framework Express e a biblioteca PdfMake. Se alguém olhar meu perfil vai ver que fiz uma pergunta sobre PDF corrompido após o download. Acontece que eu descobri que os arquivos estão corrompidos porquê eles são enviados para download antes mesmo de ser concluído a criação deles, pois todo o processo ocorre de forma assíncrona.
O que eu preciso saber é o seguinte: Com qual processo SÍNCRONO eu poderia verificar se o arquivo está pronto e pode ser enviado para download, ou como faço para criar o PDF de forma síncrona??
Servidor:
pdfMake = printer.createPdfKitDocument(docDefinition);
pdfMake.pipe(fs.createWriteStream('../pdfs/Tabela.pdf'));
console.log('Imprimiu!!');
pdfMake.end();
if(fs.existsSync('C:/ProjetosLeonardo/Relatorios/pdfs/Tabela.pdf')) {
    let file = 'C:/ProjetosLeonardo/Relatorios/pdfs/Tabela.pdf';
    res.download(file);
}

Cliente:
 axios({
      method: 'post',
      url: '/server/gerarpdf',
      responseType: 'arraybuffer',
      data: this.pessoas
    })
    .then(function (response) {
      let blob = new Blob([response.data], {type: 'application/pdf'})
      let link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'TabelaTeste.pdf'
      link.click()
    })

Comment: Compartilhe o trecho de código relevante da criação e download do arquivo por favor.
Comment: Está adicionado, peço desculpas pelo incoveniente...
Answer: Pode ser enviado quando o evento terminar:
pdfMake = printer.createPdfKitDocument(docDefinition);
let stream = pdfMake.pipe(fs.createWriteStream('../pdfs/Tabela.pdf'));
pdfMake.end();

stream.on('finish', function() {
    if(fs.existsSync('C:/ProjetosLeonardo/Relatorios/pdfs/Tabela.pdf')) {
        let file = 'C:/ProjetosLeonardo/Relatorios/pdfs/Tabela.pdf';
        res.download(file);
    }
}

Você consegue "ouvir" certos eventos porque Streams são EventEmitter, por isso você conseguirá detectar quando estiver terminado.
Comment: Funcionou perfeitamente, conforme eu esperava. Muito obrigado!


Canonical scheme structure on the singular locus of (affine) schemes so that the inclusion map is closed immersion

Question: Let $R$ be an excellent local ring (https://en.wikipedia.org/wiki/Excellent_ring) . Let $X:=Spec (R)$ and $Y:=Sing (R)=\{P\in X: R_P $ is not regular$\}$. How can we give a canonical Scheme structure on $Y$ such that the inclusion map $i:Y\to X$ is a closed immersion ? Do we need the local, or excellent assumption on $R$ ? And more generally can we do this for the singular locus of schemes that are not necessarily affine ?
Answer: The first thing to note is that per the wikipedia link provided, $R$ excellent implies $R$ is J-2 and thus the locus of non-regular points is closed. So the first question is really just "given a closed subset of a scheme, what scheme structure should be put on it so that inclusion is a closed immersion?". If you don't already have any idea about what the scheme structure should be (I should point out that in the case where $R$ is an algebra of finite type over a perfect field, one may use the Jacobian criteria to find the ideal), one can always place the reduced induced scheme structure on $Y$. This is the unique reduced scheme structure on a closed subset of a scheme, so if you have to pick something, this is the thing to pick. For a reference, any introductory algebraic geometry book or StacksProject will describe the construction.
In regards to your follow up questions, the fact that $R$ is local is not needed here, nor is the full generality of excellent. By looking around on the wikipedia page you've linked, one may discover that all one needs in order to have the non-regular points be a closed subset of $\operatorname{Spec} R$ is that $R$ is a J-1 ring - in fact, this is a definition. In the case of non-affine schemes, as long as one can produce a covering by $\operatorname{Spec} R$ so that $R$ is J-1, one will have that the singular locus is a closed subset because a set is closed iff it's closed when intersected with every element of an open cover. From there, we are back to the discussion of the first paragraph on the subscheme structure.


$\lim _{x\to 0}\left(\frac{e^x-1}{\:x^3}\right)$

Question: I apply L'Hopital thrice and I get 1/6 but here they've stopped at infinity.
What is the correct answer?
Comment: In this case you don't need l'Hopital at all. In case you want apply let verify if the form is indeterminate at each step you use it.
Answer: Note that L'Hopital rule is used only for limits of $\frac00$ or $\frac{\infty}{\infty}$ form.
Right now, on substituting $x=0$, we get a $\frac00$ form. But, if we differentiate it once, we get: $$\lim_{x \to 0} \frac{e^x}{3x^2}$$ which is not of $\frac00$ form. So, we cannot use L'Hopital rule here.
Evaluating the above limit, the answer is obviously $\infty$.
Comment: If I get \frac{\infty }{0} do I apply L'Hopital?
Comment: @Husun No it is applicable **only** for the forms $\frac00$ and $\frac{\infty}{\infty}$. It is not applicable for any other forms such as $\frac{\infty}{0}, \frac10$, etc.
Comment: What do I do with the form \frac{\infty }{0} ?
Comment: Another question is $ \lim _{x\to \infty }\left(\frac{x^{-\frac{4}{3}}}{sin\left(\frac{1}{x}\right)}\right) $
I'm get \frac{\infty }{0} when applying limit
Comment: its x to the power -4/3
Comment: https://math.stackexchange.com/questions/2585391/lim-x-to-infty-left-fracx-frac43sin-left-frac1x-right here it is
Answer: $$\frac{e^x-1}{\:x^3}=\frac{e^x-1}{\:x}\frac1{x^2}\to1\cdot +\infty=+\infty$$
Comment: @Bernard Thanks for the appreciation!
Answer: using the rules of L'Hosptal one times we get
$$\lim_{x\to 0}\frac{e^x}{3x^2}=+\infty$$ you Can NOT use the rules one more times
Comment: As usual, one can wonder who can upvote such... *things*.
Comment: "you Can use the rules one more times" How? Most probably a wrong suggestion.
Comment: no probably a TYPO
Comment: Obviously not a typo but the unfortunate propagation of a common mistake.
Comment: ok that is your opinion
Answer: I don't know how you used L'Hopital rule but look(assume I'm taking the limit all the time):
$$\frac{e^x-1}{x^3}=\frac{e^x}{3x^2}$$
This is a limit in the form of $\frac1{0}$, which in this case is determinate form, it goes to $+\infty$ because $\lim_{x\to0}x^2$  goes to $0$ from the positive direction
The answer is infinity
Comment: @samjoe I rewrote it to be more accurate, hope it makes it clearer


What does "chi" mean in football fan language?

Question: In an English football match, a player left the pitch, giving the impression that he had been injured by another player, then went along the goal line and returned to the pitch without an injury. A fan shouted something which sounded like "chi-chi-chi".
What does this mean?
Answer: My best guess is that the fan was actually chanting "Cheat! Cheat!", and their English accent made it sound like "chi, chi" (as an Englishman myself, I can affirm that we tend not to pronounce our "T"s, especially in informal settings like football matches). In this case, the "cheating" would be the footballer pretending to be injured in order to win a free kick and/or get play to be stopped. This is indeed cheating (specifically, simulation), and is strongly frowned upon by most football fans.


Como procurar um nome com struct

Question: Estou fazendo um código que vai receber os nome de 5 pessoas e o 3 presentes que ela levou para festa, e depois vai ser pedido o nome da pessoa e o presentes que ela trouxe para festa, e mostrar se existe ou não, só que quando eu tento comparar, nunca encontra o nome, mesmo o nome estando na lista.
Aqui está o meu código
#include <stdio.h>
#include <string.h>

#define pessoas 5
#define pre 3

 struct p
 {
   char nome[100];
   char presentes[3][100];
 };

  int main(int argc, char** argv)
 {
    struct p convidados[pessoas];
    char teste[100], pesquisa[100];
    int i, j;
    for(i = 0; i < pessoas; i++)
    {
      setbuf(stdin, NULL);
      scanf("%s", convidados[i].nome);
      for(j = 0; j < pre ; j++)
      {
         setbuf(stdin, NULL);
         scanf("%s", convidados[i].presentes[j]);
      }
   }
   setbuf(stdin, NULL);
   scanf("%s %s", teste, pesquisa);
   for(i = 0; i < pessoas; i++)
   {
     for(j = 0; j < pre; j++)
    {
         if(strcmp(convidados[i].nome, teste) == 0 &&
   strcmp(convidados[i].presentes[j], pesquisa) == 0)
         {
            printf("Nome encontrado:\n");
         }
         else
         {
             printf("Nao\n");
         }
     }
   }
  return 0;
}

Answer: A pesquisa que tem está correta mas a forma como mostra o valor encontrado não, porque tem um printf para cada presente que analisa. Em vez disso o que quer fazer é guardar numa variável se encontrou o que procurava e apenas no fim dos dois laços/ciclos apresentar o resultado ao usuário:
int encontrado = 0;
for(i = 0; i < pessoas; i++) {
    for(j = 0; j < pre; j++) {
        if(strcmp(convidados[i].nome, teste) == 0 &&
                strcmp(convidados[i].presentes[j], pesquisa) == 0) {
            encontrado = 1;
        }
    }
}

if (encontrado == 1){
    printf("Nome encontrado:\n");
} else {
    printf("Nao\n");
}

Pode também tornar o código mais eficiente colocando break nos dois for caso a variável encontrado já seja 1, pois nesse caso já encontrou logo não precisa de pesquisar mais.
for(i = 0; i < pessoas; i++) {
    for(j = 0; j < pre; j++) {
        if(strcmp(convidados[i].nome, teste) == 0 &&
                strcmp(convidados[i].presentes[j], pesquisa) == 0) {
            encontrado = 1;
            break;
        }
    }
    if (encontrado == 1) break;
}

Veja como funciona no Ideone
Tornei o array mais pequeno para ser mais facil de testar

Como procurar um nome com struct


What should I look for in a portable audio recorder to be able to record loud concerts/jam sessions?

Question: Whenever I try recording concerts or practice sessions with my smartphone the resulting audio is, as one would expect, horrible. Putting a tape over the microphone usually just amplifies the hum in my case. The audio distorts when the volume is too loud and in general audio quality leaves a lot to be desired.
I'm looking in the market for an audio recorder (something like one of those Tascam handhelds), but I don't know exactly what I'm looking for. Is it tolerance for sound above some specific dB level? If so which? Is there anything else I should be looking for?
Answer: You need a recorder that: 1) Has a microphone (or microphones) that will be able to handle those sound levels without clipping and 2) A system that will let you control the input level, so you can fine-tune it for a specific situation sound level-wise.
As you have noticed, handling those levels of amplitude is not something every system can do. You need something that can handle high amplitude levels mechanically (the mic), electrically (preamps), and digitally (converters, software). Otherwise you will get distortion.
Other things to look for is signal processing like parallel recording and compression/limiting. These might actually be required depending on how formal/serious your recording is.
Parallel recording will let you record in two tracks at the same time, one of which is set -XdB lower than the other (usually -6dB or more), so if one track clips you have the other as backup. You can then in post-production mix between both, or only use the one that didn't clip, or whatever you need. It gives you options.
Compression/limiting will let you handle the peaks of the input audio. It will limit how high the peaks can go, preventing them from reaching a clipping point (above 0dBFS in digital).
As you can see, avoiding clipping at all costs (at least the kind of clipping that sounds horrible) is the name of the game, so there are systems out there that will include all these features and tools, and some more (like stereo or surround recording).
In general, good portable recording systems will have some or all of these features, the best ones having even more. Zoom and Tascam are the most popular choices, but you have many options from a wide price range. Some examples:
Zoom H1, H4n, H5, H6, H2n
Tascam DR-05, DR-07, DR-40
Roland R-05, R-26
Yamaha PR7
Here are more portable recorders.
Things to look at:

Inputs and mics. Will I only need the mics included in the system? Will I be able to use other microphones if I wanted to? You might want phantom power for condenser mics. See for example the Yamaha PR7, it only has one input and it is a TS, so you won't be able to run a balanced microphone XLR signal into it. If you are going to use external mics, maybe you want to avoid that one.
Signal processing. Which tools the system offers? Compression/limiting and parallel recording are very useful (again, maybe required depending on how formal and serious you are about recording). There are many more, some have editing possibilities and/or guitar amp modeling, and/or reverb, delay, etc. I really like the Tascam DR-40 in that sense, it offers both limiting and parallel recording (they call it dual recording).
If you are going to use the included mics, the quality of the included mics is important. Be sure that you like the included mics. Here is a comparison of the included mics of many portable recorders.

Here is a review of some of the most popular recorders.

Loud concerts and jams can get really loud.
The included mics on these systems might not be able to handle very loud sound levels. You might need to use another mic that can handle higher amplitudes (a dynamic mic, most likely). It all depends on how loud is your scenario. Loud as in a band rehearsal in a garage or studio? Or Loud as in an stadium concert? You might need to make some adjustments regarding the mic in very high amplitude scenarios.
Answer: Try the Zoom H2 (http://www.pixelproaudio.com/zoom-h2-recorder-s22948.html?gclid=COKjl-zT4b8CFTOZMgoddUYAJQ)
The drummer in my band uses it all the time to record practices and gigs. He's been using it for years.
Answer: I have the H2 but you'll probably have similar experiences with other devices.  First thing to note with this thing is that you don't get better signal-to-noise ratio by using external mics since the builtin preamps are making enough noise of their own when using external input.  This is actually also supposed to be the case for the H4 (which has phantom power on its mic inputs).  Of course, where the microphone arrangement can be important, and external mic may still make sense, but if you start juggling with mic stands and what not, you'll use something better than a handheld recorder anyway.
Then this thing offers 24bit recording which you can safely ignore since the noise floor is in the upper 16bit anyway.
Then you have a crude sensitivity switch on the outside with settings H/M/L.  It turns out that setting H is not interesting for uncompressed (WAV) recording since it just brings the noise floor higher up.
Then you have a gain control which can be set to values from 0 to something like 119 (?).  The thing to note is that this is a digital gain control so it cannot save you from clipping.  Leave it at 100.
The only real decision you have to make is whether to put the (analog) gain switch on the outside in M or in L position.  It sounds like you want L for your use case.  All other things you want to do, you can do with the finished recording.  The device offers stuff like automatic gain control.  Again, this works entirely in the digital domain so it can only make WAV/PCM recordings worse (if you are recording speech straight to MP3, there might be a point, but not for uncompressed audio).
Now this sounds rather disillusioning, but actually this lack of effective choices makes it easy to make the best recording one can expect this kind of device to deliver.  All the rest of the available settings are snake oil.
You get pretty usable practice recordings for checking on yourself.  You don't get stuff fit for selling: for that you need a good mic arrangement, good preamps and mastering/mixing.


OpenVPN disallow clients talking to each other but allow traffic to server host

Question: I am using the client-to-client configuration option to allow clients to reach out to the VPN host over it's internal IP address but I would like to prevent clients from reaching out to each other.
Subnet:
172.16.12.0/22
Clients communicate with the server over 172.16.12.1.
Answer: client-to-client directive allows to keep all the routing logic inside virtual OpenVPN network.
If you disable it (just remove it in the config) the clients should be able to reach 172.16.12.1 but not each other.


Probability of events from an unknown population.

Question: This a real world problem I am working on but I need some help. The candles are camouflage but the problem is real.
There are X candles that are broken in to two halves. X(max) is somewhere between 24 - 72, that is 48 and 144 halves. 48 halves have been found: (exactly 24 top halves and 24 bottom halves). It is not known for sure if any are missing.
Also, it is not known if any of the 48 found halves are a match for each other.
Here's the problem: X(max) should be 72 candles (144 halves) But we can only find 24 candles (48 halves) and we have found an equal quantity of top and bottom halves. We suspect that there was only ever 24 candles and not 72. How can I prove this mathematically? I can sense it to be a probability problem but I am at a loss.
Comment: You cannot "prove this mathematically" but there are standard statistical techniques in wide use.  Google e.g. "hypothesis testing" and "Bayesian".  Your conclusion will depend on e.g. a measure of how hard you looked (i.e. probability of there being other candle ends you have not found yet) and maybe a prior estimate of the probability of there being only 24 to start with.
Comment: hi @antkam.. thank you for replying, I do appreciate it but I am confused by your answer. You say that it cannot be solved mathematically but then you point me at mathematical or statistical procedures that might do it. I did look into Bayesian but it is way above my competence level. Any further help would be gratefully appreciated. Thanks again.
Answer: What I mean by my original comment is this: different mathematical procedures lead to different mathematical results (i.e. different precise mathematical statements) but people have different preferences re: which result they consider "acceptable" as "proof" that there aren't 72 candles.
If Bayesian is too complicated, try https://en.wikipedia.org/wiki/Statistical_hypothesis_testing
The basic idea of hypothesis testing is that you first ASSUME there are indeed 72 candles (so called "null hypothesis"), then you calculate the probability that, assuming there were indeed 72 candles, yet you only find 48 halves.  If this probability is very small, you "conclude" there can't be 72 candles after all.  (I put "conclude" in quotes because many people would not agree this is a "conclusive proof".)
How you calculate the probability is up to you.  But at minimum you need to a value $p$ for "probability that, despite looking and looking, I cant find a 49th end".  This is domain specific as I have no idea how hard you looked.
Another assumption you can make is to assume each end (out of 144 ends) is equally like to be found next.  So you can calculate the probability that the first 48 ends to be found happen to be 24 tops and 24 bottoms.  This has a precise answer (under all the assumptions stated) $= {72 \choose 24}{72 \choose 24} / {144 \choose 48} \approx 0.14$.  I.e. if the null hypothesis is true, your chance of finding 24 tops and 24 bottoms (among the first 48 ends to be found) is 14%.
If this number were much lower (e.g. 1%) some people may reject the null hypothesis already, by reasoning that they couldn't have been so (un)lucky as to hit a 1% chance event.  However 14% is high enough that people usually won't reject the null hypothesis due to this alone.  You would need help from the probability $p$ defined earlier.
So that's the general idea.  You assume the null hypothesis (in this case, 72 candles), then if you can show that probability of observing what you observed is "very low" (pick your own threshold), you reject the null hypothesis by saying "hey I couldn't have been so (un)lucky as to hit that small a probability".  As I said, people disagree as to the acceptability of this reasoning as "proof".  Also, note that this does NOT let you conclude that therefore there are only 24 candles (unless you somehow know it must have been one of two cases only, and not e.g. 25 candles).
Hope this helps?  Read the wiki.
Comment: thank you again.. I like the Hypothesis route. I understand P values. You have been most helpful. Thank you. FYI: we looked very very hard for the missing candles.
Comment: Since the 14% is insufficient (IMHO) to reject the 72 candle hypothesis, it all comes down to your estimate $p$ of how hard you look.  i.e. all this theory sounds fine but it still comes down to what number you plug in.  that's math for you.  :)