text:
Q: verificar iterativamente se os elementos de um dicionário possuem a mesma chave e realizar operações com os valores do dicionário Tenho um dicionário de arrays, preciso percorrer todos os arrays do dicionário e verificar de forma iterativa se os arrays estão contidos na mesma chave.
Caso se trate de arrays em uma mesma chave do dicionário, eu preencho a posição referente de sua matriz de custo com o custo zero.
Caso se trate de arrays em chaves distintas, preciso calcular a distância euclidiana entre esses arrays e armazenar o valor calculado na respectiva posição i j da matriz de custo.
Exemplo dicionário:
{0: array([[21.8472593 , 23.07639831]]), 1: array([[8.54825372, 1.23984289],
   [8.30116683, 1.73755953],[7.89875198, 2.12075148],
   [7.38954636, 2.34320015],
   [6.83496766, 2.37807495],
   [6.30190627, 2.22116945],
   [5.85465726, 1.89140877],
   [5.54716545, 1.42856693],
   [5.41651891, 0.88846947],
   [5.47847552, 0.33626013]]), 2: array([[ 4.3455991 , 17.14658312],
   [ 3.88626636, 17.45929259],
   [ 3.34768183, 17.59604232],
   [ 2.79480676, 17.54033827],
   [ 2.29432605, 17.29889918],
   [ 1.90660505, 16.90084616],
   [ 1.67840863, 16.39419028],
   [ 1.63726066, 15.84004172],
   [ 1.78812419, 15.30523897],
   [ 2.11280285, 14.85428714]])}

Com o código abaixo eu consigo iterar da forma que quero para preencher a matriz, porém eu preciso que o tamanho da minha matriz seja i x j, onde i = j = instance.values(). Mas estou obtendo uma matriz com i^2 x j^2!!!!.
Como resolvo a dimensionalidade da matriz?

for k,  v in instance.items():
    for q, w in instance.items():
    #guardo os arrays de cada chave em matrizes auxiliares que eu possa iterar
        aux_v = v
        aux_w = w
        for i in range(len(v)):
            for j in range(len(w)):
                if k == q:
                    costMatrix[i][j]=0

                else:
                    dist = np.linalg.norm(aux_v[i] - aux_w[j])
                    costMatrix[i][j]= dist  * 1e3 + M

'''

A: Atualização: esclarecido nos comentários e na pergunta qual é o objetivo do algoritmo, existe um método do numpy para iterar sobre arrays de dimensão desconhecida que é o nditer.
Assumindo que cada valor do teu dicionário pode ser tratado como um array único, então:
import numpy as np

instance = {0: array([[21.8472593 , 23.07639831]]), 1: array([[8.54825372, 1.23984289],
   [8.30116683, 1.73755953],[7.89875198, 2.12075148],
   [7.38954636, 2.34320015],
   [6.83496766, 2.37807495],
   [6.30190627, 2.22116945],
   [5.85465726, 1.89140877],
   [5.54716545, 1.42856693],
   [5.41651891, 0.88846947],
   [5.47847552, 0.33626013]]), 2: array([[ 4.3455991 , 17.14658312],
   [ 3.88626636, 17.45929259],
   [ 3.34768183, 17.59604232],
   [ 2.79480676, 17.54033827],
   [ 2.29432605, 17.29889918],
   [ 1.90660505, 16.90084616],
   [ 1.67840863, 16.39419028],
   [ 1.63726066, 15.84004172],
   [ 1.78812419, 15.30523897],
   [ 2.11280285, 14.85428714]])}
M = 0.0
costMatrix = dict()
for chave_um, valor_um in instance.items():
    for chave_dois, valor_dois in instance.items():
        for indice_um, array_um in enumerate(np.nditer(valor_um)):
            costMatrix[indice_um] = dict()
            for indice_dois, array_dois in enumerate(np.nditer(valor_dois)):
                ed = np.linalg.norm(valor_um - valor_dois)
                costMatrix[indice_um][indice_dois] = ed * 1e3 + M
print(costMatrix)

Não é necessário testar se o array está na mesma posição, porque a distância euclidiana entre um ponto e ele mesmo é 0.0. Mas se isto for um requisito,então o array é o mesmo somente se (chave_um == chave_dois) and (indice_um = indice_dois).

Em relação ao cálculo de distância euclidiana, o norm() do módulo de álgebra linear do numpy só funciona porque a ordem padrão é equivalente a calcular a distância euclidiana, mas esse método vai retornar um array do numpy, e não a distância. No scipy tem uma função que faz exatamente o que tu quer:
import scipy
ed = scipy.spatial.distance.euclidean(array1, array2)

Resposta anterior para referência:
Iterar sobre range(len(dicionario.values())) é anti pytônico. Existem métodos para iterar em dicionários mais eficazes, dependendo do que tu precisa fazer.
Depender do método sorted() pra ordenar dicionários não é confiável. Dicionários em Python não são ordenados. Para os casos onde tu precisa de ordem existe o OrderedDict, mas neste caso ele não é necessário.
Dito isto, tem como fazer seguindo a lógica que tu apresentou. O que tu quer é iterar sobre as chaves, e não sobre os valores. Usar uma sequência de números presumindo que o dicionário está bem formado e respeitando essa sequência é possível mas quase sempre desnecessário, e este caso não é exceção. Tu pode iterar sobre as chaves com o iterador instance.keys():
for i in instance.keys():
    for j in instance.keys():
        if i == j:
            costMatrix[i][j] = 0
        else:
            ed = np.linalg.norm(instance[i] - instance[j])
            costMatrix[i][j] = ed * 1e3 + M

É muito mais fácil acessar os valores do dicionário se tu tem a chave, do que acessar a chave a partir do valor.
Se precisar dos valores tu pode obter as chaves e valores com o iterador instance.items():
for chave_um, valor_um in instance.items():
    for chave_dois, valor_dois in instance.items():
        if chave_um == chave_dois:
            costMatrix[chave_um][chave_dois] = 0
        else:
            ed = np.linalg.norm(valor_um - valor_dois)
            costMatrix[chave_um][chave_dois] = ed * 1e3 + M

Mas como eu escrevi, essa abordagem é ineficiente. Ela é útil pra enxergar melhor o que está acontecendo. Já que tu está usando numpy, tem métodos mais eficientes, rápidos de fazer a mesma coisa. Estudar estes métodos e aprimorar o código é um exercício para quem está lendo. Até simples compreensões de lista e dicionários já melhorariam a eficiência neste caso.


text:
Q: C# Use Windows 7 control look in windows xp I found out how to do it in WPF but how can I achieve this in winforms?  The most important thing I want to use is the new calendar control but I would love to have the whole app be Windows 7-like.  Sorry if this has been answered already but I didn't find the answer.

A: There is no native way to do it with WinForms. WPF is a "Exception" as it draws everything itself instead of through the system...
There are though a number of companies that sell themed controls. Such as...
https://www.devexpress.com/Products/Free/NetOffer/
This company also has a lot of controls including a calander:
http://www.bcgsoft.com/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to download Yosemite Long story short: I'm on OSX 10.6.8 and I'm trying to download the Yosemite package in order to (re)create a bootable USB.
When I go to the App Store, I go to the first tab and click on "Free" under yosemite and the OSX icon appears on the bottom bar:

If I hover over it it says "Downloading...". I wanted to check out the speed and progress of the download, but apparently if I go to App Store > Purchased tab, what I see is this:

while, as I understand, there should be informations about the current download.
I've already done this process once already from 10.6.8 on the same computer and I succeeded. This is a clean install of Snow Leopard (updated to 10.6.8) though and my download speed is very low (0.99Mb/s vs 5Mb/s I had back then) this week.
I've tried canceling the download, trying again. I've tried restarting (also shutting down and then manually start it again), as well as canceling and restarting the download numerous times. I've also tried starting the download from the Purchased tab, but that doesn't seem to start the download and just makes the "Download" button go back grey again. Even waiting for a while doesn't show any message and/or progress.
What should I do next?

A: I've solved this by making sure there were no updates left. Basically after the first "cycle of updates" after a clean install, new updates are silently "unlocked". You need to run all updates. One of them fixes the problem.

A: I found that I had to delete all instances of "Install OSX Yosemite", which I had renamed to "Install OSX Yosemite_10.10.1" from /Applications/ and eject my old USB key, which was labeeled "Install OSX Yosemite_10.10.1" before my computer would download the latest (10.10.2) installer.
Just FWIW, might be worth a try

A: Try to close the "app store" application and open it again, go to updates and it shows the process status...


text:
Q: Execution Context Stack. Violation of the LIFO order using Generator Function The specifications says that the LIFO order of the Running Execution Context transitions in the Execution Context Stack may be violated by some ECMAScript featues:

Transition of the running execution context status among execution
  contexts usually occurs in stack-like last-in/first-out manner.
  However, some ECMAScript features require non-LIFO transitions of the
  running execution context.

However the specification doesn't explicitly tell by which exactly.
I've read that the violation may occure when using the Generator Functions. But I absolutely don't understand why. Morover I couldn't have been able to find any mentions of this in the 25.3.3 section of the specification.
function *gen() {
    yield 1;
    return 2;
}

let g = new gen();

console.log(g.next().value);

// some other operations

console.log(g.next().value);

As far as I understand the lifecycle of the Execution Context Stack in the exmple above may look as follows:
EC(global)

->

EC(gen1)
EC(global)

->

EC(global)

->

EC(gen2)
EC(global)

->

EC(global)

So I don't see any LIFO violations here.
May be Generator Functions don't even lead to such violation? Or, may be, I misread the specification. Anyways, could you please explain what's going on with the Execution Context Stack when using generators? And how (and why) does LIFO order of the Running Execution Context transitions violates?


text:
Q: export several rasters from grass I'd like to export 127 raster files from grass to .tif in one operation. I already stumbled over this post How to batch export using r.out.gdal command in GRASS but it doesn't work (I don't even know exactly where to enter this -python console or command shell?).
I'm not too familiar with programming, so I hope there's a simple solution.


text:
Q: VSCode + PHP + xdebug + launch.json I have a Laravel project, and I have Xdebug working in VSCode.
But unfortunately I'm doing this in two steps. I want to combine it into one.
What I'm doing now, I write:

*

*In cmd:
php -S localhost:1000 -t public

*Have a VSCode > debug > launch.json
{
    "name": "Listen for XDebug",
    "type": "php",
    "request": "launch",
    "port": 9000
},

How can I combine this into one task?
I've tried to create the 1. part as a task, but it didn't work.
task.json:
{
    "taskName": "PhpServe",
    "type": "shell",
    "command": "php -S localhost:1000 -t public"
}

launch.json
{
    "name": "Listen for XDebug",
    "type": "php",
    "request": "launch",
    "preLaunchTask": "phpServe",
    "port": 9000
},

The PHP server starts up, and runs until I close it. After I close it Xdebug starts up. Not what I want.
How do I launch PHP server and xdebug at the same time?


text:
Q: AttributeError: 'numpy.ndarray' object has no attribute 'score' error I have tried to look for a problem but there is nothing Im seeing wrong here. What could it be? This is for trying binary classification in SVM for the fashion MNIST data set but only classifying 5 and 7.
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn import svm
from sklearn.preprocessing import MinMaxScaler
from sklearn.svm import SVR
from sklearn.model_selection import KFold
import matplotlib.pyplot as plt

trainset = 'mnist_train.xlsx'
trs = pd.read_excel(trainset)
testset = 'mnist_test.xlsx'
tes = pd.read_excel(testset)
xtrain = trs.iloc[:, [1, 783]]
ytrain = trs.iloc[:, 0]
xtest = tes.iloc[:, [1, 783]]
ytest = tes.iloc[:, 0]

##Linear SVC

svclassifier = SVC(kernel='linear', C=1)
svclassifier.fit(xtest, ytest)
ypred = svclassifier.predict(xtest)
print(ypred.score(xtrain, ytrain))
print(ypred.score(xtest, ytest))

##Gaussian SVC

svclassifier = SVC(kernel='rbf', C=1)
svclassifier.fit(xtrain, ytrain)
ypred = svclassifier.predict(xtest)
print(ypred.score(xtrain, ytrain))
print(ypred.score(xtest, ytest))

A: ypred is an array of predicted class labels, so the exception makes sense.
What you should do is use the classifier's score method:
svclassifier = SVC(kernel='rbf', C=1)
svclassifier.fit(xtrain, ytrain)
# ypred = svclassifier.predict(xtest)  # We don't actually use this.
print(svclassifier.score(xtrain, ytrain))
print(svclassifier.score(xtest, ytest))


text:
Q: Nexus High disk watermark...free: 8191.9pb[-99.9%] I have an instance of Nexus deployed in a docker container using AWS Elastic File System to store it's data.  I've been getting an error when uploading some artifacts:
Failed to deploy artifacts: Could not transfer artifact com.etc from/to remote (http://mynexusurl/repository/maven-releases/): Could not write to resource 'com/etc/whatever.jar'

In the Nexus logs I can see the following message over and over:
high disk watermark [90%] exceeded on [_atm8vFNT5qLzS5GYeNyFQ][E610BDF5-BD17F9DC-9567365A-380D6026-8419CF79][/nexus-data/elasticsearch/nexus/nodes/0] free: 8191.9pb[-99.9%], shards will be relocated away from this node

Seems like an integer overflow, does anyone know a way of working around this?


text:
Q: Como fazer contagem regressiva em um MessageBox Uso Delphi XE7, precisava colocar uma contagem regressiva em um MessageBox, no botão Não. Por exemplo uma contagem de 10 seg ao lado do caption do botão Não (10) e assim ele vai diminuindo Não (9).
Minha alternativa é criar o próprio dialog e fazer as mudanças que eu necessito. Mas primeiro queria saber se é possível fazer essa alteração no MessageBox ou no MessageDlg.

A: Eu tenho um formulário onde nele tenho dois botões, e em um deles eu uso um timer para habilitar
No FormShow
procedure TfrmMensagem.FormShow(Sender: TObject);
begin
  inherited;
  fCaption := btn1.Caption;

  a1 := 2;
  a2 := 0;

  if (Timer1.Enabled) then
  begin
    btn1.Caption := 'Aguarde ('+IntToStr(a1)+')';
    btn1.Enabled := false;
  end;

  scrlbx.SetFocus;
end;

No Timer
procedure TfrmMensagem.Timer1Timer(Sender: TObject);
var msg: string;
begin
  inherited;
  btn1.Enabled := false;
  if (a2 = 0) then
  begin
    a1 := a1 - 1;

    msg := 'Aguarde ('+IntToStr(a1)+')';

    btn1.Caption := msg;

    if (a1 = 0) then
    begin
      btn1.Enabled := True;
      Timer1.Enabled := false;

      a2 := 1;
      a1 := 2;

      btn1.Caption := fCaption;
      if btn1.Visible then
        btn1.SetFocus;
    end;
  end;
end;

E eu tenho uma classe para trabalhar com esse form
unit Mensagem;
interface

uses SysUtils, Classes, Controls, Forms, StdCtrls;

type
  TTipoMensagem = (tmConfirmacao, tmAtencao);

  TMensagem = class
    fLimparMensagens : Boolean;
    private
      fMensagem : TStrings;
      fTipoMensagem : TTipoMensagem;

      procedure CriaLabels;
      procedure ConfiguraForm;

    public
      NumeroMensagens : Integer;

      constructor Create;
      destructor Destroy; override;

      procedure Ordenar;
      procedure Adicionar(Mensagem : String);
      procedure SetTipo(TipoMensagem : TTipoMensagem);
      procedure Limpar;
      function Show(Mensagem : String = ''; TipoMensagem : TTipoMensagem = tmAtencao; Timer: Boolean = false) : TModalResult;
  end;

implementation

uses UMensagem;

{ TMessageForm }

constructor TMensagem.Create;
begin
  fLimparMensagens := True;
  fMensagem        := TStringList.Create;
  NumeroMensagens  := fMensagem.Count;
end;

destructor TMensagem.Destroy;
begin
  FreeAndNil(fMensagem);
  inherited;
end;

procedure TMensagem.Adicionar(Mensagem : String);
begin
  fMensagem.Add(WrapText(Mensagem, 100));
  NumeroMensagens := fMensagem.Count;
end;

procedure TMensagem.Limpar;
begin
  fMensagem.Clear;
  NumeroMensagens := fMensagem.Count;
end;

procedure TMensagem.ConfiguraForm;
begin
  case fTipoMensagem of
    tmConfirmacao :
      begin
        frmMensagem.Caption:='Confirme';
        frmMensagem.btn1.Caption:='Sim';
        frmMensagem.btn1.ModalResult:=mrYes;
        frmMensagem.btn2.Caption:='Não';
        frmMensagem.btn2.ModalResult:=mrNo;
      end;
    tmAtencao :
      begin
        frmMensagem.Caption:='Atenção';
        frmMensagem.btn1.Visible:=False;
        frmMensagem.btn2.Caption:='OK';
        frmMensagem.btn2.ModalResult:=mrOk;
      end;
  end;
end;

procedure TMensagem.CriaLabels;
var count : integer;
    l : TLabel;
begin
  for count:=0 to fMensagem.Count-1 do
  begin
    l:=TLabel.Create(frmMensagem);
    l.Parent:=frmMensagem.scrlbx;
    l.Caption:=fMensagem[count];
    l.Left := 6;
    l.Top := count * 17 + 4;
  end;
end;

function TMensagem.Show(Mensagem : String = ''; TipoMensagem : TTipoMensagem = tmAtencao; Timer: Boolean = false) : TModalResult;
begin
  try
    fTipoMensagem := TipoMensagem;
    frmMensagem := TfrmMensagem.Create(nil);
    frmMensagem.Timer1.Enabled := Timer;

    ConfiguraForm;
    if Mensagem <> '' then
      Adicionar(Mensagem);
    CriaLabels;

    if NumeroMensagens > 0 then
      Result := frmMensagem.ShowModal
    else Result := mrNone;
  finally
    FreeAndNil(frmMensagem);
  end;

  if fLimparMensagens then
     Limpar;
end;

procedure TMensagem.Ordenar;
begin
  (fMensagem as TStringList).Sort;
end;

procedure TMensagem.SetTipo(TipoMensagem: TTipoMensagem);
begin
  fTipoMensagem := TipoMensagem;
end;

end.

Quando preciso utlizar, faço o seguinte:
if fMensagem.Show('Você deseja realmente finalizar a operação ' + aTipo + '?', tmConfirmacao, True) = mrYes then

A: Outra alternativa é usar a função MessageBoxTimeOut. Ela é nativa no Windows, apesar de não estar documentada na unit Windows.pas.
Detalhes de sua utilização podem ser encontrados no próprio site da Embarcadero.
A função não exibe um contador regressivo dos segundos, mas fecha o o MessageBox automaticamente, de acordo com o parâmetro definido.


text:
Q: Display Query result of one table in another table for a View? The kpiRecord table stores all user-submitted KPI data. The kpiMaster table stores general data about each KPI - i.e. name, department, whether they have a Target or Critical No. etc.
In my Index View, I'd like to display all records from the kpiRecord table. However, because this table only stores a KPI Number ("kpiNo") , for this column I want to retrieve the KPI Name ("kpiName") from the kpiMaster table and display this instead.
How can I query my kpiMaster table and display the results within my kpiRecord table in Index? (e.g. SELECT kpiMaster.kpiName WHERE kpiRecord.kpiNo == kpiMaster.kpiNo)
Controller.cs
public async Task<IActionResult> Index() {

   var tables = new KpiViewModel {
       vmKpiMaster = _context.kpirep_dev_kpiMaster.ToList(),
       vmKpiGoal = _context.kpirep_dev_kpiGoal.Where(kpiGoal => kpiGoal.isActive).ToList(),
       vmKpiRecord = _context.kpirep_dev_kpiRecord.Where(kpiRecord => kpiRecord.isActive).ToList()
   };

   return View(tables);
}

kpiViewModel.cs
public class KpiViewModel {

   public IEnumerable<kpiMaster> vmKpiMaster { get; set; }
   public IEnumerable<kpiGoal> vmKpiGoal { get; set; }
   public IEnumerable<kpiModel> vmKpiRecord { get; set; }
   }

Index.cshtml

   @foreach (var item in Model.vmKpiRecord) {

       @Html.DisplayFor(modelItem => item.kpiNo)
       @Html.DisplayFor(modelItem => item.kpiYear)
       @Html.DisplayFor(modelItem => item.kpiMonth)
       @getKpiWeek(item.kpiYear, item.kpiWeek)
       @Html.DisplayFor(modelItem => item.kpiValue)

           Details
           Deactivate
           Delete

   }

kpiMaster table

kpiRecord table

Currently, my Index looks like this:

It needs to look like this instead:

A: Join the tables.
You can write a stored procedure in SQL:
CREATE PROCEDURE [dbo].[GetKpiDetailedRecords]
AS
BEGIN

    SELECT
        *
    FROM
        KpiRecord R
        INNER JOIN KpiMaster M ON M.KpiNo = R.KpiNo

END

Or in your code with Linq:
var tables = new KpiViewModel {

    vmKpiDetailedRecords  = _context.kpirep_dev_kpiRecord.Where(kpiRecord => kpiRecord.isActive).Join(_context.kpirep_dev_kpiMaster,
    master => master.KpiNo, record => record.KpiNo,
    (record, master) => new {Kpi=master.KpiName,Year=record.KpiYear, ... }).ToList(),

    vmKpiGoal = _context.kpirep_dev_kpiGoal.Where(kpiGoal => kpiGoal.isActive).ToList()
};

A: According to the table structure and data, the kpiRecord contains the foreign key ("kpiNo"), I suppose the kpiRecord Entity and kpiMaster Entity might be contains the One-to-One or One-to-Many relationship, right?
If the kpiRecord Entity contains an navigation property (public kpiMaster kpiMaster { get; set; }), you could use the navigation properties in your model to load related entities, sample code as below:
public class kpirep_dev_kpiRecord
{
    [Key]
    public int ID { get; set; }
    public DateTime activeTimestamp { get; set; }

    //... //other properties

    //used to configure one-to-one relationship.
    [ForeignKey("kpiMaster")]
    public int kpiNo { get; set; }
    public kpirep_dev_kpiMaster kpiMaster { get; set; }

}

public class kpirep_dev_kpiMaster
{
    [Key]
    public int kpiNo { get; set; }
    public string kpiName { get; set; }
}

In the Controller method, you could the Include() method to load the kpiMaster when query the kpiRecord.
        var tables = new KpiViewModel
        {
            //vmKpiMaster = _context.kpirep_dev_kpiMaster.ToList(),
            //vmKpiGoal = _context.kpirep_dev_kpiGoal.Where(kpiGoal => kpiGoal.isActive).ToList(),
            vmKpiRecord = _context.kpirep_dev_kpiRecord.Where(kpiRecord => kpiRecord.isActive).Include(c => c.kpiMaster).ToList()
        };

        return View(tables);

Then, in the View, using the following code to display the kpiName:

    @foreach (var item in Model.vmKpiRecord)
    {

            @Html.DisplayFor(modelItem => item.kpiMaster.kpiName)
            @Html.DisplayFor(modelItem => item.kpiYear)
            @Html.DisplayFor(modelItem => item.kpiMonth)
            @Html.DisplayFor(modelItem => item.kpiValue)

                Details
                Deactivate
                Delete

    }

If you are not using the navigation property, you could use join() to join the table, then select the required properties. Then, display the result, you could refer to the following sample:
Create a ViewModel which contains the required properties(such as: kpiName):
public class kpiModelViewModel
{
    public int Id { get; set; }
    public string kpiName { get; set; }
    public DateTime activeTimestamp { get; set; }
    public DateTime inactiveTimestamp { get; set; }
    public bool isActive { get; set; }
    public string submissionBy { get; set; }
    public int kpiNo { get; set; }
    public int kpiYear { get; set; }
    public int kpiMonth { get; set; }
    public int kpiWeek { get; set; }
    public int kpiValue { get; set; }
}

public class KpiViewModel {

       //public IEnumerable<kpiMaster> vmKpiMaster { get; set; }
       //public IEnumerable<kpiGoal> vmKpiGoal { get; set; }
       //public IEnumerable<kpiModel> vmKpiRecord { get; set; }
       public IEnumerable<kpiModelViewModel> vmKpiRecord { get; set; }
}

code in the controller:
        var tables = new KpiViewModel
        {
            //vmKpiMaster = _context.kpirep_dev_kpiMaster.ToList(),
            //vmKpiGoal = _context.kpirep_dev_kpiGoal.Where(kpiGoal => kpiGoal.isActive).ToList(),
            vmKpiRecord = _context.kpirep_dev_kpiRecord.Where(kpiRecord => kpiRecord.isActive)
            .Join(_context.kpirep_dev_kpiMaster, model => model.kpiNo, master => master.kpiNo, (model, master) => new { kModel = model, KMaster = master })
            .Select(ModelandMaster => new kpiModelViewModel()
            {
                kpiName = ModelandMaster.KMaster.kpiName,
                kpiYear = ModelandMaster.kModel.kpiYear,
                kpiWeek = ModelandMaster.kModel.kpiWeek,
                kpiValue = ModelandMaster.kModel.kpiValue
            }).ToList()
        };
        return View(tables);

Then, using the ViewModel to display the kpiName:

        @foreach (var item in Model.vmKpiRecord)
        {

                @Html.DisplayFor(modelItem => item.kpiName)
                @Html.DisplayFor(modelItem => item.kpiYear)
                @Html.DisplayFor(modelItem => item.kpiMonth)
                @Html.DisplayFor(modelItem => item.kpiValue)

                    Details
                    Deactivate
                    Delete

        }

The result like this:

Reference:
Entity Framework Core One To One Relationships Conventions
Loading Related Data

A: In your Index view change:
@Html.DisplayFor(modelItem => item.kpiNo)

to:
@Html.DisplayHiddenFor(modelItem => item.kpiNo)

@Html.DisplayFor(modelItem => item.kpiName)

and fix  theader  accordingly too.


text:
Q: PHP: Sync (if else) with arrays results
I am trying to sort the days, times and the business status if it is closed or open. I am getting the results but they are not working appropriately as needed. My dates and timings are working fine but my status (if open or close... are not sync accordingly), so  here is my code please see the screenshot. Today is thursday, then the status should show on thursday and rest of the days it should be blank.
please see if you have any views on it:-
   <?php
  $datetime = new \DateTime();

  $listItem = array('
', '
');

  $status = array( "Now Open" ,"Closed",  "Opening Soon",  "Closing Soon", "Open 24 hours", "  ");

  $times = array(
    1 => date( $row_DetailRS1['monO'] ). "  ". date( $row_DetailRS1['monC'] ),
    2 =>  date( $row_DetailRS1['tueO'] ) . " ". date( $row_DetailRS1['tueC'] ),
    3 =>  date( $row_DetailRS1['wedO'] ) . " ". date( $row_DetailRS1['wedC'] ),
    4 =>  date( $row_DetailRS1['thurO'] ) . " ". date( $row_DetailRS1['thurC'] ),
    5 =>  date( $row_DetailRS1['friO'] ) . " ". date( $row_DetailRS1['friC'] ),
    6 =>  date( $row_DetailRS1['satO'] ) . " ". date( $row_DetailRS1['satC'] ),
    7 =>  date( $row_DetailRS1['sunO'] ) . " ". date( $row_DetailRS1['sunC'] ) );

  $html .= "

                 Days

                 Business Hours

                 Hours

";
  $i = 1;

    date_default_timezone_set('Australia/Melbourne');

  foreach ($times as $key => $value):

      $curDayNum = new \DateTime();
      $cd = $datetime->format('N') + 4;

        if ( $cd  == 1) {

               $timenow =     date("H:i:s", time());
               $wopeningTime = date( $row_DetailRS1['monO'] );
               $closingTime = date( $row_DetailRS1['monC'] );
               $openingSoon = date('H:i:sA', strtotime($openingTime)-3600);
               $closingSoon = date('H:i:sA', strtotime($closingTime)-3600);
               $curDay = date('l');

               if ($timenow < $openingSoon || $timenow > $closingTime ) {
                       $s = $status[1];
                   }

                   elseif  ($timenow > $openingSoon && $timenow < $openingTime ) {
                       $s = $status[2];
                   }

                   elseif  ($timenow > $closingSoon && $timenow < $closingTime ) {
                       $s = $status[3];
                   }

                   elseif  ($openingTime == " "  && $closingTime == " " ) {
                       echo "Open 24 Hours";
                   }

                   // show the checkout button
                   else {
                      $s = $status[0];
                   }
               }

               else
               {
                   $s = $status[5];
               }

               if ( $cd  == 2) {

               $timenow =     date("H:i:s", time());
               $wopeningTime = date( $row_DetailRS1['tueO'] );
               $closingTime = date( $row_DetailRS1['tueC'] );
               $openingSoon = date('H:i:sA', strtotime($openingTime)-3600);
               $closingSoon = date('H:i:sA', strtotime($closingTime)-3600);
               $curDay = date('l');

               if ($timenow < $openingSoon || $timenow > $closingTime ) {
                       $s = $status[1];
                   }

                   elseif  ($timenow > $openingSoon && $timenow < $openingTime ) {
                       $s = $status[2];
                   }

                   elseif  ($timenow > $closingSoon && $timenow < $closingTime ) {
                       $s = $status[3];
                   }

                   elseif  ($openingTime == " "  && $closingTime == " " ) {
                       echo "Open 24 Hours";
                   }

                   // show the checkout button
                   else {
                      $s = $status[0];
                   }
               }

               else
               {
                   $s = $status[5];
               }

                if ( $cd  == 3) {

               $timenow =     date("H:i:s", time());
               $openingTime = date( $row_DetailRS1['wedO'] );
               $closingTime = date( $row_DetailRS1['wedC'] );
               $openingSoon = date('H:i:sA', strtotime($openingTime)-3600);
               $closingSoon = date('H:i:sA', strtotime($closingTime)-3600);
               $curDay = date('l');

             if ($timenow < $openingSoon || $timenow > $closingTime ) {
                       $s = $status[1];
                   }

                   elseif  ($timenow > $openingSoon && $timenow < $openingTime ) {
                       $s = $status[2];
                   }

                   elseif  ($timenow > $closingSoon && $timenow < $closingTime ) {
                       $s = $status[3];
                   }

                   elseif  ($openingTime == " "  && $closingTime == " " ) {
                       echo "Open 24 Hours";
                   }

                   // show the checkout button
                   else {
                      $s = $status[0];
                   }
               }

               else
               {
                   $s = $status[5];
               }

                  if ( $cd  == 4) {

               $timenow =     date("H:i:s", time());
               $openingTime = date( $row_DetailRS1['thurO'] );
               $closingTime = date( $row_DetailRS1['thurC'] );
               $openingSoon = date('H:i:sA', strtotime($openingTime)-3600);
               $closingSoon = date('H:i:sA', strtotime($closingTime)-3600);
               $curDay = date('l');

             if ($timenow < $openingSoon || $timenow > $closingTime ) {
                       $s = $status[1];
                   }

                   elseif  ($timenow > $openingSoon && $timenow < $openingTime ) {
                       $s = $status[2];
                   }

                   elseif  ($timenow > $closingSoon && $timenow < $closingTime ) {
                       $s = $status[3];
                   }

                   elseif  ($openingTime == " "  && $closingTime == " " ) {
                       echo "Open 24 Hours";
                   }

                   // show the checkout button
                   else {
                      $s = $status[0];
                   }
               }

               else
               {
                   $s = $status[5];
               }

                  if ( $cd  == 5) {

               $timenow =     date("H:i:s", time());
               $wopeningTime = date( $row_DetailRS1['friO'] );
               $closingTime = date( $row_DetailRS1['friC'] );
               $openingSoon = date('H:i:sA', strtotime($openingTime)-3600);
               $closingSoon = date('H:i:sA', strtotime($closingTime)-3600);
               $curDay = date('l');

               if ($timenow < $openingSoon || $timenow > $closingTime ) {
                       $s = $status[1];
                   }

                   elseif  ($timenow > $openingSoon && $timenow < $openingTime ) {
                       $s = $status[2];
                   }

                   elseif  ($timenow > $closingSoon && $timenow < $closingTime ) {
                       $s = $status[3];
                   }

                   elseif  ($openingTime == " "  && $closingTime == " " ) {
                       echo "Open 24 Hours";
                   }

                   // show the checkout button
                   else {
                      $s = $status[0];
                   }
               }

               else
               {
                   $s = $status[5];
               }

                  if ( $cd  == 6) {

               $timenow =     date("H:i:s", time());
               $wopeningTime = date( $row_DetailRS1['satO'] );
               $closingTime = date( $row_DetailRS1['satC'] );
               $openingSoon = date('H:i:sA', strtotime($openingTime)-3600);
               $closingSoon = date('H:i:sA', strtotime($closingTime)-3600);
               $curDay = date('l');

               if ($timenow < $openingSoon || $timenow > $closingTime ) {
                       $s = $status[1];
                   }

                   elseif  ($timenow > $openingSoon && $timenow < $openingTime ) {
                       $s = $status[2];
                   }

                   elseif  ($timenow > $closingSoon && $timenow < $closingTime ) {
                       $s = $status[3];
                   }

                   elseif  ($openingTime == " "  && $closingTime == " " ) {
                       echo "Open 24 Hours";
                   }

                   // show the checkout button
                   else {
                      $s = $status[0];
                   }
               }

               else
               {
                   $s = $status[5];
               }

                  if ( $cd  == 7) {

               $timenow =     date("H:i:s", time());
               $wopeningTime = date( $row_DetailRS1['sunO'] );
               $closingTime = date( $row_DetailRS1['sunC'] );
               $openingSoon = date('H:i:sA', strtotime($openingTime)-3600);
               $closingSoon = date('H:i:sA', strtotime($closingTime)-3600);
               $curDay = date('l');

               if ($timenow < $openingSoon || $timenow > $closingTime ) {
                       $s = $status[1];
                   }

                   elseif  ($timenow > $openingSoon && $timenow < $openingTime ) {
                       $s = $status[2];
                   }

                   elseif  ($timenow > $closingSoon && $timenow < $closingTime ) {
                       $s = $status[3];
                   }

                   elseif  ($openingTime == " "  && $closingTime == " " ) {
                       echo "Open 24 Hours";
                   }

                   // show the checkout button
                   else {
                      $s = $status[0];
                   }
               }

               else
               {
                   $s = $status[5];
               }

    $m = $datetime->format('N');

      $html .= "
";
      $html .= "". $datetime->format('l')."	";
      $html .= "   	";
      $html .= "".$times[$m]."	";
       $html .= "   	";
      $html .= "".$s."	";
      $html .= "
";

      $datetime->add(new \DateInterval('P1D'));

      $i++;

  endforeach;
  $html .= "
";
  echo $html;

 ?>

A: Instead of putting strings into $time, put the open and close times for each day. Then you can use it in the loop to compare with the current time.
Also, the variable that just apply to the current time should be set outside the loop, since they don't change.
$times = array(
    1 => array('day' => 'Monday', 'open' => date( $row_DetailRS1['monO'] ), 'close' => date( $row_DetailRS1['monC'] ),
    2 => array('day' => 'Tuesday', 'open' => date( $row_DetailRS1['tueO'] ), 'close' => date( $row_DetailRS1['tueC'] ),
    3 => array('day' => 'Wednesday', 'open' => date( $row_DetailRS1['wedO'] ), 'close' => date( $row_DetailRS1['wedC'] ),
    4 => array('day' => 'Thursday', 'open' => date( $row_DetailRS1['thurO'] ), 'close' => date( $row_DetailRS1['thurC'] ),
    5 => array('day' => 'Friday', 'open' => date( $row_DetailRS1['friO'] ), 'close' => date( $row_DetailRS1['friC'] ),
    6 => array('day' => 'Saturday', 'open' => date( $row_DetailRS1['satO'] ), 'close' => date( $row_DetailRS1['satC'] ),
    7 => array('day' => 'Sunday', 'open' => date( $row_DetailRS1['sunO'] ), 'close' => date( $row_DetailRS1['sunC'] ) );

Then you can combine all those if statements into a single block.
$cd = $datetime->format('N'); // don't add 4

$timenow =     date("H:i:s", time());
$curDay = date('l');

// Create an array of day numbers that start with current day and loops around
$day_order = array_merge(range($cd, 7), range(1, $cd-1));

foreach ($day_order as $daynum) {
    $oc = $times[$daynum];
    $openingTime = $oc['open'];
    $closingTime = $oc['close'];
    $openingSoon = date('H:i:sA', strtotime($openingTime)-3600);
    $closingSoon = date('H:i:sA', strtotime($closingTime)-3600);
    if ($cd == $daynum) {
        if ($openingTime == ' ' && $closingTime == ' ') {
            $s = 'Open 24 hours';
        elseif ($timenow < $openingSoon || $timenow > $closingTime ) {
            $s = $status[1];
        }
        elseif  ($timenow > $openingSoon && $timenow < $openingTime ) {
            $s = $status[2];
        }
        elseif  ($timenow > $closingSoon && $timenow < $closingTime ) {
            $s = $status[3];
        } else {
            $s = $status[0];
        }
    } else {
        $s = " ";
    }

    $html .= "
";
    $html .= "". $oc['day']."	";
    $html .= "   	";
    $html .= "".$openingTime." ".$closingTime."	";
    $html .= "   	";
    $html .= "".$s."	";
    $html .= "
";

}


text:
Q: AngularJS: Display one specific object in an array at a time I want to display only one specific object from this JSON array at a a time:
{"records":[
   {"Name":"Pogrom wichra - Ole\u015bnica ","Desc":"Dystans: ok 7km (bieg w stylu poligonu s\u0142u\u017cb specjalnych Polski) Trasa: woda, b\u0142oto, trz\u0119sawisko, g\u0119ste zaro\u015bla, przeszkody naturalne i sztuczne http:www.pogromwichra.pl","Image":"9833.jpg"},
   {"Name":"Bieg herosa ? Pustynia B\u0142\u0119dowska","Desc":"Dystans: opcja do wybrania 9 km, 10kmp\u0142aski lub z przeszkodami, bieg 3 i 9 godzinny Trasa: piasek, piasek, piasek, wzniesienia, przeszkody naturalne i sztuczne www.biegherosa.pl","Image":"6273.jpg"},
   {"Name":"Dycha na 5 ? Pi\u0105tkowice (ko\u0142o Pabianic)","Desc":"Dystans: 10km z niespodziank\u0105 Trasa: nawierzchnia utwardzona ok. 5%, drogi i \u015bcie\u017cki gruntowe 95%. Na trasie do pokonania tor motokrosowy z ostrymi podbiegami i zbiegami po nier\u00f3wnym pod\u0142o\u017cu. Obcinek bardzo trudny technicznie. www.koronapabianice.pl ","Image":"5383.jpg"},
   {"Name":"Bieg rze\u017aniczka (ma\u0142y rze\u017anik) ? Cisna (Bieszczady)","Desc":"Dystans: ok. 27km Trasa: do\u015b\u0107 trudna trasa g\u00f3rska, chocia\u017c przepi\u0119kna i malownicza www.biegrzeznika.pl\/rzezniczek\/","Image":"4640.jpg"},
   {"Name":"Runmageddon ? wiele miast w Polsce","Desc":"Dystans: 6, 12, 21km Trasa: woda, b\u0142oto, ogie\u0144, bagno, przeszkody linowe, sko\u015bne i pionowe \u015bciany, zasieki, okopy www.runmageddon.pl","Image":"7378.jpg"},{"Name":"GROM CHALLENDE - SI\u0141A I HONOR - O\u015brodek Szkolenia Poligonowego GROM Gr","Desc":"Dystans: 20km Trasa: mega wyczerpuj\u0105ca, jest tam wszystko o czym by\u015b pomy\u015bla\u0142 ?. Start tylko zespo\u0142owy (2-osobowy), limit czasowy 5 godzin","Image":"8815.jpg"},
   {"Name":"Biegowa bitwa o \u0141\u00f3d\u017a - \u0141\u00f3d\u017a ","Desc":"Dystans: ok.13km Trasa: woda, b\u0142oto, trz\u0119sawisko, g\u0119ste zaro\u015bla, przeszkody naturalne i sztuczne facebook.com\/bitwaolodz","Image":"7019.jpg"},
   {"Name":"Bieg po wygas\u0142ych wulkanach -Z\u0142otoryja","Desc":"Dystans: 13-14km Trasa: Trasa ekstremalna w terenie zalesionym, b\u0142oto, rowy melioracyjne, trz\u0119sawisko, dno jeziora, przeszkody sztuczne i naturalne, strome podbiegi. www.biegwulkanow.pl","Image":"8465.jpg"}
]}

In my Javascript file, I only put the object on the scope.
$http.get("link/to/my/json/file").success(function (response) {
    $scope.recommends = response.records;
});

Finally, my HTML looks more or less like this:

{{recomended.Name}}

{{recomended.Desc}}

All I want to do is to display a single record at time, and then change it by clicking on some button on the page.

A: using ng-click, you can call a setter function on the controller to store the selected recomended item in a variable
then using ng-show decide if should display the additional data ( only when the current recomended object equals to the selected one )
http://jsfiddle.net/kcbxg14p/1/
js
angular.module('app', [])
    .controller('TodoCtrl', function ($scope) {

    $scope.setSelectedItem = function (item) {
        $scope.selectedItem = item;
    };

    $scope.recommends = [{
        "Name": "Pogrom wichra - Ole\u015bnica ",
            "Desc": "Dystans: ok 7km (bieg w stylu poligonu s\u0142u\u017cb specjalnych Polski) Trasa: woda, b\u0142oto, trz\u0119sawisko, g\u0119ste zaro\u015bla, przeszkody naturalne i sztuczne http:www.pogromwichra.pl",
            "Image": "9833.jpg"
    },
    ...
    ];

});

html

         Click to view {{recomended.Name}}

{{recomended.Name}}

{{recomended.Desc}}

A: If you want to show only one recommend at a time, why looping?
Following the Angular philosophy, you should declare what to show already in the page. In this case
{{recommend}}

where [[Controller]].recommend is a variable exposed from the relative controller, should be enough.
Leaving out the fetching part, assuming [[Controller]].records is already a list of objects, then

    {{Ctrl.recommend}} - >

and
angular.module(<your module name here>)
    .controller("MainCtrl", [function () {
        var self = this;
        self.records = [ ... ];
        self.recommend = records[0];
        self.currentIndex = 0;
        self.setNextRecord = function () {
            var nextIndex = currentIndex < self.currentIndex - 2 ? currentIndex + 1 : 0;
            self.currentIndex = nextIndex;
            return self.recommend = records[self.currentIndex];
        };
    }]);

WARNING, I couldn't test the code.


text:
Q: NSURLProtocol not responding to UIWebviews I am having an issue with UIWebviews and a couple of custom NSURLProtocols that I have in my app.
All my non web view request are invoked with NSURLSession, so in order for those request to go through the protocols I need to set the setProtocolClasses array on my sessionconfig, at this point everything works as expected.
For my web views, I do a registration on the didFinishLaunchingWithOptions: method in the AppDelegate with the [NSURLProtocol register class[MyProtocol Class]]. If i don't re-register before the execution of the web view request, that web view request won't go through the protocol.
Do you guys have any idea why I have to re-register to my custom protocol every time I try to load a web view request?

A: What is the request URL?  Is it possible that there's another protocol class that gets registered after you?  Does canInitWithRequest get called on your class at webview request time?


text:
Q: Rotating logs generated by a process that logs to stdin I have a long running process, that writes its log file to stdout. I would like to save this output to different files, automatically maintain these files (like deleting/archiving the old ones), without restarting the main process.
On solution would be to send the output to a file (process > log.txt), and use logrotate on it, but logrotate needs to restart the program, which is not possible.
The other one is to pipe the output to cronolog (process | cronolog), but in this case older files won't get deleted / archived, meaning I have to make a program that will do the maintenance for me.
The best would be to be able to use both utilities, because with cronolog I don't need to restart the process, and logrotate will maintain the old log files exactly as I want. Is there a way to get these two programs to work with each other? If not, what is a good solution to this problem?

A: Multilog from DJB's daemontools can do (almost) exactly what you are asking. The only downside that I am aware of is that not many distributions carry a package for daemontools.
If you are not managing your application with svc (part of the daemontools) you will have to find a way to pipe the output to a command like
multilog t s1048576 n100 ./my_log_directory

This translates to:

*

*t: insert a tai64n timestamp (that can be translated to readable time with tai64nlocal)

*s1048576: rotate the log file when it grows to 1MiB

*n100: keep no more than 100 rotated files

*./my_log_directory: anything starting with . or / - write the log to that directory

The log that is written will have the filename current, and when multilog rotates the log, it will be renamed to @<tai64n timestamp>.s where the filename shows the time when the file was rotated. The extension can be .s if the file was safely flushed, or .u if it may have been truncated.
For more info, just check the links.
Update:
svlogd from runit is a replacement for multilog with similar command line usage.
s6-log from s6 is another fork with more features and compatible command line usage.


text:
Q: Why does addEventListener accumulate in useEffect hook? Functionality: entering text into input, creating a list by pressing enter.
https://codesandbox.io/s/awesome-tereshkova-96pf3?file=/src/App.js
I have two addEventListeners. One is outside of any hooks, the other in useEffect.

*

*What is the logic behind the EventListener outside the hooks? Why does it behave so?

*Why is the number of clicks doubled when I click on a list item?

*What feature does addEventListener have that causes it to be accumulated in the useEffect hook and need to be cleaned up? Why does console.log (), for example, not accumulating?

A: so your first of all, think of your React components as functions that are called over and over again on each render.
So in your case your first eventListener registered outside of useEffect
document.addEventListener("click", () => console.log("foo"));
this is called every time your component is rendered => in other words, every time your component rerenders new event listener is registered. In your case this happens in this order

*

*User types 1 letter to input box

*setTodoTitle is called with new value => this causes react to update your components

*new event listener is registered because of rerender

Your second case is a little bit different, cuz you register your event listener in useEffect. Function passed (first param) to useEffect is called only when some variable from dependency array (second param) changes. So in your case useEffect is called only when todos change => after you add new todo on Enter click. You correctly use cleanup function (return {...}) in useEffect. React performs the cleanup when the component unmounts. ... This is why React also cleans up effects from the previous render before running the effects next time [react docs]

*

*component mounts for first time

*useEffect is called, because todos didn't exist before and now its set to []

*you add new todo

*useEffect triggers again, because todos changed


text:
Q: Missing MOSS 2007 Functionality? I've installed MOSS 2007 a number of times, but I always run into the same problem.  The installation goes just fine, but MOSS seems to be missing functionality.
In the Administration page, clicking the 'OK' button in Create or Extend a Web Application does absolutely nothing.  Also, clicking certain links evoke no response either.  I think something is wrong with my setup.  All of the links that do not work display javascript in the bottom-left of the browser.  I'm not sure if that has anything to do with it.
I'm running MOSS 2007 on Windows Server 2003.

A: Have you tried adding the SharePoint Central Administration site to your Trusted Sites in IE?


text:
Q: TestNG [6.9.12] fails to load in Eclipse Mars [4.5.2] -- org.eclipse.core.runtime.CoreException Expected behaviour
Should be possible to launch test via Run As -> TestNG ; also
should be able to add new Run configuration for TestNG
Actual behaviour
Plug-in org.testng.eclipse was unable to load class org.testng.eclipse.launch.TestNGTabGroup.
Exception:org.eclipse.core.runtime.CoreException: Plug-in org.testng.eclipse was unable to load class org.testng.eclipse.ui.TestNGQuickFixProcessor.
cannot be found by org.testng.eclipse_6.9.12.201607091356
Exception:org.eclipse.core.runtime.CoreException: Plug-in org.testng.eclipse was unable to load class org.testng.eclipse.ui.TestNGQuickFixProcessor.
Steps to reproduce
Install Eclipse Mars-2, 4.5.2
Install TestNG plugin from the Marketplace
Select an executable class
Attempt to "Run As TestNG"
Attempt to Run -> Run Configurations -> TestNG -> New
Running Configuration
Plugin Version: 6.9.12 [via eclipse marketplace]
(Optional) Operating System: Windows-10

A: An issue already exists on the project: https://github.com/cbeust/testng-eclipse/issues/272


text:
Q: Access VBA: The Command or Action 'SaveRecord' isn't available now In my Access form I have a Save button that executes the following command:
DoCmd.RunCommand acCmdSaveRecord

sometimes it happens that I get the error:
The Command or Action 'SaveRecord' isn't available now

I actually don't know why. In these cases, I use to close and reopen the Access file a couple of times and then it works.
Can someone explain to me why this happens?
UPDATE
Well, now I have the same problem with the Copy command:
    DoCmd.RunCommand acCmdSelectRecord
    DoCmd.RunCommand acCmdCopy
    DoCmd.RunCommand acCmdRecordsGoToNew
    DoCmd.RunCommand acCmdSelectRecord
    DoCmd.RunCommand acCmdPaste

The same error message:
The Command or Action 'Copy' isn't available now


text:
Q: Naively showing that $A_n$ mod a nontrivial normal subgroup is abelian. Suppose $H \lhd A_n$ is a nontrivial normal subgroup of the alternating group on $n$ letters. Without using the fact that $A_n$ is simple, prove that $A_n/H$ is abelian.
Can this be done?
I will allow use of the fact that the commutator subgroup of $A_n$ is $A_n$.


text:
Q: numpy roots() returns false roots I'm trying to use numpy to find the roots of some polynomials, but I am getting some erroneous results:
>> poly = np.polynomial.Polynomial([4.383930e+00, 2.277144e+14, -7.008406e+25, -4.258004e+16])
>> roots = poly.roots()
>> roots
array([-1.64593692e+09, -1.91391398e-14,  3.26830022e-12])
>> poly(roots)
array([-3.74803539e+23, -7.99360578e-15, -1.89182003e-13])

What is up with the false root -1.64593692e+09 which results in -3.74803539e+23? This is clearly not a root.
Is this the result of floating-point errors? or something else?..
And more importantly;

Is there a way to get around it?

..perhaps something I can tweak, or a different function I can use?. Any help is much appreciated.
I found this and this previous question which seemed to be related, but after reading them and the answers/comments I don't think that they are the same problem.

A: The root appears real:
x = np.linspace(-2e9, 1000, 10000)
plt.plot(x, poly(x))

The problem is that the scale of the data is very large. -3e23 is tiny compared to say 6e43. The discrepancy is caused by roundoff error. Third order polynomials have an analytical solution, but it's not going to be numerically stable when your domain is on the order of 1e9.
You can try to use the domain and window parameters to attempt to introduce some numerical stability. For example, a common choice of domain is something that envelops your entire dataset. You would have to adjust the coefficients to compenstate, since those values are usually used for fitting data.

A: First of all, computing the roots of a polynomial is a classically ill-conditioned problem, meaning (roughly) that no matter what algorithm you use to solve it, small changes in the coefficients of many polynomials can lead to huge changes in their roots. That means we should be a little careful not to place an extraordinary amount of faith in root-finding results in general, and that perhaps that we shouldn't be too surprised when a root finder gives weird results. There's a pretty good example on Wikipedia, Wilkinson's polynomial, that shows how things can go wrong.
In this instance, the coefficients of the polynomial of interest are of such different magnitudes that it's not surprising that the results seem poor. But consider this: if our original polynomial is p() and it has a root x, then p(x) = 0, but also c*p(x) = 0 for any constant c. In other words, we can scale the coefficients without changing the roots, so happen if we normalized the polynomial by dividing by the coefficient of largest magnitude, 7e25?

*

*Original polynomial: p(x) = 4.4 + 2.3e+14*x - 7.0e25*x**2 - 4.3e16*x**3

*Scaled polynomial: p(x) = 6.3e-26 + 3.2e-12*x - x**2 - 6.1e-10*x**3
So for this polynomial, the largest coefficient ~7e25 is so huge that the smallest coefficient ~4.4 is essentially negligible. That should give us a hint that what counts as zero in a root finding iteration isn't what we would normally consider "small."
The short answer is that the root calculated by NumPy isn't perfect, but it is an estimate of an actual root. Here's some code to convince us.
>>> import numpy as np

>>> coefs = np.array([4.383930e+00, 2.277144e+14, -7.008406e+25, -4.258004e+16])
>>> coefs_normed = coefs / np.abs(coefs).max()
>>> coefs_normed
array([ 6.25524549e-26,  3.24916108e-12, -1.00000000e+00, -6.07556697e-10])

>>> poly = np.polynomial.Polynomial(coefs)
>>> roots = poly.roots()
>>> roots
array([-1.64593692e+09, -1.91391398e-14,  3.26830022e-12])
>>> poly(roots)
array([-3.74803539e+23,  8.43769499e-14, -1.89182003e-13])

>>> poly_normed = np.polynomial.Polynomial(coefs_normed)
>>> roots_normed = poly_normed.roots()
>>> roots_normed
array([-1.64593692e+09, -1.91391398e-14,  3.26830022e-12])
>>> poly_normed(roots_normed)
array([-5.34791419e-03,  1.20534089e-39, -2.11221641e-39])

Now, -5e-03 is not very close to machine epsilon, but that should convince us that maybe the calculated root isn't quite as bad as it seemed at first.
A final point: the np.polynomial.Polynomial class has domain and window arguments that determine how it does its computations. Since polynomials get absolutely huge as the domain tends to +infinity or -infinity, it's unrealistic to expect accurate calculations for a value around 10^9.


text:
Q: Conditional grouping in a pivoty query mysql My schema looks like,
CREATE TABLE `test` (
  `Id` int(11) NOT NULL,
  `CategoryName` varchar(45) DEFAULT NULL,
  `type` varchar(40) DEFAULT NULL,
  `value` decimal(15,4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

INSERT INTO `test`
(`Id`,
`CategoryName`,
`type`,
`value`)
VALUES
(1 ,'Allowance' ,'ADDITION',4000),
(1,'Salary' ,'ADDITION',1500),
(1,'Telephone' ,'ADDITION',200),
(1,'Other' ,'ADDITION',500),
(1,'Fine' ,'DEDUCTION',500),
(1,'Other Deduction' ,'DEDUCTION',500),
(1,'Salary Deduction' ,'DEDUCTION',100),
(2,'Salary' ,'ADDITION',300),
(2,'Other' ,'ADDITION',1300)
;

The requirement is to show certain categories summed up and others as is. In this case Salary & Allowance to be shown on their own columns, while any other addition type to be summed up. Same applies to the deduction type.
select Id,MAX(CASE
        WHEN CategoryName = 'Salary' THEN pi.value
        ELSE 0
    END) AS 'Salary',
    MAX(CASE
        WHEN CategoryName = 'Allowance' THEN pi.value
        ELSE 0
    END) AS 'Allowance',
    MAX(CASE when pi.type = 'ADDITION' THEN
    CASE
        WHEN CategoryName not in ('Salary','Allowance') THEN pi.value -- sum(pi.value)
        ELSE 0
        END
    END) AS 'Other Allowances',
    MAX(case WHEN CategoryName = 'Fine' THEN pi.value -- sum(pi.value)
        ELSE 0
    END) AS 'Fine' ,
     MAX(CASE when pi.type = 'DEDUCTION' THEN
    CASE
        WHEN CategoryName not in ( 'Fine') THEN pi.value -- sum(pi.value)
        ELSE 0
        END
    END) AS 'Other Deductions'
     from  test pi group by Id;

Now when i put sum(pi.value) I get error Error Code: 1111. Invalid use of group function. Without the sum function the max is returning the max value only and ignoring the rest, like the Telephone addition, which is as expected.
Id  Salary      Allowance   Other Allowances    Fine     Other Deductions
1   1500.0000   4000.0000    500.0000          500.0000    500.0000
2   300.0000    0.0000       1300.0000          0.0000      *null*

So the Other Allowance column for id 1 should show 700 i.e. 500 (Other) + 200 (Telephone)
What would be the right way to get the sum in this case while using the pivot query ?
dbfiddle


text:
Q: Do we need to split the data for Unsupervised Anomaly Detection? I'm struggling with understanding the concept of splitting data for unsupervised anomaly/outlier detection. You can find all approaches here. I found some papers and implementations that didn't split the data in their analysis or evaluate their algorithm:

*

*Unsupervised Anomaly Detection:XBOS/HBOS/IForest

*Histogram-based Outlier Score (HBOS):
A fast Unsupervised Anomaly Detection
Algorithm
I also found some other implementations of the splitted data in their analysis:

*

*Testing Isolation Forest on Non-Financial Data - 2 KDDCUP99 Sets

*Is train/test-Split in unsupervised learning of neural network necessary?
The questions are:

*

*Why should I split or not split my datasets when I apply unsupervised anomaly/outlier detection?

*What is the advantage or disadvantage of both approaches?

*The result(accuracy: AUC or AP, FP) of detection should be the same whether I split the data (e.g., 70%train-30%test) or un-cut data?

Generally, Unsupervised outlier detection algorithms (e.g. IsolationForest, HBOS) predict outliers based on their outlier scores over unlabeled data.
Suppose I split the data (e.g., 70%train-30%test including startify, there is still somehow a possibility of neglecting/missing the possible outliers exist the trainset, while the model results reflect based on test-set observations at the end of the day (there is no guaranty). On the other hand, it might be the case that the final evaluation would not be fair. please see this post
In my case, I want to apply some algorithms on famous outlier detection datasets/benchmark without labels/target column and although the labels are there BUT not for being used, a bit confusing, it is more to validate & plotting purposes the approaches afterwards to compare different detection models with my own built algorithm.
Please see the Pythonic code after dopping the labels exist in name_target:
X, y = df.loc[:, df.columns!= name_target], df[name_target]
seed = 120
test_size = 0.3
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=test_size,
                                                    random_state=seed,
                                                    stratify=y)

A: The splitting of datasets is used to give an estimate of generalized performance, and is used for predictive models - models that are designed to take new datapoints and output new predictions for them.
Predictive models can be made using supervised learning (most common for classification and regression), unsupervised learning (common for anomaly detection) or combinations of unsupervised and supervised learning (semi-supervised, self-supervised etc).
So, whenever you are making a predictive model - use train/validation/test splits.
And also note that even if applying unsupervised learning, it is extremely useful to have labeled validation and test sets - because the labels are key to most meaningful performance metrics.
Note: Sometimes unsupervised learning methods are used for models which are not designed to be predictive models. Common example are (a) clustering when used for example for Explorative Data Analysis, or (outlier detection when used for cleaning a particular dataset. In these cases we only care how the models work on a given dataset, and not on new data - and the dataset splitting is not needed.


text:
Q: Object expected, javascript error Please check out this code? why do i get object xpected error? Thank you...
 var object_url = "http://test.com/flash/custom-freechat/";
        var param_url = "category=boy&subcategory=18_22&tags=boy,18_22&ismember=false&appletbrand=jasmin&subbrand=livejasmin&size=1&appletcol=&txtcolor1=&txtcolor2=&txtcolor3=&txtcolor4=&txtcolor5=&txtcolor6=&txtcolor7=&txtcolor8=&txtcolor9=&txtcolor10=&membcol=&guestcol=&asc=GGGGGG&lowCamFeed=false&muteAudio=false&as=0111111011110010&ato=0&isproxy=1&sessionid=572e1f4258ca212116c2ea18de9ddee0&appletroot=" + object_url + "&appletlang=appletlang.xml&appletservers=servers069.xml&freeskin=appletskin.swf&appleturls=appleturls020.xml&appletstream=sharevideo_livejasmin009.swf&tipAnim=3.swf&nxt=exit_chat&performerid=TooHotJack&type=40&serverid=inner4q7opo85n9f0d5q7o4psli6e2712msv9&psid=awempire&pstour=t1&psprogram=REVS&pstool=&isad=true&livefeed=livefeed&issb=1&nodeid=HUBUD&memberip=109.71.162.34@583a56ac26afb30b952b3e0ea39bf66f&proxyip=109.71.162.193:8080&";

        function init() {
            document.getElementById('object_container').innerHTML = "<object width=\"710px\" height=\"284px\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" id=\"flash\"><param value=\"" + object_url + "memberchat001.swf\" name=\"movie\"><param value=\"high\" name=\"quality\"><param value=\"always\" name=\"AllowScriptAccess\"><param value=\"\" name=\"bgcolor\"><param value=\"" + param_url + "\" name=\"FlashVars\"><embed width=\"710px\" height=\"284px\" flashvars=\"" + param_url + "\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" quality=\"high\" bgcolor=\"\" allowscriptaccess=\"always\" src=\"" + object_url + "memberchat001.swf\"></object>";
        }

        window.onload = init;

I call this script like this: I cannot edit the script cause it's from another server, an affiliate program. I can edit only the way i call it, which is displayed below:

**

**

A: The most likely problem is that there's no element on the page with the "id" value "object_container".

A: window.onload does not mean that the DOM is ready on all browsers. As you tagged your question jquery, replace it with
$(document).ready(function(){
    $('div#object_container').html('your string to set innerHTML');
});

A: Maybe there is anything blocked by antivirus-software. If I take a short fragment out of the object_url and search for it on google there are a couple of results depending on  malware: google: /flash/custom-freechat/

A: Is this code on a page with other code on it? The script may be overwriting window.onload after another script on your page does, and then another of the other script's event handlers may be failing because the necessary window.onload handler did not run. If that is the case, putting this script before the affiliate script would probably fix the page:
if(window.addEventListener) {
    window.onload && window.addEventListener('load', window.onload, false);
} else {
    window.onload && window.attachEvent('onload', window.onload);
}
window.onload = null;

Another possibility is that the init function conflicts in name with another script on the same page. If that's the case, there's no other option than loading the affiliate script in a separate document in an iframe (or fixing the other script that is on the page).

A: Webmasters ,
How come javascript scr has php
src="http://live-cams-1.livejasmin.com/fca/scripts.php?

can you fix this first.
and next do a null check on object_container.


text:
Q: Oracle : 'Count over Partition by' output on first row of the keyword alone I have to query a table which will look like as follows.
select count(*) over (PARTITION BY offer_status) as count, name, status
from tablename

Output will be as:
3  |  name1  |  entered
3  |  name1  |  entered
3  |  name2  |  cleared
1  |  name3  |  completed
3  |  name3  |  cleared
3  |  name1  |  entered
3  |  name2  |  cleared

I would like to get it as :
3  |  name1  |  entered
    |  name3  |  entered
3  |  name2  |  cleared
1  |  name3  |  completed
    |  name3  |  cleared
    |  name3  |  entered
    |  name3  |  cleared

To get the count of status only for the first occurance of the keyword (of status), as it is not necessary to get the count again and again.

Or you can suggest me any other way to get it done.

A: I would do something like:
SELECT CASE WHEN rn=1 THEN cnt END cnt, order_name, status
FROM
(
SELECT count(*) OVER (PARTITION BY status) cnt,
  ROW_NUMBER() OVER (PARTITION BY status ORDER BY order_name) rn,
  order_name,status
FROM input_table
)

See SQL Fiddle
As Gordon Linoff said, you need some sort of ordering. I ordered them by order_name but if you have some other field in the table you could use that instead.


text:
Q: MongoDB multiple update isolation I'm confused about how MongoDB updates works.
In the following docs: https://docs.mongodb.com/manual/core/write-operations-atomicity/ says:

In MongoDB, a write operation is atomic on the level of a single
  document, even if the operation modifies multiple embedded documents
  within a single document.
When a single write operation modifies multiple documents, the
  modification of each document is atomic, but the operation as a whole
  is not atomic and other operations may interleave.

I guess it means: if I'm updating all fields of a document I will be unable to see a partial update:

*

*If I get the document before the update I will see it without any change

*If I get the document after the update I will see it with all the changes

For a multiple elements the same behavior happens for each document. I guess we could say there is a transaction for each document update instead of a big one for all of them.
But let's say there are a lots of documents on the multiple update, and it takes a while to update all of them. What happen with the queries by other threads during the update?

*

*They will see the old version? Or they will be blocked until the update finishes?

*Other updates to same documents are possible during this big update? If so, could this intermediate update exclude some document from the big update?

A:
They will see the old version? Or they will be blocked until the update finishes?

I guess other threads may see the old version of a document or the new, depending on whether they query the document before or after the update is finished, but they will never see a partial update on a document (i.e. one field changed and another not changed).

Other updates to same documents are possible during this big update? If so, could this intermediate update exclude some document from the big update?

Instead of big or small updates, think of 2 threads doing an update on the same document. Thread 1 sets fields {a:1, b:2} and thread 2 sets {b:3, c:4}. If the original document is {a:0, b:0, c:0} then we can have two scenarios:
Update 1 is executed before update 2:
The document will finally be {a:1, b:3, c:4}.
Update 2 is executed before update 1:
The document will finally be {a:1, b:2, c:4}.


text:
Q: How can I rename files to have a single quote? I have multiple files on my Ubuntu system that are spread across web root folder /var/www with broken names:
GermanyXXXs-enchanting....

I want to replace XXX with an apostrophe ' to have the following output:
Germany's-enchanting....

The following command works with regular characters but not with quotes, even if I escape it:
find /var/www/html -name '*XXX*' -exec bash -c ' mv $0 ${0/XXX/\'}' {} \;

A: In Bourne-like shells, you can't have single quotes inside single quoted strings, they needs to be quoted some other way, whether that's with \', "'", $'\''...
Also remember that in bash, parameter expansions must be quoted with double quotes at least when in list contexts such as in arguments to commands.
When renaming recursively, you also need to make sure files are renamed depth-first and make sure you only rename the basename part of the file (not the directory components)
find /var/www/html -depth -name '*XXX*' -execdir bash -c '
  ret=0
  for file do
    mv -- "$file" "${file/XXX/\'\''}" || ret=$?
  done
  exit "$ret"' bash {} +

Here quoting ' as \' outside of the '...'.
$file was quoted as "$file" as it's in list context to avoid split+glob. $? didn't need to be quoted as it's an assignment to a scalar (non-list/array) variable, though writing ret="$?" would not have harmed.
Beware -execdir (used here so that $file contains only the basename (possibly prefixed with ./ with some find implementations)) is a non-standard extension though is relatively widely supported these days.
With -execdir cmd {} + (+ instead of ;), some find implementations will try and call cmd with more than one file as argument when possible, but also and maybe more importantly that allows failures of cmd if any to be reported back in find's exit status.
Or you can use specialised batch-renaming tools. For instance, if using zsh instead of bash, you could use its zmv autoloadable function:
autoload -Uz zmv
zmv '(**/)(*XXX*)' '$1${2/XXX/'\''}'

Why takes all the above into account and also runs some sanity checks beforehand to avoid you losing data.
Beware it leaves hidden files alone. If you want them to be renamed, change it to:
zmv '(**/)(*XXX*)(#qD)' '$1${2/XXX/'\''}'

You can add the -n option to zmv for a dry-run.

A: Single quotes within a single quote pair can be escaped by closing the single quote, entering \', then restarting the single quote pair
echo 'It isn't hard'     # broken
echo 'It isn'\''t hard'  # fixed

which turns one broken string into the three units 'It isn' and \' and 't hard'. Another way to think about it: every ' within a '...' single quote must be replaced with '\''.


text: Q: How to import table's clob data type column along with other columns to Hadoop Have a table in oracle with total 11 columns, out of those 1 column data type CLOB. When we import table into hadoop,CLOB column datatype will get converted to string, But we want in a format where we can aceess values using attibute


text:
Q: Setting differing send and receive kernel buffer sizes What disadvantages (or advantages) are there to setting different values for a send and receive buffer on opposite sides of a connection? It seems to make the most sense (and the norm) to keep these values the same. But if one side (say the sender side) has the resources to double their buffer size, what implications could this have?
I guess a related question is, what disadvantages are there to setting a larger-than-required buffer size? From what I've read, it sounds like you could potentially overflow the receive buffer if your send buffer is larger. Additionally, it seems like there may not be a need to increase buffer sizes as long as your applications are keeping up with the load and can handle max-size messages. It doesn't necessarily mean you could handle more data throughput because you are still limited by the opposite endpoint. Is this correct?
The specific kernel settings in question are as follows:
net.core.wmem_max
net.core.rmem_max

A: a large buffer size can have a negative effect on performance in some cases. If the TCP/IP buffers are too large and applications are not processing data fast enough, paging can increase. The goal is to specify a value large enough to avoid flow control, but not so large that the buffer accumulates more data than the system can process

A: *

*A TCP send buffer size smaller than the receiver's receive buffer size will prevent you from using the maximum available bandwidth

*a UDP send buffer larger than the receiver's receive buffer size will prevent you from finding out at source about datagrams that are too large.

Neither of these problems is major, unless you're transmitting large amounts of data in the TCP case. In the UDP case you shouldn't attempt to send datagrams larger than 534 (or 576 or whatever that magic number is) anyway.


text:
Q: .net core bot DI error Unable to resolve service I'm am trying to follow Microsofts documentation how to add LUIS to my bot
so I created a BotServices class and in Startup.cs I am adding it to my service collection
    var connectedServices = new BotServices(botConfig);
    services.AddSingleton<BotServices>(sp => connectedServices);

and then I am injecting it into my MyBot class
  public MyBot(BotServices botServices)

but I get this error
System.InvalidOperationException: Unable to resolve service for type 'BotServices' while attempting to activate 'MyBot'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)

A: As you are instantiating the object yourself have you tried doing the following:
var connectedServices = new BotServices(botConfig);
services.AddSingleton<BotServices>(connectedServices);

i.e no need for the factory lambda which you have now (which is picking up a the local variable pointing to your instance ... maybe causes issues...

A: the problem with my code was that I registered the BotServices in the services.AddBot<IBot> call like this
Didn't work:
   services.AddBot<MyBot>(options =>
       {
          var botConfig = BotConfiguration.Load(botFilePath ?? @".\MyBot.bot", secretKey);
          services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded. ({botConfig})"));
          var connectedServices = new BotServices(botConfig);
          services.AddSingleton<BotServices>(sp => connectedServices);
       }

I did it like this because 'botConfig' variable is defined there by default when created with the empty bot template so I moved it out  and it works! (but I still can't explain why it shouldn't work)
Works
      var botConfig = BotConfiguration.Load(botFilePath ?? @".\MyBot.bot", secretKey);
      services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded. ({botConfig})"));
      var connectedServices = new BotServices(botConfig);
      services.AddSingleton<BotServices>(sp => connectedServices);
      services.AddBot<MyBot>(options =>
       {
           //all the bot configuration code
       }


text:
Q: How to map a value back to an enum? Given an enum where each instance is associated with some value:
public enum SQLState
{
  SUCCESSFUL_COMPLETION("00000"),
  WARNING("01000");

  private final String code;
  SQLState(String code)
  {
    this.code = code;
  }
}

How can I construct a Map for efficient reverse look-ups? I tried the following:
public enum SQLState
{
  SUCCESSFUL_COMPLETION("00000"),
  WARNING("01000");

  private final String code;
  private static final Map<String, SQLState> codeToValue = Maps.newHashMap();
  SQLState(String code)
  {
    this.code = code;
    codeToValue.put(code, this); // problematic line
  }
}

but Java complains: Illegal reference to static field from initializer. That is, the static Map is being initialized after all enum values so you cannot reference it from the constructor. Any ideas?

A: use:
static {
  for (SQLState sqlState : values()){
     codeToValue.put(sqlState.code, sqlState);
  }
}

A: As you are using Guava, i recommend using the following code:
public enum SQLState {

    SUCCESSFUL_COMPLETION("00000"),
    WARNING("01000"),
    ;

    private final String code;
    private SQLState(String code) {
        this.code = code;
    }

    public static final Function<SQLState,String> EXTRACT_CODE = new Function<SQLState,String>() {
        @Override
        public String apply(SQLState input) {
            return input.code;
        }
    };

    public static final Map<String, SQLState> CODE_TO_VALUE = ImmutableMap.copyOf( Maps.uniqueIndex(EnumSet.allOf(SQLState.class), EXTRACT_CODE) );

    public static void main(String[] args) {
        System.out.println( SQLState.CODE_TO_VALUE.get("00000") );
    }

}

This produces as expected: "SUCCESSFUL_COMPLETION"
Using static initializer is nice when you can't init the final variables inline, but in this case, with Guava, you really can, in a functionnal approach with Guava functions.
Furthermode, you make your list immutable in the same time which is nice if you need to expose it publicly
You can also make your list immutable with a static block but you need to fill a temporary list before initializing the final list.

Check the
Maps uniqueIndex documentation which is a really cool function of Guava that permits to index any object by any of its attribute.
In case many objects are sharing the same attribute value, you can use Multimaps.index which, for each key, will give you a list of objets having this attribute.

A: Initialize the static map in static{...} block before the constructor. Look up static initializer blocks.


text:
Q: prevent opening another the same tab in browser Let's say I have main.php and page1.html on my www apache server.
Part of main.php:
 ...

 ...
 <?php
  echo  "
start
";
 ?>

When I click link above, I have  opened two tabs: main.php and page1.html. And my aim is to prevent user opening another tab with page1.html, when he press link on main.php.
Or , when user click link on main.php, tab with page1.html should be refreshed, but new tab shouldn't be opened.
thanks in advance.

A: You can't control a browsers behaviour, and if you could, it would be highly frowned upon.  The user should always have full control over what tabs open where.  You could actually achieve this using AJAX and Cookies but mobile compatability would be a big headache.
I would recommend finding a way to solve your problem that keeps the user in control of their browser.

A: You can try it like this:

But now, this doesn't guarantee that it'll open in a new tab only. This will depend on the user's browser settings. By default it opens in a new tab, so it might work out for you!
Check and see if it helps!


text:
Q: Programmatically setting a silverlight multi-select list box Is it possible to programatically set the values of a silverlight list box when the selection mode is "multiple"?  The "SelectedItems" property is not settable,
and "SelectedIndex" only works when the selection mode is "single".

A: Add items to SelectedItems collection:
myListBox.SelectedItems.Clear();
foreach(var item in selection)
    myListBox.SelectedItems.Add(item);


text:
Q: How to continue save the history of validation loss in Keras Let say I want to train with 100 epoch. But after 50 epoch, I would like to save the model once every 5 epoch. I also would like to save the history as well. I wasn't sure how to do it, so I did something like below. Please let me know how to continue to save history.
history = model.fit(X_train, y_train, validation_split = 0.2, shuffle=True, batch_size=gb.BATCH_SIZE, epochs=50)

counters = gb.EPOCHS_COUNT  // 5

for counter in range(counters):
    history += model.fit(X_train, y_train, validation_split = 0.2, shuffle=True, batch_size=gb.BATCH_SIZE, epochs=5)
    modelName = "model_weights_total_0"+str(counter)+".h5"
    model.save(model_save_path+modelName, overwrite=True)

A: One way is to sum history.history values manually.
val_losses = []
for counter in range(counters):
    history = model.fit(X_train, y_train, validation_split = 0.2, shuffle=True, batch_size=gb.BATCH_SIZE, epochs=5)
    val_losses += history.history['val_loss']


text:
Q: How to handle Parse.com's transformation of a HTTP error to a NSError? I'm calling a 3rd-party server from Cloud Code. The former can return HTTP errors which I want to pass to a calling iOS app.
I'd like my iOS app to handle the HTTP error details when the 3rd-party server throws a HTTP exception.
The only way I've found so far is to treat those exceptions as a Cloud Code "success"!
Is there a better way?
An example
When the 3rd-party server returns a HTTP 400, "Missing Name" error:
From my Cloud Code I can call:
response.error(httpResponse);

Then in Swift I can parse this with:
PFCloud.callFunctionInBackground("func", withParameters:[]) {
    (result, error) -> Void in
    if error == nil {
        // handle success
    } else {
        // handle error
        // Parse.com has wrapped the originating http error with a status code of 141 so I'll need to JSON parse the deeper fields to get 400 & "Missing Name".
    }

But, instead, from Cloud Code, I can call response.success(httpResponse) and then do this:
PFCloud.callFunctionInBackground("func", withParameters:[]) {
    (result, error) -> Void in
    if error == nil {
      let result = result as! [String:AnyObject]
      let status = result["status"]
      let text = result["text"] as! String
      // status will be 400
      // text will be "Missing Name"
    } else {
       // handle Parse.com's 141s
    }

This makes field parsing more accessible. But I'm handling HTTP errors along with successful calls.

A: You can potentially customize the error message/data but unfortunately you cannot change the error code 141 if you use response.error() method. See this


text:
Q: RuntimeError: no such column: inf I have this route and it says that the error is on line 80, but It all looks fine. When I run it, it says RuntimeError: no such column: inf. I have never seen this before, so does anyone have any tips?
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    # If method is get, go to the html file
    if request.method == "GET":
        return render_template("buy.html")
    #declare global variables
    #get the amount of shares
    shares = int(request.form.get("shares"))
    # get the symbol of the stock
    sym = request.form.get("symbol")
    # get the user id for the session
    uid = session["user_id"]
    # get the user cash by looking at their user id
    userMoney = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id = uid)[0]["cash"]
    # lookup the stock symbol from the function in helpers.py
    symbol = lookup(sym)
    # get the purchase value of the stock and all the shares
    purchaseVal = shares * symbol["price"]
    # get the date & time to put it in the table
    currentDate = datetime.datetime.now()
    #check to make sure that all values exist
    if not symbol:
        return apology("That symbol doesn't exist")
    if int(shares) < 0:
        return apology("Only positive shares!")
    # if userCash < int(purchaseVal):
    #     return apology("Not enough money to purchase!")
    #get the new user cash after purchasing the stock
    newCash = userMoney - purchaseVal
    db.execute("UPDATE users SET cash = ? WHERE id = ?", newCash, uid)
    #update the table
    db.execute("INSERT INTO purchases (user_id, shares, symbol, price, date) VALUES(?, ?, ?, ?, ?)", uid, shares, sym, purchaseVal, currentDate)

    # display a successful purchase message using flash function that was included above
    flash("Successful!")
    #redirect to home page after purchasing
    return redirect("/")

Full error:   File "/workspaces/97107415/finance/helpers.py", line 34, in decorated_function
return f(*args, **kwargs)
File "/workspaces/97107415/finance/app.py", line 80, in buy
db.execute("UPDATE users SET cash = ? WHERE id = ?", newCash, uid)
File "/usr/local/lib/python3.10/site-packages/cs50/sql.py", line 27, in decorator
return f(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/cs50/sql.py", line 398, in execute
raise e
RuntimeError: no such column: inf


text:
Q: Python Social Auth - How to know if social media connect is successful? I have installed Python Social Auth. I use it to associate user site account with his social media accounts.
Facebook connect link is:
Connect

Redirection works but how to know if social media association is successful?
If an exception is catch, I can display get_messages() function. It's perfect!
But any return if it's successful.
I have tried to custom a pipeline but I have not access to request variable to set message like it: messages.success(request, "Successful message!')

A: You do have access to request in your custom pipeline:

The pipeline functions will get quite a lot of arguments, ranging from the backend in use, different model instances, server requests and provider responses.

You can read more about it here.
and you can get access to request object like this:
def custom_pipeline(strategy, *args, *kwargs):
    request = strategy.request

and do whatever you wanted with messages.

A: There is an option
SOCIAL_AUTH_LOGIN_ERROR_URL = '/error/'

in python social auth settings which redirects to the url you mention in above setting.
This way you will know whether the connect is success or not.
Hope this is helpful.


text:
Q: Issue Saving Certificate to iOS Keychain -25300 (not found) if deleting, but -25299 (duplicate item) if adding I've hit an interesting issue with the Apple keychain and am wondering what I am doing wrong.
    func saveCert(accessGroup: String? = nil, certData: Data, label: String? = nil) -> Error? {
        var query = createKeychainAddQueryDict()
        if let accessGroup = accessGroup {
            query[String(kSecAttrAccessGroup)] = accessGroup
        }

        query[String(kSecValueData)] = certData
        query[String(kSecClass)] = kSecClassCertificate

        if let label = label {
            query[String(kSecAttrLabel)] = label
        }

        var status = SecItemDelete(query as CFDictionary)
        if status != noErr {
            print("Error deleting cer from keychain. Error: \(status)")
        }

        let resultCode = SecItemAdd(query as CFDictionary, nil)
        return getErrorFromKeychainCode(code: resultCode)
    }

I'm saving a self signed certificate, but I've verified the serial number is different for each item I'm trying to store.
I get a -25300 error (cannot find item) when I try to delete the cert out, but I get a -25299 error (duplicate item already exists) when I try to save into the keychain.
I'm stumped as to why or how, loading or deleting the key out of that location are both failing, and saving is declaring the position is taken.
Any insight? I've experimented with hardcoding a number of random labels that I've never used before, and they too get the duplicate entry error.

A: I found two solutions:

*

*Request values for a particular key later. Use async delayed. From time to time the Keychain doesn't provide the result with -25300. The keychain is an SQLite database too. It seems the database is currently busy. So, request the data later.

*You have already written something into this key but, you used another protection level. To avoid this, use keys with protection level inside its name. E.g., someKey into someKey-afterFirstUnlock

A: I tried lots of things, and none of them worked. I eventually found out that the kSecCertificate class uses the issuer and serial number attributes to compute its uniqueId.
Because I'm using a self-signed certificate the SecCertificateCreateWithData operation fails with result nil. I believe this is causing all my certificates to evaluate to the same empty - empty id. I tried storing this same data in a kSecGenericPassword, and set a distinct account attribute, and the issue has gone away.


text:
Q: Data download issue in Shiny I've run into a problem with downloadHandler() in Shiny:
I want to choose from three data sets to download any file via this function. The dropdown menu in the app shows the three files to choose from, but when I click download it's always the first dataset that is downloaded.
The overall code is pretty long, but this is the relevant part. I appreciate if someone points out to where I'm making a mistake:
ui <- fluidPage(  tabPanel("Downloading Data",
                  titlePanel("Download Data"),
                  sidebarLayout(
                    sidebarPanel(
                      selectInput("dataset",label="Choose a dataset:",c("m.census","f.census","mortality.rates")),
                      downloadButton("downloadData","Download")
                    ),
                    mainPanel(
                      tableOutput("tab3")
                    )
                  )
                )
              )

server <- function(input, output) {
  datasetInput<-reactive({
    switch(input$dataset,
       "m.census"=m.census,
       "f.census"=f.census,
       "mortality.rates"=mortality.rates)
  })

  output$tab3<-renderTable({
    datasetInput()
  })

  output$downloadData<-downloadHandler(
    filename=function(){
      paste(input$dataset,".csv",sep="")
    },

    content=function(file){
      write.csv(datasetInput(),file,row.names = FALSE)
    }
  )
}


text:
Q: How do I get my Facebook Friends' Pictures in a stream? How do I access facebook friends' recent pictures of my users on my facebook app?  I would like my users to see a recent feed of the pictures that their friends are posting on facebook (regardless if that user is tagged in the picture or not.
I have seen this in an android application and I wanted to program it for a website app.

A: Not sure why Android is tagged here but use the Facebook API


text:
Q: Convert Date user-defined function not working Hi I'm trying to create a user-defined function in SQL Server 2008, to convert dates from one format to another.
the date im using is missing the centuary i.e. 1610101 is 1961/01/01 and 213/02/15 is actually 2013/02/15.
i've searched this a good few websites for a solution but i cant see whats wrong with it.
create function Convert_Date(@Cdate Date)
returns Date
as
Begin
declare @return date
select @return = case @Cdate
when (LEFT(@Cdate,1) = 1) then convert(date,('19'+ CONVERT(VARCHAR(30), right(@Cdate,6))))
when (LEFT(@Cdate,1) = 2) then convert(date,('20'+ CONVERT(VARCHAR(30), right(@Cdate,6))))
return @return
end

A: You want something like this:
CREATE FUNCTION Convert_Date(@Cdate DATE)
RETURNS DATE
AS
BEGIN

    DECLARE @return DATE

    SELECT @return =
    (
        CASE LEFT(@Cdate,1)
            WHEN '1' THEN CONVERT(DATE, ('19'+ CONVERT(VARCHAR(30), RIGHT(@Cdate,6))))
            WHEN '2' THEN CONVERT(DATE, ('20'+ CONVERT(VARCHAR(30), RIGHT(@Cdate,6))))
        END
    )

    RETURN @return
END

Your when statements should be the times when your result matches the case.


text:
Q: YAP initialization file? I am wondering if there is an equivalent of the SWI initialization file "~/.plrc" in YAP.
I would like to define some directories with: file_search_path/2 before loading YAP, but I do not know where to do it.
Any help will be highly appreciated!.

A: In my .yaprc
:- multifile(library_directory/1).
library_directory('~/ftp/Prolog-inedit').


text:
Q: How to show webview when it's finished loading? I am working on an android log-in application. When logged in the user will be redirected to a webview. Currently everything is working great, however i want to change what is displayed when loading.
Currently I use ProgressDialog. I figured I could just change the setContentView() and onPageFinished() but it's resulting in a nullPointerException
Here is the current, working method:
private void goToSite() throws IOException {

    //Create and start the 'loading' animation
    final ProgressDialog progDailog = ProgressDialog.show(this, "Gegevens       controleren","Een ogenblik geduld...", true);

    //Initialize the webview and set the contentView to display it
    String url=VarControl.DEFAULT_LINK;
    setContentView(R.layout.webview);
    webView = (WebView) findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClient() {
        //This inner method dimisses the 'loading' dialog when the page is fully loaded
        public void onPageFinished(WebView view, String url) {
            progDailog.dismiss();
        }
    });

    //Collect the login data and post it to the server
    String postData = "token="+loadToken()+"&deviceid="+VarControl.regid+"&webview=true"+"&devicetype=Android";

    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.setWebChromeClient(new WebChromeClient());
    webView.getSettings().setDomStorageEnabled(true);
    webView.postUrl(url, EncodingUtils.getBytes(postData, "base64"));
}

And here is what I am trying to do:
private void goToSite() throws IOException {

    //Initialize the webview and set the contentView to display loadingscreen
    String url=VarControl.DEFAULT_LINK;
    setContentView(R.layout.loadingscreen);//Changed this
    webView = (WebView) findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClient() {
        //show the webview when the page is fully loaded
        public void onPageFinished(WebView view, String url) {
           setContentView(R.layout.webview);// And changed this
        }
    });

    //Collect the login data and post it to the server
    String postData = "token="+loadToken()+"&deviceid="+VarControl.regid+"&webview=true"+"&devicetype=Android";

    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.setWebChromeClient(new WebChromeClient());
    webView.getSettings().setDomStorageEnabled(true);
    webView.postUrl(url, EncodingUtils.getBytes(postData, "base64"));
}

Unfortunatly this is resulting in a nullPointerException and I have no idea why.
Here is my stackTrace:
12-05 09:40:49.680    1514-1514/com.alserdamedia.wiib E/AndroidRuntime﹕ FATAL EXCEPTION:     main
Process: com.alserdamedia.wiib, PID: 1514
java.lang.RuntimeException: Could not dispatch event: class     com.alserdamedia.wiib.AsyncTaskResultEvent to handler [EventHandler public void             com.alserdamedia.wiib.MainActivity.onAsyncTaskResult(com.alserdamedia.wiib.AsyncTaskResultEvent)
throws java.io.IOException]: null
        at com.squareup.otto.Bus.throwRuntimeException(Bus.java:456)
        at com.squareup.otto.Bus.dispatch(Bus.java:386)
        at com.squareup.otto.Bus.dispatchQueuedEvents(Bus.java:367)

        at com.squareup.otto.Bus.post(Bus.java:336)
        at com.alserdamedia.wiib.MyAsyncTask.onPostExecute(MyAsyncTask.java:103)
        at com.alserdamedia.wiib.MyAsyncTask.onPostExecute(MyAsyncTask.java:22)
        at android.os.AsyncTask.finish(AsyncTask.java:632)
        at android.os.AsyncTask.access$600(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.alserdamedia.wiib.MainActivity.goToSite(MainActivity.java:96)
at com.alserdamedia.wiib.MainActivity.onAsyncTaskResult(MainActivity.java:71)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.squareup.otto.EventHandler.handleEvent(EventHandler.java:89)
at com.squareup.otto.Bus.dispatch(Bus.java:384)
at com.squareup.otto.Bus.dispatchQueuedEvents(Bus.java:367)
at com.squareup.otto.Bus.post(Bus.java:336)
at com.alserdamedia.wiib.MyAsyncTask.onPostExecute(MyAsyncTask.java:103)
at com.alserdamedia.wiib.MyAsyncTask.onPostExecute(MyAsyncTask.java:22)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)

Why is this error occuring, and what can I do to solve my problem?
EDIT: the answer below states that webView is not in my loadingscreen, i have no idea what he means by this, i am initializing webView right?? if not what do I do to add it to loadingscreen??

A: Take a look at this :
setContentView(R.layout.loadingscreen);//Changed this
webView = (WebView) findViewById(R.id.webView);

The error occurred because the webView is not in your loadscreen.
I think the simplest way is to manually show (in onPreExecute) and dismiss (in onPostExecute) the ProgressDialog without using setContentView


text:
Q: API Call to create folder with %-Symbol either fails or doesn't decode I'm implementing REST Calls to Sharepoint in Java. I create folders by sending POST Requests to
/_api/web/GetFolderByServerRelativeUrl('/sites/MySite/Folder/')/folders/add('NewFolder')

This creates a new folder NewFolder in the parent folder Folder
Now I want a percent in the name:
/_api/web/GetFolderByServerRelativeUrl('/sites/MySite/Folder/')/folders/add('NewFolder%')

This fails because the percent is not encoded:
java.lang.IllegalArgumentException: Illegal character in path at index 151: ...

    at java.base/java.net.URI.create(URI.java:883)
    at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:73)

Wikipedia and all the other sources out there know, that a percent is encoded as %25. So I alter my call to
/_api/web/GetFolderByServerRelativeUrl('/sites/MySite/Folder/')/folders/add('NewFolder%25')

But this creates a folder named NewFolder%25. The %25 is not decoded but taken literally.
So how can I create a folder that justs named NewFolder%?
Strange thing is: other characters work
The strang thing is, that percent-encoding works for all the other characters (that I tried)
Lets say I want a space in the folder name. A spaces encodes to %20 and
/_api/web/GetFolderByServerRelativeUrl('/sites/MySite/Folder/')/folders/add('New%20Folder')

perfectly creates a folder named New Folder.
Want something more exotic? Try this:
/_api/web/GetFolderByServerRelativeUrl('/sites/MySite/Folder/')/folders/add('Test%20(%C3%A2)')

This creates a folder named Test (â)

A: You could use rest end point to add folder with %: POST http://<site>/_api/web/folders/AddUsingPath(decodedurl='Path')
https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/supporting-and-in-file-and-folder-with-the-resourcepath-api
SharePoint folder naming restrictions:
https://support.office.com/en-us/article/invalid-file-names-and-file-types-in-onedrive-and-sharepoint-64883a5d-228e-48f5-b3d2-eb39e07630fa