Como fazer login de aplicação desktop via aplicação web?

Question: Tenho uma aplicação web desenvolvida com ASP.NET MVC e faço o login armazenando os dados na Session.
Tenho uma outra aplicação, porém desktop, que efetua algumas tarefas que não podem ser feitas na web, porém esta aplicação precisa ser autenticada com o mesmo usuário e senha da aplicação web.
Existe uma forma de fazer a autenticação da aplicação desktop utilizando o login ativo da aplicação web?
Comment: Você vai precisar usar um webservice para isso. Você já tem noção disso? Sem mais detalhes a pergunta pode ser considerada como muito ampla, de qualquer forma é uma pergunta interessante +1. Aliás, comente quando editar a pergunta e me mencione, talvez eu possa te ajudar.
Comment: Você quer usar os mesmos dados de um usuário já logado, no caso os dados da Session, ou quer utilizar o mesmo login e senha?
Comment: @jbueno Sim, já tenho noção de webservices, porém utilizo pelo Visual Studio e fazendo um WebMethod no meu controller da aplicação web, não tive sucesso. Na verdade não consegui pensar na lógica de como os dados serão fornecidos à aplicação desktop C# sabendo que provavelmente eu terei mais de um usuário logado no sistema ao mesmo tempo...isso me deixou meio confuso.
Comment: @Randrade eu quero usar os mesmos dados do usuário já logado para evitar que o usuário tenha que efetuar o login na aplicação desktop também. Basicamente é a mesma aplicação, mas tem coisas que não vou conseguir fazer pela web e que com desktop é mais tranquilo, como por exemplo acessar a Certificate Store do Windows para utilizar os certificados digitais para operações com notas fiscais nos webservices da SEFAZ. Já tentei várias coisas, mas com o fim das applet próximo os limites da web para acessar os recursos da máquina do usuário, uma opção válida seja uma aplicação dupla (web e desktop).
Comment: @JeffersonPedro, a minha resposta te dá o caminho das pedras para o seu problema. Caso não seja o suficiente para soluciona-lo, favor me passe mais informações sobre a sua aplicação que editarei minha resposta para melhor atente o seu problema.
Answer: Se a aplicação for realizar vários requests para a aplicação web, o ideal é fazer um metodo no controller de autenticação que retorne um JWT(Json Web Token) e que você use esse token para fazer as requisições ao servidor sem precisar ficar dando um hit no banco a cada request para validar o usuário, você poderia armazenar esse token em alguma variável da aplicação desktop.
Caso você só precise validar esse usuário uma vez e receber os dados como grupo, email, nome, foto, etc, você pode criar um method no controller que receba usuario e senha, e se for válido retorne um json com os dados que você precisa, caso contrário retorne uma falha de login. Eu faria isso
Comment: A ideia é muito interessante, acho que vai me facilitar muito as coisas e ainda vou ter menos trabalho do que achava mediante essa sua explicação. Mas eu não tenho conhecimento nenhum sobre JWT. Você poderia, por gentileza, me indicar algum material e de preferência que tenha algum exemplo prático para eu estudar e entender como funciona as coisas direitinho?
Comment: Você pretende realizar várias requisições depois de efetuar o login ou apenas logar e retornar os dados do usuário? Se você quer apenas validar o login nem precisa usar JWT. Se você quiser usar JWT veja essa implementação: http://www.codeproject.com/Articles/369657/Simple-Authentication-using-Jwt-in-Asp-Net-Web-Api

Qualquer dúvida: email@example.com
Comment: A minha dificuldade é entender como autenticar um app desktop com o login vigente do app web. Basicamente o usuário vai acessar o site e quando for executar algumas determinadas operações, o site irá pedir pro usuário fazer pelo app desktop, quando o app desk for iniciado, ele faria a autenticação de usuário e senha baseado na autenticação feita na web, sem que o usuário refaça o login, quando terminar as operações no app desk a página web só receberia um comando de atualização para exibir os novos dados... Dá pra fazer dessa forma?
Comment: Você precisa arrumar uma forma de chamar a aplicação Desktop pela aplicação WEB, existem várias formas de fazer isso, você precisa arranjar uma forma de fazer isso enviando dados como parâmetro para o programa desktop, assim você nem precisa criar um form de login no desktop.
Answer: Se a validação tem que ser com a "autenticação da aplicação desktop utilizando o login ativo da aplicação web" (conforme suas palavras) o mais correto é quando o usuário se autenticar na aplicação web esse login gerar um "token" de autenticação no sistema.
Aconselho ter uma tabela, por exemplo, "UsuarioToken" ao invés de guardar em "Session":
CREATE TABLE [dbo].[UsuarioToken] (
[Token]              UNIQUEIDENTIFIER NOT NULL,
[IdUsuario]          SMALLINT         NOT NULL,
[DataInicial]        DATETIME         DEFAULT (getdate()) NOT NULL,
[DataFinal]          DATETIME         NULL,
PRIMARY KEY CLUSTERED ([Token] ASC),
CONSTRAINT [FK_UsuarioToken_Usuario] FOREIGN KEY ([IdUsuario]) REFERENCES [dbo].[Usuario] ([idUsuario]));

Ao "logar" na web, cria o token com a data de acesso (DataInicial). Ao "deslogar" inativa o token (DataFinal). Observe que a DataInicial tem como valor DEFAULT o getdate(), a DataFinal não, pois ela será a data e hora que o usuário "deslogar" da aplicação web. Será a DataFinal quando NULL que indicará se o token esta ativo ou não.
Com o token criado, agora vai depender da sua regra de negócio e o que mais for aplicável e/ou viável a sua situação, então o que vem abaixo é apenas exemplo/idéia:
Na aplicação desktop:

Ao invés de ter um formulário com Usuário e Senha, teria um form para indicar a "chave de acesso", token criado no login web, que poderia ser enviado ao "cliente" via e-mail (e-mail este dos dados de cadastro do usuário). Se token ativo, ex.: ValidarToken(Guid token), faz o processamento, se não retorna que token é inválido.
Ter sim um form de login com usuário e senha para identifica e validar, a primeira vez, se o usuário (idUsuario) é cadastrado no sistema web, após isso verifica se token ("chave de acesso") esta associado ao usuário que esta logando e se token esta ativo no sistema web. Resumindo, você identifica uma vez se o usuário e senha é válido, se válido verifica se há uma "chave de acesso" ativa na aplicação web, se há armazena o token em uma variável no desktop e nos próximos processos que exija token, como ele já esta armazenado em memória, apenas verifica se o mesmo ainda esta ativo na aplicação web ValidarToken(Guid token). Se não estiver, volta para o processo de login novamente.

Enfatizo as regras de segurança, pois o token deve ser invalidado após realizado todos os processos necessários no desktop.
Answer: Para realizações de autenticações a forma mais elegante de fazer seria usando Claims.
Com Claims há uma fazibilidade para fazer o que você precisa, pois temos a possibilidade de autenticação de terceiros.
http://www.asp.net/web-api/overview/security/external-authentication-services
O que você pode fazer também é separa a sua aplicação para que possua uma camada de Serviço. E nela aplicar uma funcionalidade de autenticação.


In Transformers, for the maximum length of Encoder's input sequences and Decoder's input sequences - should they be two different numbers?

Question: I noticed that there's usually a limit for the input length of transformers. But considering there are actually two input layers - one for the Encoders and one for the Decoders, can we and should we have two separate MAX_TOKENS for them?
If we have different MAX_TOKENS for Encoder  input and Decoder input, then the cross attention matrix would be not a square matrix anymore. However in my opnion there are practical reasons to do so, for example, in machine translation we have a source language sentence and target language sentence, which highly likely have different lengths.
English: I like weightlifting. ------------------ 3 tokens
Chinese: 我 喜 欢 举 重。----------- 5 tokens
But from TensorFlow's Tutorial on Transformers (Neural machine translation with a Transformer and Keras), the source sequence and target sequence are trimmed to the same length MAX_TOKENS:
    MAX_TOKENS=128
    def prepare_batch(pt, en):
        pt = tokenizers.pt.tokenize(pt)      # Output is ragged.
        pt = pt[:, :MAX_TOKENS]    # Trim to MAX_TOKENS.
        pt = pt.to_tensor()  # Convert to 0-padded dense Tensor

        en = tokenizers.en.tokenize(en)
        en = en[:, :(MAX_TOKENS+1)]
        en_inputs = en[:, :-1].to_tensor()  # Drop the [END] tokens
        en_labels = en[:, 1:].to_tensor()   # Drop the [START] tokens

        return (pt, en_inputs), en_labels

Is this just for the sake of simplicity, or it is a norm to use a unified MAX_TOKENS for both Encoder input and Decoder input?
In a practical application, what is the best way to determine the value of MAX_TOKENS?
Answer: In the tutorial you refer to, the only reason is simplicity. However, in machine translation practice, there is typically no reason to use different maximum lengths.
Transformers often use learned position embeddings (instead of the sinusoidal position encoding in the original Transformer paper). In that case, limiting the source or target side more would mean less training signal for the position embeddings. Also, due to byte-pair encoding and similar algorithms used for input text segmentation, the length of the source and target sentences are typically similar, even for languages that typically use a different number of words to express the same thing.
Comment: So, in summary, theoratically/programmingly we can use different `max_length` for encoder input and decoder input respectively, but this does not bring any benefits?

In the transformer tutorial I mentioned, the author has made a plot for both English (Decoder side) and Portugese (Encoder side) sentence lengths after tokenization, and from the plot he determined the "max length" by skipping some "outliers" of the length values.

Actually I am considering non-NLP scenarios for Transformer model, therefore I will not need the tokenization or text segmentation. I'll use entity IDs directly.


Sabre API *A OR *IM command equivalent

Question: PNR not created on DELTA carrier, need assistance
I'm receiving this warning on PassengerDetailsRQ
DIRECT CONNECT MESSAGES RECEIVED - ENTER *A OR *IM
All pricing is extracted ok and Segment status is HK but PNR is not generated((
Could you please tell me what will be Sabre API equivalent for *A OR *IM commands and how to fight this issue.
Comment: This is probably not the best forum for those kinds of questions. Rather consult Sabre first as this looks like a very specific error.
Answer: Assuming you are using XML services you may try to run SabreCommandLLSRQ which is responsible for running commands. Exact command instruction is put in <HostCommand> node. Example for IM command below (header section is empty for verbosity)
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>

  </soap:Header>
  <soap:Body>
    <SabreCommandLLSRQ xmlns="http://webservices.sabre.com/sabreXML/2003/07" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" TimeStamp="2014-03-04T14:00:00" Version="1.8.1">
      <Request Output="SCREEN" CDATA="true">
        <HostCommand>IM</HostCommand>
      </Request>
    </SabreCommandLLSRQ>
  </soap:Body>
</soap:Envelope>

Comment: Note that the HostCommand should be `*IM`, the `*` (aka Display Key) is required.
Answer: As mentioned you can use the SabreCommandLLSRQ to run exact host commands specified in the error message but the equivalent web service command for *A would be TravelItineraryReadRQ with a FULL subject area (and no UniqueID specified).
After retrieving the PNR again you can simply EndTransactionLLSRQ again.

Sabre API *A OR *IM command equivalent


angularJS array element shows as undefined

Question: I am debugging a web app written in angularjs, I can see that the array contains all the values, but when I begin iterating through the items and want to see the value for each on my watch, it shows as undefined, but I can see the array and the values. It might be the way I am setting the counter?
This is what shows in developer tools in Chrome:

When I select data.[i].Name on item 0, it says that it is undefined, but as you can see on the right, the array contain values.
Can you see where is my error?
Thank you,
Erasmo
updated screen shot
Comment: You should loop over `data.data`
Answer: First of all, the data object you're iterating over actually contains another attribute called data, so you need to reference this as data.data at the start of your loop.
You also need to define the array item in your function callback, then you can reference it without the index i:
angular.forEach(data.data, function(item) {
    var b = {
        Name: item.Name,
        Email: item.Email
    };

    $scope.arr.push(b);
});

I'm leaving i out for brevity, and because it is not relevant to the operation of your loop. You can of course reintroduce it as you see fit.
By adding this parameter to your function callback, you are telling the iterator, "When I loop through this array called data, just call each entry item." This way you don't have to maintain a counter. For a more generic example, these two loops produce the same output:
data = ['a', 'b', 'c'];

angular.forEach(['a', 'b', 'c'], function(item) {
    console.log(item);
});

for(var i = 0; i < data.length; i++) {
    console.log(data[i]);
}

You can still get a handle to the current index of your loop as well as the object itself from the function callback:
angular.forEach(data, function(item, index, obj) {
    console.log("Item " + index + " of " + obj + " is " + item);
});

For more information, see the AngularJS API.
Comment: Let me give that a try. Thank you!
Comment: I can access the array now, just that now I see the keys: Name and Email as undefined. Please see my newest screen shot.
Comment: none of the options are working. i keep seeing the array with data, but when I attempt to assign the values to the b array, they show as undefined.
Comment: I am sorry @Bucket, I do not have a lot of experience. How can I show you how item looks?
Comment: @erasmocarlos Oh, I see why - your `data` object should actually be `data.data`. See your first screenshot.
Comment: @erasmocarlos See my edits. The `data` object returned by your Promise has yet another property called `data` which actually references the array you want. Reference this as `data.data`.
Comment: @erasmocarlos happy to help
Comment: I have another question, and I will add it shortly to this forum. I hope you are around and can spare sometime to see if you can offer a hand. I think is a simple question but for me is challenging.


How do I do Select queries on a table that is inside of a schema in PostgreSQL?

Question: I have an RDS instance set up on AWS. I can't connect to the PostgreSQL database without issues.
When I try to run select statements against the table I am getting odd results. It just lists the logged in user. The table is User. I see that the table is inside of the public schema. I tried searching for SELECT * From public.User but that fails. What am I missing here? The table does exist because I can see it with data in PSequel I just wanted to query the data using select.
Comment: "it just lists the logged in user" <--- does this mean that, if you log in to the database with user `johndoe`, the query lists `johndoe`? How do you know that there are several rows in the table?
Answer: Try SELECT * FROM public."User";. Postgres lower-cases the table names if you don't put quotes around them. I'd just make all my tables lower-case to avoid the trouble.
Comment: That was totally it. Thanks for the help. I love it when the solution is so simple.


Understanding D3D11_BOX

Question: I've made some modifications to https://github.com/NVIDIA/video-sdk-samples/tree/master/nvEncDXGIOutputDuplicationSample to convert the desktop image to a cv mat.
I have a dx11 2d texture and I want the 640x640 center of the texture (cropping in opencv is slow). CopySubresourceRegion (https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-copysubresourceregion) works until I pass a D3D11_BOX. When I convert it to a cv mat, it's just a black screen.
<code>my_box.left = 1600;
my_box.top = 480;
my_box.right = 1600;
my_box.bottom = 480;
</code>
Can anyone give me a hint as to what I might be missing?
Comment: Make sure you enable the DirectX debug layer: https://learn.microsoft.com/en-us/windows/win32/direct3d11/using-the-debug-layer-to-test-apps and https://walbourn.github.io/direct3d-sdk-debug-layer-tricks/ check all errors, and post some code, we can't guess what you may be missing w/o code https://stackoverflow.com/help/minimal-reproducible-example
Comment: @mateeeeeee with fresh eyes this morning I figured it out. I  missed this relevant portion in the docs and assumed it was the same left right bottom top everyone else does

The values for right, bottom, and back are each one pixel past the end of the pixels that are included in the box region. That is, the values for left, top, and front are included in the box region while the values for right, bottom, and back are excluded from the box region. For example, for a box that is one pixel wide, (right - left) == 1; the box region includes the left pixel but not the right pixel.
Comment: how do you create the Mat?
Comment: Are you sure those are the values you want in your box desc?
Comment: @SimonMourier Really that's the entire relevant code. The subresource copy works and displays without D3D11_BOX. Idk that anyone else could get anything out of it. It's not a logic problem, I just need someone that's done this
Comment: @ChristophRackwitz I init the dx context for opencv, then do         cv::directx::convertFromD3D11Texture2D(myText, mat); This works as long as I don't provide D3D11_BOX
Comment: you should post that as an answer then. self-answering is encouraged on this site (provided it solves the problem). perhaps revise the question too, in ways that lets others with the same problem find this question and the solution. you should also copy excerpts of relevant code into the question, so the question contains something approaching an [mre]. the question should contain the essentials of the problem. linking to an entire github repo should only be supplemental.
Answer: So there's a lot of x/y box options out there. I initially thought this was negatives. As in, you will define the area to not cap and you get the inverse. This is a very popular approach. This is a little goofier than that.
So lets say you want center. That's dimension(so w or h)/2-desired_box_size/2. The answer you get on each of these will be left and top. From here, you'll just add however much to get the box size. For a 3840 by 1600 monitor with a 640x640 crop your box looks like this:
<code>    my_box.front = 0;
    my_box.back = 1;
    my_box.left = 1600;
    my_box.top = 480;
    my_box.right = 2240;
    my_box.bottom = -160;
</code>
Note front and back. The box is 3d as it says, but since we're working with a 2d text, we want to go 1 pixel deep. As stated in the docs, it's going to be back-front.

Understanding D3D11_BOX


Progress bar based on role

Question: I am looking to creating a progress bar on which it is displayed how far you are between role 1 and role 20 (Role names: Level 1 - level 20)?
I take it I would have to use some php or javascript with a hook into the specific users role.
Any ideas on how to go about this?
Cheers,
Answer: You can read user roles using below code...
global $user;
$user_roles = $user->roles;
$progress_value = x * 5; // where x is value extracted from $user_roles
if( is_numeric($progress_value) && $progress_value > 0 && $progress_value <= 100 ) {
  $style = "width: ".round($progress_value)."%; display: block";
}
print '

  <div id="progress-value" style="<?php print $style; ?>">

';

Now the solution needs some CSS to make it look like a progress bar. Start with a basic style - just a black border with a gray filling:

Comment: Cool! Thanks a bunch!

But where do I put all this? (Yes I'm a newbie)
Comment: Do I just place it within a block for instance?
Comment: Yes, You can use a block either using php filter or block implemented using a custom module.. Since you are a newbie i would suggest block using php filter..
Comment: You are welcome..  If one of the answers above fixes your issue, you should accept it (click the check mark next to the appropriate answer). That does two things. It lets everyone know your issue has been resolved, and it gives the person that helps you credit for the assist. See [here](http://meta.stackexchange.com/a/5235/187716) for a full explanation"
Comment: Aight thank you! You helped me a step closer to completing my page - such thanks ;-)

Progress bar based on role


how to segregate monthly average data based on station wise using pandas?

Question: I have 30 years of data that has been collected from 385 stations. I would like to calculate the monthly average of all years according to individual stations and export it into a CSV file. I am very new to coding I don't know how to execute this. please help someone to sort out my issues .herewith I have enclosed the code for one station. as same as like i should prepare csv file all 385 stations

#selective column only
ap= data[data["station_id"]=='C0A520']
ap=ap[['station_id','TEMP','YEAR','MONTH']]
grouped = ap.groupby(by=["YEAR","MONTH"])

monthly_mean = grouped.mean()
monthly_mean.head()

#export groupby
grouped.mean().reset_index().to_csv('D:/My_files/Research Progress/data/Temperature/final/coa520.csv')

Answer: I am assuming that your existing code works as intended and that you do not want to write the code for each of the 385 stations. This can be achieved in a simple for loop iterating over the station names:
for station in data["station_id"].unique():

    # selective column only
    ap= data[data["station_id"]==station]
    ap=ap[['station_id','TEMP','YEAR','MONTH']]
    grouped = ap.groupby(by=["YEAR","MONTH"])

    # export groupby
    grouped.mean().reset_index().to_csv(f'D:/My_files/Research Progress/data/Temperature/final/{station}.csv')

(You did not use the monthly_mean variable, so I wrote it out)
Comment: thank you so much .. i would like to know further that will it calculate monthly mean temperature for every month when you group only year and month variable.


Prove by mathematical induction $1+ a + a^2 +a^3+ ...+a^n =\frac {1-a^{n+1}}{1-a\;\;\;}$. a does not equal one

Question: Prove by mathematical induction $$1+ a + a^2 +a^3+ ...+a^n =\frac  {1-a^{n+1}}{1-a\;\;\;\;}$$ where  $a \neq1$
When doing the proof, wouldn't this fail the base case since $s(1)$ would make it false?
Comment: Since you think it is false: what _is_ $s(1)$, the base case, in this case? Write it out explicitly, so we can help you understand what you've done wrong.
Comment: Why shouldn't $a$ equal zero? It is $1$ that is the dangerous value for $a$ in this case.
Comment: If $ n=1$, the formula is true, because $1+a = (1-a^2)/(1-a) $. So there is no problem with the base case.
Comment: **Hint** The value of $a$ isn't relevant so long as it's not $1$. Induction is done on $n$.
Comment: That is the problem. I know that a is the dangerous value for this case. The problem that has been given to me requires that a not equal zero!
Comment: The expression is correct. Wouldn't using -1 fail the rules of mathematical induction though?
Comment: Oh I see what I done wrong here. The answer would be 1-a^2/1-a
Comment: Yet another induction exercise that's better done another way. Multiply both sides by $1-a$. That operation is reversible since $a \ne 1$.
Comment: If $n=0$ the formula is true since $1 = \frac{1-a}{1-a}$.
Answer: If
$1+ a + a^2 +a^3+ ...+a^n
=\frac  {1-a^{n+1}}{1-a}
$
then
$\begin{array}\\
1+ a + a^2 +a^3+ ...+a^n+a^{n+1}
&=(1+ a + a^2 +a^3+ ...+a^n)+a^{n+1}\\
&=\frac  {1-a^{n+1}}{1-a}+a^{n+1}\\
&=\frac  {1-a^{n+1}+(1-a)a^{n+1}}{1-a}\\
&=\frac  {1-a^{n+1}+a^{n+1}-a^{n+2}}{1-a}\\
&=\frac  {1-a^{n+2}}{1-a}\\
\end{array}
$


Given $f'$ is continuous and $(f'(0))^2>3$, what can I say about $f'(x)$ near $0$?

Question: I'm working on problem where I want to use the continuity of $f'$ to assert that $f'(x)$ cannot be zero ("bounded away from zero"?) near $x = 0$.  We know that $(f'(0))^2 >3$.
So, I think that what I really want to ask is this:  if $f'$ is cts, must $f'$-squared also be continuous?
Can I use the epsilon-delta definition?:
Since $f'$ is continuous, for every $\epsilon>0$, there exists $\delta>0$ such that:
$$|x-0|<\delta \implies|f'(x)-f'(0)|<\epsilon$$
$$ \implies -\epsilon < f'(x) - f'(0) < \epsilon $$
$$ \implies f'(0)-\epsilon < f'(x)   < f'(0)+\epsilon $$
From here I'm not sure how to use the fact that $(f'(0))^2>3$.
Thanks,
Answer: Well, $x\mapsto f'(x)$ is continuous, and $y\mapsto y^2$ is also continuous, so what can you say about $x\mapsto\left( f'(x)\right)^2$?
Answer: Very generally, if $f$ and $g$ are both continuous functions, then $f \circ g$ is a continuous function. (If you haven't proved this, then you should). Here, you are composing the square-function with the derivative of $f$.
Answer: $f'(0)^2>3\implies |f'(0)|>\sqrt{3}$
However, the function is continuous at $x=0$, so for some $\delta$, we have $|f'(x)-f'(0)|<\sqrt{3}$ whenever $|x|<\delta$.
However, this asserts that, $|f'(0)-f'(x)|<\sqrt{3}\implies |f'(0)|-|f'(x)|<\sqrt{3}$ by using the triangle inequality.
Thus, we have,
$|f'(x)|>|f'(0)|-\sqrt{3}>\sqrt{3}-\sqrt{3}=0$ whenever $|x|<\delta$.
Thus, we reach the conclusion that $f$ is bounded away from $0$ near $x=0$.
Comment: Thanks so much Hasan.  Nice usage of the reverse triangle inequality :-)


sql script to create a new database

Question: I have following script.
I don't know how to create new database in sql server 2005.
I run following script, and it create tables under model instead of seperate database. it look massy.
how can I create separate database.
I am copy some script here for your adive and course of action.
-----------------------------------------------------------
-- SQL Server 2000 Bible
-- Hungry Minds
-- Paul Nielsen

-- OBX Kites sample database - CREATE Database, Tables, and Procs

-- this script will drop an existing OBXKites database
-- and create a fresh new installation

-- related scripts:
-- OBXKites_Populate

-- T-SQL KEYWORDS go
-- DatabaseNames

-----------------------------------------------------------
-----------------------------------------------------------
-- Drop and Create Database

USE master
GO
IF EXISTS (SELECT * FROM SysDatabases WHERE NAME='OBXKites')
  DROP DATABASE OBXKites
go

-- This creates 1 database that uses 2 filegroups
CREATE DATABASE OBXKites
  ON PRIMARY
    (NAME = 'OBXKites', FILENAME = 'D:\SQLData\OBXKites.mdf'),
  FILEGROUP Static
    (NAME = 'OBXKitesStatic', FILENAME = 'c:\SQLData\OBXKitesStatic.ndf')
  LOG ON (NAME = 'OBXKitesLog',  FILENAME = 'c:\SQLData\OBXKites.ldf')
go

-- set to Full Log

go

SET QUOTED_IDENTIFIER ON
go
USE OBXKites
go

-----------------------------------------------------------
-----------------------------------------------------------
-- Create Tables, in order from primary to secondary

CREATE TABLE dbo.OrderPriority (
  OrderPriorityID UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL DEFAULT (NEWID()) PRIMARY KEY NONCLUSTERED,
  OrderPriorityName NVARCHAR (15) NOT NULL,
  OrderPriorityCode NVARCHAR (15) NOT NULL,
  Priority INT NOT NULL
  )
  ON [Static]
go

Comment: Who voted this down? on what grounds?  Developers work with SQL technologies all of the time.
Answer: CREATE DATABASE OBXKites
ON PRIMARY
     (NAME = 'OBXKites', FILENAME = 'D:\SQLData\OBXKites.mdf'),
   FILEGROUP Static
     (NAME = 'OBXKitesStatic', FILENAME = 'c:\SQLData\OBXKitesStatic.ndf')
LOG ON
   (NAME = 'OBXKitesLog',  FILENAME = 'c:\SQLData\OBXKites.ldf')
go

This code in your script should create a new database. If no error occurrs in the process.
Comment: I understand. can you also explain me filename thing in above script.
Comment: This tells sql server where to locate the database files. In this case it is creating two database files for data an one for log (transactions). Usualy there will be only 2 files for small-medium databases.

You can delete this piece of code and the files will be alocated in the default directory for the server. You can move this files later if you want/need to. In your code, it will work only with the first sentence I quoted.
Comment: But what is problem with create table. I am still getting filegroup error.
Comment: It would be helpful if you post the complete error. I'm prety sure you are looking for the error in the wrong way. May be the database is not being created for an external problem (security, permisions, ...).
Comment: it is solved now. I removed ON [STATIC] from tables. it is working..
thank you.
Answer: Can you simplify it down? or do you have to do all of that checking?
If it can be simplified I beileve some code such as:
CREATE DATABASE OBXKites

USE OBXKites

CREATE TABLE OrderPriority(syntax)

If simple code like this doesn't work, you may have deeper issues with rights or files or something as suggested by queen3 just before me.
Afterthought: At my school we were having issues like this as well I believe... after a few classes we finally arived at the conclusion that we didn't have rights to add files to the program files directory on the lab computers and SQL wasn't reporting the error to us.
Answer: Are there any errors in output? The script itself does already do what you requested.
I'd suspect that you incorrectly specified filenames - some of them are on drive C:, and some on drive D:.
Answer: Your script in question will create the tables in the OBXKites database (see the USE OBXKites statement in your script)
Does the OBXKites database already exist in your server instance? If so, that's probably why it appears that it is creating the tables in the current database, since the script is effectively removing and recreating the OBXKites database. If you need a different name for the database, find all instances of "OBXKites" in your script above after the line that reads "This creates 1 database that uses 2 filegroups" and rename it to the new database name you desire.
The only other option could be that the script has execution errors creating the database, if your user account lacks the proper permissions to do so. However, the script continues to execute, creating the tables in the current database you are logged in to, which is why you are seeing the tables there.
Answer: Create DataBase In Ubuntu Terminal
my database name is database_name
you can use anything
create database database_name;
How to select this database to create a table inside it.
use database_name;

sql script to create a new database


Auto Filtro VBA - excel

Question: Preciso fazer um filtro com um determinado valor em uma aba de uma planilha,depois do filtro feito, preciso copiar, abrir um novo documento, e colar essa informção.
Desenvolvi o código abaixo mas não está dando certo.
segue o código
Sub filtrar()

Worksheets(Array("Planilha3", "Planilha2", "Planilha3",)).Copy

ActiveSheet.Range("Planilha3").AutoFilter Field:=Range("E1:E1048576").Column, Criteria1:="Cell 01"

With ActiveWorkbook

    ActiveWorkbook.SaveAs Filename:=fname1, FileFormat:=xlOpenXMLWorkbookMacroEnabled
    ThisWorkbook.Save
    ThisWorkbook.Close

End With
End Sub

Comment: Você usa a Planilha3 duas vezes e possui uma vígula no fim. Portanto a função espera 4 Planilhas. `Worksheets(Array("Planilha3", "Planilha2", "Planilha3",)).Copy`. O correto seria `Worksheets(Array("Planilha1", "Planilha2", "Planilha3")).Copy`
Comment: @danieltakeshi obrigado pela observação, mas errei na hora de digitar
Comment: o Erro apresentado é :

Erro em tempo de execução 1004

Erro de definição de aplicativo ou de definicao de objeto
Comment: Em que linha ocorre o erro? E creio que `ActiveSheet.Range("Planilha3").AutoFilter` está errado. Você quer filtrar somente a coluna 3 da Planilha3 nova para o dado `="Cell 01"`?
Comment: O erro ocorre na linha ActiveSheet.Range("Planilha3").AutoFilter Field:=Range("E1:E1048576").Column, Criteria1:="Cell 01"
Comment: e sobre o filtro é isso mesmo, quero buscar na aba ( planilha 3) na coluna 3 o dado = "cell 01'
Answer: Código
Sub filtrar()
    Dim ws3 As Worksheet
    Dim UltimaLinhaE As Long
    Worksheets(Array("Planilha1", "Planilha2", "Planilha3")).Copy
    Set ws3 = ActiveWorkbook.Worksheets("Planilha3")
    With ws3
        'Limpa os Autofiltros da Planilha para evitar erros
        If .FilterMode Then
            .ShowAllData
        End If
        'Última Linhada colunaE
        UltimaLinhaE = .Cells(.Rows.Count, "E").End(xlUp).Row
        'Autofiltro
        .Range("E1:E" & UltimaLinhaE).AutoFilter Field:=1, Criteria1:="Cell 01"
    End With

    With ActiveWorkbook
        ActiveWorkbook.SaveAs Filename:=fname1, FileFormat:=xlOpenXMLWorkbookMacroEnabled
        ThisWorkbook.Save
        ThisWorkbook.Close
    End With
End Sub

Explicação
O Método Autofiltro estava sendo usado incorretamente.
O método é Range.Autofilter, portanto uma range precisa ser inserida.
Deste modo: .Range("E1:E" & UltimaLinhaE)

Obs.: A variável fname1 não está sendo especificada neste código. E se o que deseja é filtrar antes de enviar para o novo arquivo Excel, usar .SpecialCells(xlCellTypeVisible) e criar uma nova planilha temporária para ser copiada ao novo arquivo.
Comment: obrigado pela ajuda, porem o filtro esta sendo feito na coluna a , onde mudo para filtrar a coluna e ?
Comment: Como você está utilizando o Range? `.Range("E1:E" & UltimaLinhaE).AutoFilter Field:=1, Criteria1:="Cell 01"` Pois se estão descritas todas as colunas da planilha, mudar o campo Field para `Field:=5`
Comment: Deu certo, obrigado @danieltakeshi

Auto Filtro VBA - excel


Fazer select com LIKE e AND ao mesmo tempo

Question: Tenho esse script que faz uma busca:

$(function($) {
  $("#loc_menu").autocomplete({
    source: "php/search_cidades.php",
    minLength: 2,

    select: function(event, ui) {
      // Set autocomplete element to display the label
      this.value = ui.item.label;

      // Store value in hidden field
      $('#h_l').val(ui.item.id);

      // Prevent default behaviour
      return false;
    }
  });

  $("#loc_menu").click(function() {
    $('#h_l').val(0);
    $('#loc_menu').val('');
  });
});
<?php
 /******* Conexão com o bando de dados *******/
 include "../Conexao/config.php";
 mysqli_select_db($config, $database_config);
 mysqli_set_charset($config,"utf8");
 /******* Conexão com o bando de dados *******/

 //get search term
 $searchTerm = $_GET['term'];
 //$cidade_uf  = $_GET['cidade_uf'];

 $sql_1 = mysqli_query($config, "SELECT * FROM tb_sub_categorias WHERE sub_categoria LIKE '".$searchTerm."%' ORDER BY sub_categoria ASC") or die(mysqli_error($config)); // LIMIT 5

 if(@mysqli_num_rows($sql_1) <= '0'){
  //echo "$erro";

  $sql_2 = mysqli_query($config, "SELECT * FROM tb_empresas WHERE razao_social LIKE '%".$searchTerm."%' AND cidade_uf = '$cidade_uf' ORDER BY razao_social ASC") or die(mysqli_error($config)); // LIMIT 5

  if(@mysqli_num_rows($sql_2) <= '0'){
   $output_array[] = array(
    'id' => '0'
    , 'label' => 'Nenhum resultado encontrado'
    , 'value' => 'Nenhum resultado encontrado'
   );
  }else{
   while($r_sql_2 = mysqli_fetch_array($sql_2)){
    //$selecao = $r_sql_2['razao_social'];
    //$data[]  = $selecao;

    $output_array[] = array(
     'id' => "co_" . $r_sql_2['id']
     , 'label' => $r_sql_2['razao_social']
     , 'value' => $r_sql_2['razao_social']
    );
   }
  }
 }else{
  while($r_sql_1 = mysqli_fetch_array($sql_1)){
   //$selecao = $r_sql_1['sub_categoria'];
   //$data[]  = $selecao;

   $output_array[] = array(
    'id' => "ca_" . $r_sql_1['id']
    , 'label' => $r_sql_1['sub_categoria']
    , 'value' => $r_sql_1['sub_categoria']
   );
  }
 }

 //return json data
 echo json_encode($output_array);

 mysqli_close($config);
?>

Precisaria refinar esse busca.
Estou tentando fazer dessa forma:
$sql_1 = mysqli_query($config, "SELECT * FROM tb_sub_categorias WHERE sub_categoria LIKE '".$searchTerm."%' AND id_sub_cat IN (1306, 1405) ORDER BY sub_categoria ASC") or die(mysqli_error($config));

Tenho uma tabela de categorias e outra de clientes/categorias.
Gostaria que o script buscasse as categorias que estão atreladas aos clientes cadastrados, ao invés de buscar todas as categorias.
Todas as tentativas que fiz não fazem a pesquisa refinar.
Comment: Essa query procura as subcategories com id 1306 ou 1405 e que comecem com o termo de pesquisa. É isso que queres?
Comment: Esses ids foram um exemplo. Se for seguir essa dinâmica, farei um select antes e extrairei de um array os ids.
Answer: Você necessita de um Join e a forma mais simples é ter uma FK de sub_categoria em cliente.
SELECT * FROM TB_SUB_CATEGORIA SC, CLIENTES CL
WHERE SC.CD_SUB_CATEGORIA = CL.CD_SUB_CATEGORIA
AND SC.SUB_CATEGORIA LIKE '".$SEARCHTERM."%'
AND SC.ID_SUB_CAT IN (1306, 1405)

Talvez necessite modificar uma coisa ou outra, mas deve ser isso, espero ter ajudado!


Remove character from string in Kotlin

Question: I am trying to create an Android calculator which uses strings in Kotlin. I do not know how to delete a comma (or the negative) if it already contains one.
Here is my code which adds the comma correctly but doesn't delete it if the user clicks again:
if (!buClickValue.contains(".")) {
    buClickValue += "."
} else {
    buClickValue.replace(".", "")
}

Comment: You say you are trying to add/remove comma, yet your code implies you are adding/removing dot.
Comment: Sorry my fault. If you look at the code you can see that if there is no "." in the string, it should add one to the string, but if there already is one, he should remove it.
Comment: Unclear what you are asking.
Comment: My question is how do I remove the "."? // I added my git to the question, maybe that helps
Comment: Replace is not the good way to remove a char or sequence in a string: use filter in place of replace
Answer: The replace() method is designed to return the value of the new String after replacing the characters. In your case, the value obtained after replacing the characters is never reassigned back to the original variable.
Specifically in your else clause, the line should be changed to -
buClickValue = buClickValue.replace(".", "")

Comment: Thank you very much, that solved my problem and explained it well!
Answer: The more logical technic is not to replace but to filter
buClickValue = buClickValue.filterNot { it == "."[0] }

or

buClickValue = buClickValue.filterNot { it == '.' }

Or to extend
filtered = ".,;:"

buClickValue = buClickValue.filterNot { filtered.indexOf(it) > -1 }

Comment: The 1st exemple didn't compile anymore. I added ".get(0)"
Comment: This should be preferred over the accepted answer. Nice answer!
Comment: why not just ".filterNot { it == '.' }"
Comment: @Xan You will see a lint error that says "Operator == cannot be applied to Char and String".
Comment: @YUSMLE you spiked to @ Xan about my solution or???
Comment: @Luc-Olivier No, I was showing the issue after applying Xan's offer.
Comment: @YUSMLE got it! @ Xan is right. We can express a char with single quotes.

Remove character from string in Kotlin


Two sounds speak in a same time, how can I set it back?

Question: I have a Studiologic SL-880 and a problem too with it.

When I hit a key on the master keyboard, two different sounds speak in a same time. Like it be detuned. I use it with a Sennheizer Midi controller, not else. How can I set it back to the standard status?
Comment: Which software you use to play sounds? There may be a problem in MIDI routing.
Comment: I don't use any software, because the Midi controller doesn't use any software.
Answer: The problem sounds like the MIDI routing is going into a feedback loop. This means the sampler device getting signals from Studiologic, is sending the MIDI data back to the Studiologic. And Studiologic doesn't understand that it is its own signal returning back but thinks that the MIDI signal is coming from another controller. Therefore Studiologic passes it directly to the sampler, which causes a feedback loop. Since this happens very rapidly, you hear a detuned sound because same sample is triggered more than once with very close intervals.
The channel on the sampler should only accept MIDI signals, not send any MIDI signals back.
For example this is how it's done in Nuendo 4 channel settings. MIDI-in of the instrument channel is accepting signals from Scarlett but not sending any:
.


How do I perform a Left Outer Join in Linq?

Question: I am new to Linq, and I need to convert this query to a left outer join between DocumentStores and Orders, as not all documents are related to an order:
<code>    var documents=(from d in _dataContextOrders .DocumentStores
                           join o in _dataContextOrders.Orders on d.OrderID equals o.ID
                           join t in _dataContextOrders .DocumentTypes on d.DocumentType equals t.DocTypeID
                       select new
                           {
                               d.ID,
                               o.PORef ,
                               t.DocTypeDescription,
                               d.Name,
                               d.ContentType
                           }).ToList();
</code>
How do I achieve this?
Comment: Why do I see a new one of these questions every day?
Comment: You may check this article i've written:  http://www.experts-exchange.com/Programming/Languages/.NET/A_11369-Joining-in-LINQ.html
Answer: <code>from a in dataContext.<tableA>
join _b in dataContext.<tableB> on a.id equals _b.aid into _b
from b in _b.DefaultIfEmpty()
select <whatyouwanttoselect>
</code>
b will be null, if the join on the ids fails


Apache2 vhost works with www, but not without

Question: Ok so my site works with the www. but not without. If I visit the page without the www. , I get a 404 message

Not Found
The requested URL / was not found on this server.
Apache/2.2.17 (Ubuntu) Server at mintuz.com Port 80

my apache 2 access log
<code>::1 - - [03/Nov/2012:11:36:51 +0000] "OPTIONS * HTTP/1.0" 200 152 "-" "Apache/2.2.17 (Ubuntu) (internal dummy connection)"
X.X.X.X - - [03/Nov/2012:11:37:01 +0000] "GET / HTTP/1.1" 404 496 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4"
X.X.X.X - - [03/Nov/2012:11:37:01 +0000] "GET /favicon.ico HTTP/1.1" 404 502 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4"
</code>
my apache 2 error log

[Sat Nov 03 21:05:06 2012] [error] [client 18.104.22.168] File does not
  exist: /etc/apache2/htdocs [Sat Nov 03 21:05:06 2012] [error] [client
  126.96.36.199] File does not exist: /etc/apache2/htdocs

My vhost config.
<code><VirtualHost *:80>
        DocumentRoot /var/www/mintuz.com
        ServerName www.mintuz.com
        ServerAlias mintuz.com *.mintuz.com
</VirtualHost>
</code>
I feel as if it's not my DNS because it is hitting my server in both instances, just my server replies with a 404. Any suggestions welcome.
Comment: Try this, ServerName mintuz.com
ServerAlias *.mintuz.com
Comment: You quote the access_log but not the error_log, which may have interesting tips. Also, are you sure the  you quote is the only one? Another one may be elsewhere in the large Apache config files, and take precedence.
Comment: I have included my error log
Answer: Adding my ip address to the  fixed my issue as well as uncommenting some stuff in the default vhost file.
Comment: Really, "uncommenting some stuff?"  How useful do you think that's going to be to anyone else?


C - function that allocates memory

Question: I've written a procedure, that creates 2 matrices and multiplies them. However I have to divide my code into functions, and I have a problem with declaring a function that will allocate the memory for matrices.
Here's my code:
void matrixMult(){
int **A, **B, **C; //matrices
int rowA, colA, rowB, colB; //rows and columns
int i, j, k; //for iterations

printf("Number of rows in matrix A: \n");
scanf("%d", &rowA);
printf("Number of columns in matrix A: \n");
scanf("%d", &colA);

printf("Number of rows in matrix B: \n");
scanf("%d", &rowB);
printf("Number of columns in matrix B: \n");
scanf("%d", &colB);

//memory allocation
A = (int**)malloc(rowA * sizeof(int));
B = (int**)malloc(rowB * sizeof(int));
C = (int**)malloc(rowA * sizeof(int));

for (i = 0; i < rowA; i++)
  {
   A[i] = (int*)malloc(colA * sizeof(int));
  }

for (i = 0; i < rowB; i++)
  {
   B[i] = (int*)malloc(colB * sizeof(int));
  }

for (i = 0; i < rowA; i++)
  {
   C[i] = (int*)malloc(colB * sizeof(int));
  }
/*
the rest of code
*/
}

What should this function look like?
Comment: What's wrong with it? Does it not work? Is it slow? Does it cause memory leaks? Is it ugly?
Comment: http://stackoverflow.com/questions/35542391/segmentation-fault-but-unable-to-reason-how-memory-allocation-looks-fine-to-me
Comment: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc
Comment: @Beta well, the bad indentation sure does not make it pretty.
Comment: One of the usual suspects can provide the link: Don't cast the result of `malloc`.
Comment: There are no matrices (i.e. 2D arrays) in your code. Nor something that can point to them.
Answer: You have two ways of doing it that are both used in practice:

Write a function that allocates the matrix and returns the result - your function would have the following signature: int **alloc_matrix(size_t rows, size_t columns)
Write a function that takes a pointer to matrix pointer, and returns a status code - the signature would be int alloc_matrix(int*** res, size_t rows, size_t columns)

The value returned from the second function would indicate a success or a failure in allocating the memory.
Comment: Actually for a matrix/2d array, this is wrong. OP should use a correct 2D array.
Answer: The first allocation you have an error. You have to alocate an array of pointers to Ints.
A= (int**)malloc(rowA * sizeof(int*));
B = (int**)malloc(rowB * sizeof(int*));
C = (int**)malloc(rowA * sizeof(int*));

for the function problem
int** alocatingArray(size_t nRows, size_t nCols){
...
}

this function will be used to each array returning the primary pointer to the matrix

C - function that allocates memory


Calcular tempo de importação de DUMP

Question: Gostaria de saber, se possível, teria como calcular aproximadamento o tempo de importação de um Dump.
Poderia ser algo considerando os seguintes itens:

Tamanho do DUMP em GB.
Quantidade de Tabelas.
Quantidade de Registros e(ou) linhas/colunas por tabela.
Quantidade de Objetos, como Triggers, Functions, Procedures, etc.
Alguma forma de calcular a eficiência computacional de processamento do computador?

Oracle Database 11g Enterprise Edition Release 184.108.40.206.0 - 64bit
  NOARCHIVELOG

O computador que utilizo para realizar os IMP:

Windows 7 Professional 64bits
  4gb RAM
  i3 3.3GHz

OBS.: Utilizando o comando IMP e/ou IMPDB.
Comment: Não sei se te ajuda, mas olha aqui: http://www.dba-oracle.com/t_monitor_data_pump_import_job.htm
Comment: @Diego, no link resolve com IMPDP preciso com IMP também, mas muuuuito obrigado!!!
Comment: @Diego, alterei a pergunta com as respostas.
Comment: @Diego, posta sua resposta com DataPump que eu marco como respondida.
Comment: Pergunta: você está planejando alguma migração de banco ou apenas quer estimar um tempo de restauração para um possível crash? Ou nenhuma destas?  Qual é sua versão de banco? Standard ou EE? está com archivelog ativo? S.O?
Comment: Se eu utilizar como efeito de comparação um dump de 1gb e gastar 2h para importação então fazer regra de três para descobrir o tempo de um dump de 5 gb dando 10 horas de importação? kkk
Comment: Creio que isso vai te ajudar: [Data PUMP Import](http://www.dba-oracle.com/t_monitor_data_pump_import_job.htm)
Comment: @Diego coloca uma resposta completa, com explicação do link (e porque o conteúdo do link responde) à pergunta que vou também votar `+1`
Answer: É possivel monitorar o tempo usando essa query:

col table_name format a30

select substr(sql_text, instr(sql_text,'"')+1,
               instr(sql_text,'"', 1, 2)-instr(sql_text,'"')-1)
          table_name,
       rows_processed,
       round((sysdate
              - to_date(first_load_time,'yyyy-mm-dd hh24:mi:ss'))
             *24*60, 1) minutes,
       trunc(rows_processed /
                ((sysdate-to_date(first_load_time,'yyyy-mm-dd hh24:mi:ss'))
             *24*60)) rows_per_min
from
   v$sqlarea
where
  upper(sql_text) like 'INSERT % INTO "%'
  and
  command_type = 2
  and
  open_versions > 0;
select
   sid,
   serial#
from
   v$session s,
   dba_datapump_sessions d
where
   s.saddr = d.saddr;

select
   sid,
   serial#,
   sofar,
   totalwork
from
   v$session_longops;

Fontes: Aqui e aqui
Comment: Essa resposta serve somente para IMPDB, ou seja, DataPump. Utilizando o comando IMP não seria possivel

Calcular tempo de importação de DUMP


TCP/IP Connection with Multiple Threads Speaking for Chat Application

Question: i have a TCP Chat Server code sample like this, it creates multiple threads correctly, but it doesn't send the  message to all threads. I want the message to be sent accross all threads, like a group chat. Can you help me?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;

class NewClient
{
    public Socket newServerSocket;

    public NewClient(Socket client)
    {
        this.newServerSocket = client;

    }
    public void speakWithClient()
    {

        int recv;
        byte[] data = new byte[1024];
        IPEndPoint clientep = (IPEndPoint) newServerSocket.RemoteEndPoint;
        Console.WriteLine("Connected with {0} at port {1}",
                        clientep.Address, clientep.Port);

        string welcome = "Welcome to my test server";
        data = Encoding.ASCII.GetBytes(welcome);
        newServerSocket.Send(data, data.Length,SocketFlags.None);

Right here, it sends the given message back to the client, but it doesn't send the message to all threads.

        while (true)
        {
            data = new byte[1024];
            recv = newServerSocket.Receive(data);
            if (recv == 0)
                break;

            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
            newServerSocket.Send(data, recv, SocketFlags.None);
        }

        Console.WriteLine("Disconnected from {0}",
                          clientep.Address);
        newServerSocket.Close();
    }

}
class SimpleTcpSrvr
{
   public static void Main()
    {
        int recv;
        byte[] data = new byte[1024];
        IPEndPoint ipep = new IPEndPoint(IPAddress.Any,9060);

        Socket newsock = new Socket(AddressFamily.InterNetwork,
                                    SocketType.Stream,
                                    ProtocolType.Tcp);
        newsock.Bind(ipep);
        newsock.Listen(10);

        Console.WriteLine("Waiting for a client...");

        while (true)
        {
            Socket client = newsock.Accept();

            NewClient threadliclient = new NewClient(client);
            Thread newthread = new Thread(new ThreadStart(threadliclient.speakWithClient));
            newthread.Start();
        }

    }
}

Comment: Let's assume you have a group of 20 users and your server has only 8 threads how you gone handle that?
Comment: Unless there's a specific reason you want to use sockets directly, I'd recommend using SignalR for a chat group.
Comment: well i have to use sockets unfortunately
Comment: You probably shouldn't be using threads anyway. Consider using `async` and `await`
Answer: It's been a while since I've done any socket programming, but...  don't you need to keep a list of your client sockets and loop through them every time you receive a message?
public static List<Socket> Clients = new List<Socket>();

while (true)
{
    Socket client = newsock.Accept();
    Clients.Add(client);

    NewClient threadliclient = new NewClient(client);
    Thread newthread = new Thread(new ThreadStart(threadliclient.speakWithClient));
    newthread.Start();
}

public void speakWithClient()
{
    int recv;
    byte[] data = new byte[1024];
    IPEndPoint clientep = (IPEndPoint) newServerSocket.RemoteEndPoint;
    Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);

    string welcome = "Welcome to my test server";
    data = Encoding.ASCII.GetBytes(welcome);

    newServerSocket.Send(data, data.Length,SocketFlags.None);
    while (true)
    {
        data = new byte[1024];
        recv = newServerSocket.Receive(data);
        if (recv == 0)
            break;

        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
        foreach (Socket client in SimpleTcpSrvr.Clients)
        {
            client.Send(data, recv, SocketFlags.None);
        }
    }

Comment: thank you, this actually kinda solved my problem, the thing is, now when i send the message, it won't show the message right away. When i send a message from another client, it only shows the message then. I need to show the message right away, somehow.
Comment: So again I say....  been a long time since I've done any Socket programming, but...  I'm wondering if you need to set NoDelay on your sockets to true.


Angular2 routing don't know where to put router output

Question: I'm using angular2 rc4 version. I have 3 components.
AppComponent: Here, in the app.component.html file I render another component named HomeComponent with selector <app-home></app-home>
HomeComponent: Here, in the home.component.html file there are some contents and a link to Dashboard.
Dashboard

DashboardComponent: here in the dashboard.component.html file some content.
In my main.ts file I've declared my routes and import my necessary components. Code snippet:
import { provideRouter, ROUTER_DIRECTIVES, Router, RouterConfig } from '@angular/router';
import { DashboardComponent } from './app/dashboard/dashboard.component';

const routes: RouterConfig = [
  { path: '', redirectTo: 'home', terminal: true },
  { path: 'dashboard', component: DashboardComponent }

];

bootstrap(AppComponent, provideRouter(routes));

Now the problem. I paste <router-outlet></router-outlet> in my home.component.html file and then clicked on the dashboard link. It renders the dashboard.component.html but the contents of home.component.html file was still in the root-url/dashboard page.
If i put <router-outlet></router-outlet> in top of home.component.html file then after clicking dashboard dashboard.component.html contents shows first, then shows home.componet.html contents. If i put <router-outlet></router-outlet> in bottom of home.component.html file then after clicking dashboard home.component.html contents shows first, then shows dashboard.componet.html contents.
What I want is, clicking on the dashboard link will only show dashboard contents. How am I supposed to do that? As I'm a newbie I m unable to figure that out on my own.
Answer: You should put <router-outlet> in app.component
working demo : https://plnkr.co/edit/hXJ6ZRv81kt4rvWhxoBD?p=preview
import { provideRouter, ROUTER_DIRECTIVES, Router, RouterConfig } from '@angular/router';
import { DashboardComponent } from './app/dashboard/dashboard.component';

const routes: RouterConfig = [

  { path: '', redirectTo: 'home', terminal: true },
  { path: 'home', component: HomeComponent},
  { path: 'dashboard', component: DashboardCompnent}

];

bootstrap(AppComponent, provideRouter(routes));

and in home.component
import { Router} from '@angular/router';
import { ROUTER_DIRECTIVES } from '@angular/router';

Dashboard

constructor(private router: Router) {}
redirect()
{
    this.router.navigate(['/dashboard']);
}

Comment: Nope you can't use it @RahulKumar
Comment: It's working (+1). But main url should be defined as `{ path: '', component: HomeComponent },`. Is this the only solution? Because, then why angular2 team put `routerlink` concept then?
Comment: Routelink is there for navigation and updates your current view and inject new template into `router-outlet`. Here you want to update whole page and not only the part of page. so you have to put `router-outlet` in app.component.
Comment: @Emu : wrt your first comment, even I want the answer to be like that, but no finding so far! :(  (P.S.: I am also a newbie)
Comment: can't i use  in index.html instead of app.component.html


MySQL get records what have max value

Question: This is my table named period.
id | year | month
222 | 2014 | 2
345 | 2013 | 5
33 | 2014 | 1
224 | 2014 | 2

I want get only id what have latest month (2014-02). Result should be 222, 224.
I wrote following query.
SELECT id, MAX(year*100 + month) FROM period

But it is returning following result.
222| 201402
How can i get my result
Comment: Why do you need **only** the ID? What's wrong with it including the month?
Comment: what is the reason for down vote.
Comment: I don't know, didn't downvote.
Comment: @BenM sorry. it is not for you. I want get id for join with another table
Comment: Upvotes and downvotes are almost arbitrary in SO. Don't take it personally.
Comment: @Strawberry no. I didn't get it personally. But i wanted to know the reason because i could explain my question again with another way.
Answer: SELECT x.*
  FROM period x
  JOIN
     ( SELECT year
            , month
         FROM period
        ORDER
           BY year DESC
            , month DESC
        LIMIT 1
     ) y
    ON y.year = x.year
   AND y.month = x.month;

Comment: Incidentally, if it was me, I'd try to find a way of storing the dates as dates - e.g. '2014-02-01'
Answer: You should you the following query:---
SELECT id FROM period where year=(SELECT max(year) from period) and month=(SELECT max(month) from period);

Comment: Er, no. Think about it.
Comment: you checked year with 2014 and month with 5. I want 2014 02

MySQL get records what have max value


Can we put a vecctor inside integral?

Question: $v$ is a column vector. Can I write like this? Is it possible that the result of integral is vector?
$$\int_{\Omega}v(x) dx $$
The domain is in $\mathbb R^n$.
Comment: Yes. All you do is divide $v$ into it's components, integrate them all separately and then put back the components to give you another vector. That vector is the integral.
Comment: The integral of the vector is the vector of the integrals.
Answer: A general approach (with most details omitted) is to define the integral
of a non scalar function $v$ as the value $I$ iff for all linear functionals $\phi$, we have $\phi(I) = \int \phi(v(x)) dx$.
This reduces the integral down to a scalar integral.
In the case of $\mathbb{R}^n$, it is sufficient to consider the
functionals $e_k^*(x) = x_k$, in which case we have
$\int v(x) dx  = \begin{bmatrix} \int v_1(x) dx \\ \vdots \\ \int v_n(x) dx \end{bmatrix}  $.
Answer: Two remarks about domains and ranges:
1) an important amount of such integrals have $\Omega \subset \mathbb{R}$ as their domain instead of $\Omega \subset \mathbb{R}^n$. It is the case for parameterized curves $(x(t),y(t))$.
2) the range may also be $\mathbb{R}$ instead of $\mathbb{R}^n$. Of course, it is not in the same framework that you have presented your question. But there is an important notion which is $\int_{\Omega}v(x).dx$ (with a point denoting a dot product, sometimes omitted...). As a dot product is a number, its integral is in fact a number ; in this case we speak about the line integral of a vector field. See for example this.

Can we put a vecctor inside integral?


Creating a name column from email

Question: I have a dataframe that has an email column in the following format:
Email
firstname.lastname@example.com
firstname.lastname@example.com

I'd like to create a new column that tells me the full name of the person, based off of the email column (removing the _ and @email.com). So the new column would look like:
Full Name
Jane Anderson
Andy Smith

Comment: from discussion below - real world data rarely is this well behaved. Might you run into 1) more than one first name, or 2) using dot instead of underscore to separate names?
Comment: @Sirius In real world data, there may be multiple first name and last name.  But, I would say that people who post questions here may not be working on real world data.  It could be a clean dataset or even some practise test for learning.  So, if we look every question by that generalizable POV, it would become a complex solution needlessly
Answer: We can use extract to capture the first word ((\\w+)) followed by underscore, then one or more letters in a second capture group followed by the @ and other characters
library(tidyr)
extract(df1, Email, into = c("Full", "Name"), "^(\\w+)_([A-Za-z]+)@.*")
#  Full     Name
#1 Jane Anderson
#2 Andy    Smith

Or use base R with read.table after removing the suffix part
read.table(text = trimws(df1$Email, whitespace = "@.*"), sep="_",
      header = FALSE, col.names = c("Full", "Name"))
#   Full     Name
#1 Jane Anderson
#2 Andy    Smith

data
df1 <- structure(list(Email = c("email@example.com",
"email@example.com"
)), class = "data.frame", row.names = c(NA, -2L))

Comment: might want to rewrite it to handle multiple first names, its not unreasonable
Comment: @Sirius without a pattern of how that multiple names are occuring, it is not easy to suggest
Comment: That is true, but I assume the OP have only this pattern in their data (`I have a dataframe that has an email column in the following format:`) or else the OP should specify that.
Comment: Honestly, this is probably doomed to fail with real-world data. Real people don't neatly fall into "Firstname Lastname".
Comment: doing what OP does, but allowing for underscores and dots to split names would go along way, just shove all n-1 first words into the first name , and the single nth word as the last name. His use of `format` could easily just relate to column names. Anyway.
Comment: @Sirius Can you please comment your concerns below the OP's post as I read the post as `I have a dataframe that has an email column in the following format:`

Creating a name column from email


How do I update YUM repositories to get Postgres9.x version?

Question: I need to install some Postgres9.1 libs, but "yum list" only shows 8.4 version.
How to "update" yum repo list to get 9.1 version?
My Linux version:
# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 5.9 (Tikanga)

Comment: See if any 3rd-party repository has it (it's likely because rhel5.9 is a bit old for pgsql91): http://pkgs.org/search/postgresql
Answer: You can use the yum repository provided by the PostgreSQL project:
rpm -hiv http://yum.postgresql.org/9.1/redhat/rhel-5-x86_64/pgdg-redhat91-9.1-5.noarch.rpm

or
rpm -hiv http://yum.postgresql.org/9.1/redhat/rhel-5-i386/pgdg-redhat91-9.1-5.noarch.rpm

That will add their repository for you. See this document for more information.
Answer: PGDG publishes RHEL 5 packages; see http://yum.postgresql.org/ for instructions.
The package name for PostgreSQL in the PGDG repository is different. That prevents postgresql packages from being upgraded with a simple yum update. That is by design, because it'd leave you with a surprise major version upgrade - causing at minimum some significant downtime, and probably compatibility problems too.
Read the release notes for each major PostgreSQL release between your 8.4 and the current 9.3, i.e read the notes for 9.0, 9.1, 9.2 and 9.3 (especially the compatibility sections).
Then to install 9.3:
yum install postgresql93-server postgresql93-contrib

This will not upgrade your current server. It will add a new one. You can then migrate the data with pg_upgrade or a dump and reload, change the port so that 9.3 runs on port 5432, and when you're done, stop and uninstall 8.4.
For more info, see the README.rpm-dist at /usr/share/doc/postgresql93/README.rpm-dist after installing postgresql93 packages.


Finding $\ T $ invariant subspaces of $\ V $

Question: I need to find any $\ T $ invariant subspace of $\ V$ where $\ T: V \rightarrow V  , V =\mathbb R^3$
$$\ T = \begin{bmatrix} 1 & 0 & 1 \\ 0 & 1 & 1 \\ 0 & 0 & 2 \end{bmatrix} $$
So the a characteristic polynomial is $\ c_A(x) = (1-x)^2(2-x) $
$$\ E(1) = sp\{(1,0,0), (0,1,0)\} \\
E(2) = sp\{(1,1,1)\}$$
Not sure I understand this topic. Question is, if any eigen value has its own subspace and $\ V $ is always the direct sum of all the subspaces spanned by the eigen vectors, then the eigen vector/s of each value is a $\ T $ invariant subspace (Assume $\ T $ is diagnosable)?
Then in this case the $\ T $ invariant subspaces of $\ V $ are, $\ \mathbb R^3, \{0\} , \ \{(1,1,1)\} $ (dim 1) & $\ \{(1,0,0),(0,1,0)\}$ (dim2)
Comment: Any space spanned by a set of eigenvectors is invariant
Comment: There are many other 1 and 2-dimensional invariant subspaces, for example the span of $(1, 1, 0)$ is $T$-invariant, as is the span of $\{(1, 1, 1), (1, 0, 0)\}$.
Comment: @bm No. The fact that $T$ is diagonalizable means that every $T$-invariant subspace is spanned by a set of eigenvectors.
Comment: Ok, read a little bit more and found that any subspace of the Eigenspaces is also $\ T -$ invariant, can't see why $\ {(1,1,1),(1,0,0)} $ is also $\ T- $ invariant though?
Comment: Thanks! are there also T-invariant subspaces that are not spanned by a. set of eigenvectors ?
Answer: I wouldn't bother with "characteristic polynomials" or "characteristic numbers".  (x, y, z) is in an "invariant subspace" of T if and only if
$\begin{bmatrix}1 & 0 & 1 \\ 0 & 1 & 1 \\ 0 & 0 & 2 \end{bmatrix}\begin{bmatrix} x \\ y \\ z \end{bmatrix}= \begin{bmatrix} x+ z \\ y+ z \\ 2z \end{bmatrix}= \begin{bmatrix} x \\ y \\ z\end{bmatrix}$
So we have x+ z= x, y+ z= y, 2z= z.  All of those are satisfied if z=0, no matter what x and y are.  The invariant subspace is the two-dimensional subspace spanned by $\begin{bmatrix}1\\0 \\ 0 \end{bmatrix}$ and $\begin{bmatrix}0 \\ 1 \\ 0 \end{bmatrix}$


Estou tentando instalar o Ionic 2 mas esta dando erro no na hora de executar o npm install -g codova ionic

Question: Gustavo@Gustavo-PC MINGW64 ~
$ npm install -g cordova ionic
npm WARN deprecated email@example.com: Use uuid module instead
npm WARN deprecated email@example.com: Please update to minimatch 3.0.2 or higher                                                                                to avoid a RegExp DoS issue
npm WARN deprecated email@example.com: Please update to minimatch 3.0.2 or higher                                                                                to avoid a RegExp DoS issue
npm WARN deprecated email@example.com: Please update to minimatch 3.0.2 or higher                                                                                to avoid a RegExp DoS issue
npm WARN deprecated firstname.lastname@example.com: Use uuid module instead
C:\Users\Gustavo\AppData\Roaming\npm\cordova -> C:\Users\Gustavo\AppData\Roaming\npm\node_modules\cordova\bin\cordova
C:\Users\Gustavo\AppData\Roaming\npm\ionic -> C:\Users\Gustavo\AppData\Roaming\npm\node_modules\ionic\bin\ionic
C:\Users\Gustavo\AppData\Roaming\npm
+-- firstname.lastname@example.com
| +-- firstname.lastname@example.com
| | +-- email@example.com
| | +-- email@example.com
| | | `-- email@example.com
| | +-- firstname.lastname@example.com
| | +-- email@example.com
.
.
.
  | `-- email@example.com
    `-- firstname.lastname@example.com

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\ionic\node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for firstname.lastname@example.com: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN In firstname.lastname@example.com replacing bundled version of mime-types with firstname.lastname@example.com
npm WARN In email@example.com replacing bundled version of cross-spawn with email@example.com
npm WARN In email@example.com replacing bundled version of semver with firstname.lastname@example.com
npm WARN In email@example.com replacing bundled version of form-data with email@example.com
npm WARN In email@example.com replacing bundled version of request with email@example.com
npm WARN In email@example.com replacing bundled version of ionic-app-lib with email@example.com

Gustavo@Gustavo-PC MINGW64 ~
$ ionic
bash: ionic: command not found

Gustavo@Gustavo-PC MINGW64 ~
$ cordova --version
bash: cordova: command not found

Gustavo@Gustavo-PC MINGW64 ~
$ ionic start like_app sidemenu --v2
bash: ionic: command not found

Comment: Na verdade, parece-me que o pacote foi instalado, apesar dos avisos. Veja se o caminho do `ionic` está no seu PATH
Comment: deu certo realmente esta faltando o caminho no PATH, eu tinha trocado o sistema para outro HD e acabei não vendo o caminho.
Comment: Vou criar uma resposta, e você pode marcá-la como correta. =)
Answer: Os avisos do NPM (WARN) não devem impedir o funcionamento do seu pacote. Eles ocorrem quando alguma coisa poderia ser melhorada, ou quando algum método está deprecado, ou quando algum outro pacote é recomendado, mas, por si só, não impedem o funcionamento do mesmo. Problemas ocorrem quando você tem erros (ERR), e aí sim o funcionamento vai estar comprometido.
No seu caso, os avisos são sobre métodos deprecados (que eventualmente vão deixar de funcionar), dependências opcionais que não foram instaladas, e alguns replaces que o instalador, por algum motivo, achou que deveria fazer. Ou seja, o pacote foi instalado corretamente.
O seu problema mora no PATH, que é aonde você estabelece o caminho pros binários de pacotes que você quer rodar via linha de comando. No Windows 7, onde estou agora (sim, Windows 7 =/), basta apertar a tecla "Windows" e digitar "variáveis de ambiente". No primeiro resultado, um dialogo já é aberto para que você edite o PATH. Concatene, nessa string, o caminho do ionic (algo como C:\user\node_modules\ionic\bin). Depois disso, tudo deve funcionar!


$\int_0^\infty x^n e^{-x^{12}\sin^2x}dx$ is divergent for any natural numbers $n$?

Question: $\int_0^\infty x^n e^{-x^{12}\sin^2x}dx$ is divergent for any natural numbers $n$? My attempt: Cauchy criteria near $2k\pi$ for integers $k$.
Answer: $$\begin{align}\int_{k\pi}^{(k+1)\pi}e^{-x^{12}\sin^2x}\,\mathrm dx
&= \int_0^\pi e^{-(k\pi+x)^{12}\sin^2x}\,\mathrm dx \\
&> \int_0^\pi e^{-((k+1)\pi)^{12}x^2}\,\mathrm dx \\
&= \int_0^\pi e^{-\pi^{10}((k+1)^6x)^2}\,\mathrm dx \\
&> \int_0^{\frac1{(k+1)^6}} e^{-\pi^{10}((k+1)^6x)^2}\,\mathrm dx \\
&> \int_0^{\frac1{(k+1)^6}} e^{-\pi^{10}}\,\mathrm dx \\
&=\frac{e^{-\pi^{10}}}{(k+1)^6}
\end{align} $$
so that you will readily find that the integral diverges at least for $n\ge 6$.
Comment: For a more precise result, I think one can use [Laplace's method](https://en.wikipedia.org/wiki/Laplace%27s_method) to get $\int_{k \pi-\pi/2}^{k\pi+\pi/2} x^n \exp(-x^{12}\sin^2(x))\sim C (k \pi)^{n-6}$ when $k\to\infty$.
Comment: It seems that for $1\leq n<6$, the integral is also divergent. But I can not prove it.


Interior and Closure of a set in a Cofinite Topology on R

Question: Considering the Cofinite Topology on Real Line
My question is what is the Closure and Interior of [a,b] with respect to this topology.
Actually I am a beginner. If you explain the underlying concept along with the answer to me then that would be very helpful.
Thank you.
Comment: What are the open sets contained in $[a,b]$? What are the closed sets containing $[a,b]$?
Answer: If $b>a$ then $[a,b]$ contains infinitely many elements, hence the only closed subset (in the cofinite topology) containing $[a,b]$ is $\Bbb R$ itself; it follows that the closure of $[a,b]$ is $\Bbb R$. Similarly for the interior. As $\Bbb R\setminus[a,b]$ contains infinitely many elements, the only open subset contained in $[a,b]$ is the empty set, hence $[a,b]^\circ=\emptyset$.
Answer: In this topology the open sets are very big, so let's try to keep this in mind when we are computating. I will denote the closure of $[a,b]$ as $\overline{[a,b]}$
Claim $\overline{[a, b]} = \mathbb{R}$, clearly $[a,b] \subset \mathbb{R}$ so let $x \in \mathbb{R} \text{ and } U \text{ an open set such that} x \in U$, now as $U$ is open $\mathbb{R}-U$ is finite and as $[a,b]$ is infinite then $ [a,b] \not\subset \mathbb{R}-U \Rightarrow\exists y \in [a,b] - (\mathbb{R}-U)$ then $y \in [a,b] \cap U \Rightarrow [a,b] \cap U \neq \emptyset$ so by definition $x \in \overline{[a,b]}$ this is true for each $x \in \mathbb{R}$ so $\mathbb{R} \subseteq \overline{[a,b]}$ therefore we conclude $\overline{[a,b]} = \mathbb{R}$
With this in mind try to calculate the interior ¿Can $[a,b]$ contain any open set?
Spoiler: int($[a,b]$) = $\emptyset$


How to check current request resource is a page in C# ASP.NET?

Question: I have an IHttpModule implementation with a delegated method hooked to PostAcquireRequestState, for each HTTP Request, I would like to know how to check if the current requested resource is a Page (aspx) discriminating all other resources like *.css, *.ico, *.png and so on.
Actually I can do the following:
private static void OnPostAcquireRequestState(object sender, EventArgs e)
{
  bool isPage = HttpContext.Current.Request.Path.EndsWith(".aspx");
}

But I would like to know if there is something different to do than hard checking with ".aspx".
Comment: What about `ashx, asmx, asx` and other server-side executable formats?
Comment: @Abel, that's the reason I would to know if there is *something different to do a hard checking against the format `".aspx"`*. Thanks for highlighting that point, since I didn't put it on my question. :)
Comment: What are you trying to achieve?
Comment: @Be.St. I would like to check if the `Session` object exists when requesting a page, because when requesting another resources such an icon the `Session` seems like to be always `null`.
Comment: Is not enough to check if (Request.Session==null)?
Or are you in a situation like: "if the request is for a page check session. Then if session is null do something else do something different"?
Comment: Indeed, this is my situation. I need to check the `Session` if the request is for a Page.
Answer: One thing you could do is to get a list of registered HTTP Handlers and check whether they are handled by a system class. Assuming you don't name your own classes in a namespace System.*, this is quite foolproof:
using System.Configuration;
using System.Web.Configuration;

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
HttpHandlersSection handlers = (HttpHandlersSection) config
                               .GetSection("system.web/httpHandlers");

List<string> forbiddenList = new List<string>();

// next part untested:
foreach(HttpHandlerAction handler in handlers.Handlers)
{
    if(handler.Type.StartsWith("System."))
    {
        forbiddenList.Add(handler.Path);
    }
}

Alternatively, you can revert the lookup and list all existing handlers except those in your own (or current) domain, possibly provided some exceptions (i.e., if you want to override an existing image handler). But whatever you choose, this gives you full access to what's already registered.

Note: it's generally easier to do the reverse. You now seem to want to blacklist a couple of paths, but instead, if you can do whitelisting (i.e., make a list of those extensions that you do want to handle) you can make it yourself a lot easier.


Why can this code not return the bpEffect variable with the value 505.5?

Question: The expected result from the following code should be 505.5, but instead it returns 3.97541e+70. Why is this the case and how can the problem be solved ?
#include <iostream>
#include <string>
using namespace std;
class Position {
public:
    Position(int s, double p, string n) {
        shares = s;
        price = p;
        name = n;
    }
    double getBpEffect() {
        return bpEffect;
    }
private:
    string name;
    int shares;
    double price;
    double bpEffect = (shares*price) / 2;

};

int main() {
    Position xyz = Position(100, 10.11, "xyz");
    double buyingPower = xyz.getBpEffect();

    cout << buyingPower;

    system("pause");
    return 0;

}

Comment: `(shares*price) / 2` happens too early, before `shares` and `price` get initialized. You are doing arithmetic on random garbage, so of course you get garbage out. Initialize `bpEffect` after you've assigned values to `shares` and `price`.
Comment: Igor is correct. You should be putting `(shares*price) / 2` into a method, such as your constructor, not as an initializing statement in your code.
Comment: as said by Igor Tandetnik, you're managing garbage; garbage in imply garbage out; The solution is obvious: `Position(int s, double p, string n): name{n}, shares{s}, price{p}, bpEffect{(shares*price)/2} {}`
Answer: double bpEffect = (shares*price) / 2; is run before the body of your constructor using the undefined values in shares and price.  You need to calculate bpEffect after you have initialized the other variables.
Answer: The shown class gets initialized by a mixture of constructor code, and explicit member initialization.
Unless the order in which various bits and pieces of class construction occurs is fully understood, it's quite easy to get things happen in the wrong order.
The best thing to do is to initialize everything in one place, removing all ambiguity:
Position(int s, double p, string n)
   : name(n), shares(s), price(p),
     bpEffect((shares*price) / 2)
{
}


MySQL - Returning NULL even though it contains an integer

Question: I'm using Python CGI and MySQL (phpmyadmin). I'm trying to run this SQL statement in python: (tk_journey = 620 for this example - where the %s is)
SELECT tk_id, tk_seat_number FROM tickets
        WHERE tk_journey = '%s'
        ORDER BY tk_id DESC LIMIT 1;

It works perfectly in phpmyadmin and displays what it should (which is this):
tk_id tk_seat_number
 94         2

However, when I run this through a python script it returns None/NoneType for each.
I've tried using this: SELECT MAX(tk_id), tk_seat_number FROM tickets WHERE tk_journey = '%s' but that gave the same result.
I tried to use %s without the quotes but it also generated an error - in mysql syntax. I also tried closing and opening the database connection - didn't work.
I've tried researching this problem a lot but to no help.
Here is the python code:
def getSeatNum(jid):
    statement = '''SELECT tk_id, tk_seat_number FROM tickets
        WHERE tk_journey = '%s'
        ORDER BY tk_id DESC LIMIT 1;'''
    cursor.execute(statement, jid)
    row = cursor.fetchone()
    seat_num = row[0]
    return(seat_num)

seat_no = getSeatNum(jid)

jid = 620.
The db connection works fine as there are several other functions similar to this selecting/inserting information into tables, but this one seems to be failing?
Thanks in advance!
EDIT: I'm not sure if this is what I am meant to do. This got marked as a duplicate of this question: Python MySQL TypeError. I never got this TypeError. If the program ran without generating an error - it just returned 'NULL', which in turn affected a later program as the variable would just be 'NULL'. The errors I would get were the SQL syntax error as shown above and various Python errors when I was fiddling around to get it to work. Not this TypeError one.
Answer: The second argument to cursor.execute() must be a tuple containing the values to fill in all the placeholders in the query. Even if there's only one placeholder, you need a tuple. So it should be:
cursor.execute(statement, (jid,))

Comment: Thanks Barmar! That worked, i can't believe it was that simple and I'd spent so long trying to figure it out! :')


Como retirar um certo elemento na hora de fazer o site responsivo?

Question: gente eu sei que parece uma pergunta besta mas é o seguinte eu estou fazendo um site responsivo e claro que o que eu fiz para web não ira se encaixar em um celular.
entao supondo que eu fiz para web uma tabela com 9 partes, em um celular eu gostaria apenas de deixar 4 ou 5, como retirar o restante dos elementos sem interferir no html do site web?  pois é obvio que mesmo que eu faça as reduções no css uma tabela de 9 partes ficaria ridicula e pequena demais.
espero que tenham entendido,

então a parte das tabelas ate consegui arrumar pra colocar uma embaixo da outra, mas ainda não sei como retiro elementos tipo uma foto.
no html vai estar la
no css eu posso editar img {... tal }
mas  pra retirar? tipo eu não quero mais esta imagem aparecendo na parte responsiva como faço? pq um none não tem como dar. e como retiro sem alterar o html e o css da parte web

e tambem pq tem muitos itens que não quero que apareçam no responsivo senão ficara grande demais
Comment: Não está dando para entender o que você chama de "partes" da tabela. São colunas? Linhas? Blocos? Favor [edit] a pergunta acrescentando mais informações. Obrigado.
Comment: Sua pergunta não está clara... Vc já tem o código da versão desktop de 9 partes pelo menos? Tem alguma imagem de como deve ficar o layout no desktop ou no mobile? Só com esse relato não da para te ajudar muito...
Answer: Você pode usar media queries para fazer isso. Seria algo assim:
<code>@media screen and (max-width: 300px) {
//Ocultar colunas
}
</code>
Existem duas alternativas, uma é a que você falou na pergunta, que seria esconder colunas. Aqui tem um tutorial passo a passo:
https://phppot.com/css/automatic-column-hiding-using-css-in-responsive-table/
A outra seria inverter a tabela, ou seja, transformar as colunas em linhas. Aqui tem um exemplo:
https://css-tricks.com/responsive-data-tables/


Can I connect aux sends back into the mixer inputs?

Question: I am considering getting a mixer for band practice. The model I'm looking at (Zoom L-12) has 5 individual submixes meant to be used as headphone monitoring outputs.
What has struck me when I looked at it, was the possibility to reroute the submix back into the mixer again. An example connection could look like this:

The path could work like this:

Blue: dry guitar signal using High-Z input
Orange: dry guitar signal again, from the A submix to e.g. amp modeler
Green: wet guitar signal
Red: actual main mix

What this gives me is e.g. ability to mix dry/wet guitar signal in main mix, record the dry signal for reamping etc.
Is there anything that would prevent this from working? I know that master outputs can't be used that way because they could form an infinite loop that amplifies the signal, but in this case I could mix that so that the A submix doesn't receive the track 2 at all (to avoid the feedback loop specifically).
Comment: Just don't turn your aux send up on the channel that has the return. Unless you are going for feedback. ;)
Comment: [This video](https://www.youtube.com/watch?v=RrKISMxPEeI) seems to be showing exactly the thing I'm after, but I'd still like a confirmation and some tips.
Comment: Pretty sure i used to do similar about 25 yrs ago. Nothing's going to go bang, just keep the volumes down as you try it.
Comment: As other commenters have noted, just watch the levels.  Treat the dry guitar as you would a guitar or microphone, and treat the "wet" guitar as you would a line level device.
Comment: I don't see how the levels alone would generate feedback in this set up. As long as the signal is routed correctly, there shouldn't be a problem with feedback.
Answer: This should be possible, but I see one potential problem:
The signal coming out of Phone 1 will not be high impedance (Hi-Z). So if you are sending it to a guitar effects unit or amp, you may not sound the same as plugging the guitar in directly.
A more traditional way to do this would be to utilize a DI box. In that case, you plug the guitar into the DI box, send the XLR-out on the DI box to channel 1 on the mixer, send the Thru-out on the DI box to your effects, and send the effected sound into channel 2 on your mixer. This way you can still mix the wet/dry levels while still matching impedances.
Comment: That's a good point. That's what I actually wanted to do, albeit having a dibox integrated in the fx unit makes it even simpler. That was just one example, though, this idea could be applied to any other signal as well.


State-space model with contemporaneous effects

Question: I have the following system of equations:
$$
\begin{align}
y_t^{(1)}&=y_t^{(2)}-x_t+\epsilon_t\\
y_t^{(2)}&=x_t+\nu_t\\
x_t&=\alpha x_{t-1}+u_t
\end{align}
$$
where $y_t^{(1)}, y_t^{(2)}$ are observed and $x_t$ is not.
I'm having some issues putting this into the state-space formulation. The issue I have is that in order to get $y_t^{(2)}$ in the (measurement) equation for $y_t^{(1)}$ I need to put it in the state vector. But I need $y_t^{(2)}$ in the measurement equation in order to get $x_t$ in there. So what do I do with $y_t^{(2)}$ in the state vector? Can I simply skip that row in the state equation? That would give me:
$$
\begin{align}
\begin{pmatrix}y_t^{(1)}\\ y_t^{(2)}\end{pmatrix}&=\begin{pmatrix}-1 & 1 \\
0 & 1\end{pmatrix}\begin{pmatrix}x_t \\ y_t^{(2)}\end{pmatrix}+\begin{pmatrix}\epsilon_t\\\nu_t\end{pmatrix}\\
x_t&=\begin{pmatrix}\alpha & 0 \end{pmatrix}\begin{pmatrix}x_{t-1} \\ y_{t-1}^{(2)}\end{pmatrix}+u_t.
\end{align}
$$
Answer: Substitute the second equation into the first and you have
\begin{align}
y_t^{(1)}&=y_t^{(2)}-x_t+\epsilon_t\\
&=x_t+\nu_t-x_t+\epsilon_t\\
&=\nu_t+\epsilon_t.
\end{align}
So it's
\begin{align}
\begin{pmatrix}y_t^{(1)}\\ y_t^{(2)}\end{pmatrix}&=\begin{pmatrix}0 \\
1\end{pmatrix}x_t+\begin{pmatrix}1 & 1 \\ 0 & 1\end{pmatrix}\begin{pmatrix}\epsilon_t\\\nu_t\end{pmatrix}\\
x_t&=\alpha x_{t-1}+u_t.
\end{align}
Another way to see it is to rewrite the measurement equations as
\begin{align}
y_t^{(1)}-y_t^{(2)}&=-x_t+\epsilon_t\\
y_t^{(2)}&=x_t+\nu_t,
\end{align}
which is equivalent to
$$\begin{pmatrix}1 & -1 \\ 0 & 1\end{pmatrix}\begin{pmatrix}y_t^{(1)}\\ y_t^{(2)}\end{pmatrix}=\begin{pmatrix}-1 \\
1\end{pmatrix}x_t+\begin{pmatrix}\epsilon_t\\\nu_t\end{pmatrix}.$$
To isolate the observables on the left hand side, note that
$$\begin{pmatrix}1&-1\\0&1\end{pmatrix}^{-1}=\begin{pmatrix}1&1\\0&1\end{pmatrix}.$$
Multiply both sides by that and you get
\begin{align}
\begin{pmatrix}1&1\\0&1\end{pmatrix}\begin{pmatrix}1 & -1 \\ 0 & 1\end{pmatrix}\begin{pmatrix}y_t^{(1)}\\ y_t^{(2)}\end{pmatrix}&=\begin{pmatrix}1&1\\0&1\end{pmatrix}\left[\begin{pmatrix}-1 \\
1\end{pmatrix}x_t+\begin{pmatrix}\epsilon_t\\\nu_t\end{pmatrix}\right]\\
\begin{pmatrix}y_t^{(1)}\\ y_t^{(2)}\end{pmatrix}&=\begin{pmatrix}1&1\\0&1\end{pmatrix}\begin{pmatrix}-1 \\
1\end{pmatrix}x_t+\begin{pmatrix}1&1\\0&1\end{pmatrix}\begin{pmatrix}\epsilon_t\\\nu_t\end{pmatrix}\\
\begin{pmatrix}y_t^{(1)}\\ y_t^{(2)}\end{pmatrix}&=\begin{pmatrix}0 \\
1\end{pmatrix}x_t+\begin{pmatrix}1&1\\0&1\end{pmatrix}\begin{pmatrix}\epsilon_t\\\nu_t\end{pmatrix}.
\end{align}


how to get value of span on image click

Question: I want to get span value my code is below.  All i want is get span value with class="hideme" when i click any of image. Im using html5 jquerymobile phonegap_v2.0 framework Xcode_v4.3
css code:
.hideme{
diplay:none;
}

html code:

         John1

          Carmen2

          Julia3

how to do in javascript or jquery
Comment: What have you tried? Those are two different problems: 1: assign a click event to an element. 2: read the value (=text/html?) of an element. Both are pretty easy in JQuery, so if you look at them seperately, you'll find hundreds of examples which you only need to combine.
Comment: none of the two answers working for me
Answer: Span elements don't have a "value". If you're asking how to get the text content of the span contained within the same
 element as a clicked  element then you can do this with jQuery:
$("#ulist img").click(function() {
    var spanContent = $(this).closest("li").find("span.hideme").text();
});

If you're asking how to get the id attribute, use .attr("id") instead of .text().
Comment: function GetId(){
             var spanContent = $("#ulist img").closest("li").find("span.hideme").text();
                alert(spanContent);
            } is working for me but it is giving all values from all spans how i get only the clicked li span text
Comment: You need to use `$(this).closest...` rather than `$("#ulist img").closest)` _within a click event handler_ for the image element(s), where jQuery will set `this` to the clicked image element. As shown in my answer.
Comment: i need only selected li span text
Comment: your code giving me array of all span's text
Comment: You tried the code from my answer exactly as shown? You didn't just take part of it like in your first comment?
Answer: this worked for me
 $(function() {
              $('li').click(function() {
                 var list_item = $(this);
                  var Id = list_item.find('span.hideme').text();
                   alert(Id);
                            });
              });

Answer: Are you looking something like this,
Demo: http://jsfiddle.net/W33rK/
$('img').click(function(){
   var span = $(this).parents('li').find('span.hideme').text();
   //alert(span)
})

Comment: i dont know but its not working can you check your code in jsfiddle. no alert working
Comment: im not good at jquery. do i have to give onlcick event in every image?
Comment: there is no jquerymobile framwork in jsfiddle how do i test my script

how to get value of span on image click


directory listing export to csv

Question: I'm trying to pull the names of files from a directory into a csv file with the following:
Get-ChildItem -name | % { [IO.Path]::GetFileNameWithoutExtension($_) }
                                                  | Export-Csv users.csv

Using '% { [IO.Path]::GetFileNameWithoutExtension($_) }' to display the files with out extensions.
All I get is the following in return:
>>
Length
12
10
13
9
14
18
14
11

Any Ideas?
Answer: What does the directory really look like? Guessing the dir does not have dirs named  12,10,13... It does help us help you when we know what you're working with.
Why not just use "basename"?
PS C:\temp\post> ls

    Directory: C:\temp\post

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---          3/5/2012   2:55 PM         72 mark.txt
-a---          3/5/2012   2:55 PM         72 mike.txt
-a---          3/5/2012   2:55 PM         72 molly.txt
-a---          3/5/2012   2:57 PM         81 users.csv

PS C:\temp\post> gci | select baseName | export-csv users.csv -noTypeInfo

PS C:\temp\post> gc .\users.csv
"BaseName"
"mark"
"mike"
"molly"
"users"

Comment: using basename worked (i'd not used it before). Thank you :)

directory listing export to csv


React update child component state from parent using getDerivedStateFromProps

Question: Am new to React, I like to maintain state in parent component itself and pass the same to all child components on child component I would like to update the child state from the parent component state am using getDerivedStateFromProps to update it. But i guess am doing it wrong as the values are updated in inner level object like inside state there is a level object named state, I had tried to spread it as well but it didn't work.
Parent Component
  import React from 'react';
  import './App.css';
  import Navbar from './components/Navbar';

  class App extends React.Component {
    state = {
      name: 'Kannan',
      countryCode: '',
      mobile: '',
      isModalOpen: false,
    };

    render() {
      return (

          <Navbar params={this.state}></Navbar>

      );
    }
  }

  export default App;

Child Component
  class NavbarComponent extends React.Component {
  constructor(props) {
    super(props);

    console.log(props.params);

    this.state = {};
  }

  static getDerivedStateFromProps(props, state) {
    console.log(state);
    return { state: props.params };
    // return  {state: { ...props.params }} ;
  }

  render() {
    console.log(this.state);
    return (

           "Something"

    );
  }
}

I have tried with { state: ...props.params} and also {state: props.params} in the render console.log am getting
   {state: {…}}
     state: {name: "Kannan", countryCode: "", mobile: "", isModalOpen: false}
    __proto__: Object

what am expecting is
 state: {name: "Kannan",countryCode:"",mobile:"",isModalOpen:false}

Note:
No REDUX. I don't want to use REDUX If there is any other better approach to update child component state? Also, I would like to know whether maintaining state for each child component is a good practice or not? Any help is appreciated
Comment: You may find this article a useful introduction: https://reactjs.org/docs/lifting-state-up.html
Comment: Why does the child need state at all? Can it not just use props?
Comment: Yes we can but I would like to try with child state is it wrong approach?
Comment: Trying to duplicate props into state is almost always the wrong approach. Have the parent component be the single source of truth. It will have the value in its state, and then all other components will get the value via props.
Comment: @NicholasTower Am going to have multiple child component under Navbar component which is child component of APP component shall i still have the state only in APP component?
Comment: Do you have one set of data which all the components base themselves off of? Then put the state in the parent, pass it as props, and don't duplicate it. Does each child have independent sets of data? Then *remove* state from the parent, don't pass it as props, and have each child do their own thing. It is very rare that taking in props and duplicating it to state is the right approach. Please read this article: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
Comment: @NicholasTower  Mine is bit of both I have few data's like contact details which I need on the main parent component as well inner child component few data I need only on child component, for example am writing navbar as child component in navbar component am writing modal component as child component which have its own data like when to open the modal or to close same goes with navbar component as well which has own data what has to be happened when I click navbar buttons, Remember I need contact details from parent component so can you tell me a good approach in my case
Comment: Nothing you have described requires duplicating props to state. Use the standard react approach: For a given piece of data, keep it as state in the parent component (or whatever component is the common ancestor of the components that need that data). Then use props to pass it down to any components that need it.
Comment: @NicholasTower thanks man I'll check it out and get back to you if I have any queries
Answer: Well I would suggest to use redux instead of passing the whole state from Parent to child. But if you really wanna do this then it should be like below:
import React from 'react';
import './App.css';
import Navbar from './components/Navbar';

**Parent Component**

class App extends React.Component {
  state = {
    name: 'Kannan',
    countryCode: '',
    mobile: '',
    isModalOpen: false,
  };

  render() {
    return (

        <Navbar params={this.state}></Navbar>

    );
  }
}

export default App;

**Child Component**

class NavbarComponent extends React.Component {
  static getDerivedStateFromProps(props, state) {
    return { ...props.params };
  }

  constructor(props) {
    super(props);
    this.state = props.params;
  }

  render() {
    return (

        "Something"

    );
  }
}

Answer: Instead of
static getDerivedStateFromProps(props, state) {
    return { state: props.params };
}

Try
  static getDerivedStateFromProps(props, state) {
    return props.params;
  }

In the first piece of code, you're passing an object with a key state, and your child component will have it's state set to {state: whateverCameFromAnotherComponent} as you mention in "inside state there is a level object named state". If you just pass the state from your parent as you receive it, the child's state should be the very same as the parent's.
I tried to recreate your scenario here:

and as you can see, the Navbar's state is set to Object {name: "Kannan", countryCode: "", mobile: "", isModalOpen: false}, without the state key in it.