text:
Q: Azure ACS alternative for ADFS mobile authentication I've been using azure ACS to authenticate my mobile clients with corporate ADFS to my asp.net server app. I managed not only to have it working nicely in the web browser but also on mobile apps (with webview to get a jwt token that would then be sent to the server to be validated and generate the app auth token).
But unfortunately Azure ACS is being discontinued so I have to look for an alternative.
Using this article I managed to have ADFS auth directly without any external service and that is a HUGE plus for me since some customers might have internet restrictions on their intranet.
The problem begins when trying to also implement this for the native clients (Windows WPF, Android and iOS) since I can't find a solution for these cases.
ADAL for Android and iOS seems to require Windows Server 2012 R2. This restriction is a big no no.
I found a 3rd party auth provider Auth0 but I really want to avoid external services.
There's also Azure B2C Authentication but it has the same issue of external services.
Is there a way to implement what I had with Azure ACS directly on ADFS? What I need is a way to get a jwt token (or even SAML2 token) directly from ADFS.

A: ACS uses WS-Fed which is what that sample uses as the protocol.
Mobile devices use OAuth which is why you need ADFS 3.0 (limited support) or ADFS 4.0 (full support plus OpenID Connect).
If you just want ADFS to return a JWT token instead of a SAML one, refer to this article.

Set-ADFSRelyingPartyTrust –TargetIdentifier 'urn:MyWebApp' –EnableJWT
  $true

However, that requires ADFS 3.0.
The other way is to use WCF. This invokes the WS-Fed active profile which returns a SAML token as a web service as per this article.

A: I created a custom solution for my needs. Basically I implemented a solution akin to ACS flow.
The apps load a special login page on a webview that redirects the browser to the ADFS challenge page with a final callback to my webapp. There I notify the app with the token by the usage of notification javascript call like ACS does:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Loading...</title>
    <script type="text/javascript">
        try{
            window.external.notify('@ViewBag.Result');
        }
        catch(err){
            alert("Error ACS50021: window.external.notify is not registered.");
        }
    </script>
</head>
<body>
</body>
</html>

This way my app will not handle the user credentials directly and I no longer need external services :)
And unlike ACS I have direct control on the last step and I can export the token via a redirect to a custom protocol that helps the implementation on iOS (on ACS we had to inject javascript to the page in the webview to achieve this).


text:
Q: What are the Oracle best practices to return data to c# I am totally green to Oracle and I am looking for the best practice to calling and retrieving data from an Oracle DB.
In C# I can do this...
    OracleCommand cmd = new OracleCommand();
    cmd.Connection = conn;
    cmd.CommandText = "SELECT * FROM MyTable WHERE id = 3";
    cmd.CommandType = CommandType.Text;
    OracleDataReader dr = cmd.ExecuteReader();
    dr.Read();
    string lastName = dr.Get<string>("A_Field_1");

However I want to create a stored proc in Oracle to return a data table back.
For example "Select * from MyTable".
Is it better practice to create the stored proc in Oracle, maybe utilize a function or in line in my code base?
I would prefer to create a stored proc, but I am struggling with the syntax necessary to accomplish this simple task.

A: It is best practice to create a stored procedure rather than using dynamic SQL in your C#. In your case you can create a simple procedure like this;
create procedure myproc (prc out sys_refcursor)
is
begin
   open prc for SELECT * FROM MyTable WHERE id = 3
end;

However, as Klaudiusz points out you, could also use some kind of ORM.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot find name 'Component' - Angular 2 TypeScript error2304 I'm new in Angular2 and TypeScript. When I try some examples like this bellow
  @Component({
  selector: 'counter',
  template: `
    {{ value }}
    <button (click)="increase()">Increase</button>
    <button (click)="decrease()">Decrease</button>
  `
  })
  class Counter {
    value: number;

    constructor() {
    this.value = 1;
    }

    increase() {
    this.value = this.value + 1;
    }

    decrease() {
    this.value = this.value - 1;
    }
}

I face "Cannot find name 'Component'" error on compile.
What's the problem?
What should I do?

A: You need to import things in TS, It doesn't know what that decorator is otherwise, but within angular you can provide it.
import { Component } from '@angular/core';

Also make sure you export your class so you can import it elsewhere.
export class Counter


text:
Q: selenium element not interactable i started using selenuim, node js
it was working all perfect so far, sudenly the same script is throwing and error
"unhandled promise rejection warning element not interactable"
i tried setting  wait, until and nothing
<script>

  const {Builder, By, Key, until, wait } = require('selenium-webdriver');

  var driver = new Builder()
.forBrowser('chrome')
.build();

 driver.manage().window().maximize()
 driver.get('http://www.google.com/testsite')
driver.findElement(By.id('username')).sendKeys('test@emal');
driver.findElement(By.id('password')).sendKeys('passowrod');
driver.findElement(By.className('acceder')).click();
driver.quit();

</script>

i search all over but all examples simply did not work for me, due that they dont have that issues,..
https://www.youtube.com/watch?v=C6qQojzN7bE&index=4&list=PLA4JPGpQHctT__mDO9EHvOrWVW0Hkf5Mk

A: These locators worked for me for the url you shared:
driver.findElement(By.xpath('(//input[@id="username"])[2]')).sendKeys('test@emal');
driver.findElement(By.xpath('(//input[@id="password"])[2]')).sendKeys('passowrod');
driver.findElement(By.xpath('(//button[@class="boton acceder"])[2]')).click();

The reason for using 2nd index for all the elements is that the same elements are in HEADER which are hidden.
Note: I tried these in python, so please adjust if any string syntax error.

A: The problem:  While running the automation, the window size is is not fully presented on screen so some elements are rendered outside of the visible area in your configured chrome web driver.
The solution would be using this snippet in your base configuration:
browser.driver.manage().window().maximize();


text:
Q: Calculate driving distance in KM when a Form is submitted I need to adapt the script below so that when a form is submitted, the response email indicates the driving distance between the origin (partida) and destination (destino) in kilometers.
var docTemplate = "1FteemZEe52j244XldbZnE7qKHNiZFEoKYZK1xNge3Cs";
var docName     = "AUTORIZAÇÃO PARA RETIRADA DE VEÍCULO";

// Create the function
function onFormSubmit(e) {
//Get the variables
  var email_address = "user@example.com";
  var nome = e.values[2];
  var carro = e.values[3];
  var data = e.values[4];
  var hora = e.values[6];
  var destino = e.values[7];
  var motivo = e.values[5];
  var partida = e.values[8];

// Copy and start temp document
  var copyId = DriveApp.getFileById(docTemplate)
                .makeCopy(docName+' para '+nome)
                .getId();

  var copyDoc = DocumentApp.openById(copyId);

  var copyBody = copyDoc.getActiveSection();

   copyBody.replaceText('keyNome', nome);
   copyBody.replaceText('keyCarro', carro);
   copyBody.replaceText('keyData', data);
   copyBody.replaceText('keyHora', hora);
   copyBody.replaceText('keyDestino', destino);
   copyBody.replaceText('keyMotivo',motivo);

// I need put here the simple calculator for distance in KM from variable partida and variable destino

// Salve the temp document
   copyDoc.saveAndClose();

// Convert in PDF the temp document and send email

   var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
   var subject = "AUTORIZAÇÃO DE VEÍCULO";
   var body    = "Esta é a autorização do(a) " + nome + "";
   MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});

// Delete the temp document
   DriveApp.getFileById(copyId).setTrashed(true);
}

A: A function for calculating driving distance is presented in the Google Apps Script Quickstart: Macros, Menus, and Custom Functions. An adapted version that accepts multiple waypoints is shown in Looking for distance between multiple points in a googlesheets script.
With either of those functions included, you can modify your code like this:
...
copyBody.replaceText('keyDestino', destino);
copyBody.replaceText('keyMotivo',motivo);

// Calculate distance in KM from partida to destino
var distancia = drivingDistance(partida, destino) / 1000;
copyBody.replaceText('keyDistancia',distancia);

// Save the temp document
copyDoc.saveAndClose();
...

If you wish to format the calculation, use Utilities.formatString().

A: I got my code functional! Its works fine! Mogsdad, "você é o cara!". Thanks so much!
// Pega um template do Google Docs e nomeia
var docTemplate = "1FteemZEe52j244XldbZnE7qKHNiZFEoKYZK1xNge3Cs";
var docName     = "AUTORIZAÇÃO PARA RETIRADA DE VEÍCULO";

// Quando o formulário é enviado (lembre-se de acionar uma trigger para que este código funcione)
function onFormSubmit(e) {
//Pega as informações do formulário e organiza em variáveis. Note que a posição de cada variável depende da coluna da planilha
  var email_address = "user@email.com.br";
  var nome = e.values[2];
  var carro = e.values[3];
  var data = e.values[4];
  var hora = e.values[6];
  var destino = e.values[7];
  var motivo = e.values[5];
  var partida = e.values[8];

// Pela o modelo do documento e faz uma cópia temporária
  var copyId = DriveApp.getFileById(docTemplate)
                .makeCopy(docName+' para '+nome)
                .getId();
// Inicializa o documento temporário
  var copyDoc = DocumentApp.openById(copyId);
// Pega o corpo do documento
  var copyBody = copyDoc.getActiveSection();

// Troca pelas palavras chaves do documento cada variável
   copyBody.replaceText('keyNome', nome);
   copyBody.replaceText('keyCarro', carro);
   copyBody.replaceText('keyData', data);
   copyBody.replaceText('keyHora', hora);
   copyBody.replaceText('keyDestino', destino);
   copyBody.replaceText('keyMotivo',motivo);

// Obtem a localização e calcula a distancia em Km por carro entre o ponto de partida e destino
  function getDirections_(partida, destino) {
  var directionFinder = Maps.newDirectionFinder();
  directionFinder.setOrigin(partida);
  directionFinder.setDestination(destino);
  var directions = directionFinder.getDirections();
  if (directions.routes.length == 0) {
    throw 'Não foi possível calcular a distancia entre esses endereços.';
  }
  return directions;
  }
  function drivingDistance(partida, destino) {
  var directions = getDirections_(partida, destino);
  return directions.routes[0].legs[0].distance.value;
  }

  var distancia = drivingDistance(partida, destino) / 1000;
// Salva e fecha o documento temporário
   copyDoc.saveAndClose();

// Converte o documento temporário em arquivo PDF
   var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");

// Anexa o PDF e envia por email
   var subject = "AUTORIZAÇÃO DE VEÍCULO";
  var body    = "Esta é a autorização do(a) " + nome + ". O total de kilometros é: " + distancia;
   MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});

// Deleta o documento temporário
   DriveApp.getFileById(copyId).setTrashed(true);
}


text:
Q: Differential equations - show solution given by expression Show that the solution of the problem of Cauchy
$\ddot{x}(t)=-a^2x(t)+ b(t)$ with $ x(0)=x_0$ and $\dot{x}(0)=v_0$
Is given by
$\displaystyle x(t)=x_0 \cos(at)+\frac{v_0}{a} \sin(at)+\frac{1}{a}\int_{0}^{t}b(s) \sin(a(t-s))ds$
Well, already tried to solve the problem using the methods of differential equations, in which calculated values and eigenvectors. But do not get to anything feasible, and fatigue is already one, which does not help.
Thanks for all help

A: As suggested in the comments, we can use the Laplace Transform.
$$\tag 1 x''(t)=-a^2x(t)+ b(t)$$
with $ x(0)=x_0$ and $x'(0)=v_0.$
So, we have:
$$\mathcal{L}(1) \rightarrow s^2 x(s) - sx(0) -x'(0) = -a^2 x(s) + b(s)$$
Substituting IC's, grouping  like terms and solving for $x(s)$, yields:
$$\displaystyle x(s) = \frac{s x_0}{s^2 + a^2} + \frac{v_0}{s^2 + a^2} + \frac{b(s)}{s^2 + a^2}$$
Now, using the inverse Laplace Transform, we have:
$$\displaystyle \mathcal{L}^{-1} x(s) = x(t) = x_0 \cos at + \frac{v_0}{a} \sin at + \frac{1}{a} \int_0^t b(s) \sin(a (t-s))~~ds$$
You can actually verify that this solves the DEQ.
As an alternate approach (it is not too bad for this example), you could have solved for the homogenous equation (convert second order system to two first-order systems) and found eigenvalues/eigenvectors and then solved for the particular solution. I recommend doing this approach too, just to get your hands around it!
So, we can write $x'(t) = Ax(t) + B(t)$, as:
$$x'(t) = \begin{bmatrix}0 & 1\\-a^2 & 0\end{bmatrix}x(t) + \begin{bmatrix}0 \\b(t) \end{bmatrix}$$
Find the eigenvalues/eigenvectors, solve for the IC's and then find $x(t)$.
This yields:

*

*$\displaystyle \lambda_1 = -i a, v_1 = \left(\frac{i}{a}, 1 \right)$

*$\displaystyle \lambda_2 = i a, v_2 = \left(-\frac{i}{a}, 1 \right)$

From these, you can already see the $\sin at$ and $\cos at$ terms from the homogeneous solution.
Next, you would find the particular solution for the time-varying forcing function.


text:
Q: Converting light-year to $m\cdot y/s$ For the solution to question $a$ of this problem, I'm confused with what that $3.0\times 10^8 m/s$ conversion factor is. I thought that light year is a measurement of distance, so why are we multiplying it by m/s where $s$ is a unit of time?

A: There is a subtle unit conversion going on.
Recall that $(1 {\rm\ ly})=(3\times 10^8 {\rm\ m/s})(1 {\rm\ y})$, the distance traveled by light in one year.
By substitution, which may be what they meant but didn't do correctly
[so your complaint and confusion is warranted]
\begin{eqnarray*}
(2.3 \times 10^4 {\rm\ ly})
&=& 2.3 \times 10^4\  (1 {\rm\ ly}) \\
&=& 2.3 \times 10^4\ (3\times 10^8 {\rm\ m/s})(1 {\rm\ y})\\
&=& 6.9 \times 10^{12} {\rm\ (m/s)y} \\
&=& 6.9 \times 10^{12} {\rm\ m\  (y/s)}
\end{eqnarray*}
Note that this is a distance [in some number of meters] because $(y/s)$ is a dimensionless number.
Essentially, you are trading

the "l" for "light-" (in light-year)
for "$(3\times 10^8{\rm\ m/s})$"  in "$(3\times 10^8{\rm\ m/s})\cdot y$".

Another way to do this is by "fancy-multiplication by 1".
Since $(1 {\rm\ ly})=(3\times 10^8 {\rm\ m/s})(1 {\rm\ y})$,
then
$$1 = \frac{ (3\times 10^8 {\rm\ m/s})(1 {\rm\ y})}{ \rm\ ly}.$$
So, by "fancy-multiplication by 1"
\begin{eqnarray*}
(2.3 \times 10^4 {\rm\ ly})
&=&
(2.3 \times 10^4 {\rm\ ly})(1) \\
&=&
(2.3 \times 10^4 {\rm\ ly}) \frac{ (3\times 10^8 {\rm\ m/s})(1 {\rm\ y})}{ \rm\ ly}
\\
&=&
(2.3 \times 10^4 )  (3\times 10^8 {\rm\ m/s})(1 {\rm\ y})
\\
\end{eqnarray*}


text:
Q: Using a local python project with Poetry within a Dockerized project I have a dockerized project that uses Poetry for dependency management. I'm developing a Python library that I'm using within that dockerized project and would like to be able to make a change to that library and then use it within the project, preferably without doing more than saving those changes.
Right now, this works:

*

*Make a change

*poetry build

*Copy the *tar.gz file into the dockerized project's root directory

*Run docker-compose up --build
I've tried changing the path field for the project to something like, since the dockerized project and the lib both live on the same level on my filesystem:
my-lib = {path="../my-lib", develop=true}
Poetry can't find it, so I added a COPY command in my dockerfile. Docker didn't like that. I started finding a workaround for that, but thought, "Maybe somebody knows a better way."
Is there something I'm missing?
Is there a better way to do what I'm trying to do?


text:
Q: How to Make a Game Like Cut the Rope using vrope class? How to Make a Game Like Cut the Rope using vrope class ???
my game is on cocos2d for iphone >> cut the rope

A: try this tutorial for this game
In this tutorial series, you'll build a cool Cut the Rope-type game from scratch using Cocos2D and Box2D.
CutThe Rope Part -1
CutThe Rope Part -2

A: Check out the tutorial over at Ray Wenderlich's site that covers this: http://www.raywenderlich.com/14793/how-to-make-a-game-like-cut-the-rope-part-1


text:
Q: Proxy does not return data I have been working with the kafka-rest for a couple of weeks, but I am running into some issues that I cannot understand.  When I write data to the topic, I would expect that I would see that data semi-real time in the proxy.  What I am seeing is that the proxy will return data at random over many requests.  I have changed the min bytes and the fetch.ms but they do not seem to change the behavior.  Is there a setting that I am missing or is this just how the proxy works?  This is the URL that I am using for the get request:
http://{settings.ZookeeperClientPortAddress}:{settings.ZookeeperClientPort}/consumers/{settings.ConsumerGroupName}/instances/{settings.Name}/topics/{settings.TopicName}

It is pretty straightforward, but I must be missing something.  Thanks in advance!


text:
Q: Dataadapter update with VB I hope some vb expert could tell me what I am doing wrong.
I am trying to open, modify and update a record in Northwind MDF.
The DA.Update(DS)   statement always generate an error.
I find several examples on the net but only in C and thatI dond't understand, only work in VB. I find myself  so stuppid not to understand the update mechanism.
My source:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Call GETNWDS()
        ContactNamebox.Text = ContactNamebox.Text + "   " + Now
        Call UpdateNWDS()
    End If
End Sub

Public Sub GETNWDS()
    '' open custumor  DataAdapter daaset DS

    Dim connectionString = ConfigurationManager.ConnectionStrings("NW testConnectionString").ConnectionString
    Dim queryString As String = "SELECT CustomerID, CompanyName, ContactName FROM Customers where CustomerID='ALFKI'"

    Dim CN As New SqlConnection(connectionString)
    Dim DA As SqlDataAdapter = New SqlDataAdapter(queryString, CN)
    Dim DS As DataSet = New DataSet
    DA.Fill(DS)
    Dim DT As DataTable = DS.Tables(0)
    Dim row As DataRow = DT(0)

    CustomerIDbox.Text = row("CustomerID").ToString
    CompanyNamebox.Text = row("CompanyName").ToString
    ContactNamebox.Text = row("ContactName").ToString

    CN.Close()
End Sub

Public Sub UpdateNWDS()

    Dim connectionString = ConfigurationManager.ConnectionStrings("NW testConnectionString").ConnectionString
    Dim queryString As String = "SELECT CustomerID, CompanyName, ContactName FROM Customers where CustomerID='ALFKI'"

    Dim CN As New SqlConnection(connectionString)
    Dim DA As SqlDataAdapter = New SqlDataAdapter(queryString, CN)
    Dim DS As DataSet = New DataSet
    DA.Fill(DS)
    Dim DT As DataTable = DS.Tables(0)
    Dim row As DataRow = DT(0)

    row("CustomerID") = CustomerIDbox.Text
    row("CompanyName") = CompanyNamebox.Text
    row("ContactName") = ContactNamebox.Text

    Textbox.Text = row("ContactName").ToString

    ' DA.Update(DS)  ' skip to avoud error
    CN.Close()

    End Sub
The webform is being filled with 3 DB items.
Then 1 box is changed and the update toutineis called but there is an error on the update statement.
Skippimg this statement shows this webform.
Note that the new row value is displalyed in a textbox.


text:
Q: Game Server Blocking Tor Somehow So, I've been connecting to one of my games through a proxy connection (tor). Recently, the connection attempt to the game servers simply times out. This was right after an "update" to the game. My guess is that because of problems that moderators have been having with trolls, they removed the ability to connect via tor. Is there any way around this?

A: The simple alternative would be to not use tor. Why is it that you need to connect through a proxy?
You can find a cheap shared hosting plan for ~$10-50 per year. Some of them have unlimited bandwidth and allow SSH tunneling, etc.
IMO it's a much better, and reliable alternative to Tor (so long as you're not doing anything illegal =P)

A: You can't "IP Ban TOR", because TOR comes out of a very large number of possible IPs. However, there are other possible issues. TOR can cause very high ping, so if the maximum ping was lowered that could cause the problem. Additionally, your account may have been blocked from the server, or the TOR users don't have particular ports open. If you want a good answer, try explaining why you need TOR for gaming so we can suggest an alternative.

A: The detection of Tor on the server side usually works by comparing the source IP address to the list of IP addresses of the Tor exit relays which is freely available. See for example http://torstatus.blutmagie.de/
If you really need to use Tor the solution could be to change the source IP address once more after exiting the Tor network. There are two basic means:

*

*Proxy over Tor

*

*Through the Tor network connect to a proxy server. The proxy server must handle the protocols used by the application/game.

*VPN over Tor

*

*Connect the VPN client to the VPN gateway through the Tor network. The VPN must run over TCP (for example SSL VPN) because Tor transports only TCP.

For both solutions:

*

*The exit IP addresses of the VPN gateway or proxy must not be blocked by the application/game.

*You must be able to route the traffic to the proxy or the VPN gateway through the Tor network. For example Tails could take care of it.

*To keep your anonymity any identification you use with the proxy or VPN services must not be re-used or connected to activities without being protected by Tor. Not adhering to this principle could make the anonymization by Tor relaying pointless.


text:
Q: Какие значения фиксированы для объекта RecyclerView? У меня есть двухуровневый RecyclerView, обозначающий конкретную папку и файл. У этих объектов на gui есть галочка(checkbox) и мне нужно сохранять состояние этой галочки. Через что можно реализовать? (костыли приветствуются)

A: Я смог это реализовать! Создал массив объектов, в который добавлял/убирал выбранные элементы. Для синхронизации с родителем я каждому объекту присваивал ViewHolder каждый раз, когда он появляется на экране(onBindViewHolder). Так же, в RecyclerViewAdapter есть свойство hasStableIds, которое позволяет закрепить цифровые id за каждым элементом(как я понял). Но у меня были папки с файлами, поэтому я использовал первый вариант(List).
В модель родителя и ребенка я добавил св-ва curholder и path.


text:
Q: ComboBoxes won't show up Why won't the comboboxes show up on the form? (They are invisible)
private ComboBox[] statsValues;

public frmMain()
{
    InitializeComponent();
    statsValues = new ComboBox[5];
    for (byte b = 0; b < statsValues.Length; b++)
    {
        statsValues[b] = new ComboBox();
        statsValues[b].Location = new System.Drawing.Point(300, 300);
        statsValues[b].DropDownStyle = ComboBoxStyle.DropDownList;
        statsValues[b].Visible = true;
        statsValues[b].Enabled = true;
    }
}

A: The controls created dinamically in this way need to be added to the Form controls' collection
this.Controls.AddRange(statsValues);

As a side note, you are creating 5 combox all at the same position. When you show them on your form you won't be able to see all of them, only the last one on the top of the other fours


text:
Q: Tables Stretching divs I'm using a div based layout and GWT which LOVES to use tables everywhere. The problem I'm encountering is that the tables can stretch beyond the height of the div they are contained in.  Is there anyway to expand the div vertically if needed?
BTW content is being added to the table using javascript if that matters.
If you want to check out what I'm playing with go here.  Just add a whold bunch of text to the input box and you will see.

A: Get rid of height:100%; in .main-area. If you have to, use min-height.

A: To get rid of tables, build layout with HTMLPanel widget and fill it with interactive elements (other widgets).


text:
Q: Pauli Matrix's eigenvector formalism In the Wikipedia page for the Pauli matrices, there is a list of the eigenvectors of the Pauli matrices.
Notice at $\sigma_y$, it's eigenvectors are $\begin{pmatrix} 1 \\ \pm i \end{pmatrix}$ but not  $\begin{pmatrix} \pm i\\ 1 \end{pmatrix}$, same for $\sigma_x$ and $\sigma_y$.
By which formalism or customs stated that Pauli matrices' eigenvectors are $\begin{pmatrix} 1 \\ \pm i \end{pmatrix}$ but not  $\begin{pmatrix} \pm i\\ 1 \end{pmatrix}$?

A: The standard way to encode vectors on the Bloch sphere sets the first component as a positive real number, and this convention is influenced by that.
But that's about it: it is a convention, and you're welcome to change it if there's a specific reason why that would suit your purposes better.
However, if there isn't a well-defined reason why it's better for you in some measure, then I would advice against trying to buck this convention: the only thing that it's going to achieve is that a good fraction of your readers is going to waste time wondering why the phase convention on your eigenbases has been chosen in a non-standard way, and you want your readers' attention to be focused on what you want to say instead of on your notation. The positive-first-component is just a part of the shared language that makes it easier to communicate clearly about the content; there's no good reason to make one choice over others (unlike in other domains) but having a common choice that breaks that degeneracy takes that uncertainty out and leaves more room for the physics.


text:
Q: migrating to d3 v4 cause duplicates on drag I am migrating this project https://bl.ocks.org/cjrd/6863459 to d3 v4  https://github.com/d3/d3/blob/master/CHANGES.md#dragging-d3-drag
JSFIDDLE https://jsfiddle.net/9wwqgwhh/1/
Canvas is rendering, but there is some kind of problem with dragging.
I have to change this code.
  GraphCreator.prototype.dragmove = function(d) {
    var thisGraph = this;
    if (thisGraph.state.shiftNodeDrag){
      thisGraph.dragLine.attr('d', 'M' + d.x + ',' + d.y + 'L' + d3.mouse(thisGraph.svgG.node())[0] + ',' + d3.mouse(this.svgG.node())[1]);
    } else{
      d.x += d3.event.dx;
      d.y +=  d3.event.dy;
      thisGraph.updateGraph();
    }

};
Somehow thisGraph.updateGraph(); causing infinite node ceation on dragging, but it's all that I could find out.
This is a updateGraph function

// call to propagate changes to graph
  GraphCreator.prototype.updateGraph = function(){
var thisGraph = this,
    consts = thisGraph.consts,
    state = thisGraph.state;

thisGraph.paths = thisGraph.paths.data(thisGraph.edges, function(d){
  return String(d.source.id) + "+" + String(d.target.id);
});
var paths = thisGraph.paths;
// update existing paths
paths.style('marker-end', 'url(#end-arrow)')
  .classed(consts.selectedClass, function(d){
    return d === state.selectedEdge;
  })
  .attr("d", function(d){
    return "M" + d.source.x + "," + d.source.y + "L" + d.target.x + "," + d.target.y;
  });

// add new paths
paths.enter()
  .append("path")
  .style('marker-end','url(#end-arrow)')
  .classed("link", true)
  .attr("d", function(d){
    return "M" + d.source.x + "," + d.source.y + "L" + d.target.x + "," + d.target.y;
  })
  .on("mousedown", function(d){
    thisGraph.pathMouseDown.call(thisGraph, d3.select(this), d);
    }
  )
  .on("mouseup", function(d){
    state.mouseDownLink = null;
  });

A: In updateGraph() replace the lines
newGs.append("circle")
  .attr("r", String(consts.nodeRadius));

newGs.each(function(d){
  thisGraph.insertTitleLinebreaks(d3.select(this), d.title);
});

with these
newGs.each(function(d) {
  if (this.childNodes.length === 0) {
    d3.select(this)
      .append("circle")
      .attr("r", String(consts.nodeRadius));
    thisGraph.insertTitleLinebreaks(d3.select(this), d.title);
  }
});

Tested with d3 up to version 5.7


text:
Q: Best practices / tools for high performance IIS? Recently I come across high performance web server nginx.
I would wonder, where does IIS stands as far as performance matters?
What are the tools/best practices to increase IIS 7 / 7.5 performance for a web application hosted on IIS.
Web Servers like Apache, nginx, or IIS plays an important role in performance and this would definitely help developers to understand how does it matters to choose correct web server for scalable web application.

A: It's very hard to do a meaningful benchmarks/comparison between Apache/Nginx and IIS, but if you're really concerned about ASP.NET/IIS performance, this is a good start: Chapter 6 — Improving ASP.NET Performance.
In practice, profiling your application/addressing the performance issues within application and properly using caching would likely result in much bigger performance gain as compared to simply tuning IIS.


text:
Q: Sending a file from a java client to a server using wcf method? I want to build a wcf web service so that the client and the server would be able to transfer files between each other. Do you know how I can achieve this? I think I should turn it into a byte array but I have no idea how to do that. The file is also quite big so I must turn on streamed response.

A: It sounds like you're on the right track.  A quick search of the interwebz yielded this link: http://www.codeproject.com/Articles/166763/WCF-Streaming-Upload-Download-Files-Over-HTTP
Your question indicates that you want to send a file from a java client to a WCFd endpoint, but the contents of your question indicate that this should be a bidirectional capability.  If this is the case, then you'll need to implement a service endpoint on your client as well.  As far as that is concerned, I cannot be of much help, but there are resources out there like this SO question: In-process SOAP service server for Java
As far as practical implementation, I would think that using these two links you should be able to produce some code for your server and client.
As far as reading all bytes of a file, in C# you can use: File.ReadAllBytes  It should work as in the following code:
//Read The contents of the file indicated
string fileName = "/path/to/some/file";
//store the binary in a byte array
byte[] buffer = File.ReadAllBytes(fileName);
//do something with those bytes!

Be sure to use the search function in the future:


text:
Q: Detect URL redirect path php I want to get full redirect path of the url.
Let's say if source.com redirects to destination.com after multiple redirects like this:
http://www.source.com/ -> http://www.b.com/ -> http://www.c.com/ -> http://www.destination.com/
how do I get all redirected URL's?
using this below code I am getting only http://www.destination.com/ how do I detect full url redirect chain?
<?php
$url='windows.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow the redirects
curl_setopt($ch, CURLOPT_HEADER, false); // no needs to pass the headers to the data stream
curl_setopt($ch, CURLOPT_NOBODY, true); // get the resource without a body
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // accept any server certificate
curl_exec($ch);

// get the last used URL
$lastUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

      curl_close($ch);

   echo $lastUrl;
?>

This code has another problem it can't detect redirected url of youtube redirects.
Tested URL : https://www.youtube.com/redirect?redir_token=QUFFLUhqbkVxUFZUME9NbWF4RThxdFpGV3pmTTJEdFVWQXxBQ3Jtc0tubGJqU016TzJ6WnlfeUItX0ZmOUItUE1jRlZoZXhxMzNpQllpM0NLSk4ycnBLMGNidTFsX3N6WkU2X3RsUTRZb1lXQVp5SEZjbnU3eDFuZS1VU3dhdzg2QW9ZMTl1azFCZFZHcHRLdFF3dTM1MlRWdw%3D%3D&event=video_description&v=KEa2XWRGf_4&q=https%3A%2F%2Fwww.facebook.com%2Fabhiandniyu
My question is how do I detect full url redirect chain for all types of redirect requests.

A: You're probably missing:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);

add it to your CURL config and it should work then.

A: Don't follow HTTP redirects: curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
And output HTTP headers, while testing: curl_setopt($ch, CURLOPT_HEADER, true);
Then you can obtain the Location header from the received HTTP 302 response.
When it's more than one redirect, this would have to run in a loop, until HTTP 200 has been received. In this context HTTP 200 means, that the final destination has been reached.


text:
Q: I cannot connect to the websocket using Postman I am trying to create a simple chat application using websockets. I followed this tutorial: https://www.baeldung.com/websockets-spring.
This is my config:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
         registry.addEndpoint("/chat");
         registry.addEndpoint("/chat").withSockJS();
    }
}

@Controller
public class WebSocketController {
    @MessageMapping("/chat")
    @SendTo("/topic/messages")
    public OutputMessage send(Message message) throws Exception {
        return new OutputMessage(message.getFrom(), message.getText(), Instant.now());
    }
}

@Builder
@Getter
public class Message {
    private final String from;
    private final String text;
}

@Builder
@Getter
public class OutputMessage {
    private final String from;
    private final String text;
    private final Instant date;
}

At the start of the application I got:
2021-12-31 14:22:39.442  INFO 1952 --- [MessageBroker-1] o.s.w.s.c.WebSocketMessageBrokerStats    : WebSocketSession[0 current WS(0)-HttpStream(0)-HttpPoll(0), 0 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(0)-CONNECTED(0)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], outboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], sockJsScheduler[pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]

I thought I had everything configured so I decided to try to connect using postman, but without success :/
I executed the following endpoints:
ws://localhost/app/chat
ws://localhost:8080/app/chat
ws://localhost/chat
ws://localhost:8080/chat

none of them work :/
I am using Postman Websockets beta to perform requests.
Did I miss something in the configuration or am I using postaman wrong?

A: According to the reply from Postman Team in their blog: https://blog.postman.com/postman-supports-websocket-apis/ .
Postman does not support subscribe to a topic at present. So in this case, you can only connect to server with 'ws://localhost:8080/chat', but you can not send messages between web client and server. What a pity!

A: ws://localhost:8080/chat - this endpoint seems to work.


text:
Q: How to run map function in Reactjs? How to run map function I am trying to map function but it throws error cannot read the property of map undefined in Reactjs
I'm trying to do something like the following in React JSX component
const data = {
    Details: [
{
        "id": "6f12",
        "nextPart": {
          "id": "1ae2",
          "text": "Details",
          "heading": "twice data and staff memeber",
          "checks": [
            {
              "value": "A"
            },
            {
              "value": "B"
            }
          ],
          "Types": "Error"
        },
        "conclusion": "final"
    }
    ]
  }

A: The nextPart property is an object, not an array. Map works on arrays.
If your Details is intended to be an array of objects (which looks like it does), you can do it like this
{data.Details.map((item) => {
    const { text, heading, checks } = item.nextPart;
    return (

{text}

{heading}

          {checks.map(({ value }) => (

{value}

          ))}

    );
  })}


text:
Q: NullPointerException with OnTouchListener on appcompat v21 I am trying to port my app to appcompat v21.
I have fixed my gradle file, and my themes are inherited from the appcompat themes.
public boolean onCreateOptionsMenu(Menu menu) {
        final SharedPreferences touch_prefs = PreferenceManager.getDefaultSharedPreferences(this); //allows preferences to be accessed in the fucntion
       setPassword();

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.multiscreen, menu);

    final Button decodeButton = (Button) findViewById(R.id.decodeButton); //getting the decode button
    decodeButton.setOnTouchListener(new OnTouchListener() { //setting the touchlistener for the button
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) { //ontouch listener so we can perform actions while the button is held down
            TextView text = (TextView) findViewById(R.id.messageOutput); //so we can set the text of message output
            EditText message_input = (EditText) findViewById(R.id.messageEdit); //gets the message thing
            EditText pass_input = (EditText) findViewById(R.id.passEdit); //gets the password thing
            TextView decode_hint = (TextView) findViewById(R.id.textHint);
            decoder decode = new decoder(); //new instance of classes
            ran verify = new ran(); //new instance of ran class
            boolean legal; //boolean variable that will indicate whether the function should proceed or not

            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    legal = verify.verifyString(message_input); //checks to see if message is aight
                    if (!legal) { //stops function if message contains unsupported characters
                        illegalCharacter(verify.illegal_character);
                    }
                    else if (legal) { //allows functions to proceed if the message is ok
                        s_output = decode.decode_message(message_input, pass_input);
                        decode_hint.setText(R.string.decode_hint_prompt);

                        if (touch_prefs.getBoolean("instaclear_checkbox", true)) { //checking prefs
                            pass_input.setText("");
                        }
                        if (touch_prefs.getBoolean("clear_message_checkbox", true)) { //checking prefs
                            message_input.setText("");
                        }
                        text.setText(s_output); //displays the decoded string
                    }
                    break;
                case MotionEvent.ACTION_UP:

                        if (touch_prefs.getBoolean("passpeek_checkbox", true)) { //checking preferences
                            text.setText("");
                            decode_hint.setText("");
                        }
                    break;
            }
            return true;
        }
    });
    return true;
}

This is the part that is returning an error. The error shows a NullPointerException on this line:
decodeButton.setOnTouchListener(new OnTouchListener() {

my xml for the layout/fragment is as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rel_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".multiscreen">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/passEdit"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:hint="@string/password_text"
        android:maxLength="500"
        android:layout_toLeftOf="@+id/clearMessage" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/messageEdit"
        android:hint="@string/message_hint"
        android:layout_below="@+id/passEdit"
        android:layout_marginTop="45dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:maxLength="8000"
        android:layout_toLeftOf="@+id/clearMessage" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/decode_text"
        android:id="@+id/decodeButton"
        android:layout_below="@+id/messageEdit"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:clickable="true"
        android:enabled="true"
        android:focusable="false"
        android:longClickable="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textHint"
        android:textIsSelectable="false"
        android:layout_below="@+id/encodeButton"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/messageOutput"
        android:enabled="true"
        android:textIsSelectable="true"
        android:selectAllOnFocus="true"
        android:layout_below="@+id/textHint"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/clear_text"
        android:id="@+id/clearMessage"
        android:singleLine="true"
        android:layout_alignTop="@+id/messageEdit"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignBottom="@+id/messageEdit"
        android:onClick="clearMessage"
        android:enabled="true"
        android:clickable="true" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/passEdit"
        android:text="@string/clear_text"
        android:id="@+id/clearPassword"
        android:layout_alignRight="@+id/clearMessage"
        android:layout_alignEnd="@+id/clearMessage"
        android:singleLine="true"
        android:layout_above="@+id/messageEdit"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/passEdit"
        android:onClick="clearPassword"
        android:enabled="true"
        android:clickable="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/encode_text"
        android:id="@+id/encodeButton"
        android:layout_below="@+id/messageEdit"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:enabled="true"
        android:clickable="true"
        android:onClick="message_encode" />
</RelativeLayout>

here is the setcontent portion:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_multiscreen);
}

A: decodeButton is null because it's not found in whatever class you're working with. Get your layout (rel_layout), and then do layout.findViewById since decodeButton is a child of rel_layout.
I probably wouldn't do this in onCreateOptionsMenu, but instead wherever you are inflating your layout.
View layout = getLayoutInflater().inflate(R.layout.rel_layout, null);
Button decodeButton = (Button) layout.findViewById(R.id.decodeButton);
decodeButton.setOnTouchListener(this);


text:
Q: HTML Imagemap - Border Is it possible to add a css border to a HTML Imagemap?

A: I doubt there's a cross browser CSS solution, but this jQuery plugin can do what you're after:
jQuery MapHilight
It can show the border without hover if you specify alwaysOn:true, as seen on the first example there (the black part is done using the plugin).

A: 2 option :
1 - wrap your image with div and give him border .
2 - build your image map with divs + css background images
like in this example :
http://www.noobcube.com/tutorials/html-css/css-image-maps-a-beginners-guide-/


text:
Q: What do Java developers think of Scala? I've noted that IDE support is nowhere near as good, but the language itself supports functional programming idioms much more cleanly.

A: When I initially dabbled with Scala 2 years ago, it looked alien and intimidating to me. At some point I discovered that the core language is actually much simpler than Java, but its syntax and semantics are so flexible that you can create new language constructs like it, even without a macro feature. I have since completely switched to Scala for all my Java projects, because it lets me write without too much boilerplate code.
I like Clojure, but there are situations, where the platform needs you to compile to static bytecode (Android, applets, ...) and while you can do that, in Scala, it's just there.
While Scala lets you solve many problems in a functional way, I often find problems where using classes feels more natural. That makes things a bit more complex, but nowhere near the complexities and pains of C++.
The biggest takeaway for me when I really started learning the language was that I could program just I did in Java, just without the noise (a little bit like when you start Groovy), but eventually you want to try to dive deeper into the power of the language - it grows with you.
About the IDE question: After using Emacs for everything, all my IDE issues went away :-)

A: I like Scala for many reasons, but there is one that is often overlooked: its simplicity.
Scala might not be as simple as, say, Oberon, but it is quite a lot simpler than some other languages. The Scala Language Specification is ~160 pages, the Java Language Specification is ~600 (just the language, not the JVM or the libraries!), the ECMA-334 C# Language Specification (which AFAIK corresponds to a subset of Visual C# 2.0) is ~440 pages (this is without stuff like LINQ query comprehensions, lambda expressions, extension methods, generic co- and contravariance, dynamic, optional arguments with default values, keyword arguments, var). Even the current draft for ECMAScript 5.1 is bigger at ~210 pages. And of course my own "default" language, Ruby, whose current ISO Draft weighs in at ~310 pages, which only specify an almost unusably tiny subset of the intersection of Ruby 1.8.6, 1.9.1 and 1.9.2.

A: Here is what sucks about Scala:

*

*The null pointer was a pretty bad idea to begin with. Hoare called it his "billion dollar mistake", but Scala is even worse. It has objects named null, Null, None, and Nil. null is for interoperability with Java. Null is the null pointer form W3C DOM specification, None is what null should have been replaced with, and Nil is an empty something.

*When language constructs turn out to be hacky it is usually the programmer who is to blame and not the language. In Scala, however, the core language already contains library classes whose only documented behavior is "This is a hack". Don't believe it? Search the scaladoc for scala.xml.Group.

*Last not least, Scala is badly documented. Hardly any of the scala classes in the official documentation comes with example code. Scala is significantly harder to learn than Java and requires profound knowledge in computer science.
To avoid being mistaken for a Scala-hater, here is what I love about it:

*

*I have fewer exceptions. I never had a ClassCastException and very few NullPointerExceptions when interacting with Java.

*Code is much shorter and more concise than Java

*It is intellectually challenging. Java feels like baby language when compared.

A: It's an excellent language that is simpler than Java in many ways.
Most people won't like it, Java programmer or not, for the same reasons that most people, programmers or not, don't like learning new programming languages.  I suspect that most people who learned a programming language did not even like learning that.
If you're worried about a language being as complicated as C++, I would avoid Clojure like the plague.  Whining that Scala is more complicated than Clojure has become the fallback argument for people who are completely ignorant regarding one or both languages.
Clojure has macros, which means you can alter the language's syntax as much as you want, giving you not just "a myriad of different ways of doing things" but an almost infinite number of ways of doing things.  And none of this new syntax the programmers are creating with the macros will be documented anywhere in the language specification.
"But we can avoid using macros or regulate which ones are allowed in our code", you say.  Congratulations, you're now having "to artificially limit what language features you're going to use and what not", which is exactly what the babbling idiots who are using Clojure of Scala used as their reason for avoiding Scala to begin with.

A: I really like the Scala library's more granular types.  It seems like the new collections library was well thought-out.  I also like how it reduces the amount of code required for simple classes, and the functional concepts it adds.  Its type inference is also very helpful.  It feels like Java without the training wheels.  After using C# for a while, Scala actually feels like a competitor, with Java still useful but being left behind.

A: Well, I think Scala is too complex. It feels like C++ in that it has a myriad of different ways of doing things. Some would call this "richness", "expressiveness" or "power", but your mileage may vary. In many real world projects you would have to artificially limit what language features you're going to use and what not, so that all developers involved could speak the same subset of the language.
For functional programming I prefer Clojure, which is way simpler than Scala.
Let the holy war begin ;-)

A: As a Java programmer, I initially found Scala interesting.  However, after dabbling with it for awhile (and running into nearly all the positives/negatives already listed by others), I was left feeling very "meh" towards it.  The language improvements are offset by the lower availability of toolsets.  I just couldn't come up with any defining reason to switch over.  It's good, but it's not "better enough" to make a case for switching.  Doesn't have that subjective excitement factor either (like Clojure seems to).

A: I've been programming Scala for more than one year now, so I'll try to set myself back a year to answer this question.

*

*Scala code is more
concise than Java code (no setter or
getter, a lot of the type information
can be inferred)

*The built-in support for XML literal is very appealing.

*Java library compatibility and interoperability is great

*The support for certain functional idioms is refreshing (for comprehension, closure, lambda functions, map, fold, reduce)

*There does not seem to be a cool feature that the language creator did not want to include

The points above were more or less what I thought of Scala before I started to learn it.
In the course of a year, here is what I found out:

*

*Buying the staircase book was a great investment and has saved me hours of learning things on my own

*The syntax has some quirks and there was sometimes where I was really puzzled why something was not valid. The trade off is once you're familiar, the code has less clutter and is easier to read. Note that this isn't really an issue if you read rather than write code.

*The collection library in 2.8 is a pleasure to use. It's hard to come back to the Java one.

*XML literal is nice, but beyond some basic things, I had to reach out to the Java library ecosystem. It's convenient though.

*Using Java libraries from Scala is super easy and convenient. Using Scala classes from Java is a bit more tricky, but it works.

*I've switched to IntelliJ IDEA community edition and although it's not perfect it's more than good enough.

*The language creator really thought about the set of feature and all works really nicely together. The object oriented support is better than in Java (with the traits) and you can do functional programming.

*It's a language that apparently some Java developers hate with a passion. For me, it has brought back the joy of programming.

A: About one year ago, as I became more and more frustrated about the future of my startup's products if I continued to use Java, I decided to give Scala a try. I was already programming in JavaScript and Python at the time, Ruby was also a good alternative, but I was looking for a statically typed language, preferably one that could run on the JVM.
I really tried to like Scala, I really did, but I found it's code utterly ugly and hard to understand. I dramatically wondered that if Scala was our best answer to Java, then I was surely screwed and sentenced to continue working with a language I didn't liked after all...
Fortunately, not too long afterwards, I found out about Fantom. Oh man, did I loved it! To me, it was like american's splendor answer to german bureaucracy! It matched the requirements I was looking for in Scala, but much more elegantly. It had Vim, Eclipse and Netbeans integration, a nice web framework, mature products running with it, a small but incredibly helpful community... Dynamic and Static typing! I rejoiced!
(I could continue but this post is meant to be about Scala, not Fantom, so I stop here. My preference is clear, nevertheless there's this post comparing the two. I never could understand why Fantom gets so little attention when compared to Scala. But apparently I'm not the only one, if you listen to this podcast [mp3] until the end.)

A: Scala is complex. No way around it! Its syntax is extremely flexible and can be customized in numerous ways (above all operators / infix notation) - and the type system has more different features than any other language I know.
So things aren't that straight as e.g. in Haskell: Typeclasses to cover them all.
As Scala tries to put together functional programming, OO, procedural programming and java libraries as well as own ideas, we finally end up with lots of concepts that somehow seem to go "in the same direction":

*

*Implicit values

*Implicit functions

*Existentials

*Wildcards

*Traits

*Interfaces

*Abstract classes

*Case classes

*Structural types

*Generic constraints

*View bounds

*Anonymous types

Choosing among them seems difficult at first and one might easily wonder if one has found the correct solution to some problem. It's even easily possible to produce hacky stuff by abusing implicits.
But the interesting thing is: Scala works. It's sometimes hard to understand why (especially figuring out through what implicit conversions + inheritance + ... some object has got functionality X), but you don't have to bother about that most of the times.
Write Scala as straightforward as possible and it will work. Don't get confused by everything that is possible and just use what you need. And if you need something, you can be sure that somehow Scala has it ;)
And the better you get, the more you'll be able to customize Scala with operators, implicits, monads, funky syntax ... and finally get something close to a DSL that will perfectly address your problem.
After all, you have always the possibility to just use Scala as a much much better Java with cleaner, easier syntax, type inference and some functional features.


text:
Q: Puppeteer can't distinguish between two selectors with same ID I have a puppeteer implementation I'm working on to fill out a form on a website that (sadly) doesn't offer an API.
Everything goes great until I use this code to click the second button on a list of buttons:
await page.click('#calculateCharge'); // open the set values dialog

Reason being, the #calculateCharge id is used multiple times on the page, like this:
<button id="calculateCharge" type="button" name="amount" class="btn btn--secondary btn--full-mobile btn--full ">$ 80.00</button>
<button id="calculateCharge" type="button" name="amount" class="btn btn--secondary btn--full-mobile btn--full ">$ 35.00</button>
<button id="calculateCharge" type="button" name="amount" class="btn btn--secondary btn--full-mobile btn--full ">$ 42.00</button>

Puppeteer clicks the first button every time because whoever wrote the HTML didn't id the buttons dynamically.  The ids are all the same, so I don't know how to access the 2nd or third buttons.  I also don't have access to the HTML source (not my page), so I can't fix it from the other side.
Any ideas?

A: I solved my issue by using xPaths instead of ids.
First, right click on the button in your browser and click inspect. In the inspector's HTML tree, right click on the highlighted HTML and copy the full xPath.
Second, set the element as a variable using the copied xPath.  Note the x after the $.
let butt = await page.$x('xPath')
Last, click the button by referencing the first position of the variable's array.
await butt[0].click()
Copy/paste from my production file:
    let butt = await page.$x('/html/body/div[1]/div/main/div[1]/div[2]/div[2]/div/div/div/form/div[1]/div[2]/table/tbody/tr[5]/td[2]/div/div/button');
    await butt[0].click();


text:
Q: How to process a column's multiple strings I have a comma separated file that looks similar to his format:
aa.com,1.21.3.4,string1 string2 K=12     K2=23  K3=45 K4=56
bb.com,5.6.7.8,string1 string2 K=66     K2=77  K3=88 K4=99

I want to take the third column which contains strings separated by spaces. I want to process the file to separate the third columns first two strings by a comma and ignore the rest of the strings in column 3. The first two fields do not contain spaces. Please note the number of strings in the 3rd column is not fixed to all records. In this example, it is 6 strings separated by 5 spaces. But it can be more or less.
All that I need is to take the 3rd columns first two strings, separate them by a comma, and ignore the rest of column 3 strings.
aa.com,1.21.3.4,string1,string2
bb.com,5.6.7.8,string1,string2

A: try:
awk '{print $1, $2}' OFS=, infile
aa.com,1.21.3.4,string1,string2
bb.com,5.6.7.8,string1,string2

If in such a case you had white-spaces in first or second fields, you would do:
awk -F, '{ match($3, /[^ ]* +[^ ]*/);
           bkup=substr($3, RSTART, RLENGTH);
           gsub(/ +/, ",", bkup); # replace spaces with comma
           print $1, $2, bkup
}' OFS=, infile

Explanation: read in man awk:
match(s, r [, a])
          Return the position in s where the regular expression r occurs,
          or 0 if r is not present, and set the values of RSTART and RLENGTH. (...)

substr(s, i [, n])
          Return the at most n-character substring of s starting at I.
          If n is omitted, use the rest of s.

RSTART
          The index of the first character matched by match(); 0 if no
          match.  (This implies that character indices start at one.)

RLENGTH
          The length of the string matched by match(); -1 if no match.

A: Try this:
awk -F '[, ]' '{print $1","$2","$3","$4}' file
aa.com,1.21.3.4,string1,string2
bb.com,5.6.7.8,string1,string2

A: You could do this as follows :
sed -ne 's/[[:blank:]]\{1,\}/,/;s//\n/;P' input-file.txt

A: awk -F "[, ]" '{print $1,$2,$3,$4;OFS=","}' file

F "[, ]" Will take both space and comma as field separator and ;OFS="," will set Output field separator as comma.


text:
Q: Is there any efficient way to assign an id to cells while comparing two dataframes? I want to assign a specific ID serially to the data in df2 and based on that, ID I want to convert all its occurrences in df1. The code I have written takes a lot of time to execute. Is there any other way?
for i in range (0,35261):
    for j in range (0,54793):
        if (df2.V_ID[i] == df.V_ID[j]):
            df.V_ID[j] = i

sample data for df:
        time               IP1           IP2        GETVIDEO    V_ID                       IP3
0   2008-03-11 17:28:17 63.22.65.77 205.181.173.92  GETVIDEO    ORDhCi6JQaY&signature   254.212.25.169
1   2008-03-11 17:28:20 63.22.65.94 35.139.184.95   GETVIDEO    xEcFchOvj4Y&signature   254.212.19.255
2   2008-03-11 17:28:22 63.22.65.73 35.139.176.183  GETVIDEO    z-oBoCMSfbw&signature   254.212.19.196
3   2008-03-11 17:28:23 63.22.65.73 102.15.230.123  GETVIDEO    pSo-_TavE1U&signature   254.212.25.206
4   2008-03-11 17:28:23 63.22.65.77 102.15.134.225  GETVIDEO    kHtaORb0LUk&signature   254.212.22.122
5   2008-03-11 17:28:23 63.22.65.77 102.15.111.222  GETVIDEO    t7qjlPPmeJE&origin  105.136.78.115
6   2008-03-11 17:28:27 63.22.65.73 35.139.31.8     GETVIDEO    2UPaRi0WY7c&origin  105.136.78.115
7   2008-03-11 17:28:28 63.22.65.73 102.15.143.68   GETVIDEO    lAzrUxpybs0&signature   254.212.21.130
8   2008-03-11 17:28:30 63.22.65.73 205.181.139.118 GETVIDEO    J_KKyw8V-l0&origin  105.136.78.115
9   2008-03-11 17:28:31 63.22.65.73 102.15.143.20   GETVIDEO    xnsPfRdSU0Q&origin  105.136.78.115
10  2008-03-11 17:28:34 63.22.65.94 102.15.141.151  GETVIDEO    qDKx6CkQM04&origin  105.136.78.115

sample data for df2 :
        V_ID            count
0   2UPaRi0WY7c&origin  768
1   t7qjlPPmeJE&origin  142
2   CKrTlXN9-iE&origin  107
3   IZtPejST9IQ&origin  103
4   FKb3qRljGBc&origin  93
5   LcM0OT6mnqA&origin  67
6   7sei-eEjy4g&origin  62
7   qDKx6CkQM04&origin  53
8   4rb8aOzy9t4&origin  46
9   wjv4Fp7GiGk&origin  46
10  SKDXBvPIepI&sign    44

Expected output:
time               IP1           IP2                    GETVIDEO    V_ID                       IP3
    0   2008-03-11 17:28:17 63.22.65.77 205.181.173.92  GETVIDEO    42  254.212.25.169
    1   2008-03-11 17:28:20 63.22.65.94 35.139.184.95   GETVIDEO    13  254.212.19.255
    2   2008-03-11 17:28:22 63.22.65.73 35.139.176.183  GETVIDEO    21  254.212.19.196
    3   2008-03-11 17:28:23 63.22.65.73 102.15.230.123  GETVIDEO    14  254.212.25.206
    4   2008-03-11 17:28:23 63.22.65.77 102.15.134.225  GETVIDEO    23  254.212.22.122
    5   2008-03-11 17:28:23 63.22.65.77 102.15.111.222  GETVIDEO    1   105.136.78.115
    6   2008-03-11 17:28:27 63.22.65.73 35.139.31.8     GETVIDEO    0   105.136.78.115
    7   2008-03-11 17:28:28 63.22.65.73 102.15.143.68   GETVIDEO    33  254.212.21.130
    8   2008-03-11 17:28:30 63.22.65.73 205.181.139.118 GETVIDEO    42  105.136.78.115
    9   2008-03-11 17:28:31 63.22.65.73 102.15.143.20   GETVIDEO    19  105.136.78.115
    10  2008-03-11 17:28:34 63.22.65.94 102.15.141.151  GETVIDEO    7   105.136.78.115

A: import pandas as pd

df2 = pd.DataFrame({'V_ID': ['a','b','c','d'], 'count':[12,5,7,9]})
df = pd.DataFrame({'time':['2008-03-11', '2008-03-11', '2008-03-11','2008-03-11', '2008-03-11', '2008-03-11', '2008-03-11'],
                   'V_ID': ['a', 'sdf', 'c','rge', 'gfg', 'a', 'a']})

# Create an index column for df2
df2 = df2.reset_index()

# Key-value pairs of index and V_ID
mapping = df2['V_ID'].to_dict()

# Invert key-value pairs
mapping = {v: k for k, v in mapping.items()}

# Replace values in df['V_ID'] that matches with keys in mapping with values
df['V_ID'] = df['V_ID'].replace(mapping)

print(df)

         time V_ID
0  2008-03-11    0
1  2008-03-11  sdf
2  2008-03-11    2
3  2008-03-11  rge
4  2008-03-11  gfg
5  2008-03-11    0
6  2008-03-11    0


text:
Q: Matrix transformation into block off-diagonal form Consider the 4-by-4 matrix $\boldsymbol M = \boldsymbol M_0 + \boldsymbol M_1$, where
$\boldsymbol M_0 = \alpha \left( \begin{matrix}
  1 & 0 & 0 & 0 \\
  0 & 1 & 0 & 0 \\
  0 & 0 & -1 & 0 \\
  0 & 0 & 0 & -1 \\
 \end{matrix} \right)$ and  $\boldsymbol M_1 = \beta \left( \begin{matrix}
  0 & \gamma & 0 & -\gamma^{*} \\
  \gamma^{*} & 0 & -\gamma^{*} & 0 \\
  0 & \gamma & 0 & -\gamma^{*} \\
  \gamma & 0 & -\gamma & 0 \\
 \end{matrix} \right)$
where $\alpha$ and $\beta$ are constants and $\gamma = \gamma_x + i \gamma_y$ is complex.
Is it possible to unitary transform $\boldsymbol M$ into block off-diagonal form $\boldsymbol M_B$?
Namely, I want to find a unitary transform $\boldsymbol U$ so that I can write down $\boldsymbol M_B = \boldsymbol U \boldsymbol M \boldsymbol U^{*}$ (here $\boldsymbol U^{*}$ is the conjugate transpose).
Explicitly, the required block off-diagonal matrix is (in general form)
$\boldsymbol M_B = \left( \begin{matrix}
  0 & \boldsymbol Q \\
  \boldsymbol Q^{*} & 0
 \end{matrix} \right)$ where $\boldsymbol Q = \left( \begin{matrix}
  Q_z & Q_x - i Q_y \\
  Q_x + i Q_y & -Q_z
 \end{matrix} \right)$
Is there a general recipe to find such a unitary transformation matrix $\boldsymbol U$ which leads to the block off-diagonal form, $\boldsymbol M \to \boldsymbol M_B$?

A: I think this $4 \times 4$ matrix is the answer.
$$\frac{1}{\sqrt2}
\begin{pmatrix}
1 & 0 & 1 & 0 \\
0 & 1 & 0 & 1 \\
-I & 0 & I & 0 \\
0 & -I & 0 & I
\end{pmatrix}$$


text:
Q: Typescript no repeat value is there a way how to declare type array with uniq values,
i have aray of string literals and would by nice if i can say there can be only one of each string literal.
export type AllMapLibraries = 'drawing' | 'geometry' | 'places' | 'visualization';

export const getGoogleApiUrl = (apiKey: string, libraries: AllMapLibraries[]) => {
  const librariesString = libraries.join(',');
  const url = `https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=${librariesString}&key=${apiKey}`;
  return url;
};

const url = getGoogleApiUrl('123', ['drawing', 'geometry', 'drawing']); // here should be error that drawing was already defined;

it hasnt to be only array.
but i didnt find anything, and think that this is not possible.
heres the playground

A: If you really want to represent "array with no repeat elements" in the type system, your best bet will be as a generic type that acts as a constraint.  Here's how I'd start:
type RemoveArrayRepeats<T extends readonly any[]> = {
    [K in keyof T]: (
        T[number] extends { [P in keyof T]: P extends K ? never : T[P] }[number]
        ? never
        : T[K]
    )
}

So, the type RemoveArrayRepeats takes a tuple type and converts it to a version of itself where any repeated elements are replaced with the never type.  Like this:
type TestSame = RemoveArrayRepeats<[1, 2, 3, 4, 5]>; // [1, 2, 3, 4, 5]
type TestDiff = RemoveArrayRepeats<[1, 2, 3, 2, 5]>; // [1, never, 3, never, 5]

A sketch of how it works: given a tuple type T, it maps over each numeric-like index K, and compares the union of element types of T (i.e., T[number]) with the union of element types of T without the element at the index K (i.e., {[P in keyof T]: P extends K ? never: T[P]}[number].).  If they are different, great, leave this property alone.  If they are the same, we have a repeat... replace it with never.
As an example with [1,2,3,2,5]: If K is "0", then we compare the union of elements of [1,2,3,2,5], namely 1|2|3|5 with those of [never,2,3,2,5], namely 2|3|5.  Since those are different, then the first element of the tuple is not a repeat and it is left alone: 1.  Now we look at K being "1".  We compare 1|2|3|5 with the elements of [1,never,3,2,5], which is still 1|2|3|5.  Those are the same, meaning that the second element of the tuple will be replaced with never.  Eventually we build up the array [1,never,3,never,5].

Next we declare the getGoogleApiUrl function to be a generic function, where the libraries parameter is constrained to both AllMapLibraries[] and to RemoveArrayRepeats<T>:
declare const getGoogleApiUrl: <T extends AllMapLibraries[]>(
    apiKey: string,
    libraries: (T & RemoveArrayRepeats<T>) | []
) => string;

The details of how the constraint happens are a bit weird.  I chose to put T & RemoveArrayRepeats<T> in the parameter position so that T itself would only be constrained to AllMapLibraries[]; that keeps error messages on mistakes like 'drawink' understandable.  But you could have instead done T extends AllMapLibraries[] & RemoveArrayRepeats<T> for very similar behavior.
Oh, and that | [] in the type of libraries is a trick that gives the compiler a hint that we'd like to infer a tuple type for libraries if possible.  Without it, the compiler sees ["drawing", "drawing", "drawing"] as type Array<"drawing">, which completely loses the information we need to detect repeats.

Let's see if it works:
getGoogleApiUrl('', []); // okay
getGoogleApiUrl('', ['drawing']); // okay
getGoogleApiUrl('', ['drawing', 'geometry']); // okay
getGoogleApiUrl('', ['drawing', 'geometry', 'places', 'visualization']); // okay
getGoogleApiUrl('', ['foo']); // error!
//                   ~~~~~
// Type '"foo"' is not assignable to type 'AllMapLibraries'

getGoogleApiUrl('123', ['drawing', 'geometry', 'drawing']); // error!
//                      ~~~~~~~~~              ~~~~~~~~~
// Type 'string' is not assignable to type 'undefined'

That all behaves more or less as expected.  The error message in the last case (like "string is not undefined") is not what you might hope to see in a perfect world.  If there were a supported custom invalid type, we would use it to tailor the error message.  But there isn't.
At least the red squigglies are in meaningful locations.  Well, maybe you'd want only one of those to be an error; but that would make RemoveArrayRepeats even more complicated (e.g., only compare an element to elements at lower indices, but the compiler doesn't understand "lower indices" so we'd need some representation and it would get ugly quickly).
But this is about the closest I can get to your requirements without pages of code.  It's up to you whether even this version is worth it.  Anyway, hope that helps; good luck!
Link to code

A: You can use Set!
var uniques = new Set([0,1,1,2])

This results in:
Set(3) {0, 1, 2}

Then adding new elements like:
uniques.add(1)

Will also result in:
Set(3) {0, 1, 2}

A: You have a few options if you need compile-time checking.

*

*Use an Object which has in built duplication errors.

type AllMapLibraries = 'drawing'|'geometry';
type AllMapLibraries_Obj = {[P in AllMapLibraries]:boolean};
const getGoogleApiUrl = (apiKey:string, librariesObj:AllMapLibraries_Obj) => {
    const libraries = Object.keys(librariesObj) as AllMapLibraries[];

    // alternatively you could do
    if ('geometry' in librariesObj) {}

    // ...
};

// This will error, you can't specify the same object property twice
const url = getGoogleApiUrl('123', { drawing: true, drawing: true });

// This will work
const url = getGoogleApiUrl('123', { geometry: true });

*Use a Tuple which has index based constraints.

type AllMapLibraries = Partial<['drawing', 'geometry']>;
const getGoogleApiUrl = (apiKey:string, libraries:AllMapLibraries) => {
    // ...
};

// This will error, you can't use 'drawing' in the index that 'geometry' goes
const url = getGoogleApiUrl('123', ['drawing', 'drawing']);

// This will work
const url = getGoogleApiUrl('123', [,'geometry']);

Drawbacks:
Objects can be more annoying to work with and may need a lot of rewriting.
Tuples are hard to use if you have a big array, as you may need many commas to get to the correct index. You also need to filter out undefined.


text:
Q: How do I implement CBC mode? My problem lies around the AES encryption algorithm and implementing an IV into the algorithm. I have the ECB version of AES working and I have thoroughly tested it. I'm trying to make it more secure by adding in an IV. I am looking to understand it better by knowing how the IV is implemented in the algorithm.
I am understanding that the IV is XOR'd with the plain text before encryption, and the IV is then stored with the encrypted data for decryption. But then when I go to decrypt, do I do the same XOR computation after the decryption process?
I tried the above process and my test for encryption and decryption work with the same values, but when I put the two processes side by side I get values very close to one another, but it doesn't seem to be working quite right. Not asking for code to be fixed, just the process laid out for me so that I know I'm doing this correctly. Thanks.

A: I always find the Wikipedia diagrams useful for visualizing what happens in CBC-mode:

You need to decrypt the first block of ciphertext, then XOR the IV to get the first block of plaintext. Thereafter, you need to XOR the previous block of ciphertext with the current block of decrypted data.


text:
Q: "borrowed value does not live long enough", but why do we need it to live so long? There are lots of similar questions, but I couldn't find the answer to my exact question.
In my Rust code, I have a generic type and want to implement a method that takes a reference to another instance of the that type, and then another method that consumes its argument but does exactly the same thing as the first one:
#[derive(Debug, PartialEq, Clone)]
pub struct Wrapper<T> {
    v: T,
}

impl<T> Wrapper<T> {
    pub fn f_ref(&self, _other: &Wrapper<T>) { /* ... */ }
    pub fn f_consume(&self, other: Wrapper<T>) {
        self.f_ref(&other)
    }
}

It compiles just fine.
Now I want to do basically the same, but while implementing a trait. First, the function that takes a reference:
use std::ops::AddAssign;

impl<'a, T> AddAssign<&'a Wrapper<T>> for Wrapper<T> where T: AddAssign<&'a T> {
    fn add_assign(&mut self, other: &'a Wrapper<T>) {
        self.v += &other.v;
    }
}

#[test]
fn test() {
    let mut a = Wrapper { v: 1_i32 };
    let b = Wrapper { v: 2 };
    a += &b;
    drop(b);
    assert_eq!(a, Wrapper { v: 3 });
}

It works, too.
Now I want to implement AddAssign for Wrapper<T> based on the implementation of AddAssign<&Wrapper<T>> that I already have. I understand that if T has references in it, it will cause trouble, so I make sure it has 'static lifetime. I'm OK with it: in my program, I expect T to be something like an owned matrix of numbers wrapped in some custom struct.
impl<'a, T> AddAssign for Wrapper<T> where T: 'static + AddAssign<&'a T>, Wrapper<T>: 'static {
    fn add_assign(&mut self, other: Wrapper<T>) {
        *self += &other;
    }
}

And it fails. The compiler says that other must stay valid after we used a reference to it to in a += expression. But when we used such a reference in the test() function above and dropped b there (which played the role of other here) and used the result later, the compiler agreed it's OK. Why?
I suspect that I need to specify some additional trait bounds for T or Wrapper<T> but don't understand what these bound should be.
Code in playground.


text:
Q: Jquery is not working with update panel while update panel is updated in asp.NET Jquery is not working with update panel while update panel is updated in asp.NET

Uncaught Sys.InvalidOperationException: Sys.InvalidOperationException: Could not find UpdatePanel.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="datepicker.aspx.cs" Inherits="WebApplication1.datepicker" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script>
        $(document).ready(function () {
            $("#dater").datepicker({
                changeMonth: true,
                changeYear: true
            });
        });
    </script>
</head>
<body>
    <form runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <p>
            Pick a Date:
            <asp:UpdatePanel ID="UpdatePanel2" runat="server">
                <ContentTemplate>
                    <asp:TextBox ID="dater" runat="server" AutoPostBack="true" OnTextChanged="dater_TextChanged"></asp:TextBox>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </ContentTemplate>
            </asp:UpdatePanel>
        </p>
    </form>
</body>
</html>

A: Try this:
  $(function () {
            $("#dater").datepicker({
                changeMonth: true,
                changeYear: true
            });
        });
        $(document).ready(function () {
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

            function EndRequestHandler(sender, args) {
                $("#dater").datepicker({
                    changeMonth: true,
                    changeYear: true
                });
            }

        });

A: not only in date picker,same issue is coming in like tooltip messages, model views which ever controls are using jquery with update panel


text:
Q: How to load non-default models? In CakePHP2.x, I have frequently used $uses attribute in controllers but it seems that this attribute is no longer available in CakePHP 3.0.
The only way I know to load models which is not default one is to use loadModel() method.
Is this recommended way to load models? Or is there any other way to load models?

A: Your observations are correct, there is no $uses property anymore, instead models/tables that do not match the controller (ex PostsTable for PostsController) and are not available via associations, must be loaded explicitly.
This can be done by using either

*

*Controller::loadModel() which adds the instance to the controller as a property.

*or  TableRegistry::get() which just returns the instance.

*and as of CakePHP 3.1 using TableLocator::get(), either by retrieving the locator via TableRegistry::locator() (TableRegistry::getTableLocator() as of CakePHP 3.5.0), or via LocatorAwareTrait::tableLocator() (LocatorAwareTrait::getTableLocator() as of CakePHP 3.5.0), which however usually shouldn't be required in a controller.

So this is kind of a yes to your question, Controller::loadModel(), ie
$this->loadModel('Name');

is a viable way of adding model/table instances to your controller as properties, wich at least in the default configuration, is essentially the shorthand for:
$this->Name = TableRegistry::get('Name');

but more loadModel() is more abstracted, and supports non-table repositories.


text:
Q: webview into sherlock fragment I have researched here in the forum but failing to implement a webview in sherlockfragment, what should I do?
public class LatestFragment extends SherlockFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_latest, container, false);
    return rootView;
}
private WebView web_v;

public class OracoesActivity extends WebviewActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadUrl("file:///android_asset/html/oracoes.html", getResources().getString(R.string.menu_about));
        //loadUrl("http://www.yoursite.com/about.html");
    }
}

}


text:
Q: sqlx named query inserting new ST_MakePoint - column not found I had a table in Postgres which holds lat/lng and geography(POINT,4326). I'm using sqlx and db.PrepareNamed statement to insert a new value into the table like this:
create, err := db.PrepareNamed(`INSERT INTO loc(longitude, latitude, geog) VALUES (:longitude, :latitude, ST_MakePoint(longitude, latitude) )`)

When I run it I receive an error: column longitude not found
And it is working fine when ST_MakePoint(longitude, latitude) replaced with ST_MakePoint(0.0, 0.0)
Table definition
CREATE TABLE loc(
    id  BIGSERIAL PRIMARY KEY,
    longitude    float8   NOT NULL,
    latitude    float8   NOT NULL,
    geog geography(POINT,4326) NOT NULL
);

Is it possible to incorporate insert ST_MakePoint into DB with PrepareNamed statement?

Does not work:
    create, err := db.PrepareNamed(`INSERT INTO logs.logs(key, user_id, scope, data, longitude, latitude, geog) VALUES (:key, :user_id, :scope, :data, :longitude, :latitude, ST_MakePoint(longitude, latitude) )`)

create, err := db.PrepareNamed(`INSERT INTO logs.logs(key, user_id, scope, data, longitude, latitude, geog) VALUES (:key, :user_id, :scope, :data, :longitude, :latitude, ST_MakePoint(:longitude, :latitude) )`)

Works:
create, err := db.PrepareNamed(`INSERT INTO logs.logs(key, user_id, scope, data, longitude, latitude, geog) VALUES (:key, :user_id, :scope, :data, :longitude, :latitude, ST_MakePoint(0.0, 0.0) )`)


text:
Q: dollar sign is shown in before any integer value rather than actual value when setcellvalue phpexcel? I am using the below code to set the cell value, but it shows the output in the cell which is different than the original:
$excel2->getActiveSheet()->setCellValue("F2",'1234567890');

Output
$1,234,567,890.00

The actual output which I expect is 1234567890, but I don't know why it is showing like this, any help would be appreciated.

A: Use number format and set format code as per your requirement.
Try below code.
$excel2->getActiveSheet()->setCellValue("F2",'1234567890')->getNumberFormat()->SetFormatCode('#,##0');

A: you should add number format to your cell
$excel2->getActiveSheet()->getStyle('F2') ->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
For more information of cell styling have look here and look Style classes on left navigation links.


text:
Q: Convergence in probability in a random point In general I am trying to solve this problem:
I know:
$f_{n}(x) \rightarrow f(x)$ in probability for all $x  \in I$, $I$ is compact interval. $X$ is random variable with density in $I$. Can I prove, that:
$f_{n}(X) \rightarrow f(X)$ in probability?
To be specific my original problem is about asymptotic mean square error of local linear estimator conditioned by $X=(X_{1}, \ldots , X_{n})$:
$MSE[\hat{m}_{LL}(x)| X]=O_{P}(h^{4}_{n}+\frac{1}{nh_{n}})  \stackrel{?}{\Rightarrow}$
$MSE[\hat{m}_{LL}(X_{i})| X]=O_{P}(h^{4}_{n}+\frac{1}{nh_{n}})$.
Thanks in advance for any help.


text:
Q: How to get bitmap from file manager? I'm going to create attachments in my android application. I need to attach images.
Here is my code:
...
attachButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "Select image"), CHOOSE_IMAGE);
        }
    });
...

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == CHOOSE_IMAGE) {
        if(resultCode == RESULT_OK) {
            Uri uri = data.getData();
            ImageView imageView = new ImageView(this);

            Bitmap bitmap = getDecodedImageFromUri(uri);
            imageView.setImageBitmap(bitmap);
         }
    }
 }

 private Bitmap getDecodedImageFromUri(Uri uri) {
    InputStream inputStream = null;
    try {
        inputStream = getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Rect rect = new Rect(0, 0, 0, 0);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    BitmapFactory.decodeStream(inputStream, rect, options);
    options.inSampleSize = getInSampleSize(options, 128, 128);

    options.inJustDecodeBounds = false;
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream, rect, options); //HERE IS PROBLEM - bitmap = null.
    return bitmap;
}

private int getInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    int width = options.outWidth;
    int height = options.outHeight;
    int inSampleSize = 1;

    if(height > reqHeight || width > reqWidth) {
        int halfHeight = height / 2;
        int halfWidth = width / 2;

        while ((halfHeight / inSampleSize) > reqHeight &&
                (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

I add comment where is problem.
So, I did debug, and on this moment:
 Bitmap bitmap = BitmapFactory.decodeStream(inputStream, rect, options);

bitmap equals to null.
What's problem? What I do wrong?
As you can see, these helper methods are from android developer's guide.
UPDATED
I need to decode two times, because I need to get options and then get image size to calculate InSampleSize to zip this image.
On second time, options not equals to null - I check it via debug.
But, after second decoding options has outWidth and outHeight as -1. So, it set to default. I don't know what happens on this moment.

A: I guess your problem may be because the calling to decodeStream twice
BitmapFactory.decodeStream(inputStream, rect, options); //HERE
options.inSampleSize = getInSampleSize(options, 128, 128);

options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, rect, options); //HERE AGAIN
return bitmap;

A: You can try  BitmapFactory.decodeStream(inputStream, null, options);

A: From the docs, the default constructor of the BitmapFactory.Options may be giving you this troubl:

BitmapFactory.Options()
  Create a default Options object, which if left unchanged will give the same result from the decoder as if null were passed.

And if the options paramter is null (or behaving as null) then the result will be null:

The decoded bitmap, or null if the image data could not be decoded, or, if opts is non-null, if opts requested only the size be returned (in opts.outWidth and opts.outHeight)

Try making a better options object or using the method
public static Bitmap decodeStream (InputStream is)

A: What If you try this way:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        Uri imageUri = data.getData();
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    }
}


text:
Q: You are not authorized to perform this action in Yii When I open my site, it redirects to a blank page.
Any ideas?
live url:- http://hermosacreative.com/builder/index.php?r=site/login
CHttpException

You are not authorized to perform this action. (C:\xampp\htdocs\hermosacreative.com\yii\framework\web\auth\CAccessControlFilter.php:182)
#0 C:\xampp\htdocs\hermosacreative.com\yii\framework\web\auth\CAccessControlFilter.php(145): CAccessControlFilter->accessDenied(Object(CWebUser), 'You are not aut...')
#1 C:\xampp\htdocs\hermosacreative.com\yii\framework\web\filters\CFilter.php(38): CAccessControlFilter->preFilter(Object(CFilterChain))
#2 C:\xampp\htdocs\hermosacreative.com\yii\framework\web\CController.php(1145): CFilter->filter(Object(CFilterChain))
#3 C:\xampp\htdocs\hermosacreative.com\yii\framework\web\filters\CInlineFilter.php(58): CController->filterAccessControl(Object(CFilterChain))
#4 C:\xampp\htdocs\hermosacreative.com\yii\framework\web\filters\CFilterChain.php(130): CInlineFilter->filter(Object(CFilterChain))
#5 C:\xampp\htdocs\hermosacreative.com\yii\framework\web\CController.php(291): CFilterChain->run()
#6 C:\xampp\htdocs\hermosacreative.com\yii\framework\web\CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#7 C:\xampp\htdocs\hermosacreative.com\yii\framework\web\CWebApplication.php(282): CController->run('error')
#8 C:\xampp\htdocs\hermosacreative.com\yii\framework\base\CErrorHandler.php(368): CWebApplication->runController('site/error')
#9 C:\xampp\htdocs\hermosacreative.com\yii\framework\base\CErrorHandler.php(351): CErrorHandler->renderError()
#10 C:\xampp\htdocs\hermosacreative.com\yii\framework\base\CErrorHandler.php(218): CErrorHandler->renderException()
#11 C:\xampp\htdocs\hermosacreative.com\yii\framework\base\CErrorHandler.php(131): CErrorHandler->handleException(Object(CHttpException))
#12 C:\xampp\htdocs\hermosacreative.com\yii\framework\base\CApplication.php(750): CErrorHandler->handle(Object(CExceptionEvent))
#13 [internal function]: CApplication->handleException(Object(CHttpException))
#14 {main}

A: There is a bit of logic in your SiteController#actionLogin which requires the user to be logged in before it happens. All acts in the login action should be for a guest.
Remove any aspect of code which requires Yii::app()->user->isGuest to be false


text:
Q: A question on base change Let $X$ be a regular integral projective scheme of dimension 1 over a field $k$ (not algebraically closed). Further, assume $X$ satisfies $dim_kH^0(X,\mathscr{O}_X)=1$. Let $\bar{X}$ denote the fibered product $X\times_k\bar{k}$. Then is it true that $\bar{X}$ is integral?

A: No, there are many counterexamples. Suppose that $a \in k$ is not a square; then the conic in $\mathbb P^2_k$ with equation $x^2 - ay^2$ is integral, while after base changing to $\overline k$ it splits into two components (these are switched by the Galois group).

A: This is an answer to the updated question, and it is positive in far more general situations. By EGA, IV.9.7.7, for any morphism of finite presentation $X\to Y$, the set $E$ of $y\in Y$ such that $X_y$ is geometrically integral is locally constructible. In your situation, $Y$ is noetherian and the set of the closed points is dense in $Y$. As $E$ contains the closed points of $Y$, it is equal to $Y$. So every fiber of $X\to Y$ (including the generic fiber when $Y$ is irreducible) is geometrically integral.
You don't need flatness neither smoothness neither properness hypothesis.
EDIT: The fact that $E=Y$ is only true when $Y$ is an algebraic variety because the set of the closed point is very dense. In general, $E$ contains a dense open subset, so the generic fiber is  geometrically integral.


text:
Q: Objectif Function Gams I'm beginner with gams , so i'm trying to create this new function into gams
MAX   (Σ(t=0-->2020) (Vusage (t )  * pusage   * 1-busage  ))
where pusage and tusage are two constants and Vusage (t ) is a function depending on t incremental.
How can I write the code of gams
Thanks for all

A: You should first recognize your set (t),
after that you can write your objective as below:
z=e=sum(t$(ord(t)<2020), (Vusage(t)*pusage*(1-busage) );


text:
Q: Parsing multilevel headers in Pandas Trying my hands pandas multi level indexing. Have shown sample for input as well as output. I tried transposing, reading part by part, not sure where I am going incorrect:
Input:
import pandas as pd
import numpy as np
df = pd.DataFrame(index=['2016-11-21', '2016-11-22', '2016-11-23', '2016-11-24', '2016-11-25'],
                  columns=pd.MultiIndex.from_product([list('AB'), list('ab')]),
                  data=np.array([[2,3,5,6,6], [1,4,2,3,3], [3,1,1,1,0], [0,0,6,5,2]]).T)
print (df)
            A     B
            a  b  a  b
2016-11-21  2  1  3  0
2016-11-22  3  4  1  0
2016-11-23  5  2  1  6
2016-11-24  6  3  1  5
2016-11-25  6  3  0  2

Desired Output:
I need to get value for '2016-11-22' across column a for both A and B

     a
 A   3
 B   1

A: to match your output you can use df.xs with unstack
df.xs('a',axis=1,level=1,drop_level=False).loc['2016-11-22'].unstack()

   a
A  3
B  1

however if you are interested for a single level and index , you could also try:
df.xs('a',axis=1,level=1).loc['2016-11-22']

A    3
B    1
Name: 2016-11-22, dtype: int64

A: try filter and .loc
df.filter(like='2016-11-22',axis=0).loc[:,df.columns.get_level_values(1).isin(['a'])].stack(0)

          a
2016-11-22 A  3
           B  1

A: I used the date index to find the row then a select the columns using a tuple pair matching the multi-index for all level 0 columns and only 'a' for level 1 columns
df = pd.DataFrame(index=['2016-11-21', '2016-11-22', '2016-11-23', '2016-11-24', '2016-11-25'],
              columns=pd.MultiIndex.from_product([list('AB'), list('ab')]),
              data=np.array([[2,3,5,6,6], [1,4,2,3,3], [3,1,1,1,0], [0,0,6,5,2]]).T)

 columns=df.columns.levels[0]
 print(df.loc['2016-11-22',(columns,'a')])

 output:
 A  a    3
 B  a    1
 Name: 2016-11-22, dtype: int32


text:
Q: Generate weights for mean, such that mean of weighted means is closest to $G$, while minimising std. dev. of weights Given some fixed 'target' $T=150$, and a set of sets of arbitrary numbers $G$ in the range $0 < x \leq T\ln\left(T\right)$, for instance:
$$
G=\left[
\begin{array}{ccc}
  p_1&p_2&p_3&p_4&p_5&p_6\\
  \hline
  204&216&2&597&302&401\\
  188&551&478&417&71&383\\
  314&583&203&42&189&510\\
  231&64&298&95&23&312\\
  417&210&112&224&90&432\\
  495&297&490&580&361&477\\
  298&163&568&590&64&388\\
  175&360&526&583&352&96
\end{array}
\right]
$$
... we can simply taking the mean of each of these rows, resulting in (rounded to nearest integer):
$$
M=\{\operatorname{mean}(d) : d \in G \}=\left[
\begin{array}{ccc}
  287\\
  348\\
  307\\
  171\\
  248\\
  450\\
  345\\
  349
\end{array}
\right]
$$
The mean of these means is then simply evaluated to be $\approx313$ - not very close to our target, $T$. However, by weighting each of $p_x$ by some 'weight', we can alter the final mean of means quite significantly. For instance, by multiplying the value of each column as follows:
$$
W=\left[
\begin{array}{c|c}
  p_1&p_2&p_3&p_4&p_5&p_6\\
  \hline
  \frac{1}{2}&\frac{2}{5}&\frac{2}{7}&\frac{1}{2}&\frac{1}{2}&\frac{2}{3}\\
\end{array}
\right]
$$
we get the weighted grid:
$$
G'=\left[
\begin{array}{ccc}
  p_1\cdot W'_1&p_2\cdot W'_2&p_3\cdot W'_3&p_4\cdot W'_4&p_5\cdot W'_5&p_6\cdot W'_6\\
  \hline
102&86&1&299&151&267\\94&220&137&209&36&255\\157&233&58&21&95&340\\116&26&85&48&12&208\\209&84&32&112&45&288\\248&119&140&290&181&318\\149&65&162&295&32&259\\88&144&150&292&176&64
\end{array}
\right]
$$
giving us the table of means:
$$
M'=\left[
\begin{array}{ccc}
  151\\159\\151\\83\\128\\216\\160\\152
\end{array}
\right]
$$
which gives us the final value as $\operatorname{mean}(M')\approx 150=T$, when all is rounded.
However, although these 'weights' do work to give us a result, they are all quite small (less than $1$, in fact, so I'd hesitate to even call them weights as they function more as coefficients). Ideally, $\frac{\sum{W}}{|W|}$ should be greater than one, where possible.
Therefore, I am looking for an algorithm, formula, method, or even citation regarding how I might go about evaluating the members of set $W$ given $G$ and $T$, such that (in order of significance):

*

*$\operatorname{abs}\left(\cfrac{\sum_{x \in G}{\cfrac{\sum_{i=1}^{|x|}{x_i\cdot W_i}}{|x|}}}{|G|} - T\right)$ is minimised (it is not always possible for the mean of means to equal $T$ exactly, but it should be as close as possible);

*$\operatorname{mean}\left(W\right)$ is maximised — i.e. each weight is as large (therefore as 'precise', relative to the others) as possible — but;

*$\frac{\sigma\left(W\right)}{\operatorname{mean}\left(W\right)}$ (where $\sigma$ is std. dev.) is minimised.

So far, I have no better ideas than just random guessing and checking, particularly in order to expand this to arbitrary sizes of $G$ and values for $T$. Although I'm not expecting a neat or closed-form solution by any means, I'm fairly sure that there has to exist some better approach to try to get optimised values.
Thanks in advance for any advice/assistance!


text:
Q: Difference between regression between groups vs across all subjects (continuum)? I'd like to understand this better in terms of drawbacks and suitability.
For example, if my data includes investigating differences between 2 patient groups and a control group (3 groups in total), how can I tell which is a more appropriate method to use and maybe, adding strength to the model?
Thank you very much.

A: I'm not entirely sure on this one, so I hope somebody else can join in the discussion.
One option is to do a standard linear regression with indicator variables for patient groups (i.e. x1 is a binary variable with 1 meaning patient group 1 and 0 meaning patient group 2 or control and x2 is a binary variable with 1 meaning patient group 2 and 0 meaning patient group 1 or control) and the other covariates as you please. You will then compare both patient groups to the controls but you will not compare the patient groups with each other. You can do this by changing indicator variable x1 for another, we can call it x3, which is constructed so that 1 means control and 0 means patient groups 1 or 2. However, the drawback of this model is that you do not take the matching in account, and that's where I'm not sure.
Since you did the matching only by age and gender, including these variables (and possibly their interaction term) should be enough, provided the assumption of a linear relationship between age and the DV holds (if there is a relationship). If not, you need to add a non-linear variable.
Anyway, I'm not sure this is the best way to handle the case-control design. Perhaps a linear mixed model could be used, so that each patient and its control(s) will share the same level in a factor variable and this factor acts as a random intercept, but I'm not sure this would be appropriate.
Hope this helps.