text:
Q: Event onclik button em tabela html dinâmica StringBuilder Boa tarde pessoal do forum, estou tentando adicionar um button em uma tabela html dinâmica para redirecionar para outra pagina passando parâmetro pela url. Mas não estou conseguindo via javascript. Estou utilizando WebForms asp.net C#. Montei a seguinte função para escrever via StringBuilder o html da tabela na pagina aspx:
    public void LoadTable()
    {
        StringBuilder html = new StringBuilder();
        html.Append("
");
        html.Append("
Processo	Parte Contraria	"+
            "Pesquisa/bens	"+
            "Status
");

        foreach (var item in ProcessoCRUD.GetProcessoRank())
        {
            html.AppendFormat("
{0}	", item.ProcessoID);
            html.AppendFormat("{0}	", item.ParteContraria);

            if(item.PesquisaBens == false)
                html.AppendFormat("	", item.PesquisaBens);
            else
                html.AppendFormat("	", item.PesquisaBens);

            if (item.Ativo == true)
                html.AppendFormat("Ativo	", item.Ativo);

            if(item.Arquivado == true)
                html.AppendFormat("Arquivado	", item.Arquivado);

            if(item.Irrecuperavel == true)
            html.AppendFormat("Irrecuperavel	", item.Irrecuperavel);

            html.AppendFormat("<button id='btnVisualizar' runat='server' class='btn btn-default' data-toggle='tooltip' "+
                "title='Visualizar' href='javascript: void(0)' onclick='window.open('Processo.aspx?NumeroProcesso={0}')>"+
                "</button>
", item.NumeroProcesso);
        }
        html.Append("
");

        //Append the HTML string to Placeholder.
        PlaceHolder1.Controls.Add(new Literal { Text = html.ToString() });
    }

Não consigo redirecionar para a pagina Processo.aspx?NumeroProcesso={0}.

Alguém poderia explicar uma forma de escrever um button via StringBuilder para redirecionar para outra pagina.

A: Obrigado pessoal pela ajuda!
Resolvi de outra maneira sem usar javascript, no próprio html assim:
            html.AppendFormat(
                "" +
                "	" +
                "
", item.NumeroProcesso);

Função completa:
    public void LoadTable()
    {
        StringBuilder html = new StringBuilder();

        html.Append("
");

        html.Append(
            "
Processo	Parte Contraria	"+
            "Pesquisa/bens	" +
            "Status	" +
            "
");

        foreach (var item in ProcessoCRUD.GetProcessoRank())
        {
            html.AppendFormat("
" +
                "{0}	", item.ProcessoID);

            html.AppendFormat("{0}	", item.ParteContraria);

            if(item.PesquisaBens == false)
                html.AppendFormat(
                    "" +
                    "" +
                    "	");
            else
                html.AppendFormat(
                    "" +
                    "" +
                    "	");

            if (item.Ativo == true)
                html.AppendFormat(
                    "" +
                    "" +
                    "Ativo	");

            if(item.Arquivado == true)
                html.AppendFormat(
                    "" +
                    "" +
                    "Arquivado	");

            if(item.Irrecuperavel == true)
            html.AppendFormat(
                "" +
                "" +
                "Irrecuperavel	");

            html.AppendFormat(
                "" +
                "	" +
                "
", item.NumeroProcesso);

        }
        html.Append("
");

        //Append the HTML string to Placeholder.
        PlaceHolder1.Controls.Add(new Literal { Text = html.ToString() });
    }

A: Escrevi o exemplo de como escrever em C#, para aprendizado.
Começando a string com '@', é possível quebrar de linha e adicionar aspas com ""
    html.AppendFormat(
@"
<button id='btnVisualizar' runat='server' class='btn btn-default' data-toggle='tooltip' title='Visualizar' href='javascript: void(0)' onclick=""window.open('Processo.aspx?NumeroProcesso={0}')"">

</button>
	", item.NumeroProcesso);

A: Você precisa concatenar a string de forma que retorne um HTML válido.
Nesse ponto o HTML deixa de ser válido:

  <button id='btnVisualizar'
      runat='server'
      class='btn btn-default'
      data-toggle='tooltip'
      title='Visualizar'
      href='javascript: void(0)'
      onclick='window.open('Processo.aspx?NumeroProcesso={0}')>

  </button>

Você precisa que o HTML saia nesse formato:

  <button
      id="btnVisualizar"
      runat="server"
      class="btn btn-default"
      data-toggle="tooltip"
      title="Visualizar"
      href="javascript: void(0)"
      onclick="window.open('Processo.aspx?NumeroProcesso={0}');">

  </button>

Tente concatenar da seguinte forma:
    html.AppendFormat(
    "
        <button
           id=""btnVisualizar""
           runat=""server""
           class=""btn btn-default""
           data-toggle=""tooltip""
           "+"
           title=""Visualizar""
           href=""javascript: void(0)""
           onclick=""window.open('Processo.aspx?NumeroProcesso={0}');"">
           "+"

        </button>

", item.NumeroProcesso);

Obs.: A identação dos exemplos estão assim só para facilitar nossa visualização do código.


text:
Q: How can I make a vector with all values of a column in R? I want to make a vector for a loop with al values of a column.
Is this possible?
Currently I did it like this:
Client_id_conversion_vector <- as.vector(Test$dimension1)
dimension1 are the clientId's I want in my vector
The problem is that I get the same value over and over

A: You might be looking for the unique function:
Client_id_conversion_vector <- unique(Test$dimension1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which method should be used for evaluating the linearity assumption of logistic models? I've come across two methods for evaluating the linearity assumption for logistic regression (i.e., whether there is a linear relationship between continuous predictor variables and the logit of the outcome):

*

*Box-Tidwell: For any continuous predictor in the model, include the product of that variable and its natural logarithm (i.e., x * log(x)) as an additional predictor, and see if it comes out significant. If it does, the linearity assumption is likely violated for that variable. See here for a CV discussion.

*Visual inspection: Visually inspect the scatter plot between each continuous predictor and the logit values, like in this STHDA example.

The problem is that I get different verdicts from these two methods, so am not sure which one to go with (if either).
Based on the models I've been testing so far, it seems that, when Box-Tidwell suggests non-linearity, the visual inspection method concurs; but the latter method suggests non-linearity in several cases where Box-Tidwell does not.
For example, this looks non-linear to me, but the Box-Tidwell method doesn't flag it (p-value: 0.177646):

Any advice here (on the general question of what method to use - not on this particular example) would be greatly appreciated.


text:
Q: If statement in PowerShell dependant on if RPC Server is unavailable I'm writing a script in PowerShell that ideally would gather information from another server.  If it's not able to reach that server, I want to prompt it to have the user manually enter the information.  I know how to do all of these, but I'm getting hung up when the RPC Server is unavailable.  I will also say that I know how to fix the error when it occurs, but I do not want to rely on my end users to have to go in and fix this.
As an example, if I run:
Get-WmiObject Win32_ComputerSystem -Computer 10.5.21.94

the result I get back is:

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:1 char:1
+ Get-WmiObject Win32_ComputerSystem -Computer 10.5.21.94
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject],
COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

I'm trying to find a way to write an if statement that will check to see if the RPC server is available or not, but I'm not sure what to check in order to create a true/false variable.  And again, I'm not really looking for someone to tell me how to write the if statement, I'm just trying to figure out any query I can run to determine if I can properly connect to this server and get a result back that can tell me to continue on or not.

A: An easy way to get around it in an if-statement is just to ignore potential errormessages with Erroraction and use a -not statement to check whether it can reach the destination or not and then append a $false value to a variable if it can't.
See the below example.
$status = ""
if (!(Get-WmiObject Win32_ComputerSystem -ComputerName 10.5.21.94 -ErrorAction SilentlyContinue)) {
Write-Host "Server is unavailable!"
$status += $false
}

    else {
    Get-WmiObject Win32_ComputerSystem -ComputerName 10.5.21.94
    }

if ($status -eq $false) {
    $Server = Read-Host "Please enter the destionation"
    Get-WmiObject Win32_ComputerSystem -ComputerName $Server
}

A: There was a suggestion for a Try/Catch block, but since this is not a terminating error, it didn't work initially.  Then I found this:
Try/catch does not seem to have an effect
There is an answer in there about making all errors terminating:
try {

   $ErrorActionPreference = "Stop"; #Make all errors terminating
   get-item filethatdoesntexist; # normally non-terminating
   write-host "You won't hit me";
} catch{
   Write-Host "Caught the exception";
   Write-Host $Error[0].Exception;
}finally{
   $ErrorActionPreference = "Continue"; #Reset the error action pref to default

}
This gave me exactly what I was looking for!


text:
Q: "No module named waitress" while running the Flask app on EC2 machine 0|waitress |   File "/home/ubuntu/machine-learning/ML-Rest-Api/waitress_server.py", line 1, in
0|waitress |     from waitress import serve
0|waitress | ImportError: No module named waitress
These are version info-
waitress - 2.2.2
Flask - 2.2.2
python - 3.9.13
ubuntu - 18.04
I am trying running the Flask app in EC2 machine on python's waitress-server, I have checked site-packages for waitress, and it is available there. Any idea on how to resolve it.


text:
Q: Celery - purge a specific queue using Redis from Python script I'm aware of Celery's command-line options:
celery -A my_app purge -Q queue_name

But I am looking for a way to purge queue_name from my Python app with Celery, something along the lines of:
def start_chunk(num_of_objs):
    # clear current queue before starting here
    RELEVANT CODE HERE TO PURGE queue_name
    for num in num_of_objcts:
         some_task.apply_async(kwargs={'num': num}, queue="queue_name")

Note, I'm aware of this:
from proj.celery import app
app.control.purge()

But as I understand this purges all queues.

A: I admit, it is little bit difficult to get it right. But the first thing you should look at for hints how to solve this problem is bin/purge.py (that is what I've done). After analysing the mentioned file, I think something like the following should work:
from celery.app.base import Celery
from yourproject import celery_app

def purge_queue(app: Celery, queue_name: str):
    with app.connection_for_write() as conn:
        conn.default_channel.queue_purge(queue_name)

purge_queue(celery_app, "celery")  # purge the "celery" queue

The above is more/less what celery -A yourproject.celery_app purge -Q celery does.

A: One way is to call the purge command through the os, we must use the -f flag:
import os
os.system("celery -A app_name purge -Q queue_name -f")

I don't know if there are any cons to this compared to DejanLekic's answer, which looks cleaner.


text:
Q: Adding dateCreated field to existing object I want to add a "dateCreated" field to an object that is already exiting, and the corresponding table already has several objects in it.  When the dateCreated timestamp column is added the timestamp is set to '0000-00-00 00:00:00', but I need to set it to the actual dateCreated value that I call when I am at the groovy/grails level.
Is there a way to populate the new column with the correct 'dateCreated' value?

A: You may possibly be able to do this by setting a default value for the dateCreated field in your domain class?
eg.
class ExistingDomainObject {
    Date dateCreated = someFunctionToCalculateCorrectDateCreated()
}


text:
Q: Save user form input info for later visits with PHP cookies? Basically I want to create a cookie in PHP that remembers what a user has entered into a form (that directs to a separate page), so that anytime they come back to the page, the form is already prepopulated with whatever information they put into it the first time around.
I've looked everywhere and can't really find a good answer for how to do this. This is how my code is configured right now (which isn't working).
PHP:
$fname =  $_POST['fname'];
$lname = $_POST['lname'];

if( ( $fname != null ) and ( $lname != null ) )
{
  setcookie( "fname", $fname, time() + 36000 );
  setcookie( "lname", $lname, time() + 36000 );
  exit();
}
?>

HTML:
<form method="post" action="hidden.php">

First Name: <input type="text" maxlength="40" name="fname" id="fname" value="<?php if(isset($_COOKIE['fname'])){echo $fname;} else {echo "";} ?>"/>

Last Name: <input type="text" maxlength="40" name="lname" id="lname" value="<?php if(isset($_COOKIE['lname'])){echo $lname;} else {echo "";} ?>"/>

Any mind telling me what I'm doing wrong and how I can fix it? Thank you!

A: <?php if(isset($fname))...

should be
<?php if(isset($_COOKIE['fname']))

the same goes for the lname command
edit (not sure if this is your setup but if you put the next code in a file it should work)
<?php
$fname =  $_POST['fname'];
$lname = $_POST['lname'];

if( ( $fname != null ) and ( $lname != null ) )
{
  setcookie( "fname", $fname, time() + 36000 );
  setcookie( "lname", $lname, time() + 36000 );
}

echo "post fname ".$_POST['fname']."
";
echo "post lname ". $_POST['lname']."
";
echo "cookie ". $_COOKIE['fname']."
";
echo "cookie ". $_COOKIE['lname']."
";
?>

<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<form method="post" action="hidden.php">

First Name: <input type="text" maxlength="40" name="fname" id="fname" value="<?php if(isset($_COOKIE['fname'])){echo $_COOKIE['fname'];} else {echo "";} ?>"/>

Last Name: <input type="text" maxlength="40" name="lname" id="lname" value="<?php if(isset($_COOKIE['lname'])){echo $_COOKIE['lname'];} else {echo "";} ?>"/></p

<input type="submit" name="submit" value="Send">


text:
Q: Posting to Microsoft Cognitive Face API using Ionic - AngularJS Currently I am using Ionic to develop a Facial Recognition app.
I am using Microsoft's Face API for the same.
My problem is I keep getting Error 400: Decoding error, image format unsupported.
After doing some research, I ran into this link
Quoting START,

When you're submitting a binary payload, you should not base64 encode it.  Here's what you might do instead..

URI uri = builder.build();
HttpPost request = new HttpPost(uri);
request.setHeader("Ocp-Apim-Subscription-Key", "...");

File file = new File("...");
FileEntity reqEntity = new FileEntity(file, ContentType.APPLICATION_OCTET_STREAM);
request.setEntity(reqEntity);

Quoting END
With Ionic/AngularJS, the captured image using Device Camera or selected from Image Gallery is returned in the form of base64 string. So I looked for ways to decode the data into Binary using this gist but still failed.
Here's my controller code where I make the API call.
$scope.postToAPI = function () {
             // make http call to MS cognitive API
                var formData = new FormData();
                formData.append('file', $scope.picture);
                $http.post($scope.cognitiveServices.endpoint, formData, {
                    headers: { 'Content-Type': 'application/octet-stream', 'Ocp-Apim-Subscription-Key':$scope.cognitiveServices.apiKey }
                }).success(function (data) {
                    console.log(JSON.stringify(data));
                    alert("Awesome");
                }).error(function (err) {
                    alert("Fail ->" + err.code + " " + err.message);
                    console.log("Some error occured");
                });
            }

I have

*

*tried setting transform:angular.identity and Content-Type: undefined

*tried sending image without Form Data (just a random trial)

*tried converting base64 string to Uint8 Array (by following the solution to this SO question)

All my attempts so far have failed. Can someone explain what I am doing wrong?
P.S: This is my first time with Ionic framework.


text:
Q: Incluir Loading em Botão - Bootstrap v4 - JSP Olá, estou tentando alterar um botão onde, quando for clicado. Seu conteúdo seja alterado para mostrar um "loading" e apos o carregamento da pagina o botão volte ao estado anterior. Já tentei de varias formas mas sem sucesso, não sei se é conflito; poderiam me ajudar por gentileza?
O front end do projeto é em JSP, usamos bootstrap 4.4.
O codigo do botão que quero alterar é:
 Pesquisar

/*Codigo que quero alterar*/

    <button class="btn btn-sm btn-primary" name="Pesquisar" type="submit">Pesquisar</button>

Eu tentei da forma abaixo passar os dados usando ID na DIV, pq possuem outros class "button" na pagina que não quero incluir o Loading.
HTML:
  Carregando">Pesquisar

JS/JQ:
 $('#load').click(function () {
                var btn = $(this)
                btn.button('loading')
                setTimeout(function () {
                    btn.button('reset')
                }, 9000)
            });

/*codigo que tentei*/

    <button type="submit" class="btn btn-sm
        btn-primary" id="load" data-loading-text=" Carregando">Pesquisar</button>

A: Boa tarde pessoal,
No meu caso consegui resolver conforme abaixo; meu problema é que utilizo no projeto bootstrap 4.0, e os o efeitos que queria utilizar nos botões "class='fa fa-spinner fa-spin" por exemplo, estão disponíveis apenas no bootstrap 4.4. Como não posso atualizar a versão do bootstrap utilizado no projeto, resolvi achando as classes CSS dos efeitos que estão apenas na versão que não posso usar e inclui os mesmo no projeto. no meu caso foram os CSS's abaixo:

  <button type="submit" id="load" class="btn btn-sm btn-            primary">Pesquisar</button>


text:
Q: HttpResponseMessage always empty if using MemoryStream instead of FileStream I want to create a HttpResponse that streams a local file.
I want to use a MemoryStream, so that I can delete the file afterwards (well actually before returning the repsonse).
I always end up with an empty response although the stream seems to be valid.
Working with a FileStream in API Controller works, though.
 public HttpResponseMessage GetExcelFile(Guid id)
        {
            // this model is needed to internally create an .xls file that represents this model
            var exportModel = this.myService.GetExport(id);

            // this approach does not work -> respone always empty although memory stream has content
            // var stream = new MemoryStream();
            // internally creates a .xls file (using lib) and returns its content as memory stream
            // this.myService.ConvertToStream(exportModel, stream));

            // this works fine
            var stream = File.OpenRead(@"D:\test0815.xls");

            var result = this.Request.CreateResponse(HttpStatusCode.OK);

            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentLength = stream.Length;
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                                                            {
                                                                FileName = $"{exportModel.Name}-Sheet.xls"
                                                            };

            return result;
        }

this is my method that actually converts to memorystream:
 private MemoryStream SaveToStream(MemoryStream stream)
        {
            using (FileStream source = File.Open(
                @"D:\test0815.xls",
                FileMode.Open))
            {
                Console.WriteLine("Source length: {0}", source.Length.ToString());

                // Copy source to destination.

                source.CopyTo(stream);
            }

            return stream;
        }

I also tried writing to memory stream but this did not work either.
It seems that result.Content = new StreamContent(stream); is just not working with an memory stream.
Any ideas?

A: finally I found a working solution:
  var memoryStream = new MemoryStream((int)fileStream.Length);
            fileStream.CopyTo(memoryStream);
            fileStream.Close();
            memoryStream.Seek(0, SeekOrigin.Begin);

            HttpContent content = new StreamContent(memoryStream);

            var result = this.Request.CreateResponse(HttpStatusCode.OK);
            result.Content =content;
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");


text:
Q: XBox 360 Dashboard Plugins Is it possible to create plug ins for the Xbox 360 dashboard?
I was looking to turn the 360 into the hub for the family. So you could for example turn the xbox on, and there on the dashboard see all the families calendars merged, todo lists, grocery lists, birthdays etc.
I can't see anybody talking about plugins for the dashboard around the net so I'm guessing you can't, but thought I'd check. Next option will be something like a net top running in the family room, but that means 2 devices then, one for gaming and one for the family functions

A: You can't. I think your best bet will be to look at XNA, and then create a "game" that fetches and displays all the data you want.


text:
Q: pager above reviews on product page We are working on a website in magento 1.9 We have included the reviews directly on the product page, outside the tabs, by inserting
<?php echo $this->getChildHtml('reviews') ?>

into view.phtml. This works fine however, the pager above the reviews is not being displayed. On the default review-page the pager is being displayed.
What is the reason that the pager is not displayed above the productreviews on the productpage and how can we fix this?
Regards,
Erik


text:
Q: Implements the binary-searching style code in functional way Given that I have a code snippet written in binary-searching way:
(*
   pts <-- data points
   p   <-- curve degree
   TOL <-- the tolerance of fitting
*)
compactCurveFit[pts_, p_, TOL_] :=
  Module[{m, nLow, nUpp, nNow, Unow, Pnow, fitErr, tag = False, Uprev, Pprev},
    m = Length@pts - 1;

    nLow = p;
    nUpp = m;
    nNow = Floor[(nLow + nUpp)/2];
    (* special assignment *)
    Uprev = Pprev = $Failed;

    (* fit the data points in binary-seraching way *)
    While[True,
      {Pnow, Unow, fitErr} = curveFitStep[pts, nNow, p, TOL];
      tag = fitErr <= TOL;
      If[tag,
        (* fit sucess *)
        If[nNow - nLow <= 1,
          Return[{Unow, Pnow}],
          (* else *)
          nUpp = nNow;
          nNow = Floor[(nLow + nUpp)/2];
          (* save the data of the previous step *)
          Uprev = Unow;
          Pprev = Pnow
        ],
        (* else fit failed *)
        If[nUpp - nNow <= 1,
          Return[{Uprev, Pprev}],
          (* else *)
          nLow = nNow;
          nNow = Floor[(nLow + nUpp)/2]
        ]
      ]
    ]
  ]

The above implementation compactCurveFit[] is straightforward in procedural language like C or Java. However, it is not elegant in Mathematica, such as the usage of Return[], While[], which is not recommended in a functional and rule-based language.
So I would like to know if it could be refactored to functional way.


text:
Q: I want to create a method and write code for getCurrentSession in that method and use it in all the remaining methods This is my DaoImpl

import com.ram.model.Employee;

@Repository
public class EmployeeDaoImpl implements EmployeeDao{

    @Autowired
    private SessionFactory sessionFactory;

    public void ses(Session session){
        session = sessionFactory.getCurrentSession();
    }

    @Override
    public void addEditEmployee(Employee emp) {

        ses(session);
        session.saveOrUpdate(emp);

    }

}

How can I do this?
I think this is wrong declaration of session.
How to declare Session and use it in all the methods?

A: You can achieve this as:
@Repository
public class EmployeeDaoImpl implements EmployeeDao{

    @Autowired
    private SessionFactory sessionFactory;

    public Session getCurrentSession(){
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void addEditEmployee(Employee emp) {
        getCurrentSession().saveOrUpdate(emp);

    }

}

Also you need to study basic java concepts like variable scopes, methods in java, take a look at this link it might help.


text:
Q: How to resolve "relocation against undefined symbol can not be used when making a shared object" with shared object/library in c++ I am setting up a self made tracer in PyTorch source code.
When I try to build a previous version of the code, I encounter the following error :
(edited the output, it is with make VERBOSE=1)
[ 47%] Linking CXX shared library ../lib/libcaffe2.so
cd /opt/pytorch/build/caffe2 && /usr/bin/cmake -E cmake_link_script CMakeFiles/caffe2.dir/link.txt --verbose=1
/usr/bin/c++  -fPIC  -Wno-deprecated -fvisibility-inlines-hidden -fopenmp -DUSE_FBGEMM -O2 -fPIC -Wno-narrowing -fPIC -Wall -Wextra -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wno-unused-function -Wno-unused-result -Wno-strict-overflow -Wno-strict-aliasing -Wno-error=deprecated-declarations -Wno-error=pedantic

[...]

,--whole-archive,/opt/pytorch/build/lib/libonnx.a -Wl,--no-whole-archive ../lib/libonnx_proto.a ../lib/libprotobuf.a -pthread -Wl,-rpath,/opt/pytorch/build/lib:/opt/conda/envs/build/lib:/usr/local/cuda/lib64:
/usr/bin/ld: CMakeFiles/caffe2.dir/__/aten/src/ATen/native/cpu/Activation.cpp.AVX2.cpp.o: relocation R_X86_64_PC32 against undefined symbol `_ZN2at6vec25612_GLOBAL__N_118SOURCE_CODE_TRACERE' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status
caffe2/CMakeFiles/caffe2.dir/build.make:17251: recipe for target 'lib/libcaffe2.so' failed
make[3]: *** [lib/libcaffe2.so] Error 1
make[3]: Leaving directory '/opt/pytorch/build'
CMakeFiles/Makefile2:3900: recipe for target 'caffe2/CMakeFiles/caffe2.dir/all' failed
make[2]: *** [caffe2/CMakeFiles/caffe2.dir/all] Error 2
make[2]: Leaving directory '/opt/pytorch/build'
Makefile:138: recipe for target 'all' failed
make[1]: *** [all] Error 2
make[1]: Leaving directory '/opt/pytorch/build'
Makefile:4: recipe for target 'all' failed
make: *** [all] Error 2

I am not sure if I am missing a step for the tracer class import, or maybe the problem is linked to a shared library (libcaffe2.so ?) that is needed (like here : Relocation R_X86_64_PC32 against undefined symbol can not be used when making a shared object; recompile with -fPIC ) ?
To use the tracer, I am doing this :
#include "ATen/cpu/vec256/SourceCodeTracer.h"

namespace at {
namespace vec256 {
namespace {

#ifdef __AVX2__

struct Vec256i {
protected:
  __m256i values;

  static inline __m256i invert(const __m256i& v) {
    // some code
    extern SourceCodeTracer SOURCE_CODE_TRACER;
    SOURCE_CODE_TRACER.trace("vec256_int.h __m256i invert()");
    return something;
  }

The class cpp file :
#include "SourceCodeTracer.h"

SourceCodeTracer* SourceCodeTracer::_singleton = NULL;
extern SourceCodeTracer SOURCE_CODE_TRACER = SourceCodeTracer::getInstance();

SourceCodeTracer::~SourceCodeTracer() {
        // TODO: Write into
        std::cout << "Destructing object" << std::endl;
        ofstream traceOutputFile;
        try
        {
                std::cout << "Writing to " << _filePath << std::endl;
                traceOutputFile.open(_filePath);
                traceOutputFile << "Run at TODO PUT TIME" << std::endl;
                for (auto it = _map.begin(); it != _map.end(); ++it) {
                        traceOutputFile << it->first << " => " << it->second << '\n';
                }
        }
        catch (const std::exception& e)
        {
                std::cout << "Got error while trying to write trace file:" << e.what() << std::endl;
        }
        traceOutputFile.close();
}

SourceCodeTracer & SourceCodeTracer::getInstance() {
        if (SourceCodeTracer::_singleton == nullptr) {
                std::cout << "Constructing object" << std::endl;
                SourceCodeTracer::_singleton = new SourceCodeTracer();
        }
        return *SourceCodeTracer::_singleton;
}

void SourceCodeTracer::trace(const string & tr) {
        _map[tr] = _map[tr] + 1;
}

SourceCodeTracer::SourceCodeTracer() {
        _filePath = "trace.txt"; //get_env_var("TRACER_OUTPUT_FILE_PATH");
        std::cout << "Got environment value for TRACER_OUTPUT_FILE_PATH of " << _filePath << std::endl;
        if (_filePath == "") {
                // Warn that no environment variable was set
                std::cout << "No value for TRACER_OUTPUT_FILE_PATH set !" << std::endl;
                exit(1);
        }
        // Assert path is writable
}

// https://stackoverflow.com/q/631664/9876427
std::string SourceCodeTracer::get_env_var(std::string const & key) const {
        char * val;
        val = std::getenv(key.c_str());
        std::string retval = "";
        if (val != NULL) {
                retval = val;
        }
        return retval;
}

header file :
#include <iostream>
#include <string>
#include <fstream>
#include <list>
#include <map>
#include <memory>
#include <iomanip>
#include <ios>
#include <cstddef>
#include <cstdlib>

#ifndef __SOURCE_CODE_TRACER_H__
#define __SOURCE_CODE_TRACER_H__

using namespace std;
class SourceCodeTracer {
        public:
        ~SourceCodeTracer();

        static SourceCodeTracer& getInstance();
        void trace(const string& tr);
private:
        SourceCodeTracer();
        // https://stackoverflow.com/q/631664/9876427
        std::string get_env_var(std::string const & key) const;
        static SourceCodeTracer* _singleton;
        // Traceur() = delete;
        std::map<string, long> _map;
        string _filePath;
};

#endif // __SOURCE_CODE_TRACER_H__


text:
Q: JQuery REST call does not work I try to make an REST-Call with JQuery in JavaScript. The REST-Method returns a simple String.
I tried the following (JQuery is included):
$.ajax({
    type: 'GET',
    url: 'http://localhost:8080/SecureCloudboxServer/rest/connectionservice/ping',
    dataType: 'text',
    success: function(data){
        alert('success');
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR + ' : ' + textStatus + ' : ' + errorThrown);
    }
});

If I execute it in my Browser the alert-Window contains: "[object Object] : error : ".
If I call the URL directly from my Browser I get the expected answer. Does anyone have a clue why it doesn't work?

A: Use
console.log(jqXHR + ' : ' + textStatus + ' : ' + errorThrown);

alert will not display an object or array
Dont forget to use firebug or something similar with console.log


text:
Q: jbpm business rule task example Can some one provide me an working example for jbpm business rule task ? I tried creating one via jbpm work bench and executed via jbpmn eclipse plugin. It seems buiness process and rule task are not able to sync each other . Some times rule gets invoked, sometimes not.

A: You should take a look at this blog: JBPM6 - RuleTask Example Using a Rule File
The key is to make sure your Rule Flow Group in the Bussiness task matches the Rule Flow Group in the .drl file (from article in above link):

*

*Business Rule Task:

*Business Rule:

A: On the top of that, I'd make sure that your Drools Rule and the jBPM process are stored in the same folder. There's a sample project here which demonstrates the usage: Drools Rules with jBPM


text:
Q: Custom Simulink discrete-time integrator block I was trying to design my own simple implementation of a discrete-time integrator in Simulink using the trapezoidal rule.
This is the result of my efforts (consider I'm using 1 as time integration interval):

Then, just to double check if I did everything right I compared the results with the standard Simulink discrete-time integrator block (configured to use Trapezoidal rule of course):

Everything runs fine when I let the step rise at time 1 (both the custom and default integrator blocks have 0 as initial condition):

while with the step rising at time 0 I got a difference between the two integrators block response:

*

*custom block:  @ Integral(t=0)=0.5;  @ Integral(t=1)=1.5

*default block: @ Integral(t=0)=0;    @t=1 Integral(t=1)=1

I think this depends on my custom block integrating between t=0 and the initial condition = 0 (i.e. applying the trapezoidal rule between 0 and 1, therefore getting 0.5).
Which is the best way to fix this and make my custom block show the same behaviour as the default one also at zero time? Is there any parameter/setting I am missing?
Thank you!

A: Note that the trapezoidal integrator only needs, and should only have, one unit delay.  The correct implementation is shown in the image below.

From the second image that you show in the question, the output of the library block is zero at time equal to zero.  That's not the default behaviour (as shown above, and also as discussed in the Integration and Accumulation Methods subsection of the doc for the Discrete Time Integrator block).
Did you change the Initial Condition Settings from State to Output?  If so, then the state in the custom implementation needs to be modified appropriately.


text:
Q: Is there an AWS CLI command to possibly get UserName from just a resource ARN? We have folks that don't like to use tags when building things in AWS, so the problem is we need to go ascertain the UserName of the person who used the resource, is there a CLI command that we can use if we have the resource ARN?  Sure, we could look in cloud trail but that's a cumbersome process, need something less painful.  I'm open to anyway to do this, if someone has a boto3 script that would work as well.

A: There is no direct relationship between a resource in AWS and the IAM entity that created it.
When a request is sent to AWS to create a resource (eg an Amazon S3 bucket or an Amazon EC2 instance), IAM verifies that the credentials being used have permission to create the resource. These credentials could be associated with an IAM User, IAM Role, Federated identity, etc.
If the entity making the request has permission to create the resource, then the resource is created. The resource is associated with the AWS Account that generated the credentials. There is no association stored between the resource that was created and the user/entity that requested its creation.
The only link between the user and the resource would be a record in AWS CloudTrail that details the API request to create the resource, together with details of the user/entity that made the API request.


text:
Q: Wordpress MiniOrange IDP is not redirecting back to SP I have two Wordpress sites. I am using MiniOrange plugins in both sites. One of them act as SAML IDP and and the other as SAML SP.
Now issue that I am facing is, when I start SP-Initiated flow, browser is redirected to IDP which is fine. But after authenticating on IDP, browser does not redirect back to the SP. Instead, I am shown IDP's home page.
Now what I do is, in the new tab I again started SP-Initiated flow , since IDP's session is already there, this time I am correctly redirected back to SP.
So I am not entirely sure where the problem is, is it MiniOrange plugin or Wordpress?


text:
Q: How to get filename of imported modules (Including default) in Python? A little context: I'm trying to create a module that can safely copy itself and all other required files to another location.
Say I have two modules.
a.py:
import b
import os
import tkinter

print(str(__file__))
print(str(b.getfile()))

b.py:
def getfile:
    return __file__

When a.py will then output
C:/path/to/code/a.py
C:\path\to\code\b.py

Question: How, if at all, can i get the path of a different imported module (like "os.py"), or any module without this getfile() function?

A: You can access via
module_name.__file__

as in
import os
module_file_path = os.__file__

As pointed out in the comments, this won't work for some built-in modules like sys that come from the interpreter's core.

A: You can use:
import os
print(os.__file__)


text:
Q: C++ template specialized getters I am currently writing a program working with NURBS surfaces, where you can perform algorithms in two directions (U and V). To avoid code duplication I tried to use templates, but I am by no means experienced using them. Here is a small example of what I would like to do:
#include <iostream>

enum class Dir {
    U, V
};

struct Foo {

    unsigned cu, cv;

    Foo(unsigned cu, unsigned cv) : cu(cu), cv(cv) {};

    template<Dir>
    const Dir otherDir();

    template<>
    const Dir otherDir<Dir::V>() {
        return Dir::U;
    }

    template<>
    const Dir otherDir<Dir::U>() {
        return Dir::V;
    }

    template<Dir>
    unsigned count();

    template<>
    unsigned count<Dir::U>() {
        return cu;
    }

    template<>
    unsigned count<Dir::V>() {
        return cv;
    }

    template<Dir d>
    unsigned totalCount() {
        auto c = count<d>();
        auto cOther = count<otherDir<d>()>();
        return c * cOther;
    }

};

int main() {
    Foo f(3,2);
    std::cout << (f.count<Dir::U>() == 3) << std::endl;
    std::cout << (f.otherDir<Dir::U>() == Dir::V) << std::endl;
    std::cout << f.totalCount<Dir::U>() << std::endl;
}

but this doesn't compile due to the last line in main (VS2015, but I don't think it's compiler's fault):
1>...\main.cpp(42): error C2672: 'Foo::count': no matching overloaded function found
1>...\main.cpp(52): note: see reference to function template instantiation 'unsigned int Foo::totalCount<Dir::U>(void)' being compiled
1>...\main.cpp(42): error C2975: 'unnamed-parameter': invalid template argument for 'Foo::count', expected compile-time constant expression
1>...\main.cpp(27): note: see declaration of 'unnamed-parameter'
1>...\main.cpp(43): error C3536: 'cOther': cannot be used before it is initialized

Only way I got close to the functionality above is by specifying both the main direction as well as the other direction as the template arguments like this:
struct Foo {

    ...

    template<Dir d, Dir otherD>
    unsigned totalCount() {
        auto c = count<d>();
        auto cOther = count<otherD>();
        return c * cOther;
    }

};

int main() {
    Foo f(3,2);
    std::cout << f.totalCount<Dir::U, Dir::V>() << std::endl;
}

but that doesn't seem to be very elegant.

A: Probably, problem is here:
auto cOther = count<otherDir<d>()>();

Templates are "resolved" in compile time. You should use constexpr for otherDir<d>() because just simple const doesn't mean that method can be evaluated in compile time.
More traditional approach is to have structure otherDir instead of method. Create structure template, two instantiations would be with static const value = V or U.
Or you can replace enum with empty structs.
Or, what's even better, you can try to implement it without templates and create class for dimension and have one object per each dimension.

A: otherDir<d>() is not constexpr, and cannot be used in template argument (count<otherDir<d>()>()).
You may add constexpr (and static) to that method,
or use old struct to handle that:
template <Dir> struct otherDir;

template<>
struct otherDir<Dir::U>
{
    static constexpr Dir value = Dir::V;
};

template<>
struct otherDir<Dir::V>
{
    static constexpr Dir value = Dir::U;
};

Demo


text:
Q: how to pipe a file into stream using python I am trying to redirect my xls file output to a stream but i am facing error.
Below is the code i am using
#!/usr/bin/env python

import codecs

import datetime

import decimal

import csv

import sys

import xlrd

def main(self):
    # We need to do this dance here, because we aren't writing through agate.
    if six.PY2:
        stream = codecs.getwriter('utf-8')(self.output_file)
    else:
        stream = self.output_file

def dump_xls(data,active_worksheet):
                active_worksheet.append(data)
     file_name = "temp.xls"

     reader = csv.reader(self.input_file,delimiter=",")

     workbook  = openpyxl.Workbook()
     worksheet = workbook.active
     for i in reader:
         dump_xls(i,worksheet)
     workbook.save(file_name)

def launch_new_instance():
    utility = CSVXLS()
    utility.run()

if __name__ == '__main__':
    launch_new_instance

()

I already have a input stream and all the stream information . How could i convert my output file into stream so that data is visible at the output .
I am new to python, any help is much appreciated.
Many thanks !!!

A: I dont know I understand what stream are you looking for, but StringIO is also a stream, and you can write like
import StringIO
...
...
s_io = StringIO.StringIO() # Declare stream
for i in reader:
    dump_xls(i,worksheet)
    s_io.write(i) # Write to stream.

At end, s_io will represent the stream


text:
Q: Derivative of Sum over Variable of derivative I feel stupid for having to ask this, but does anybody have any idea how to handle
$$\frac{d}{x}\sum_{n=k}^{g(x)}f(n,x)?$$
Example:
$$\frac{d}{dx}\sum_{n=6}^{i^2+2i} \frac{1}{\ln{(i^2)}-\ln{\ln n}}.$$
If we were able to separate the summand into two functions, one with only $i$ as a variable, and one with only $n$ as a variable, this would be super simple.  But it is not always the case.  Any ideas?

A: This reminds me uncomfortably about a remark that Terry Tao made in this answer about the importance of teaching the derivative as a limit: at least one person tried to prove Fermat's Last Theorem by differentiating with respect to the exponent. It does not make sense.
The reason why it does not: the derivative is something that is properly defined for real (or complex) variables. If you're variable is an integer, derivatives will not make sense.
There may objects that are analogous to the derivative in some ways, but you cannot carelessly apply derivative rules.


text:
Q: Targetting a class with :last-child I have a class .side-box { margin: 0 10px 10px 0; } and what I'm trying to do is target the last .side-box in the DOM and apply margin-right: 0; to it with no jquery and no extra class to overwrite margin-right. In this way I have only a padding: 10px; wrapping the three boxes.
I tried:
.side-box:nth-child(2) {
     margin-right: 0;
}

and
.sidebars:last-child {
     margin-right: 0;
}

but didn't work. What am I doing wrong? Thanks.
FIDDLE HERE: http://jsfiddle.net/qL7wx5pp/

A: You've almost got it. You want to select the last sidebars and then get the side-box inside. Something like this:
.sidebars:last-child > .side-box
http://jsfiddle.net/qL7wx5pp/2/

A: If you read about last-child here is says:

The :last-child selector matches every element that is the last child
  of its parent.

I have highlighted the last child of its parent because that is what is causing your issue.
You have not applied the margin to the sidebars but to the side-box
So this wont do what you want.
.sidebars:last-child {
     margin-right: 0;
}

Now to target the correct side-box you need to realise how your DOM is structured.
You have a parent wrapper with 3 child sidebars
To target the last side-box, you need to target the last sidebars
Hence selecting sidebars:last-child is the correct target div. But the margin needs to be reset on the side-box div that is again a child of the last sidebars div
So the correct selector would be:
sidebars:last-child > side-box
side-box that is a child of the last child sidebars. See demo here


text:
Q: java.rmi.ConnectException: Connection refused to host:   java.rmi.ConnectException: Connection refused to host: IPSERVER0.0.0.0.0; nested exception     is:
java.net.ConnectException: Connection timed out
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:340)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at java.rmi.Naming.lookup(Naming.java:101)
at StartRMI.go(StartRMI.java:14)
at StartRMI.main(StartRMI.java:6)
    Caused by: java.net.ConnectException: Connection timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:146)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
... 7 more

I get this exception when I try to connect a remote client to my server. My Server is running RMI Server fine, and there no firewall installed. How to fix that issue ?

A: Check all you network adapters ,some time a VM network adapter interferes in this way .
Which is you current localhost or 127.0.0.1 is not any more referring to you host name or current machine ,which then create a connection refused problem. My General Recommendation is:
1.To check or disable unwanted VM or Network Adapters

2.Ping 127.0.0.1

3.Disable Firewall and Test if all the above doesn't work

4.Add security Manager with a policy file on you server if you haven't done that.

A: You have not mentioned which OS you are using, if everything is correct in terms of code and firewall then you may need to check the host entries or ip table rules.

A: Is IPSERVER mapped in /etc/hosts file to the IP address you want?
Check what you get when you do a hostname -i or hostname.
Try putting your IP address instead of the domain name.

A: Try to start the RMI registry using
start rmiregistry

for default port or
rmiregistry <port_no>

for a specified port.


text:
Q: jquery - inserting a header section on an existing webpage I am trying to inject a banner div

on top of an existing webpage in such a manner so that when a person scrolls the webpage the banner remains on top. Also the webpage should be pushed down by the banner so that every part of the page remains accessible.
Here is my CSS:
#banner {
position:fixed;
display:block;
top:0px;
background-color:#FFFFFF;
width:100%; height:250px;
border:2px solid;
}

Here is my jquery:
$("body").prepend("

");

I tried using jquery to find all divs that were fixed and changing them to relative before executing the above line but still the banner does not work. The error is shown in the following picture https://drive.google.com/file/d/0B0sCu8aj8zu2akhtcEdtajJJZEU/edit?usp=sharing
Please Help.
And I am not looking for ad revenue here this is just a practice task.

A: Here is a jsFiddle I have created. The banner div is at the top of the page.
It stays at the top while scrolling.
The HTML:

The css:
.oldBody
{
    width:100%;
    height: 3000px;
    background-color: navy;
    margin-top:250px;
}

#banner
{
    position:fixed;
    top:0px;
    background-color:#FFFFFF;
    width:100%;
    height:250px;
    border:2px solid;
    z-index:10000;
}

The JS:
$("body").wrapAll("

");
$("body").prepend("

");

A: Please maintain z-index of banner div.Z-index should be grater then other div on that page.
#banner {
position:fixed;
display:block;
top:0px;
background-color:#FFFFFF;
width:100%; height:250px;
border:2px solid;
z-index : 99999
}

A: i'd just like to present a different way to create the element:
var $banner = $('
', { 'id' : 'banner' });
$('body').prepend($banner);

this technique for creating elements with jquery comes in handy when you have several different element to create. as a note, you can also create the element like so:
var $banner = $('
').attr('id', 'banner');

A: I think the best way is first keep your ad on top in relative position when a person scroll page your function check the page-scroll .scrollTop() and then add fixed position on banner ad container just like freeze header, if you need further help in this regard let me know, I will provide you code. thanks I hope this technique will help you


text:
Q: netstandard.dll missing at GAC on fresh installation I try to setup clean CI build agent with MSBuild support. I use Build Tools for Visual Studio 2017 and component directory list
Start-Process -Wait -PassThru -FilePath vs_BuildTools.exe -ArgumentList '--add Microsoft.VisualStudio.Workload.NetCoreBuildTools \
    --add Microsoft.VisualStudio.Workload.WebBuildTools \
    --add Microsoft.VisualStudio.Workload.MSBuildTools \
    --add Microsoft.Net.Component.4.5.1.TargetingPack \
    --add Microsoft.Net.Component.4.5.2.TargetingPack \
    --add Microsoft.Net.Component.4.5.TargetingPack \
    --add Microsoft.Net.Component.4.6.TargetingPack \
    --add Microsoft.Net.Component.4.TargetingPack \
    --add Microsoft.Net.ComponentGroup.TargetingPacks.Common \
    --add Microsoft.Net.Component.3.5.DeveloperTools \
    --add Microsoft.Net.Component.4.6.2.SDK \
    --add Microsoft.Net.Component.4.6.2.TargetingPack \
    --add Microsoft.Net.Component.4.7.1.SDK \
    --add Microsoft.Net.Component.4.7.1.TargetingPack \
    --add Microsoft.Net.Component.4.7.SDK \
    --add Microsoft.Net.Component.4.7.TargetingPack \
    --add Microsoft.Net.ComponentGroup.4.6.2.DeveloperTools \
    --add Microsoft.Net.ComponentGroup.4.7.1.DeveloperTools \
    --add Microsoft.Net.ComponentGroup.4.7.DeveloperTools \
    --quiet \
    --nocache \
    --wait'

*Code snippet is part of Dockerfile
I expect netstandard.dll will be locate at GAC (c:\Windows\Microsoft.NET\assembly\GAC_MSIL\netstandard). Which package should I install additionally?

A: I've installed .NET Framework separately and it works now. Full Dockerfile

A: netstandard.dll will be in the GAC if the machine runs .NET Framework 4.7.1 or newer, I've installed it and fixed my problems with "netstandard.dll"


text:
Q: Qt/Qml VirtualKeyboard, switching language by physical keyboard shortcut in my application i using QtVirtualKeyboard and i have a problem:
When using the virtual keyboard, I cannot use the system keyboard shortcut to switch layouts.
The application will be used on touch screens and in the desktop version. I know that I can just disable the virtual keyboard for desktop mode, but I would like the virtual keyboard to be available on it too.
Tell me, is this behavior of the application when using a virtual keyboard in conjunction with a physical one - is this the norm? If so, is there a way to painlessly make friends with the system hotkey with changing the layout on the virtual keyboard?
So far, I have been able to implement only one solution - to define a hotkey in QML and, when it is activated, change the layout on the virtual keyboard, but I do not know how to get a list of available layouts in Qt.


text:
Q: Mongoose findOne queries for undefined values (not existent in database). I am using MERN to do an instagram clone I am trying to do a register for an instagram clone. You can register with username and email OR username and mobile.
When the user1 uses username and email, the mobile will be undefined in the database (not existent).
After adding the user1, I try to add the user2 using username and email as well. The mongoose findOne function queries for the undefined mobile of the user1 because user2 has undefined mobile as well. So, it says that the mobile is already in use..
user1.mobile = undefined AND user2.mobile = undefined as well, so it responds "Mobile already in use" message
I am trying to find a way to avoid for the query to find undefined or unexistent values or another way to solve my problem.
export const register = (req, res) => {
    const newUserData = req.body;
    User.findOne({ $or: [{ username: newUserData.username }, { email: newUserData.email }, { mobile: newUserData.mobile }] })
        .then(user => {
            if (user) {
                if (user.username === newUserData.username)
                    res.status(400).json({ message: { messageBody: "Username already in use", messageError: true } });
                else if (user.email === newUserData.email)
                    res.status(400).json(..."Email already in use"...);
                else if (user.mobile === newUserData.mobile)
                    res.status(400).json(..."Mobile already in use"...);
            }
            else {
                const newUser = new User(newUserData);
                newUser.save()
                    .then(user => {
                        res.status(201).json(..."Account succesfully created"...);
                    })
                    .catch(err => {
                        res.status(500).json(..."Error has occured (saving user)"...);
                    })
            }
        })
        .catch(err => {
            res.status(500).json(..."Error has occured (checking if user exists)"...);
        })

I am almost sure that the problem is because findOne finds a document that also has undefined mobile or undefined email even though the documents have nothing similar.
I could fix it..
I changed the Schema and set a default value for the email and mobile. So, if a user registers with username and email (no mobile), user.mobile will be undefined and there will not be undefined values for mobile field in the database because they will be all defaulted to something.
Cons: Cannot have default value plus unique, so had to make them not unique. Even though, The _id is still the primary key, and the username is also unique. Also, had to erase the whole database and start over.
PD: Thank you!

A: You need to check if the values exist and match with the supplied values.

if (user.username && user.username === newUserData.username)
    res.status(400).json({ message: { messageBody: "Username already in use", messageError: true } });
else if (user.email user.email === newUserData.email)
    res.status(400).json(..."Email already in use"...);
else if (user.mobile && user.mobile === newUserData.mobile)
    res.status(400).json(..."Mobile already in use"...);


text:
Q: I need help figuring this error percentage homework problem. Question: Government economists in a certain country have determined that the demand equation for soybeans is given by
$p = f(x) = \frac{55}{2x^2 + 1}$
where the unit price p is expressed in dollars per bushel and x, the quantity demanded per year, is measured in billions of bushels. The economists are forecasting a harvest of 2.4 billion bushels for the year, with a possible error of 10% in their forecast. Determine the corresponding error in the predicted price per bushel of soybeans. (Round your answer to one decimal place.)
This is my second question on similar problems and I am still having problems fully understanding this concept. So how would I go about step by step on answering this question. After seeing how wrong I was on my last question, I'd like to just start fresh and see how this is answered. Thanks for all the help in advance.

A: Hoping that I am not wrong, you are asked to evaluate the change of $$f(x) = \frac{55}{2x^2 + 1}$$ if $x$ changes by $10$% around $x=2.4$ that is to say if $\Delta x=0.24$. Using derivatives, you have $$\frac {df(x)}{dx}=-\frac{220 x}{\left(2 x^2+1\right)^2}$$ and then $$\Delta f(x)=-\frac{220 x}{\left(2 x^2+1\right)^2}\Delta x$$ So, if $x=2.4$,$f(2.4)=4.39297$,$\frac {df(x)}{dx}=-3.36841$.
I am sure that you can take from here.


text:
Q: MongoDB mgo aggregate earliest create date and latest last modified date I am trying to retrieve the earliest created date and latest last modified date for each object_name in the following data
{ "_id" : ObjectId("5a510666b2e543371cff44ef"), "object_name" : "A", "username" : "user1", "created_at" : ISODate("2018-01-06T17:24:54.026Z"), "last_modified" : ISODate("2018-01-06T17:24:54.026Z") }
{ "_id" : ObjectId("5a5106e7b2e543371cff4515"), "object_name" : "A", "username" : "user1", "created_at" : ISODate("2018-01-06T17:27:03.262Z"), "last_modified" : ISODate("2018-01-06T17:27:03.262Z") }
{ "_id" : ObjectId("5a510933b2e543371cff45be"), "object_name" : "B", "username" : "user1", "created_at" : ISODate("2018-01-06T17:36:51.300Z"), "last_modified" : ISODate("2018-01-06T17:36:51.300Z") }
{ "_id" : ObjectId("5a510939b2e543371cff45c5"), "object_name" : "C", "username" : "user2", "created_at" : ISODate("2018-01-06T17:36:57.058Z"), "last_modified" : ISODate("2018-01-06T17:36:57.058Z") }

I have no problem to group distinct object_name with each username with the following pipeline
pipeline := []bson.M{
    {"$group": bson.M{"_id": "$username", "objects": bson.M{"$addToSet": "$object_name"}}},
}

However I also want to add earliest created date and latest last modified date for each object.
Here is my desired output:
[
    {
        "_id": "user1",
        "objects": [
            {
                "object_name": "A",
                "created_at": "2018-01-06T17:24:54.026Z",
                "last_modified": "2018-01-06T17:27:03.262Z"
            },
            {
                "object_name": "B",
                "created_at": "2018-01-06T17:36:51.300Z",
                "last_modified": "2018-01-06T17:36:51.300Z"
            }
        ]
    },
    {
        "_id": "user2",
        "objects": [
            {
                "object_name": "C",
                "created_at": "2018-01-06T17:36:57.058Z",
                "last_modified": "2018-01-06T17:36:57.058Z"
            }
        ]
    }
]

I think it has something to do with $sort and $first or $last but I don't know how to put them together.

A: You can try below aggregation query.
db.colname.aggregate([
{"$group":{
  "_id":{
    "username":"$username",
    "object_name":"$object_name"
  },
  "created_at":{"$min":"$created_at"},
  "last_modified":{"$max":"$last_modified"}
}},
{"$group":{
  "_id":"$_id.username",
  "objects":{
    "$push":{
      "object_name":"$_id.object_name",
      "created_at":"$created_at",
      "last_modified":"$last_modified"
    }
  }
}}])


text:
Q: Kubernetes cannot pull image from local docker images I have a single-node k8s server.
I want to run a k8s pod from a .tar.gz file.
I do this:
$ docker load -i myapp.tar.gz

and I verify it with:
$ docker images
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
myapp        1.0     f6b7a8b41894   2 months ago     33MB

I have a values.yaml file:
myapp:
  myapp:
    image: "myapp:1.0"
    imagePullPolicy: IfNotPresent
    ifname: eth0
    resources:
      limits:
        cpu: 100m
        memory: 128Mi
      requests:
        cpu: 100m
        memory: 128Mi
    autoscale:
      minReplicas: 1
      maxReplicas: 2
      targetCPUUtilizationPercentage: 90

and I install it with Helm.
and then I check the deployed pod:
$ kubectl get pods -A

and I see ImagePullBackOff error.
When I describe the pod, I get this error:
  Normal   Scheduled  3m17s                 default-scheduler  Successfully assigned cs1/myapp-7589554bd4-4pprj to masternode1
  Normal   Pulling    100s (x4 over 3m16s)  kubelet            Pulling image "myapp:1.0"
  Warning  Failed     99s (x4 over 3m14s)   kubelet            Failed to pull image "myapp:1.0": rpc error: code = Unknown desc = failed to pull and unpack image "docker.io/library/myapp:1.0": failed to resolve reference "docker.io/library/myapp:1.0": pull access denied, repository does not exist or may require authorization: server message: insufficient_scope: authorization failed

Any idea how can I resolve this issue?


text:
Q: Does Google 'understand' microformats and will it help my SEO? Semantic HTML makes it easier for Google to crawl and 'understand' a website but what about microformats? Are microformats any more semantic/crawlable then standard HTML markup?

A: Google announced a little bit of RDFa and Microformats support in the last few days.
Links and commentary here:
http://rdfa.info/2009/05/12/google-announces-support-for-rdfa/
Yahoo has been using RDFa and Microformats to drive Search Monkey for some time:
http://developer.yahoo.com/searchmonkey/
Both will probably aid click-through rates, but not necessarily ranking. Expect more search engines to use more different RDFa vocabularies as time goes on. BOSS is also relevant here:
http://developer.yahoo.com/search/boss/
The intent is to help create more search engines and they will have access to the data in the pages.

A: For geographical information, Google will parse KML files and index them and the links in them.
I believe that Yahoo has gotten behind RDFa I don't think that Google has admitted to this yet.

A: AFAIK, all major search engines support the rel-nofollow microformat. Beyond that, I'm not aware of any support. However, there are smaller, more specialized search engines that have been specifically designed with microformats in mind. E.g. there are search engines that allow you to do searches on relationships between persons, using the XFN microformat.

A: As far as i know Google doesn't actively talk about these micro formats as a way of generating your page rank, from what i understand its more for other kinds of bots that are not just making a general purpose search engine.

A: At the moment Google did not announce any support for microformats yet. I hope, that in the near future they will.
On the other hand Yahoo has announced that it will support RDFa, eRDF and microformats.

A: They make your pages more semantic insofaras they force a bit more consistency in the way that you fit your information together. The major search engines can and do read microformats, and often use them to display what Google calls "rich snippets" ( http://googlewebmastercentral.blogspot.com/2009/05/introducing-rich-snippets.html ), which adds some interesting stuff to SERPs. Bing and Yahoo both display these too.


text:
Q: android how to get particular image present in sd card I want any one image present in the sdcard.
I only know the image name.
But how can i retrieve that particular image within my program(including path). And also to convert into a bitmap or stored in a bitmap variable
How can I do that?
Thank you

A: Here, you can show all images in SDCard and when you click one of them, you get the path of selected image:
try {
        // Set up an array of the Thumbnail Image ID column we want
        String[] projection = { MediaStore.Images.Thumbnails._ID };
        // Create the cursor pointing to the SDCard
        cursor = managedQuery(
                MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                projection, // Which columns to return
                null, // Return all rows
                null, MediaStore.Images.Thumbnails.IMAGE_ID);

        // Get the column index of the Thumbnails Image ID
        columnIndex = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);

        GridView sdcardImages = (GridView) findViewById(R.id.gallary);
        sdcardImages.setAdapter(new ImageAdapter(this));

        // Set up a click listener
        sdcardImages.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v,
                    int position, long id) {
                // Get the data location of the image
                String[] projection = { MediaStore.Images.Media.DATA };
                cursor = managedQuery(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        projection, // Which columns to return
                        null, // Return all rows
                        null, null);
                columnIndex = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToPosition(position);
                // Get image filename
                String imagePath = cursor.getString(columnIndex);
                // Use this path to do further processing, i.e. full screen
                // display
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

And here is the ImageAdapter:
/**
 * Adapter for our image files.
 */
private class ImageAdapter extends BaseAdapter {

    private Context context;

    public ImageAdapter(Context localContext) {
        context = localContext;
    }

    public int getCount() {
        return cursor.getCount();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView picturesView;
        if (convertView == null) {
            picturesView = new ImageView(context);
            // Move cursor to current position
            cursor.moveToPosition(position);
            // Get the current value for the requested column
            int imageID = cursor.getInt(columnIndex);
            // Set the content of the image based on the provided URI
            picturesView.setImageURI(Uri.withAppendedPath(
                    MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""
                            + imageID));
            picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            picturesView.setPadding(8, 8, 8, 8);
            picturesView
                    .setLayoutParams(new GridView.LayoutParams(100, 100));
        } else {
            picturesView = (ImageView) convertView;
        }
        return picturesView;
    }
}

And if you know the exact path and image name, you can get Bitmap by using:
Bitmap bitmap = BitmapFactory.decodeFile("yourImageDirectory" + "yourImageName.png");


text:
Q: How to Update the FS Manufacturer and Model on Stock Items using Acumatica I'm trying to update the Manufacturer and Manufacturer Model on the "Service Management" tab of the Stock Item (IN202500).
I'm about 99% sure that they must be in a Graph Extension, but the Schema Browser only indicates that they are in a DLL, not the name of the extension. More generically, if a field is in an Extension, is there a way to find out which one? Or enumerate the extensions that exist in a Graph Cache?
InventoryItem row = Base.ItemSettings.Current;

// This doesn't work. InventoryItemFSxEquipmentModel isn't the name of the extension and IDK how I figure out what it is.
InventoryItemFSxEquipmentModel rowExt2 = PXCache<InventoryItem>.GetExtension<InventoryItemFSxEquipmentModel>(row);

// This also doesn't work, as it isn't in the base model.
throw new PXException(row.ManufacturerID.ToString());

A: To find out which graph extension a field is in, you can use the "Customization Project Editor" in Acumatica:

*

*Open the "Customization Project Editor" (SM204505) screen in Acumatica.

*In the "Object Name" field, type "InventoryItem" and click "Search".

*Click the "+" icon next to "InventoryItem" to expand the list of customization items for the InventoryItem DAC.

*Look for the field you're interested in (in this case, Manufacturer and Manufacturer Model), and you should see the name of the graph extension that contains that field listed next to it.

Once you know the name of the graph extension, you can use that to get the extension instance for the current record, like this:
InventoryItem row = Base.ItemSettings.Current;
InventoryItemExt rowExt = row.GetExtension<InventoryItemExt>();

Replace "InventoryItemExt" with the name of the actual graph extension that contains the fields you're interested in.
Then you can access the Manufacturer and Manufacturer Model fields like this:
string manufacturer = rowExt.UsrManufacturer;
string model = rowExt.UsrManufacturerModel;

Replace "UsrManufacturer" and "UsrManufacturerModel" with the names of the actual fields in the graph extension that you're working with.


text:
Q: Como inserir um Trigger Insert na Tabela Estoque after Insert na Tabela Produto no IBM DB2 Estou tentando aprender o básico de DB2 e modelei um banco na qual preciso inserir na tabela "estoque" um valor default para cada produto cadastrado na tabela "produto" conforme recorte abaixo.
Esta inserção é realizada por um trigger que funciona com a devida sintaxe tanto no MYSQL quanto no Oracle.
No IBM DB2 V11 EXPRESS-C, entretanto, eu não consigo nem inserir o trigger pois recebo a mensagem "Failed queries => 4". Verifiquei alguns exemplos de triggers para DB2 e não consigo perceber qual o erro que estou cometendo.
Segue abaixo recorte das tabelas, do trigger e a resposta do sistema
- -----------------------------------------------------
-- Table lojamodel.produto
-- -----------------------------------------------------
CREATE TABLE produto (
  idProduto INT NOT NULL PRIMARY KEY
  GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1),
  prod_nome VARCHAR(45) NOT NULL,
  prod_descricao VARCHAR(60) NOT NULL,
  prod_grupo VARCHAR(15) NOT NULL,
  prod_codigo13d VARCHAR(13) NOT NULL,
  prod_codloja VARCHAR(5) NOT NULL,
  prod_fornecid INT NOT NULL,
  FOREIGN KEY (prod_fornecid)
    REFERENCES fornecedor (idFornecedor)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

-- Produtos
insert into produto (prod_nome, prod_descricao, prod_grupo, prod_codigo13d, prod_codloja, prod_fornecid) values('Notebook ABCERF M15', 'Notebook 16G 2T I7 15.6 ', 'Computadores', '7891000001311', '1311', 1);
insert into produto (prod_nome, prod_descricao, prod_grupo, prod_codigo13d, prod_codloja, prod_fornecid) values('Notebook ABCERF M2 S14', 'Notebook 8G 1T I5 14', 'Computadores', '7891000001312', '1312', 1);
insert into produto (prod_nome, prod_descricao, prod_grupo, prod_codigo13d, prod_codloja, prod_fornecid) values('Monitor AFODCS 24', 'Monitor 24" LED', 'Monitores', '7891000001321', '1321', 2);
insert into produto (prod_nome, prod_descricao, prod_grupo, prod_codigo13d, prod_codloja, prod_fornecid) values('Monitor AFODCS21', 'Monitor 21,5" LED', 'Monitores', '7891000001322', '1322', 2);

CREATE TABLE estoque (
  idestoque INT NOT NULL PRIMARY KEY
  GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1),
  est_quantidade INT NOT NULL DEFAULT '0',
  est_precovenda FLOAT NOT NULL DEFAULT '0.00',
  est_minquant INT NOT NULL DEFAULT '1',
  est_prodid INT NOT NULL,
  FOREIGN KEY (est_prodid)
    REFERENCES produto (idProduto)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

-- Meu  Trigger

CREATE OR REPLACE TRIGGER insere_estoque
AFTER INSERT ON produto
FOR EACH ROW MODE DB2SQL
BEGIN
  declare v_codigo int default 0;
  set v_codigo = (select max(idproduto) from produto);
  insert into estoque (est_quantidade, est_precovenda, est_minquant, est_prodid) values (0, 0.00, 2, v_codigo);
END@

--  DB2 Resultado de SQL
Script2.sql

CREATE TRIGGER insere_estoque
AFTER INSERT ON produto
FOR EACH ROW MODE DB2SQL

BEGIN
declare v_codigo int default 0
set v_codigo = (select max(idproduto) from produto)
insert into estoque (est_quantidade, est_precovenda, est_minquant, est_prodid) values (0, 0, 2, v_codigo)
END

Failed queries => 4
Total execution time => 0 ms


text:
Q: AMP-Story , Dynamic Bookend.json i want to create this dynamically
"related-articles": {
"Articles": [
  {
    "title": "Pet adoption",
    "url": "https://en.wikipedia.org/wiki/Pet_adoption",
    "image": "/assets/related-dogs.jpg"
  },
  {
    "title": "Learn about cats",
    "url": "https://en.wikipedia.org/wiki/Cat",
    "image": "/assets/related-cats.jpg"
  }
]

}
which is helpful for create amp-story bookend.json


text:
Q: Ruby-Rspec: Initialize PageObjects once in spec_helper instead of each spec I variables set for xpaths in a file called PageObjects. Each spec I run I initialize the page objects with "p = PageObjects.new". However, I would like to initialize "p = PageObjects.new" once in "spec_helper.rb" instead of each spec.
This still gives me "error: uninitialized constant PageObject"...
require 'selenium-webdriver'
require 'yaml'
require 'rspec/retry'
require 'pry'
require 'bundler/setup'

p = PageObject.new
RSpec.configure do |config|
  config.default_sleep_interval = 1
  config.default_retry_count = 4
  config.verbose_retry = false
  config.display_try_failure_messages = true
  config.exceptions_to_retry = [Net::ReadTimeout, Capybara::ElementNotFound]
end

Is there a way to achieve my goal by initializing PageObject once inside spec_helper rather than in each spec?

A: RSpec helpers seems to be the perfect solution for you
define the helper.rb
module Helpers
  def p
    @page_object ||= PageObject.new
  end
end

Configure RSpec to include it:
RSpec.configure do |c|
  c.include Helpers
end

And then you can use p method that will give you the PageObject:
specify do
  expect(p).to be_a(PagObject)
  expect(p.object_id).to eq(p.object_id)
end

A: You effectively want your test database to be maintained between tests. This is dangerous for a number of reasons, the most obvious being previous tests will affect future ones. As you're dealing with the same PageObject you will need to reset it between tests.
Putting that to one side, the options for enabling / disabling this can be found at:
https://relishapp.com/rspec/rspec-rails/docs/transactions, namely:

When you run rails generate rspec:install, the spec/rails_helper.rb
  file includes the following configuration:

RSpec.configure do |config|
  config.use_transactional_fixtures = true
end

The name of this setting is a bit misleading. What it really means
  in Rails is "run every test method within a transaction." In the
  context of rspec-rails, it means "run every example within a
  transaction."
The idea is to start each example with a clean database, create
  whatever data is necessary for that example, and then remove that data
  by simply rolling back the transaction at the end of the example.
Disabling transactions If you prefer to manage the data yourself, or
  using another tool like database_cleaner to do it for you, simply tell
  RSpec to tell Rails not to manage transactions:

RSpec.configure do |config|
  config.use_transactional_fixtures = false
end


text:
Q: Añadir valor a columnas de un GridView por medio de query Mi problema es que necesito rellenar un RadGridView, con su propio DataSource en el que tengo columnas con datos y otras columnas que no tienen, en estas columnas sin datos necesito insertarlos por medio de un query, ¿es esto posible de algún modo?
Lo que había intentado es recorrer las filas del grid e igualar el valor de las columnas a la query, pero no es posible.
private void RecorrerGrid()
{
    try
    {
        foreach(GridViewRowInfo row in radGridView1.Rows)
        {
            switch (row.Cells["Tipo_Tarea"].Value)
            {
                case "PI":
                    row.Cells["Referencia_Pedido_Cliente"].Value =
                    "SELECT COALESCE(PED.REFERENCIA,'')AS Referencia_Pedido_Cliente FROM DBO.TBLTAREASPENDIENTES AS TP LEFT OUTER JOIN DBO.TBLORDENRECOGIDALIN AS LN ON LN.IDORDENRECOGIDA = CAST(TP.TAREA AS INTEGER)  LEFT OUTER JOIN DBO.TBLPEDIDOSCLICAB AS PED ON PED.IDPEDIDOCLI =LN.IDPEDIDOCLI  LEFT OUTER JOIN DBO.TBLRUTAS AS R ON PED.IDRUTA = R.IDRUTA  LEFT OUTER JOIN DBO.TBLCLIENTES AS C ON PED.IDCLIENTE = C.IDCLIENTE WHERE(TP.TIPOTAREA= 'PI')";
                break;


text:
Q: Swap the words of a string in Javascript I want to swap words of string in such a way that the first word is swapped with the last word ,the second word with the second last word and so on using plain javascript.
Eg :- "Secret Life is Beautiful Key"
Output :- "Key Beautiful is Life Secret"

A: Hey the easiest solution would be:

  const str = 'Secret Life is Beautiful Key'

  console.log(str.split(' ').reverse().join(' '))

A: I hope this helps

var str = 'Secret Life is Beautiful Key';
var reversed = str.split(' ').reverse().join(' ');
console.log(reversed);


text:
Q: Find maximum lattice-point triangle with orthocenter at origin I was wondering if someone could help me understand this problem:
Let $S$ be the set of points $(x,y)$ in the Cartesian plane for which $\left(\tfrac{x}{x^2+y^2},\tfrac{y}{x^2+y^2}\right)$ is a lattice point. Find the largest possible area of a triangle with vertices in $S$ and orthocenter at the origin.
So I assume that means find all $(x,y)\in\mathbb{R}:\left(\frac{x}{x^2+y^2},\frac{y}{x^2+y^2}\right)\in\mathbb{Z}\backslash\{0,0\}$ correct?  If that's the case, then it's easy to identify these points as solutions to the equations
$$
\begin{align}
\frac{x}{x^2+y^2}=n\\
\frac{y}{x^2+y^2}=m
\end{align}
$$
with $(n,m)\in\mathbb{Z}$.  This turns out to be the intersections of four (infinitely) concentric circles shown in the plot below with the dot in $S$ and so the matter then becomes finding the largest triangle with such vertices and orthocenter at the origin.
Is this the correct way of interpreting this problem?  I get $3/10$ as the answer if so but that's only by brute-force checking and I at present do not have a rigorous proof.
Thanks guys.
:

A: $$\frac{x}{x^2+y^2}=n \qquad \frac{y}{x^2+y^2}=m$$
$$x^2 = n^2(x^2+y^2)^2 \qquad y^2 = m^2(x^2+y^2)^2$$
$$(x^2+y^2)=(m^2+n^2)(x^2+y^2)^2$$
$$(m^2+n^2)(x^2+y^2) = 1$$
$$x^2+y^2 = \dfrac{1}{m^2+n^2}$$
So $(x,y)$ can be any point on the circle with center at the origin and radius of $\dfrac{1}{\sqrt{m^2+n^2}}$
With $m,n \in \mathbb Z$, the largest possible radius is $\dfrac{1}{2}$.
From this answer the largest triangle will be any equilateral triangle inscribed on the circle $x^2+y^2=\dfrac 12$.  Which, as you commented, has an area of $\dfrac 38 \sqrt 3$


text:
Q: Are the highlighted past participles acting as adjectives or passive voice in these examples?
The park was covered with snow.
Mr. Smith is known to everyone in this town.
The legislator participates in the delegation and is involved in sweeping reforms.
English is spoken in the UK.

In these sentences, are the highlighted past participles acting as adjectives or passive voice?

A: For passive voice, you are describing an activity with the object at the start of the sentence.

The salmon has been smoked - an activity: passive mood

When a past participle is used to describe the state of something, its usage is adjectival:

The salmon is smoked - a state: adjective

It's difficult to tell without a context, but your first three sentences probably describe a state, not an activity: for example, the state of the park is "covered with snow". If the context gave some clues about how the snow got there, it could instead be taken as an activity. When you use a past participle to describe a state, its role is adjectival.
The final sentence could be regarded as either describing an activity (people speak English in the UK) or, more likely, a state (English is the language that is spoken in the UK).

A: All your highlighted past participles are acted as passive voice.
These are the tips to distinguish whether past participles are acted as passive voice or adjective:

*

*Describe an action that the subject could not do by itself => Passive voice
For example:

*

*The mouse was trapped.

*The park was covered with snow.

*Mr. Smith is known to everyone in this town.

*Describe the state of the subject or the native of the subject => Adjective
For example:

*

*She is interested in reading books (The native of the subject).

*I'm bored (The state of the subject).

*You are so attracted to power (The native of the subject).

*I'm very tired (The state of the subject).


text:
Q: How to write a Switch statement for unit conversion using Javascript Switch statement for unit conversion using Javascript.

A: You tried to use "unit" as js variable which is already part of loaded document, need to correct your code as below,

<!DOCTYPE html>

<input id="units" type="number" placeholder="Feet" value="1"/>

Again, need to write separate function to load values from input field to screen. it could be event based like keypressed, mouse or simple button.

A: Below are some issues in your code:

*

*unassigned variable valNum

*output was given in case 1:

*syntax error in switch-case.

function calc() {
  var unit = parseInt(document.getElementById("unit").value, 10) || -1;
  var feet = parseInt(document.getElementById("feet").value, 10) || 0;
  var result = 0;
  switch (unit) {
    case 0:
      result = 'Result is: ' + (feet / 3.2808);
      break;
    case 1:
      result = 'Result is: ' + (feet / 0.0022046);
      break;
    default:
      result = 'Unit ##.##';
      break;
  }
  document.getElementById("demo").innerHTML = result;
}

Unit ##.##

<input placeholder="Unit" oninput='calc()' id='unit' />
<input placeholder="Feet" oninput='calc()' id='feet' />


text:
Q: How to create a boost::tuple with the specified number of elements (of the same type)? Assume that I have the following class definition:
template <unsigned int N>
class foo
{
    boost::tuples::tuple<...> bar;
};

Given the compile-time constant N, I would like to expand the type of bar to be a tuple that holds N elements of a specified type. That is, the type of foo<2>::bar would be boost::tuples::tuple<T, T>. I'm guessing that I can use Boost.MPL for this, but I haven't figured out the exact sequence yet. I think I could do:
template <typename T, int N>
struct type_repeater
{
    typedef typename boost::mpl::fold<
        boost::mpl::range_c<T, 0, N>,
        boost::mpl::vector<>,
        boost::mpl::push_back<_1, T>
    >::type type;
};

So then for instance type_repeater<T, 2>::type would be equivalent to boost::mpl::vector<T, T>. I'm just not sure how/if I can take that type list and inject it into the argument list of a tuple, like I want. Is this possible?

A: This seems to be a good minimal example using C++11
#include <tuple>
template <unsigned int N, typename T>
struct type_repeater {
  typedef decltype(std::tuple_cat(std::tuple<T>(), typename type_repeater<N-1, T>::type())) type;
};

template <typename T>
struct type_repeater<0, T> {
  typedef decltype(std::tuple<>()) type;
};

int main() {
  type_repeater<3, float>::type asdf;
  std::get<0>(asdf);
  std::get<1>(asdf);
  std::get<2>(asdf);
}

A: Although this is totally doable with variadic templates and std::tuple, the best solution for what you want I think is to just use std::array. If you simply want a container with N instances of T, the std::array signature is already template <typename T, std::size_t N> class array. I think it fits your need exactly.
Having said that, if you really want std::tuple for some reason you can do it like so:
#include <tuple>

/* Forward declaration. */
template <std::size_t N, typename T>
class Tuple;

/* Convenience type alias. */
template <std::size_t N, typename T>
using TTuple = typename Tuple<N, T>::type;

/* Base case. */
template <typename T>
class Tuple<0, T> {
  public:

  using type = std::tuple<>;

}; // Tuple<0>

/* Recursive case. */
template <std::size_t N, typename T>
class Tuple {
  public:

  /* Note the use of std::declval<> here. */
  using type = decltype(std::tuple_cat(std::declval<std::tuple<T>>(),
                                       std::declval<TTuple<N - 1, T>>()));

};  // Tuple<N, T>

/* std::declval<> is necessary to support non default constructable classes. */
class NoDefault {
  public:

  NoDefault() = delete;

};  // Foo

/* Sample use. */
static_assert(std::is_same<TTuple<2, NoDefault>,
                           std::tuple<NoDefault, NoDefault>>::value, "");

int main() {}

Note: If you don't have access to C++11 but do have access to boost, boost::array and boost::tuples::tuple will do fine in lieu of std::array and std::tuple.

A: Since you explicitly ask for a way to make mpl::vector into a runtime container, I recommend you stay Boosty and use Fusion's as_vector:
Given your initial example where you mol::fold to get an mpl::vector, you would then use:
boost::fusion::result_of::as_vector<
    mpl::vector<T, T>
>::type;

To get a Fusion Vector, which seems to be what you want. Boost Fusion fills the gap between the compile-time and runtime world.
Also, this is pre C++11, which is still important in many (maybe most?) projects.


text:
Q: How to get the function name while in a function for debug strings? I want to output the function name each time it is called, I can easily copy and paste the function name, however I wondered if there was a shortcut that would do the job for me?
At the moment I am doing:
SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
    qDebug("lynxThreeFile::readSlideInfoHeader");
}

but what I want is something generic:
SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
    qDebug(this.className() + "::" + this.functionName());
}

A: If you are using gcc you may find __PRETTY_FUNCTION__ more to your liking.

A: __func__ is c99 ( which does in turn mean it might not work with visual studio - but hey it's standard :o) )
__FUNCTION__ works pretty much everywhere
__PRETTY_FUNCTION__ is gnu specific and returns the full qualified name with (namespaces?), classname, returntype, functionname, parameterslist

A: If you check out boost there is a macro BOOST_CURRENT_FUNCTION that is portable across platforms. In the C99 standard there is a compiler variable __func__ that has the desired effect. I believe has been accepted into the C++0x standard. A reasonable number of compilers will already support this.

A: "__FUNCTION__" is supported by both MSVC and GCC and should give you the information you need.

A: I see from your example that you are using Qt. In which case your best bet is to use Q_FUNC_INFO found in <QGlobal>. Here's the description:

Expands to a string that describe the
  function the macro resides in. How
  this string looks more specifically is
  compiler dependent. With GNU GCC it is
  typically the function signature,
  while with other compilers it might be
  the line and column number.


text:
Q: Show a webpage as thumbnail on mouse over I am designing a website having lot of sub-pages.  So the links are placed on a single page when the user hover the link i need to show the corresponding webpage as thumbnail in a tooltip.
I tried may jquery plugins but they are provide image based thumbnail view only.
I came across below
data:text/html,

Past it on browser's address bar will load webpage in iframe.But i dont know how make the above code works with ajax.
Thanks.

A: Source: jQuery Webpage Preview


text:
Q: Domain model and grouped data I'm starting to catch the domain model idea but there is one thing that I fail to see how this is realized in domain model - grouped data. The most obvious example is various reports, with or without dynamic column grouping and user specified order of columns.
I'll try to provide specific example. Imagine following domain model:
Orders [1-to-many] Positions [1-to-many] Production items

Displayed as simple 3 level list.
Order 1
- Position 1
  - Production item 1, length: 2.5, weight: 1.234
  - Production item 2, length: 2.5, weight: 2.345
  - Production item 3, length: 5, weight: 3.456

Then goes the requirement to modify Position level by adding "length" field (just for the display, the Position entity itself is NOT altered) from Production item and group by this field.
Order 1
- Position 1, length: 2.5
  - Production item 1, length: 2.5, weight: 1.234
  - Production item 2, length: 2.5, weight: 2.345
- Position 1, length: 5
  - Production item 3, length: 5, weight: 3.456

And next requirement is to add another SUMmed field "weight" from Production item level in Position level. Again, only on display.
Order 1
- Position 1, length: 2.5, weight: 3.579
  - Production item 1, length: 2.5, weight: 1.234
  - Production item 2, length: 2.5, weight: 2.345
- Position 1, length: 5, weight: 3.456
  - Production item 3, length: 5, weight: 3.456

What I need to change to achieve this "artifical" model?
Seems like some sort of composite value object is needed in place where goes Positions: all Position entity fields + size field + weight field. Am I on the right track?

A: If you are using NHibernate as your ORM tool, you can use the Projection functions to perform grouping and aggregate function such as 'sum' and 'count'. This leaves the problem of what entity to return from the query though, as your Position entity probably won't have the 'weight' field. I tend to just have a new entity (maybe entity is not the right word) called PositionQueryResult or something similar. Something to differentiate fromthe actual Position entity. This 'entity' has no behaviour - just properties that should be returned. I've not seen this advocated anywhere, but it works for me.
However, you refer to this as 'reporting'. One school of thought says that reporting should not be included in your domain, that it is something separate. This can be quite a good paradigm to follow, because ORM is better for Domain Model programming, but raw SQL is often better for reporting.


text:
Q: Last-child doesn't seem to be working This is the code I have:
HTML:

Link 1

Link 2

Link 3

Link 4

CSS:
#nav ul li a {
 width:162px;
 background:url('http://i.imgur.com/DmeCv.png') -164px 0px;

#nav ul li:first-child a {
 width:164px;
 background:url('http://i.imgur.com/DmeCv.png');
}

#nav ul li:last-child a {
 background:url('http://i.imgur.com/DmeCv.png') -326px 0px;
}

So far, so good. This works, and displays the image properly.
#nav ul li a:hover {
 background:url('http://i.imgur.com/DmeCv.png') -164px -50px;
}

#nav ul li:first-child a:hover {
 background:url('http://i.imgur.com/DmeCv.png') 0px -50px;

#nav ul li:last-child a:hover {
 background:url('http://i.imgur.com/DmeCv.png') -326px -50px;
}

This doesn't work, however. It displays the mid section hover image, rather than the last-child hover image.
Here is an example:
http://result.dabblet.com/gist/2973127/8bf204a16e7caca43ad129cad141fa4810bf18ce

A: In your CSS example, you are missing your closing curly brace } in first-child a:hover.


text:
Q: Concatenate object's properties of variable length of a C# object into a new property of the object Having this problem solved in JavaScript, I'm trying to do the same using C# for a C# object, not a JSON.
Basically, the JS solving looks like this:
myObject.myObject.forEach(arr => {
 arr.prop = arr.parameters.reduce((res,obj)=> res+obj.special, '')
})

so I tried to do it like:
foreach (array arr in myObject.myObject)
{
    arr.prop = arr.parameters.reduce();
}

I didn't find any function like the JS reduce in C#.
Do you have any suggestions how to solve this?

A: You could do this by first getting all fields or Properties from an object via Reflection
var fields = myObject.GetType().GetFields();

then you pull all current values from those fields and make strings of it
var values = fields.Select(e => e.GetValue(myObject)?.ToString());

and after that, just aggregate the values
var allFieldsInOne = values.Aggregate((e,f) => e + f);


text:
Q: How does wok relative time in different time zones? I am confused about using datetimes in databases and applications for international users. My application is developed asp.net web api and c# programming language.
I am using a column in database (postgresql) named created_at that type is without timezone.
When New York Time 2020-11-02 23:50:00, London Time is  2020-11-03 04:50:00. So day and hour is different.
And I want to show dates in relative time like Now, 1 Hours ago, 10 minutes ago...
If Someone adds a record in database at 2020-11-03 04:50:00 in London, someone shows the record as relative time 5 hours after. This looks a little strange.
Is this a true logic? How does it workin real applications?

A: You could store your datetime as UTC and convert it to the users time zone correspondingly.
Or you could store your values in postgreSQL via its designated time types.
(see https://www.postgresql.org/docs/9.1/datatype-datetime.html)


text:
Q: jQuery targeting data-post_id So, I have the following div and form:
<?php echo '
' ;?>

       <?php the_title(); ?>

<form>
  <input type="text" name="title" id="title">
  <input type="text" name="post_id" id="post_id">
  <input type="submit">
</form>

Now in jQuery:
 var title   = jQuery('#title').val();
 var post_id   = jQuery('#post_id').val();
 ...
 success : function(data){
     jQuery('.title ??????').html(title);
 }

So, when the form is submitted, I want to replace the
 with the input field (title in this case).
Because the form will have a specific post_id, I want to find the div with the same data-post_id.
How do I target the div with the same post_id as the form post_id based on the data-post_id?
Thanks!

A: Well actually you can do this, that should do the trick:
 var title   = jQuery('#title').val();
 var post_id   = jQuery('#post_id').val();
 ...
 success : function(data){
     jQuery('h2[data-post_id="' + post_id + '"] .title').html(title);
 }


text:
Q: Two rows in a menu with css and bootstrap I am trying to create header in a page, with a logo on the left side in the middle, and two like menus in 2 rows on the right side. How can I do it with css and using some classes from bootstrap? something like this
--------------------------------------------------|
          |    menu items 1 (aligned top-right)   |
Logo here |---------------------------------------|
          |    menu items 2 (aligned bottom-right)|
--------------------------------------------------|

A: Here is the code

    // logo goes here

      // upper part of menu

      // lower part of menu