text:
Q: Create Array Object using for loop inside javascript I am having below data
 var counts = ["2017-01-01T00:00:00Z", 0, "2017-02-01T00:00:00Z", 0, "2017-03-01T00:00:00Z", 0, "2017-04-01T00:00:00Z", 0, "2017-05-01T00:00:00Z", 0, "2017-06-01T00:00:00Z", 0, "2017-07-01T00:00:00Z", 0, "2017-08-01T00:00:00Z", 0, "2017-09-01T00:00:00Z", 0, "2017-10-01T00:00:00Z", 0, "2017-11-01T00:00:00Z", 0, "2017-12-01T00:00:00Z", 0, "2018-01-01T00:00:00Z", 0, "2018-02-01T00:00:00Z", 0, "2018-03-01T00:00:00Z", 0, "2018-04-01T00:00:00Z", 18, "2018-05-01T00:00:00Z", 482, "2018-06-01T00:00:00Z", 272];

I am trying below code to get my expected result but unfortunately not getting result.
var result = [];
for (i = 0; i < counts.length; i++) {
    console.log(counts[i]);
    resultObj = {"date":counts[i],"post":counts[i+1]};
    result.push(resultObj);
}

Expected result
var finalResults = [{"date":"2017-01-01T00:00:00Z",post:0},{"date":"2017-02-01T00:00:00Z",post:0},{"date":"2017-03-01T00:00:00Z",post:0},{"date":"2017-04-01T00:00:00Z",post:0},{"date":"2017-05-01T00:00:00Z",post:0},{"date":"2017-06-01T00:00:00Z",post:0},{"date":"2017-07-01T00:00:00Z",post:0},{"date":"2017-08-01T00:00:00Z",post:0},{"date":"2017-09-01T00:00:00Z",post:0},{"date":"2017-10-01T00:00:00Z",post:0},{"date":"2017-11-01T00:00:00Z",post:0},{"date":"2017-12-01T00:00:00Z",post:0},{"date":"2018-01-01T00:00:00Z",post:0},{"date":"2018-02-01T00:00:00Z",post:0},{"date":"2018-03-01T00:00:00Z",post:0},{"date":"2018-04-01T00:00:00Z",post:18},{"date":"2018-05-01T00:00:00Z",post:482},{"date":"2018-06-01T00:00:00Z",post:272}]

var counts = ["2017-01-01T00:00:00Z", 0, "2017-02-01T00:00:00Z", 0, "2017-03-01T00:00:00Z", 0, "2017-04-01T00:00:00Z", 0, "2017-05-01T00:00:00Z", 0, "2017-06-01T00:00:00Z", 0, "2017-07-01T00:00:00Z", 0, "2017-08-01T00:00:00Z", 0, "2017-09-01T00:00:00Z", 0, "2017-10-01T00:00:00Z", 0, "2017-11-01T00:00:00Z", 0, "2017-12-01T00:00:00Z", 0, "2018-01-01T00:00:00Z", 0, "2018-02-01T00:00:00Z", 0, "2018-03-01T00:00:00Z", 0, "2018-04-01T00:00:00Z", 18, "2018-05-01T00:00:00Z", 482, "2018-06-01T00:00:00Z", 272];

var result = [];
for (i = 0; i < counts.length; i++) {
  console.log(counts[i]);
  resultObj = {
    "date": counts[i],
    "post": counts[i + 1]
  };
  result.push(resultObj);
}

console.log(result)

A: Try the following :

var counts = ["2017-01-01T00:00:00Z", 0, "2017-02-01T00:00:00Z", 0, "2017-03-01T00:00:00Z", 0, "2017-04-01T00:00:00Z", 0, "2017-05-01T00:00:00Z", 0, "2017-06-01T00:00:00Z", 0, "2017-07-01T00:00:00Z", 0, "2017-08-01T00:00:00Z", 0, "2017-09-01T00:00:00Z", 0, "2017-10-01T00:00:00Z", 0, "2017-11-01T00:00:00Z", 0, "2017-12-01T00:00:00Z", 0, "2018-01-01T00:00:00Z", 0, "2018-02-01T00:00:00Z", 0, "2018-03-01T00:00:00Z", 0, "2018-04-01T00:00:00Z", 18, "2018-05-01T00:00:00Z", 482, "2018-06-01T00:00:00Z", 272];

var result = [];
for(var i = 0; i < counts.length; i+= 2){
  var obj = {};
  obj.date = counts[i];
  obj.post = counts[i+1];
  result.push(obj);
}
console.log(result);

A: Use this

 var counts = ["2017-01-01T00:00:00Z", 0, "2017-02-01T00:00:00Z", 0, "2017-03-01T00:00:00Z", 0, "2017-04-01T00:00:00Z", 0, "2017-05-01T00:00:00Z", 0, "2017-06-01T00:00:00Z", 0, "2017-07-01T00:00:00Z", 0, "2017-08-01T00:00:00Z", 0, "2017-09-01T00:00:00Z", 0, "2017-10-01T00:00:00Z", 0, "2017-11-01T00:00:00Z", 0, "2017-12-01T00:00:00Z", 0, "2018-01-01T00:00:00Z", 0, "2018-02-01T00:00:00Z", 0, "2018-03-01T00:00:00Z", 0, "2018-04-01T00:00:00Z", 18, "2018-05-01T00:00:00Z", 482, "2018-06-01T00:00:00Z", 272]

 var array = [];
 for(var i=0;i<counts.length/2;i++){
  var obj = {date:counts[i*2],id:counts[i*2+1]};
  console.log(obj);
  array.push(obj);
 }
 console.log(array);


text:
Q: getting a list of running SKAction instances by key/name? Is it possible to obtain the keyName (the withKey value) for a running action on a node?  Not interested in the actionForKey, that returns the action, I want the keyName (the string; let's assume it's random and I don't know it but want to find out what it's set to).

A: There is no built-in method in SKNode to retrieve all actions. Therefore, the best way is to keep a separate NSArray of action names. You'd add an action name to the list when the action is started and remove it, with help of the completion: argument.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing string parameters in JQuery function I'm working on the following piece of code:
function moveLeft() {
        if ($('#show-slider ul').is(":animated")) return;
        $('#show-slider ul').width(slideWidth*(slideCount+1))
        $('#show-slider ul li:last-child').clone().prependTo('#show-slider ul');

        $('#show-slider ul').css('left', - slideWidth).animate({'left': 0}, 333, function() {
            $('#show-slider ul').width(slideWidth*slideCount).css('left','');
            $('#show-slider ul li:last-child').remove();
        });
    };

$('.control_prev').click(function () {
        moveLeft();
    });

Here I want to pass #show-slider as a string in moveLeft() function.
I know how to pass variable parameter as given below:
var abc = '5';

function meraFunc(abc)
{
    alert(abc + " Some Text" );
}

$('#test').click(function() {
    meraFunc(abc);
});

Here's the fiddle in short - http://jsfiddle.net/codestor/hxzd9/
And this is something which I want to achieve:
function moveLeft() {
    // alert "#show-slider" in this line
    // alert "#show-slider ul" in this line
    // alert "#show-slider ul li" in this line
};

$('.control_prev').click(function () {
     moveLeft("#show-slider");
});

A: DEMO
Use this,
The class name is control-prev and not control_prev
$('.control-prev').click(function () {
     moveLeft("#show-slider");
});

function moveLeft(id) {
    alert(id);
    alert(id + ' ul');
    alert(id +' ul li');
};


text:
Q: How can I allocate memory on the stack for a pointer to an object? I am implementing a linked stack of strings in C++, mainly for fun. Every object of the list is a Node instantiation, and the list itself is an instance of StackOfStrings. Right now I instantiate a new Node using new and everything works fine, but I can't seem to figure out how to instantiate a Node on the stack and refer to it at a later point in the code.
I tried changing first = new Node; with first = &Node(); inside the push() method, but then I get a run-time std::bad_alloc error when I call the pop() method. My guess is that this Node gets created on the stack and is destroyed as soon as the program exits the push() method. So my question is: is there a way I can create assign to first a Node created on the stack and retain it for later use?
I am including the bare bones of the code, I added a comment next to the line that is causing me problems.
class StackOfStrings
{
public:
    StackOfStrings() {}; // Could be omitted, default constructor

    void push(std::string item)
    {
        Node* old_first = first;
        first = new Node;         // *** my question revolves around this line ***
                                  // ***    "first = &Node()" does not work    ***
                                  // ***  how can I have a Node on the stack?  ***
        first->setItem(item);
        first->setNext(old_first);
    }

    std::string pop()
    {
        std::string item = first->getItem();
        first = first->getNext();
        return item;
    }

private:
    Node *first = nullptr;
};

For completeness, this is the Node class:
class Node
{
public:
    std::string getItem() { return item; }
    Node* getNext() { return next; }
    void setItem(std::string item) { this->item = item; }
    void setNext(Node *node) { this->next = node; }

private:
    std::string item;
    Node* next = nullptr;
};

edit: by mistake I wrote *Node instead of &Node. I updated the question.
edit 2: a little experiment I tried:

*

*I called the push() method of StackOfStrings to insert the word "hello" inside the linked list.

*inserted a breakpoint inside the setItem() method of Node to check that the world "hello" was saved in memory. Indeed, at memory address 0x00FFF900 I found the values 68 65 6c 6c 6f, which corresponds to "hello" in ASCII

*I then placed another breakpoint inside the call to getItem() in order to analyze the same memory address again. What I found now a0 fb ff 00 28 which is garbage and certainly not "hello".

A: First this is a very very bad idea.
Second you shouldn't take address of a temporary because it will be destroyed once the semicolon is reached leaving your pointer pointing to an invalid object . I think this line shouldn't even compile ! Are you using any visual c++ extension ?
first = &Node();

you construct a temporary on the stack by calling Node() then you bind its address to first pointer then the temporary gets destroyed .
Third the exception you get is because of this :
your getItem() method returns by copy rather than by reference so once called in pop() on a dangling pointer first the std::string copy constructor is called to copy the member std::string item which is invalid because it was destroyed from the beginning .
In the copy constructor of std::string it reads the size of the other string which happens to be some random bytes on the stack since the original string was destroyed .
This number is very big that Windows can't allocate memory for it on the heap so an exception of type std::bad_alloc is thrown
If the number was small enough but not smaller than std::string internal stack array , you might get an access violation because the copy constructor will attempt to copy buffer from an invalid memory address . Or even worse ! you might corrupt the heap or read some random bytes if this chunk was related to any other object in the program

A:
How can I allocate memory on the stack for a pointer to an object?

By creating an automatic variable. Like this:
void foo() {
    Node* ptr; // this pointer is allocated on the execution stack

is there a way I can create assign to first a Node created on the stack

Sure. Create an automatic Node, and use the addressof operator:
Node node;
StackOfStrings sos;
sos.first = &node;

This simple example violates access specifiers of your class. You may want to for example pass the pointer to the constructor in order to avoid needing to change the access  specifier.

and retain it for later use?

Automatic variables (i.e. all variables allocated on the execution stack) are destroyed at the end of their scope. No exceptions. If later use is within that scope, then there is no problem. If later use is outside of that scope, then wanting to use the execution stack is a mistake.


text:
Q: foreign key problem in jdbc I have two functions:
public void Populate_flights()

public void Populate_reservations()

Flight and reservations are two tables.One of the entry i.e flight no. is in the reservation table. So it is a foreign key.
Now, I need to populate the database via jbdc. So I am using: In
public void Populate_reservations() function:
Statement s = conn.createStatement();

s.executeUpdate("DELETE FROM reservations");

public void Populate_flights() -:
 Statement s = conn.createStatement();

 s.executeUpdate("DELETE FROM flights");

So in this way, before populating the database, all my previous entries are removed and no redundant data is there.Since, there is a foreign key in reservation table, I can't delete entries from flight first. I have to remove entries from reservation first. But reservation function is called after flight function.SO how would I make it so that it will delete all the entries.
So it should be like this:
Statement s = conn.createStatement();

  s.execute("SET FOREIGN_KEY_CHECKS=0");

     s.executeUpdate("DELETE FROM flights");
 s.execute("SET FOREIGN_KEY_CHECKS=1");

A: You can temporary disable foreign key checks in MySQL to perform operations that would fail if these checks were enabled:
// Disable foreign keys check
Statement stmt = conn.createStatement();
stmt.execute("SET FOREIGN_KEY_CHECKS=0");
stmt.close();

// Do your stuff

// Enable foreign keys check
Statement stmt = conn.createStatement();
stmt.execute("SET FOREIGN_KEY_CHECKS=1");
stmt.close();

Note that this is a per connection setting so you have to do all your stuff using the same conn object.

A: So you want to cascade the foreign key references on delete. You have to set it on the foreign key constraint. First drop the old constraint and then recreate it with the cascade instruction. Assuming that the FK name is fk_flight, here's an example:
ALTER TABLE reservations
    DROP CONSTRAINT fk_flight;

ALTER TABLE reservations
    ADD CONSTRAINT fk_flight
    FOREIGN KEY (flight_id)
    REFERENCES flight(id)
    ON DELETE CASCADE;

This way all referenced reservations will be deleted if you delete alone the flight.

A: Statement s = conn.createStatement();;
s.addBatch("SET FOREIGN_KEY_CHECKS = 0");
s.addBatch("DELETE FROM reservations");
s.addBatch("DELETE FROM flights");
s.addBatch("SET FOREIGN_KEY_CHECKS = 1");
s.executeBatch();


text:
Q: LED Notification I want create one simple code that turn on the light of the led of my phone(nexus 5), when I press one button in my app!
I tried with this code that I've take on the web! But don't work!
b1.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {

                NotificationManager nm = (NotificationManager) getSystemService( NOTIFICATION_SERVICE );
                Notification notif = new Notification();
                notif.ledARGB = 0xFFff0000;
                notif.flags = Notification.FLAG_SHOW_LIGHTS;
                notif.ledOnMS = 100;
                notif.ledOffMS = 100;

            }
        });

EDIT:
I tried with this to see is the code works, but the app crash when I press the button!
 b1.setOnClickListener(new View.OnClickListener()
        {

            public void onClick(View v)
            {

                PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
                int s=100;
                manager.goToSleep(s);

                Notification notif = new NotificationCompat.Builder(getApplicationContext())
                        .setAutoCancel(false)
                        .setLights(0xff0000, 4000, 100)
                        .build();

            }
        });

I've add the permission
<uses-permission android:name="android.permission.WAKE_LOCK" />
<user-permission android:name= "android.permission.DEVICE_POWER" />

A: Try this code
b1.setOnClickListener(new View.OnClickListener()
{
    public void onClick(View v)
    {

          Notification notif = new NotificationCompat.Builder(getApplicationContext())
          .setAutoCancel(false)
          .setLights(0xff0000, 4000, 100)
          .build();
     }
 }

Hope this helps.


text:
Q: cap deploy - getting permission denied I am trying to deploy my rails project into sub-domain, but I am getting following error while running  cap deploy
 [Deprecation Warning] This API has changed, please hook `deploy:create_symlink` instead of `deploy:symlink`.
 * 2013-09-27 21:14:44 executing `deploy'
 * 2013-09-27 21:14:44 executing `deploy:update'
 ** transaction: start
 * 2013-09-27 21:14:44 executing `deploy:update_code'
executing locally: "git ls-remote git@github.com:anveshnarepo/techzoo.git master"
 Permission denied (publickey).
 fatal: The remote end hung up unexpectedly
 *** [deploy:update_code] rolling back
 * executing "rm -rf /var/www/anveshnatech.com/public_html/edupdu/releases/20130927154447; true"
servers: ["http://anveshnatech.com/edupdu/www"]
 ** [deploy:update_code] exception while rolling back: Capistrano::ConnectionError, connection failed for: http://anveshnatech.com/edupdu/www (SocketError: getaddrinfo: Name or service not known)
 Command git ls-remote git@github.com:anveshnarepo/techzoo.git master returned status code pid 12392 exit 128

If i am trying to run cap deploy:setup it is displaying something like:
[Deprecation Warning] This API has changed, please hook `deploy:create_symlink` instead of `deploy:symlink`.
* 2013-09-27 21:23:57 executing `deploy:setup'
* executing "mkdir -p /var/www/anveshnatech.com/public_html/edupdu     /var/www/anveshnatech.com/public_html/edupdu/releases    /var/www/anveshnatech.com/public_html/edupdu/shared /var/www/anveshnatech.com/public_html/edupdu/shared/system /var/www/anveshnatech.com/public_html/edupdu/shared/log /var/www/anveshnatech.com/public_html/edupdu/shared/pids"
servers: ["http://anveshnatech.com/edupdu/www"]
connection failed for: http://anveshnatech.com/edupdu/www (SocketError: getaddrinfo: Name or service not known)

How to fix this problem?

A: One error is that you defined a URI where host should go. I suspect you have
role :app, "http://anveshnatech.com/edupdu/www"

in your capfile, when you need something like:
role :app, "anveshnatech.com"

or (example)
role :app, "10.1.1.1"

These are probably not be the only errors, you have some permission problems with your git key and some strangeness with deprecation warnings.


text:
Q: Enviando um vector C++ para uma função Python Eu tenho o seguinte função escrita em python em um arquivo .py:
def coordinate(arg):
    print arg

    return True

E um exemplo de código C++ em um arquivo .CPP
#include <Python.h>
#include <vector>

int main()
{

   bool result;
   std::vector<float> coords;

   Py_Initialize();

   ...

   result = ????
   Py_Finalize();

   return true;
}

Como enviar do código C++ o float vector coords, para a função Python coordinate()?

A: VC vai precisar compilar o código para criar um módulo python...
Crie um setup.py que utilize o distutils do python, esse arquivo será o responsável por criar/linkar um módulo escrito em C/C++ que mais tarde poderá ser importado dentro do seu Código Python.
setup.py básico de exemplo:
from distutils.core import setup, Extension

setup(name='NOMEMODULO', version='1.0',  \
      ext_modules=[Extension('NOMEMODULO', ['codigo.cpp'])])

Agora você terá que compilar para criar seu módulo no python, vc terá que ter um compilador instalado e o módulo distutils devidamente instalado na sua versão python...
Na pasta que estão os seus arquivos C/C++ rode um:
python setup.py install

Antes de executar verifique se todos os Paths necessários estão nas variáveis ambientes do seu SO (onde está o exec do python, onde tá o exec do compilador, etc)
Se o comando acima rodar sem erros vc terá um módulo que poderá ser chamado dentro do seu código python..
import NOMEMODULO

Pronto agora você poderá chamar as funções que existem dentro do seu código C++ dentro do seu código Python...
Para trabalhar com vetores eu recomendo que você utilize o Numpy
Acabei de criar um exemplo simples (testevetor.c) para demonstrar como trabalhar com vetores do seu C/C++ e integrar com python com a ajuda do Numpy (estou usando python27, mas isso é a base para funcionar em qq versão):
#include <Python.h>
#include <numpy/arrayobject.h>
PyObject * testevetor()
{
          int vetor[5] = {0,1,2,3,4};
          int tamanho = 5;
          PyObject * c = PyArray_SimpleNewFromData(1,&tamanho,PyArray_INT,vetor);

           return (PyObject*)c;
}

static PyObject *ErrorObject;

static PyMethodDef OiMethod[] =
{
    {"testevetor", testevetor, METH_VARARGS, "teste do vetor"},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
initoivetor(void)
{
    (void) Py_InitModule("oivetor", OiMethod);
    import_array();
    ErrorObject = PyString_FromString("Oi.error");
    if (PyErr_Occurred())
        Py_FatalError("can't initialize module");
}

O Código acima apenas imprime os valores 0 1 2 3 4 como você pode notar eu estou usando o Numpy para criar um objeto que retorna esses valores, Só para demonstrar como se faz eu criei um módulo chamado oivetor e a função que retorna os valores se chama testevetor()
Bom feito isso é preciso criar um setup.py:
#build the modules

from distutils.core import setup, Extension

setup(name='oivetor', version='1.0',  \
      ext_modules=[Extension('oivetor', ['testevetor.c'])])

Só colocar todos os arquivos em uma pasta em compilar (claro vc tem q ter um compilador e o distutils ai corretamente instalados e com path na variável ambiente ...
Só rodar um:
Python setup.py install (C:\Python27\testevetor>C:\Python27\python.exe setup.py install)

Se nenhum erro acontecer vc deverá ter instalado o módulo...
C:\Python27\testevetor>C:\Python27\python.exe setup.py install
running install
running build
running build_ext
building 'oivetor' extension
C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python27\Lib\site-packages\
numpy\core\include -IC:\Python27\include -IC:\Python27\PC -c testevetor.c -o bui
ld\temp.win32-2.7\Release\testevetor.o
testevetor.c:30:2: warning: no newline at end of file
writing build\temp.win32-2.7\Release\oivetor.def
C:\MinGW\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.7\Release\testeve
tor.o build\temp.win32-2.7\Release\oivetor.def -LC:\Python27\libs -LC:\Python27\
PCbuild -lpython27 -lmsvcr90 -o build\lib.win32-2.7\oivetor.pyd
running install_lib
copying build\lib.win32-2.7\oivetor.pyd -> C:\Python27\Lib\site-packages
running install_egg_info
Removing C:\Python27\Lib\site-packages\oivetor-1.0-py2.7.egg-info
Writing C:\Python27\Lib\site-packages\oivetor-1.0-py2.7.egg-info

Aqui nenhum erro: vamos testar ....
import oivetor
import numpy
print (numpy.array(oivetor.testevetor()))

array([0, 1, 2, 3, 4])

Funcionando perfeitamente, é quase que um tutorial isso huahuhua
Uso isso de monte para pegar vetores de áudios processando em C/C++ e passar para Python ....


text:
Q: Create a growing and shrinking SVG canvas in a Qooxdoo window with automatic scrollbars when necessary Using Qooxdoo I want to have a window that only contains a HTML SVG element.
This SVG shall use the full available size in the resizable window. And when the window gets too small automatically scrollbars shall appear so that the SVG content is still completely visible (when the user scrolls accordingly)
How can I achieve that?

A: The some key moments of my solution are:

*

*Use qx.ui.embed.Html as wrapper of svg markup

*Use qx.ui.container.Scroll to make a container or widget scrollable

*Use properties minWidth and minHeight of widget to stop reducing its size

*A root svg element in markup has scallable width and height (in this case 100%)

*Turn off shrinking of svg container (qx.ui.embed.Html) via properties allowShrinkX: false and allowShrinkY: false
The following code contains all above mentioned things:
const win = new qx.ui.window.Window();
win.setLayout(new qx.ui.layout.Grow());

const svg = '<svg width="100%" height="100%"><circle cx="50%" cy="50%" r="50%" stroke="black" stroke-width="3" fill="red" /></svg>';
const svgWidget = new qx.ui.embed.Html(svg);
svgWidget.set({allowShrinkX: false, allowShrinkY: false, minWidth: 200, minHeight: 200});

const scroller = new qx.ui.container.Scroll().set({width: 300, height: 300, decorator: "main", padding: 5});
scroller.add(svgWidget, {width: "100%", height: "100%"});
win.add(scroller);

win.open();

const doc = this.getRoot();
doc.add(win,
{
  left : 100,
  top  : 50
});


text:
Q: Exec format error in execl() (Sorry for my english)
I'm trying to make simple console application.
I have qtqreator + ubuntu.
I make a pipe, read some info from file into pipe, and my "fork"-process must disply it.
So my code is:
using namespace std;
main(int argc, char** argv)
{
    int fildes[2];
    char ch;
    FILE *fp;
    int stat;
    pipe(fildes);
    cout << argv[1] << " " << argv[2] << endl;
    fp=fopen(argv[1],"r");

    if (!fork())
    {
        execl(argv[2],argv[2],&fildes[0],NULL);
        perror("execl() failure!\n");
    }
    else
    {
        while(!feof(fp))
        {
            ch=fgetc(fp);
            write(fildes[1],&ch,1);
        }

        fclose(fp);

        wait(&stat);

        close(fildes[0]);
        close(fildes[1]);
    }
}

The main problem is in execl() function: Exec format error.
I've tried different ways to write my path, but nothing works((
Please, help me! Thanks)


text:
Q: How to set transform_null_equals postgres parameter on a connection? First some context in case it helps with your understanding of the why piece and sometimes leads to other good answers.  I love this settings transform_null_equals because instead of

*

*sql column value=NULL where I am told null means unknown

*sql WHERE clause value=null where null means null

The setting in the title basically changes postgres so that null in WHERE clause AND column value BOTH mean 'unknown'.  I can then say WHERE c.col=null (which means find any columns WHERE c.col is unknown) and I can also do WHERE c.col="value"
In this way in null languages, I can then do c.col=variable and variable can be null for unknown and a value for something that is known.  perfect!
I realize this is a violation of the spec but it makes our team super fast(which is way more important in our business)....we have had less bugs, and WAY WAY simpler queries....OMG, way simpler.
Now, we set this on the user, but I want to set this via the connection instead so when someone installs postgres, it just magically works without them having to remember to set the setting.

*

*How to do in jdbc?

*Even better, How to do in Hikari Pool

A: You may have less trouble writing your queries with transform_null_equals, but I doubt that they will perform better, since this will just replace = NULL with IS NULL before the query is optimized.
Anyway, you can use the options parameter in a JDBC connection string to supply the parameter to the server process:
jdbc:postgresql:dbname?user=myuser&password=mypwd&options=-ctransform_null_equals%3Don


text:
Q: Getting Invalid css error when I dont have any missing "}" I have updated my vscode to version 1.41.1.
After which I am possibly getting this error in one of my scss file. I don't have much knowledge of scss and work on react most of the time, hence having a hard time to find the issue.
I do not have any missing braces and I checked it well.
Here is the error:
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/thread-loader/dist/cjs.js):
Thread Loader (Worker 1)

  --pf-c-accordion--BoxShadow: none !important;
                             ^
      Invalid CSS after "...BoxShadow: none": expected "}", was "!important;"

Approaches I have tried (but did not work):
Error for invalid css when trying to compile sass
SassMeister online interpreter: Invalid CSS, expected "{", was ""
Css file:
// Bootstrap Core variables and mixins
@import "~bootstrap-sass/assets/stylesheets/bootstrap/variables";
@import "~bootstrap-sass/assets/stylesheets/bootstrap/mixins";

// Patternfly Core variables and mixins
@import "~patternfly/dist/sass/patternfly/variables";
@import "~patternfly/dist/sass/patternfly/bootstrap-mixin-overrides";
@import "~patternfly/dist/sass/patternfly/mixins";
@import '~patternfly/dist/sass/patternfly/icons';
@import "~patternfly-react/dist/sass/patternfly-react";

$co-affinity-row-margin: 15px;

.co-catalog-tile {
  height: 290px;
}

.co-clusterserviceversion-list {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -7.5px 0;
}

.co-clusterserviceversion-details__field {
  padding-bottom: 10px;
}

.co-clusterserviceversion-link {
  .co-clusterserviceversion-logo {
    flex-direction: column;
    @media  (min-width: $screen-xs-min) and (max-width: $screen-xs-max),(min-width: $screen-md-min)  {
      flex-direction: row;
    }
  }
}

.co-clusterserviceversion-link {
  &:focus, &:hover {
    text-decoration: none;

    .co-clusterserviceversion-logo__name__clusterserviceversion {
      text-decoration: underline;
    }
  }
}

.co-clusterserviceversion-logo {
  display: flex;
}

.co-clusterserviceversion-logo__icon {
  align-items: center;
  background: #fff;
  display: flex;
  flex: 0 0 auto;
  height: 40px;
  justify-content: center;
  margin: 0 15px 5px 0;
  width: 40px;
}

.co-clusterserviceversion-logo__name {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.co-clusterserviceversion-logo__name__clusterserviceversion {
  font-size: 15px;
  font-weight: var(--pf-global--FontWeight--normal);
  margin-bottom: 5px;
  margin-top: 0;
}
.co-m-pane__heading--logo
.co-clusterserviceversion-logo__name__provider {
  font-size: var(--pf-global--FontSize--sm);
}

.co-clusterserviceversion-empty__state__namespace {
  font-style: italic;
  font-weight: var(--pf-global--FontWeight--bold);
}

.co-crd-card-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;

  .pf-c-card {
    margin-bottom: 20px;
    margin-right: 20px;
    width: 300px;
  }
}

.co-operand-details__compact-expand {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.co-operand-details__section--info dd {
  margin-bottom: 20px !important;
}

.co-catalog-install-modal .modal-header .co-clusterserviceversion-logo__icon {
  border: 1px solid #ddd;
}

.co-catalog-details {
  display: flex;
  flex-direction: column;
}

.co-catalogsource-list__section {
  margin-bottom: 40px;
}

.co-catalogsource-list__section__packages {
  align-items: flex-end;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-bottom: 20px;
}

.co-clusterserviceversion-row__status {
  display: flex;
  flex-direction: column;
}

.co-spec-descriptor--resource-requirements {
  border: 1px solid #eee;
  padding: 20px 0 20px 20px;
  margin-top: 5px;
}

.co-spec-descriptor--switch {
  align-items: center;
  display: flex;
  height: 25px;
}

.co-create-operand__accordion {
  --pf-c-accordion--BoxShadow: none !important;
  --pf-c-accordion--PaddingBottom: 0rem !important;
  --pf-c-accordion--PaddingTop: 0rem !important;
}

.co-field-group {
  --pf-c-accordion__toggle--PaddingLeft: 0rem !important;
  --pf-c-accordion__toggle--PaddingRight: 0.9375rem !important;
  --pf-c-accordion__expanded-content-body--PaddingLeft: 0.9375rem !important;
  --pf-c-accordion__expanded-content--Color: var(--pf-global--Color--100) !important;
  --pf-c-accordion__toggle-text--active--Color: var(--pf-global--Color--100) !important;
  --pf-c-accordion__toggle-text--active--FontWeight: 600 !important;
  --pf-c-accordion__toggle-text--expanded--Color: var(--pf-global--Color--100) !important;
  --pf-c-accordion__toggle-text--expanded--FontWeight   : 600 !important;
  --pf-c-accordion__toggle-text--focus--Color: var(--pf-global--Color--100) !important;
  --pf-c-accordion__toggle-text--focus--FontWeight: 600 !important;
  --pf-c-accordion__toggle-text--hover--Color: var(--pf-global--Color--100) !important;
  --pf-c-accordion__toggle-text--hover--FontWeight: 600 !important;

  .pf-c-accordion__toggle {
    border-left: none !important;
  }

  h3 {
    margin: 0rem;
    font-size: var(--pf-global--FontSize);
  }

  margin-bottom: 0.5rem;
}

.co-create-operand__form-group {
  display: flex;
  flex-direction: column;
}

.co-create-operand__header {
  border-bottom: 1px solid #ddd;
  padding: 10px 15px;
  @media(min-width: $screen-sm-min) {
    padding: 0 30px 15px;
  }
}

.co-create-operand__header-buttons {
  align-items: baseline;
  display: flex;
}

.co-create-operand__header-text {
  margin: 0;
}

.co-affinity-term {
  border: 1px solid #eee;
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
  padding: 10px 0 5px 15px;
}

.co-affinity-term__remove {
  margin-left: auto !important;
}

.co-affinity-term__topology {
  display: flex;
}

.co-affinity-term__topology-input,
.co-affinity-term__weight-input {
  margin-bottom: $co-affinity-row-margin;
}

.co-affinity-term__topology-input {
  display: flex;
  flex-direction: column;
  padding-right: 15px;
  width: 100%;
}

.co-affinity-term__weight-input {
  display: flex;
  flex-direction: column;
  padding-right: 20px;
  width: 100px;
}

.co-operand-field-group {
  border: 1px solid #eee;
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
  margin-left: 15px;
  padding: 10px 15px 5px;
}

.co-operand-field-group-title {
  align-items: center;
  display: flex;
  justify-content: space-between;
}

.catalog-source__table-row--disabled {
  background-color: var(--pf-global--BackgroundColor--200);
  color: var(--pf-global--Color--400);
}

.key-operator-value__action {
  padding: 0;
  width: 28px;
}
@media (max-width: $screen-sm-max) {
  .key-operator-value__action--stacked,
  .key-operator-value__value-field--stacked {
    padding-top: 10px;
  }
}

.key-operator-value__delete-button {
  padding-left: 0 !important;
}

.key-operator-value__heading-button {
  height: 23px; // for vertical alignment with input field; equals $pf-global--LineHeight--md
}

.key-operator-value__name-field,
.key-operator-value__operator-field,
.key-operator-value__value-field {
  padding-right: 0 !important;
}

.key-operator-value__row {
  padding-bottom: 15px;
}


text:
Q: User authentication between a rails api and a node.js app I am attempting to understand how segmented apps work so I'm building one that uses rails for the back-end api and node.js for the front and middle. What I am trying to figure out is how to let a user log in through rails and use that same session information in the node app.
I have heard of oauth2, but I don't know if that's what I need or if I need something else. My main concern is that I want to keep all the models in the rails app so I can take advantage of the syntactic sugar and associations that rails provides. The node app will just connect to the rails app through it's api.
Are there any tutorials out there for this? Or does anyone know how I can do it?

A: Found my answer here. Hope it can help someone else out


text:
Q: How to filter rows if index length not same in pandas? I need to filter rows of one pandas dataframe (df_2) if values in df_1 are greater than or equal too.
df_1 looks like this:
created_date    compare_date
2/10/18         2/11/18

df_2 looks like this:
id   compare_date
12   2/10/18
13   2/11/18
14   2/9/18

I need do the following comparison: df_1['compare_date']>= df_2['compare_date'] and df_2 in turn should look like this:
id    compare_date
13    2/11/18

My code so far:
df_1['Benchmark_Date'] >= df_2['Updated_Date']

I get error:
ValueError: Series lengths must match to compare

A: Since df_1 has exactly one row, you should compare its single value against the entire series in df_2:
df_1['compare_date'].iloc[0] >= df_2['compare_date']

iloc[0] takes the first (and in this case only) row.
The above will return a boolean series; if you want to extract the matched rows, do this:
df_2[df_1['compare_date'].iloc[0] >= df_2['compare_date']]


text:
Q: Prolog mystery(c,[a,b,c,d],Z) I think the answer is 3 but I am not sure, can anyone provide some help?
Suppose the following two statements are entered into Prolog:
mystery(X,[X|L],L).
mystery(X,[Y|L],[Y|M])  :-  mystery(X,L,M).

What would Prolog return if one then gives it the following goal?
?- mystery(c,[a,b,c,d],Z).

A: So, mystery/3 is defined as:
mystery(X, [X|L], L).
mystery(X, [Y|L], [Y|M]) :- mystery(X, L, M).

There are (at least) three ways to look at mystery:

*

*It takes an element X (first parameter), looks for its existence in a given list (second parameter) and returns that same list, minus one occurrence of X (third parameter). Thus:
?- mystery(c, [a, b, c, d], Z).
Z = [a, b, d] ;
fail.

?- mystery(c, [a, b, c, d, c], Z).
Z = [a, b, d, c] ;
Z = [a, b, c, d] ;
fail.

*Another way to look at mystery is that it checks whether the lists constituting its second and third argument only differ with respect to one element, i.e. that the second list equals the third list, except that it has one additional element in one place. Thus:
?- mystery(X, [a, b, c, d], [a, b]).
fail.

?- mystery(X, [a, b, c, d], [a, b, c]).
X = d ;
fail.

Note that order is important:
?- mystery(X, [a, b, c, d], [a, c, b]).
fail.

*Lastly, mystery can also generate all ways in which the first argument can be interspersed in the list of the third argument. Thus:
?- mystery(d, Y, [a, b, c]).
Y = [d, a, b, c] ;
Y = [a, d, b, c] ;
Y = [a, b, d, c] ;
Y = [a, b, c, d] ;
fail.


text:
Q: Question about notation for rewriting integral of Laplace Beltrami operator I was just reading about the Laplace Beltrami operator, which is a linear, second order, self-adjoint operator on a general Riemannian metric $g_\mu\nu$ space.
$$\Delta A_{\mu}=\nabla^{\alpha}\nabla_{\alpha}A_{\mu}$$
Where $A_\alpha$ is some arbitrary vector field component on M that the operator is acting on. Suppose We're looking at some integral over the manifold $M$ such as:
$$\intop_{M}B^{\alpha}\Delta A_{\alpha}dvol_{M}$$
Where $B^\alpha$ is another vector field component. Invoking the self-adjointness of $\Delta$ One may write this as:
$$\intop_{M}B^{\alpha}\Delta A_{\alpha}dvol_{M}=\intop_{M}<dB^{\alpha},dA_{\alpha}>dvol_{M}=\intop_{M}A^{\alpha}\Delta B_{\alpha}dvol_{M}$$
This might be a dumb question, but is the $d$ in the middle equation the exterior derivative of $A,B$ (respectively)? The paper I was reading skipped the derivation, and didn't explain the notation (same with the wiki page).

A: If the connection is the Levi-Civita of the metric then the exterior derivative is obtained antisymmetrizing the covariant derivative of the form.
If your manifold is orientable and closed then you have in general that
$\int_M \langle B,  \nabla^* \nabla A\rangle = \int_M \langle \nabla B, \nabla A \rangle$. Then alternating and using the inner product on forms (at this point using the metric we regard $B$ and $A$ as forms) you should get that $\int_M \langle \nabla B, \nabla A \rangle = \int_M \langle d B^\sharp, d A^\sharp \rangle$.


text:
Q: Angular ng test Module not found: Error: can't resolve I have started up this Angular project last week using the command ng new [myProjectName]. I generated the components using ng g c [componentName], which have correctly generated every component with a .spec.ts file. I then, after implementing business logic, and writing some test code, say ng test to try to run the test code, but get a whole slew of errors.
All of these errors I get on the command line, are in the form : Module not found : Error : can't resolve [someNodeJSDependency] in [someNodeJSLibFolder]. The browser that's supposed to spawn, that's supposed to contain the output of the tests, fails to capture (it starts up two or three times, but blank, and then closes). ng then says it's giving up.
Screenshots of the errors:

The package.json of the project looks like this:
{
  "name": "open-source-roads-page",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.0.0",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "core-js": "^2.4.1",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "^1.5.5",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/language-service": "^5.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.4.2"
  }
}

I tried saying node rebuild at the project root, but that didn't have any effect on these errors.

A: I've got the same error after that i removed my node_modules folder and reinstalled the latest version of node.js, and it worked for me.


text:
Q: Why does the IP assignment in my router fail (only for my server, it works fine for everything else) I just bought an old IBM X3650 M2 and installed Ubuntu Server 20.04 LTS. My router (Netgear R7000) is not obeying the IP rules I set in the router setup (and so far, I've only noticed this for this "new" server, not for the other 67 devices where I have previously assigned IPs in the router DHCP).
In the IBM server configuration, I enabled the network (IPv4), and checked the "DHCP" option.
My router assigns a random IP (192.168.0.5). I then assign an IP address in the router config (192.168.0.99) and apply. Once the router finishes restarting the DHCP, the server is now at 192.168.0.2. Rebooting the server (even power cycling) or re-assigning the IP and re-applying doesn't change anything.
It seems the router is allowed to assign IP to the server, but the router won't obey its own rules. The rule is displayed loud and clear in the router config, it's not dissapearing (as I've seen other posts complain about).
I know (think?) I could just assign a static IP in the server config, but I'd rather have it done by the router, for various reasons. And the question "why is it doing this?" is also bugging me :)
Cheers!
EDIT: I tried setting a static IP in the BIOS setup of the server. First time it worked (my testing IP, 192.168.0.99), but when I tried changing it to the permanent IP I need to use (192.168.0.100), it reverted back to the router appointed (.2) address. What more is, I can no longer set it back to the "testing IP" (.99).
In the router, the change I made between being able to assign IP in BIOS setup and not, was to delete the entry for my old server (just an old NUC type computer, really), which was previously at 192.168.0.100.

A: From both personal experience and anecdotal evidence online, Netgear firmware has a pretty unstable relationship with DHCP (e.g. [1] [2]). So in answer to the question "why is it doing this", the answer is highly likely to be some kind of firmware issue and very unlikely to be your fault. You can certainly assign a static IP in Ubuntu Server without any problems (provided there are no conflicts with other network devices). The only downside to this is not having centralised IP address management - I use DHCP reservations for all servers on my network to make things easier for me.
A few thoughts/suggestions:

*

*What, if anything, was previously at 192.168.0.2? Is this a rare instance of MAC address conflict with another reservation?

*On some routers, DHCP reservations need to be outside the DHCP address pool. So if your current DHCP pool range is .2-.254 then try changing it to .2-.90 and see if your .99 reservation sticks.

*The only other solution I have seen is to roll back to an older firmware version (which is the solution in many of the forum threads you can find online. The problem with this approach is that firmware updates often fix security issues and rolling back may make your router (and by extension, your network devices) more vulnerable to attack.


text:
Q: MAMP Apache server suddenly stopped working - no errors in the logs It worked fine and then it just stopped working. version 1.9.4

A: Presumably nothing trivial like closing the control panel and closing the MAMP server? There is a button/check box to keep the services running when the control panel is closed.
[edit] this is about setting up Symfony in MAMP but it runs through MAMP config. It an be pointed at the wrong php etc. THis is all for MAc so i am assuming that is what you are using but i think it is the same on Windows with minor variations. Hope it helps.
Howto MAMP blog


text:
Q: Replace Enclosed Alphanumerics in Python How can I replace characters such as , ①,Ⓐ to their 'normal' forms in python?
Note, however, I would still like accent character to remain the same (ç,á etc)
Hoping I don't need to make a dictionary.
More examples:
https://en.wikipedia.org/wiki/Enclosed_Alphanumerics
https://en.wikipedia.org/wiki/Enclosed_Alphanumeric_Supplement
http://xahlee.info/comp/unicode_circled_numbers.html
-=-=EDIT=--=-
For future people I used this, thanks AKX
(
         "".join(
             re.sub(r'([^\w])', '', unidecode.unidecode(ch)) #return only the word characters from the decode
                 if
                         ord(ch) > 65535  #Emoticons
                     or (ord(ch) >= 9312 and ord(ch) <= 9472)       #circled
                     or (ord(ch) >= 65296 and ord(ch) <= 65305)     #latin numbers
                     or (ord(ch) >= 65313 and ord(ch) <= 65338)     #latin upper
                     or (ord(ch) >= 65345 and ord(ch) <= 9472)      #latin lower
                 else
                     ch
                 for ch in criteria
                   )
              )

A: There's no universal way, but happily someone else has made the dictionary for you: the unidecode library works for your particular characters.
$ pip install unidecode
Successfully installed unidecode-1.3.4
$ python3
>>> import unidecode
>>> unidecode.unidecode(', ①,Ⓐ')
'[A], 1,A'
>>>

Unidecode will, however, also deburr accented characters, so you'll need a bit more to keep them.
For example, assuming all the strange characters are not in the Unicode basic plane, you can filter the string character by character:
>>> "".join(unidecode.unidecode(ch) if ord(ch) > 65535 else ch for ch in ' Oh lá lá')
'[A] Oh lá lá'


text:
Q: Validation through getElementById() I'm been trying to validate my fields by using 'getElementById()' with '.value'. However, it seems like either getElementById.value is not working or some codes has overlap the function.
Updated Javascript function:
function validate() {
    var Name = document.getElementById('Name').value;
    var Tel = document.getElementById('Tel').value;
    var FaxNo = document.getElementById('FaxNo').value;
    if (Name != "") //wanted to check for alphabets only.
    {
         alert("Correct");
         return true; //doesnt go to next.php
    }
    else
    {
          alert("Don leave blank!")
          return false;
    }
    if (isNaN(Tel)) //check only numbers. Same code for FaxNo.
    {
        alert("Correct");
        return true; //doesnt go to next.php
    }
    else
    {
      alert("invalid");
      return false
    }

  return true; //doesn't go to next.php
}

My Form:
<Form action ="next.php" method="post">
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
<input type="submit" name="submit" onclick="return validate();"/>
</Form>

I have already defined my onclick function to my Javascript and tried to add return false too. But the alert still cant appear. Kindly advise.

A: Your markup is invalid:
<input name="Name" type="text" id="Name" " value=""/>
                                         ^-----------should be removed

so correction would be removing all extra " characters:
<input name="Name" type="text" id="Name" value=""/>
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>

For preventing submition,when input is invalid, you can try something like a:
function validate() {
    var Name = document.getElementById('Name').value;
    var Tel = document.getElementById('Tel').value;
    var FaxNo = document.getElementById('FaxNo').value;

    if (Name != "") //wanted to check for alphabets only.
        alert("Correct")
    else {
        alert("Don leave blank!")
        return false;
    }

    if (isNumeric(Tel)) //check only numbers. Same code for FaxNo.
        alert("Correct")
    else {
        alert("invalid");
        return false;
    }
}
//Borrowed from jQuery lib
function isNumeric( obj ){
    return !isNaN( parseFloat(obj) ) && isFinite( obj )
}

<input type="submit" name="submit" onclick="return validate()"/>

A: Try this,
function validate() {
    var Name = document.getElementById('Name').value;
    var Tel = document.getElementById('Tel').value;
    var FaxNo = document.getElementById('FaxNo').value;
    if (Name != "") {}
    else {alert("Don leave blank!"); return false;}
    if (isNaN(Tel)){ alert("invalid"); return false;}
    else { }
return true;
}

Your HTML submit button code should be
<input type="submit" name="submit" onclick="return validate()"/>

Use return false to prevent submitting form in case of any validation errors.


text:
Q: Using itertools in Python password cracker I made a simple password cracker:
import string as s
import itertools as it

things = s.ascii_letters

for digits in range(2, 6):
    for combo in it.combinations(things, digits):
        output = ''.join(combo)
        print(output)

but it doesn't print out all possibilities.
For example, the last output this program gives out is:
VWXYZ

If I had a password starting with "X", the program wouldn't be able to find it.
Is there any way I can fix this? What is wrong with my code?

A: Use itertools.product() with the repeat parameter. Using itertools.combinations() doesn't allow for the same letter to be selected more than once:
import string as s
import itertools as it

things = s.ascii_letters

for digits in range(2, 6):
    for combo in it.product(things, repeat=digits):
        output = ''.join(combo)
        print(output)


text:
Q: What is the difference between using a type as a different name and a type alias? What is the difference between
use hyper::status::StatusCode as Error;

and
type Error = hyper::status::StatusCode;

Are the any more differences between them except that type can be also pub type? What are the benefits between using one or another?

A: In case of simple types, like in your example, there doesn't seem to be any semantic difference. Moreover, there is a direct analogue with use to pub type, it's pub use:
// will be available to other modules
pub use hyper::status::StatusCode as Error;

However, there are differences in more complex cases. For example, you can define generic type aliases or aliases for specialized generic types:
type Result<T> = ::std::result::Result<T, MyError>;

type OptionI32 = Option<i32>;

The general idea is that you usually use type aliases because they are more powerful and suggest the intent more clearly, like with Result, and you use use .. as .. when you only want to import that specific name but it conflicts with something which is already in the current namespace:
use std::io::Read as StdRead;

trait Read: StdRead { ... }

Note that using path-qualified identifiers should be preferred to use renaming. The above is better written as
use std::io;

trait Read: io::Read { ... }

(unless Read methods are used for some concrete type in the same file, of course).
Using use .. as .. as a substitute for type (in case where it is possible) is uncommon and I think it should be avoided.


text:
Q: resolv.conf being rewritten at reboot with wrong DNS IP I got a server running RHEL 8.6. Whenever it gets rebooted, I get a newly created resolv.conf not containing the proper IP for my DNS.
before reboot:
nameserver X.X.X.X

after reboot:
nameserver Y.Y.Y.Y
nameserver Z.Z.Z.Z

Those IP are wrong and breaks every program relying on DNS (postfix, dig, yum, etc.) I have to manually edit the file and add X.X.X.X.
It's especially annoying as I have to disable/enable the mail system everytime.
I have seen people online talking about network manager but I am not knowledgeable enough to know exactly what to change in it. I'm basically a user, my company threw me a server and I got virtually promoted to sysAdmin but I don't get IT support for it.
how do I stop the file being overwritten?

A: You can add a command at reboot in your root crontab :
sudo -i #then enter your root password
crontab -e

Then you can add the following line to the crontab file :
@reboot sleep 600 && echo "nameserver X.X.X.X" >> /etc/resolv.conf && sudo postfix restart

Save the file and you're good to go.
The lined added means that whenever your server gets rebooted, it will wait 10min (600s), add the right DNS to your resolv.conf then restart your mail service.


text:
Q: minikube status Unknown, Windows 10, docker I was trying to see the dashboard, previously works fine...
Now I get using minikube dashboard
λ minikube dashboard

X Exiting due to GUEST_STATUS: state: unknown state "minikube": docker container inspect minikube --format=: exit status 1
stdout:

stderr:
Error: No such container: minikube

*
╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│                                                                                │
│    * If the above advice does not help, please let us know:                                                      │
│      https://github.com/kubernetes/minikube/issues/new/choose                                                    │
│                                                                                │
│    * Please attach the following file to the GitHub issue:                                                       │
│    * - C:\Users\JOSELU~1\AppData\Local\Temp\minikube_dashboard_dc37e18dac9641f7847258501d0e823fdfb0604c_0.log    │
│                                                                                │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

With minikube status
λ minikube status
E0604 13:13:20.260421   27600 status.go:258] status error: host: state: unknown state "minikube": docker container inspect minikube --format={{.State.Status}}: exit status 1
stdout:

stderr:
Error: No such container: minikube
E0604 13:13:20.261425   27600 status.go:261] The "minikube" host does not exist!
minikube
type: Control Plane
host: Nonexistent
kubelet: Nonexistent
apiserver: Nonexistent
kubeconfig: Nonexistent

With the command minikube profile list
λ minikube profile list
|----------|-----------|---------|--------------|------|---------|---------|-------|
| Profile  | VM Driver | Runtime |      IP      | Port | Version | Status  | Nodes |
|----------|-----------|---------|--------------|------|---------|---------|-------|
| minikube | docker    | docker  | 192.168.49.2 | 8443 | v1.20.2 | Unknown |     1 |
|----------|-----------|---------|--------------|------|---------|---------|-------|

Now,...
What would be it happens?
What would be the best solution?
Thansk...

A: Remove unused data:
docker system prune
Clear minikube's local state:
minikube delete
Start the cluster:
minikube start --driver=<driver_name>
(In your case driver name is docker as per minikube profile list info shared by you)
Check the cluster status:
minikube status
Use the following documentation for more information:
https://docs.docker.com/engine/reference/commandline/system_prune/#examples
https://v1-18.docs.kubernetes.io/docs/tasks/tools/install-minikube/


text:
Q: Deploy as ZIP package from Visual Studio 2022 In Visual Studio when you create a new Publishing Profile you can choose to Deploy the project as a ZIP package.
What does this do?
Why choose this over not deploying as a ZIPPED package?


text:
Q: How to get access to Angular object in a Protractor test I'm trying to load $httpBackend in a Protractor test.  The very first thing the documentation says to do is set up an angular.module in the test.  However, I have no reference to angular inside my tests.
I tried merely console.loging angular.  I tried browser.driver.window and browser.driver.Window but was unable to get ahold of either.  I also tried just require('angular') in my protractor .spec.js files.
This stackoverflow question also seems to simply assume access will be there.
I can't find any references to $httpBackend in angular/protractor in github either (except for the one in the unit test).
Running out of ideas about how to go about setting this up.

A: This link angular/protractor in github is to protractor's unit test.
U can't inject angular services in protractor because it's end2end test framework.
There you don't inject anything. That's why You don't need even have to have this tests in the same place where your project.


text:
Q: Codable or JSONSerialization - Need to get some javascript wrapped text off a webpage Beginner here - I am trying to figure out what to google for tutorials to help me to do this: I need to get some text off a webpage that is in json script and print it into a textview.
When I look at the view-source of the webpage - http://www.sikhnet.com/hukam - here's the big block of javascript that I see with tag of what I need highlighted in orange:

I have read some posts that say that as of Swift4, json parsing is now native to Swift via Codable. I have also read about JSONSerialization. But I don't know which is better suited to accomplishing my end goal - print the text from this tag to a textview ? Which one should I use here?
I also have a < p> tag on this webpage that I'd like to print as the title of my textviewcontroller. Can Codable/JSONSerialization also help me do that?

A: You are getting into the domain of web scrapers, people who extract info from web pages in ways that the authors did not think of.
Your problem is that the shabad_lines is a property of a JSON object inside a line of Javascript code embedded in a HTML document. See how many hoops you have to jump through to get it? Codable is no help here. If you think "let's do that with regex", you add yet another problem for yourself!
Let's analyze the Javascript code:
jQuery.extend(Drupal.settings, { ... })

This means the page is adding properties to the Drupal.setings object. How about getting it back from that object? Open the debug console in Safari or Chrome and type this:
Drupal.settings.hukam.shabad_lines.gurmukhi

And we are getting all 8 lines of shabad! Couple that with the fact that WKWebView allows you to execute Javascript from a webpage and some idea should be bubbling in your mind.

The Solution
It is conceptually simple: load the page, run a line of Javascript, send the result back to Swift. If you are not familiar with WKWebView and how things are related, it can look like a mystery. The nesting goes like this:

*

*The WKWebView has a WKWebViewConfiguration, which has a WKUserContentController, which has a WKUserScript.

*Use the WKWebView to load the webpage

*Use the WkUserScript to execute the Javascript and send a message back to Swift

*Use the WKUserContentController to define message handlers, i.e. channels on which Javascript communicates with Swift.

Putting everything together:
class ViewController: UIViewController {
    private var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create a request to load the page
        let request = URLRequest(url: URL(string: "http://www.sikhnet.com/hukam")!)

        // Create the webview and load the URL
        webView = createWebView()
        webView.load(request)
    }

    func createWebView() -> WKWebView {
        // This is the Javascript to execute you receive back `shabad_lines`
        // property of `Drupal.settings`.
        //
        // Note the `window.webkit.messageHandlers.shabad.postMessage(...)` call:
        // this is how you send a message from Javascript back to Swift. `shabad`
        // is a custom message handler that we will define below. Later, when we
        // get the message back, we will check that it did come from the `shabad`
        // handler and treat it accordingly. You can have as many message handlers
        // as you want but you should name them differently so you know where
        // each message came from.
        let jsSource = "window.webkit.messageHandlers.shabad.postMessage(Drupal.settings.hukam.shabad_lines.gurmukhi)"

        // Inject the script, to be executed after the page finishes loading
        let script = WKUserScript(source: jsSource, injectionTime: .atDocumentEnd, forMainFrameOnly: true)

        //
        let contentController = WKUserContentController()

        // Define the `shabad` message handler
        contentController.add(self, name: "shabad")

        // Add the script to the `WKWebView`. The script will executed every time
        // you load a webpage, even if it's not sikhnet.com
        contentController.addUserScript(script)

        // Finally, we can build a web view with the everything we want
        let config = WKWebViewConfiguration()
        config.userContentController = contentController
        return WKWebView(frame: .zero, configuration: config)
    }
}

extension ViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        // We received a message from Javascript! Check its name and process the
        // message's body
        if message.name == "shabad", let lines = message.body as? [String] {
            // Now you have your 8 lines of shabad
            print(lines)
        }
    }
}


text:
Q: how to edit Synaptics Capabilities , right touchpad button is not working Can you help me enable my right click button of my touchpad? Please, find out my Synaptics Capabilities.
I am using Ubuntu 16.04
xinput list-props "SynPS/2 Synaptics TouchPad" | grep Capabilities

Synaptics Capabilities (300):  1, 0, 0, 1, 1, 1, 1


text:
Q: Laravel route The page isn't redirecting properly Trying to route my Laravel Basic Controller I get
**The page isn't redirecting properly**

and I try to find what I'm doing actually wrong but can't figure out
Basic Controller
abstract class BaseAdminController extends Controller {

    protected $whitelist = array();

    /**
     * The URL segment that can be used to access the system
     * @var string
     */
    protected $urlAdminSegment;

    /**
     * Initializer.
     *
     * @access public
     * @return void
     */
    public function __construct() {

        //Check CSRF token on POST
        $this->beforeFilter('ReportsAdmin\csrf', array('on' => array('post', 'put', 'delete')));

        // Set up Auth Filters
        $this->beforeFilter('ReportsAdmin\auth');
        $this->beforeFilter('ReportsAdmin\inGroup:Admins', array('only' => array('show', 'index', 'create', 'add', 'destroy', 'suspend', 'unsuspend', 'ban', 'unban', 'edit', 'update')));
        // Achieve that segment
        $this->urlAdminSegment = Config::get('reports::app.access_url_admin');

        // Setup composed views and the variables that they require
        //array('except' => array('create', 'store', 'activate', 'resend', 'forgot', 'reset')));
        $composed_views = array('reports::admin*');
        View::composer($composed_views, 'Td\Reports\Composers\AdminPage');
    }
}

filter
   Route::filter('ReportsAdmin\auth', function() {

    if (!Sentry::check())
        return Redirect::guest('admin/login');
});

routes
Route::get( 'admin/login' , array('as' => 'Reports\login',  'uses' => 'Td\Reports\Controllers\Backend\SessionController@create'));
        return Redirect::guest('admin/login');
});


text:
Q: Xamarin.Android : Add the dynamic menu items to Navigation view of DrawerLayout I followed this sample to design the Navigation menu view using android.support.v4.widget.DrawerLayout.
My Static Menu item list defined in drawer_menuList.xml as :
 <group
        android:id="@+id/group"
        android:checkableBehavior="single">
        <item
            android:id="@+id/item1"
            android:icon="@drawable/item1"
            android:title="Item1" />
        <item
            android:id="@+id/Item2"
            android:icon="@drawable/item2"
            android:title="Item2"/>
    </group>

activity_main.axml :
<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/drawer_menuList" />

I found this similar thread on stack overflow and tried this :
NavigationView mDrawerList = FindViewById<NavigationView>(Resource.Id.nav_view);

Menu menu = mDrawerList.getMenu();

I am not getting any getMenu()/GetMenu() method in xamarin.android. Can anyone suggest the right way to add the menu along with the icons dynamically in NavigationView of DrawerLayout.

A: Answering to my question :
Suppose you have a list of Menu items such as :
List<MenuItems> lst = new List<MenuItems>();
lst = GetMenuItems();

Then in xamarin we can dynamically populate the Menu items with their title and icon as :
NavigationView navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
    foreach (MenuItems objMenuItems in lst)
      {
         int iconID = (int)typeof(Resource.Drawable).GetField(objMenuItems.IconName).GetValue(null);

         navigationView.Menu.Add(objMenuItems.Title).SetIcon(iconID);
      }

By this way you can dynamically add the menu items in NavigationView of DrawerLayout.


text:
Q: Sudo android return "sudo: android: command not found" I use Ubuntu 15.04 - Gnome,
For any reason when I try to execute the function "Android" its return
bash: /opt/android-sdk-linux/tools/android: Permission denied

and when I type sudo android the bash return
sudo: android: command not found

Any solution? This can affect to "Cordova"?
Thanks in advance.

Update:
file /opt/android-sdk-linux/tools/android
/opt/android-sdk-linux/tools/android: POSIX shell script, ASCII text executable

uname -a
Linux Hope 3.19.0-33-generic #38-Ubuntu SMP Fri Nov 6 18:18:12 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 15.04
Release:    15.04
Codename:   vivid

stat /opt/android-sdk-linux/tools/android
File: '/opt/android-sdk-linux/tools/android'
Size: 3498          Blocks: 8          IO Block: 4096   regular file
Device: 801h/2049d  Inode: 786692      Links: 1
Access: (0744/-rwxr--r--)  Uid: (249512/ UNKNOWN)   Gid: ( 5000/     UNKNOWN)
Access: 2015-11-10 15:01:53.838926405 +0200
Modify: 2015-10-14 10:44:06.000000000 +0300
Change: 2015-11-10 14:50:37.671590304 +0200
Birth: -

A: There is an unknown group (gid 5000) and an unknown user (uid 249512) and ... I guess ... you are not the user with the uid 249512.
Set the permissions - everything in /opt should have the owner root and the group root:
sudo chown -R root:root /opt/android-sdk-linux

Set the executable rights:
sudo chmod 755 /opt/android-sdk-linux/tools/android

Run the script with sudo rights (a very bad idea)
sudo /opt/android-sdk-linux/tools/android

so better change the directory
cd /opt/android-sdk-linux/tools; sudo ./android

If /opt/android-sdk-linux/tools/ is in your PATH this will work too:
sudo android

And once again: Using sudo to run this application is not necessary and a VERY bad idea!

But I suspect that there are additional problems with other files in your /opt/android-sdk-linux installation.


text:
Q: Returning data where all categories exactly match I have a documents table that I'm rendering out in a ui.
This ui has a set of select2 dropdowns for different category types and the dropdowns are populated data from a categories table.
Each of these dropdowns allows for multiple selections and will post a named array of values to the server.
What I'm hoping to achieve is to only display the relevant documents based on matching the posted cat_id's within a cat_type
These are example tables
Documents
+----+------------+-------------+
| id | doc_title  | doc_version |
+----+------------+-------------+
|  1 | item 1     |           4 |
|  2 | document 2 |           3 |
+----+------------+-------------+

Categories
+----+--------+----------+
| id | cat_id | cat_type |
+----+--------+----------+
|  1 |      1 |        3 |
|  1 |      7 |        2 |
|  1 |      4 |        2 |
|  2 |      7 |        2 |
+----+--------+----------+

An example might be querying documents where the cat_id = 7 and the cat_type = 2.
This should to return row 1 and 2 of the documents table.
What I'm having difficulty with is query documents for a match where multiple cat_id's are declared for a cat_type.
An example might be querying documents where the cat_id = 7 and 4  and the cat_type = 2.
This should to return row 1 of the documents table.
I was thinking I could of used WHERE cat_id IN (4,7) AND cat_type = 2, however that returns results that match either cat_id.
How should I go about querying the data in order to return document entries that exactly match cat_id's for a cat_type?
Thanks

A: You cqan use the IN clause for that
SELECT
`id`, `doc_title`, `doc_version`
FROM Documents WHERE id in (SELECT `id`
                            FROM Categories
                            WHERE `cat_id` = 7  AND  `cat_type` = 2);

CREATE TABLE Documents (
  `id` INTEGER,
  `doc_title` VARCHAR(10),
  `doc_version` INTEGER
);

INSERT INTO Documents
  (`id`, `doc_title`, `doc_version`)
VALUES
  ('1', 'item 1', '4'),
  ('2', 'document 2', '3');

CREATE TABLE Categories (
  `id` INTEGER,
  `cat_id` INTEGER,
  `cat_type` INTEGER
);

INSERT INTO Categories
  (`id`, `cat_id`, `cat_type`)
VALUES
  ('1', '1', '3'),
  ('1', '7', '2'),
  ('1', '4', '2'),
  ('2', '7', '2');

✓

✓

✓

✓

SELECT
`id`, `doc_title`, `doc_version`
FROM Documents WHERE id in (SELECT `id`
                            FROM Categories
                            WHERE `cat_id` = 7  AND  `cat_type` = 2);

id | doc_title  | doc_version
-: | :--------- | ----------:
 1 | item 1     |           4
 2 | document 2 |           3

db<>fiddle here


text:
Q: Gridview doesn't update when the bound data changes I've bound my data grid and a bunch of check boxes to the following properties in my view model (typed Presenter).
public ListCollectionView AllOrdersView { get; set; }

public IEnumerable<CarrierType> AllCarrierTypes
{
  get { return _allCarrierTypes; }
  set
  {
    _allCarrierTypes = value;
    OnPropertyChanged();
  }
}

In the constructor of it, I assign a filter like so.
public Presenter()
{
  _allOrders = new ObservableCollection<Order>(DataAccessor.GetOrders());
  AllOrdersView = new ListCollectionView(_allOrders);
  AllOrdersView.Filter = element => AllCarrierTypes
    .Where(x => x.Active).Contains(((Order)element).CarrierType);
}

The aim is to filter off the orders that have a carrier of type that's unchecked. At the moment, it seems that the filtration only takes place initially, as the constructor is invoked. My hope was that, since the check boxes are bound, I need no further intervention with the code. It's not the case. As I select/deselect the check boxes, the data grid stays unaffected.
Furthermore, suspecting that it's got to do with the need to refresh the view, I added a call to the view as follows.
private void ToggleButton_OnUnchecked(Object sender, RoutedEventArgs eventArgs)
{
  ((Presenter)DataContext).AllOrdersView.Refresh();
}

Sadly, that doesn't seem to make any difference and I'm all stuck. So, my questions are these.

*

*Do I need to refresh explicitly in the event handler at all?

*Do I need to add another (kind of) binding?

*Do I need to implement anything more in the view model?

My bindings are done in the following way.
<ListBox ItemsSource="{Binding AllCarrierTypes}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <CheckBox Content="{Binding Name}"
                IsChecked="{Binding Active,Mode=TwoWay}"
                Checked="ToggleButton_OnChecked"
                Unchecked="ToggleButton_OnUnchecked"/>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

<DataGrid x:Name="dataGrid"
          ItemsSource="{Binding AllOrdersView}"
          AutoGeneratingColumn="DataGrid_OnAutoGeneratingColumn" .../>

Edit
Per requestion - full version of the CarrierType class in the model.
public class CarrierType : INotifyPropertyChanged
{
  private bool _active;

  public int Id { get; set; }
  public String Name { get; set; }
  public bool Active
  {
    get { return _active; }
    set
    {
      _active = value;
      OnPropertyChanged();
    }
  }

  public override String ToString()
  {
    return Name;
  }

  public event PropertyChangedEventHandler PropertyChanged;

  [NotifyPropertyChangedInvocator]
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}

A: There's seems to be a problem with the ListCollectionView in .NET 4.5 (not sure if the problem existed earlier). You would need to call Refresh() but it doesn't seem to work.
What I do is to re-assign the filter.
private void ToggleButton_OnUnchecked(Object sender, RoutedEventArgs eventArgs)
{
  AllOrdersView.Filter = element => AllCarrierTypes
    .Where(x => x.Active).Contains(((Order)element).CarrierType);
}

As requested in the comments below :
  <CheckBox IsChecked="{Binding Active,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>


text:
Q: Conditional Entropy in rolling a dice A 6-sided die is tossed once. Two events X and Y are defined. X is the event in which an even number comes up and Y is the event in which the number is a multiple of 3. The value of H(X|Y) needs to be computed using two different ways.
This is how I tried to solve it.

This means that X and Y are independent. So H(X|Y) = H(X) and I figured I only need to compute
To compute H(X|Y) using a different way, I tried to use this formula:

I thought in all the cases but {6}, p(x, y) is zero, because the die is tossed only once and we can not have different values. p(6,6) is 1/6. Based on this reasoning H(X|Y) is 1/6 * (2.58) = 0.43
I had some confusion computing p(x|y) too. I took p(6|6) to be 1/6 but I doubt if it was a correct value, because if one interprets p(6|6) as the probability that {6} shows up from X if {6} has already showed up in Y, then p(6|6) is 1. but log(1) is zero and that also doesn't make anything better.
What goes wrong in my reasoning and why do the two computed values for H(X|Y) turn out to be so different?

A: You've got the wrong support for the events' variables.
An even number either comes up or it does not.   This event can be measured by an random variable which takes the values $1$ when it happens, or $0$ if it does not.   Likewise for the event of a number divisible by 3.
Thus $X\in\{0,1\}$ and $Y\in\{0,1\}$ are indicator random variables, that depend on the value of $Z\in\{1,2,3,4,5,6\}$, which the random variable of the die's result.    Specifically:
$$X=\operatorname {\bf 1}_{\{2,4,6\}}(Z) , \; Y=\operatorname {\bf 1}_{\{3,6\}}(Z)\\p_X(0)=\tfrac 1 2, p_X(1)=\tfrac 1 2\\ p_Y(0)=\tfrac 2 3, p_Y(1)=\tfrac 1 3\\p_{X,Y}(0,0)=\tfrac 1 3, p_{X,Y}(1,0)=\tfrac 1 3, p_{X,Y}(0,1)=\tfrac 1 6, p_{X,Y}(1,1)=\tfrac 1 6$$
So indeed they are independent as: $p_{X,Y}(x,y) = p_X(x)p_Y(y)$ for all $(x,y)\in\{0,1\}^2$.
Thus : $p_{X\mid Y}(x\mid y)=p_X(x)$
The entropy of $X$ is
$$\begin{align}
H(X) &= - \sum_{x\in \{0,1\}} p_X(x)\log p_X(x)
\\ & = - (\frac 1 2 \log \frac 1 2+\frac 1 2 \log \frac 1 2)
\\ & = \log 2
\end{align}$$
The conditional entropy of $X$ given $Y$ is:
$$\begin{align}
H(X\mid Y) &= -\sum_{y\in\{0,1\}} \sum_{x\in\{0,1\}} p_{X,Y}(x,y)\log p_{X\mid Y}(x\mid y)
\\ & = -\sum_{y\in\{0,1\}} \sum_{x\in\{0,1\}} p_{X,Y}(x,y)\log p_{X}(x)
\\ & = -\left(\tfrac 1 3\log \tfrac 1 2+\tfrac 1 3\log \tfrac 1 2 +\tfrac 16\log \tfrac 1 2 + \tfrac 1 6\log \tfrac 1 2\right)
\\ & = \log 2
\end{align}$$


text:
Q: I'd like to find the formula for this triangle number sequence. This is a numeric triangle that came up in a problem I'm trying to solve. I got this sequence using the brute force approach (Javascript):
function f(s, b){
  if(s == 0 || b == 0) return 0;
  if(s > b) return 0;
  if(s == 1 || b == 1 || b == s) return 1;

  let sum = 0;
  for(let i=0; i<Math.min(s, b); i++){
    sum += (i + 1) * f(s-i, b-s);
  }

  return sum;
}

Result for the first few numbers (10 x 10).
0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1
0 0 1 2 3 4 5 6 7 8
0 0 0 1 3 5 8 12 16 21
0 0 0 0 1 4 7 12 20 30
0 0 0 0 0 1 5 9 16 28
0 0 0 0 0 0 1 6 11 20
0 0 0 0 0 0 0 1 7 13
0 0 0 0 0 0 0 0 1 8
0 0 0 0 0 0 0 0 0 1

I'm not very good at combinatorics (or math in general). I'd like to understand how I can change the brute force approach so that I can get the sequence without iterating all numbers from 0 to min(s, b). I've attempted building the sequence in many ways, but it's mostly by trying random multiplications and sums, so I don't think I'll end up having the correct formula soon with this approach.
Background (what I'm trying to achieve):
We are trying to build a structure that's made out of blocks. Each structure has s stacks of blocks, and the total number of blocks is b. The structure must be convex, not concave. The goal is to count how many different structures for each pair of s and b values can be built. For example, if the stack number is the same as the block number, we can only build one, because all blocks are being used for the base. If the block count is less than the stack count, we can build none. If s < b, then there are many ways to build a convex structure.

A: I was able to solve it. It requires two functions. I'm not sure about the function naming, and maybe it can be refactored into one function, but it works this way, and I was able to bring the complexity from $O(n^3)$ to $O(n^2)$, so I'm happy with it.
This is the C++ code:
ll dp(int s, int b) {
  if (s == 0 || b == 0) return 0;
  if (s > b) return 0;
  if (s == 1 || b == 1 || b == s) return 1;
  if (memo[s][b] != -1) return memo[s][b];
  ll result = dp(s, b - s) + 2 * dp(s - 1, b - 1) - dp(s - 2, b - 2);
  return memo[s][b] = result;
}

int calculate(int s, int b) {
  if (s == 1 || b == 1 || b == s) return 1;
  ll sum = 0;
  for (int i = 0; i < min(s, b); i++) {
    sum += (i + 1) * dp(s - i, b - s);
  }
  return (int)sum;
}

Then get the desired value (read the question statement to understand the problem) as calculate(3, 6) (i.e. ways to create a convex structure with 3 stacks and a total of 6 blocks).
Note: ll is typedef long long int ll;. The memo variable is for memoization.


text:
Q: Create 5 Point Star with e.graphics but set the x and y start position to 110,110 in VB.NET I need to create a small 5 point star that is 15 points wide by 15 points high, where the x starting position is 110 and the y starting position is 110 on my print document.
the code I found online so far creates a star, but in the top left corner at 0,0 position.
         ' Make the points for a star.
                Dim pts(4) As Point
                Dim cx As Integer = 15 \ 2
                Dim cy As Integer = 15 \ 2
                Dim theta As Double = -Math.PI / 2
                Dim dtheta As Double = Math.PI * 0.8
                For i As Integer = 0 To 4
                    pts(i).X = CInt(cx + cx * Math.Cos(theta))
                    pts(i).Y = CInt(cy + cy * Math.Sin(theta))
                    theta += dtheta
                Next i

                e.Graphics.FillPolygon(Brushes.Black, pts)

how do i now move the star graphic to position x.110 y.110?

A: Try using the sources below.
 Private Sub DrawStar(ByVal prm_StartX As Integer, ByVal prm_StartY As Integer)

      Try

         Dim pts(4) As Point
         Dim cx As Integer = prm_StartX
         Dim cy As Integer = prm_StartY
         Dim theta As Double = -Math.PI / 2
         Dim dtheta As Double = Math.PI * 0.8
         For i As Integer = 0 To 4
            pts(i).X = CInt(cx + 7 * Math.Cos(theta))
            pts(i).Y = CInt(cy + 7 * Math.Sin(theta))
            theta += dtheta
         Next i

         Dim Pen As New Pen(Color.Red, 2)

         ' Draw
         Dim formGraphics As System.Drawing.Graphics
         formGraphics = Me.CreateGraphics()
         formGraphics.DrawPolygon(Pen, pts)

         Pen.Dispose()
         formGraphics.Dispose()

      Catch ex As Exception

      End Try

   End Sub

   Private Sub Toy1Form_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick

      DrawStar(e.X, e.Y)

   End Sub


text:
Q: Move menu icon to right side on action bar Can i change the position of elements in default action bar of?
I want to move the menu icon to right side without use a component.
enter image description here


text:
Q: How can I exit SimpleHTTPServer without closing terminal? I am running the SimpleHTTPServer from powershell.
python -m SimpleHTTPServer 8080

I want to exit (control + break) the server without closing the terminal.  Any ideas?
Thanks in advance for any suggestions

A: ^C will close it (control + c)
Example of me testing control + c to send an interupt and exit:
PS C:\> python -m http.server 8080
Serving HTTP on 0.0.0.0 port 8080 ...

Keyboard interrupt received, exiting.

Note, I am using http.server as this replaces SimpleHTTPServer in Python 3 but it should work the same for you.


text:
Q: Printing HTML with PHP function produces output which is wrongly interpreted by browser maybe I am just too tired or missing something really fundamental, but I am growing frustrated.
I have table which contains data. I wrote php function which takes data from database and construct html table.
My problem is, that first row in table misses element in last table cell.
PHP function:
function printTable($stmt) {
    $result = '
';
    while ($data = $stmt -> fetch()) {
         $result .= '
'
                     . '' . $data['id'] . '	'
                     . '' . $data['name'] . '	'
                     . ''
                        . '<form method="post" action="">'
                           . '<input type="hidden" name="id" value="' . $data['id'] . '">
                           . '<button type="submit" name="edit">Edit</button>'
                        . '</form>'
                     . '	'
                 . '
';
    }
    $result .= '
';
    return $result;
}

The problem is that browser ignores form element in first row. Hidden input and button stay in place but without its parent form. So the output in browser looks like this:

      1
      Foo

         <input type="hidden" name="id" value="1">
         <button type="submit" name="edit">Edit</button>

      2
      Bar

         <form method="post" action="">
            <input type="hidden" name="id" value="2">
            <button type="submit" name="edit">Edit</button>
         </form>

      3
      Foo Bar

         <form method="post" action="">
            <input type="hidden" name="id" value="3">
            <button type="submit" name="edit">Edit</button>
         </form>

Furthermore, if I dump return value of this function, for example:  var_dump(htmlspecialchars(printTable($stmt))); it shows that first form is there, but in browser suddenly misses. Is it mysteriously dissapearing form magic?

A: Well, it seems this behaviour is related to nested forms and how browsers handle them. Nested forms are invalid by specification.
See Is it valid to have a hrml form inside another html form? or Chrome is eating my first inner form why?

A: The output in the browser certainly doesn't look the way you've shown it, because your PHP code doen't output any indentation.
So what you're probably showing us is the browser's processed DOM, which may or may not represent the actual code that is being sent to the browser.
The chances are that the code the browser is receiving is invalid in some way or another, and what you're seeing is the browser's attempt to correct the mistakes.
Without seeing the rest of the page, I can't be certain what the invalid code actually looks like, but my guess is that you've got a <form> element already open prior to the table being output. You can't have nested <form>s, so the browser sees the first one inside the table and says to itself "oh, this is invalid". So it tries to fix it, and the result is that the inner form gets removed.
As I say, that's mostly speculation, and I can't be any more accurate without seeing the rest of the page, but I'd say it's likely a fairly close guess.
In any case, you can find out for yourself what the problem really is by running the code through the W3C's HTML validator. You can find it, and other code validation tools here: https://www.w3.org/developers/tools
The easiest way to use it is to open the page in your browser, and use the "view source" option to see the actual HTML code (ie not the DOM code shown in the dev tools), and then copy+paste that into the form in the validator.
It should tell you pretty quickly what the problems are with your code.
Best of luck.

A: Just incase my suggestions were unclear I pulled your code out and faked your data
$allData = [
    ['id' => 1, 'name' => 'Foo'],
    ['id' => 2, 'name' => 'Bar'],
    ['id' => 3, 'name' => 'Baz']
];
$result = '<form method="post" action="">
';
foreach ($allData as $data) {
    $result .= '
'
        . '' . $data['id'] . '	'
        . '' . $data['name'] . '	'
        . ''
            . '<button type="submit" name="edit" value="' . $data['id'] . '">Edit</button>'
        . '	'
    . '
';
}
$result .= '
</form>';
echo $result;

A: According to HTML specs, you cannot have a form inside of a table cell, but you can have a table inside of a form. Catharsis' answer is correct, but I am baffled as to why your first opening and closing form tag have disappeared, there must be other parts of your code that are causing this to happen. Anyhow, I would take the form outside the table and for ease of readability replace all the concatenation code with HEREDOC code.
function printTable($stmt) {
    $result = '<form method="post">';
    $result .= '
';
    while ($data = $stmt -> fetch()) {
         $result .= <<<HTML

                {$data['id']}
                {$data['name']}
                <button type="submit" name="edit" value="{$data['id']}">Edit</button>

HTML;
    }
    $result .= '
';
    $result .= '</form>';
    return $result;
}


text:
Q: QApplication::postEvent правильно ли? Есть класс наследник QWidget, у которого есть виртуальный метод updateStyle(). Данный метод должен срабатывать при получение QEvent::StyleChange и один раз при конструирование формы. Просто вызвать виртуальный метод и конструктора класс нельзя, так как класс-наследник еще не создан. Чтоб это обойти я воспользовался методом QApplication::postEvent, в данном случае срабатывает updateStyle() класса-наследника как и задумывалось. Вопрос в том, на сколько корректен этот код? всегда ли будет нужное мне поведение?
extendedwidget.h
class ExtendedWidget : public QWidget
{
public:
    ExtendedWidget(QWidget *_parent = 0);

    virtual void updateLanguage();
    virtual void updateStyle();

protected:
    virtual void changeEvent(QEvent *event) override;
};

extendedwidget.cpp
ExtendedWidget::ExtendedWidget(QWidget *_parent):
    QWidget(_parent)
{
    QApplication::postEvent(this, new QEvent(QEvent::StyleChange));
}

void ExtendedWidget::updateLanguage()
{

}

void ExtendedWidget::updateStyle()
{
    qDebug() << Q_FUNC_INFO;
}

void ExtendedWidget::changeEvent(QEvent *event)
{
    switch(event->type())
    {
    case QEvent::LanguageChange:
        updateLanguage();
        break;
    case QEvent::StyleChange:
        updateStyle();
        break;
    default:
        break;
    }

    QWidget::changeEvent(event);
}

A: Ну в эту ситуацию Qt лучше не привлекать, эта проблема довольно частая и решается она обычно в явном виде, пишете какой-нибудь
virtual void init() ;

и вызываете его всегда сразу после конструктора, примерно так
ExtendedWidget *w = new ExtendedWidget;
w->init();

imho лучше способов для этого в c++ нет


text:
Q: Subsets of intervals If S $\subseteq$ $\mathbb{R}$ is a nonempty, bounded set, and I := [inf S, sup S], show that S $\subseteq$ I.  Moreover, if J is any closed bounded interval containing S, show that I $\subseteq$ J.  To show that S $\subseteq$ I, let x $\in$ S.  Since S is bounded, inf S $\lt$ x < sup S.  Thus x $\in$ I.  Therefore S $\subseteq$ I.  Is this correct?  I feel like I am missing something.  How do I show that I $\subseteq$ J if S $\subseteq$ J?

A: It's not true that $\inf S < x$; for example, if $S = [0, 1]$ and $x = 0$, this is false. What is true, and follows directly from the definitions, is that
$$\inf S \le x \le \sup S$$
since $\inf$ and $\sup$ are actually bounds on $S$. The result follows immediately from this observation.

For your second question: Suppose $S \subseteq J = [a,b]$. Argue that $a \le \inf S$, so that $a$ is a lower bound for $I$. Make the same argument for the upper bounds.


text:
Q: How to create multiple excel workbooks against the same application object? I can create multiple workbooks against the same application object simply by using the ADD property twice in  row (see code below). But this is a tedious process if I want to create more number of workbooks. So I was wondering if there is a way to specify the number of workbooks that I want to create?
Imports System
Imports Microsoft.Office.Interop
Module Program
    'declaration statements
    Dim XL As Excel.Application
    Dim WB As Excel.Workbook

    Sub Main(args As String())
        XL = CreateObject("Excel.Application")
        XL.Visible = True
        WB = oXL.Workbooks.Add
        WB = oXL.Workbooks.Add
        Console.ReadLine()
        oXL.Quit()
    End Sub
End Module


text:
Q: Javascript - trying to create a dynamic combobox im trying to create a combobox that contain a table from database

    <fieldset>
        <select class="select2_single form-control">
            <option class="default" value=""></option>
            <?php
            $tampil=mysql_query("SELECT ID_KRITERIA, NAMA_KRITERIA FROM KRITERIA ORDER BY NAMA_KRITERIA");
            while($w=mysql_fetch_array($tampil))    {
                echo '<option value="' . $w['ID_KRITERIA'] . '">' . $w['NAMA_KRITERIA'] . '</option>';  }
            ?>
        </select>
    </fieldset>

and then I want to duplicate this combobox everytime I click a button
here is my Javascript
$( document ).ready(function () {
    // set an on click on the button
        $("#newKriteria").click(function () {
            var newComboBox = $("fieldset").find("select").clone();
            $('#step-3 div:eq(0)').after("

"+newComboBox+"

");
            $(newComboBox).select2({
                placeholder: "Pilih Masukan",
                allowClear: true
            });
            return false;
        });
    });

I have tried following some way

*

*with following javascript above, my page is showing [object Object] everytime I click the button

*using .html() insted of .clone() = the combobox only show the value (not with the css)

is there any right way to do this ?

A: newComboBox is a jQuery object, that's why you end in having [Object object], try newComboBox.val() instead. It should returns you the value of the select you cloned (is clone needed anyway ?)


text:
Q: Soccer Stats Python Scraper I'm looking to scrape some Houston Dynamo stats from this season into a CSV and then visualize that data with R.
How can I scrape both the tr and td elements using lxml? Is there an easier selector I should be looking at?

A: For (reasonably) well formed HTML tables, the XML package in R makes this sort of thing pretty stupidly easy:
library(XML)
> url <- "http://www.houstondynamo.com/stats/season?page=0"
> tbl <- readHTMLTable(url)
> head(tbl[[1]])
           Player POS GP GS MINS  G  A SHTS SOG GWG PKG/A HmG RdG G/90min  SC%
1      Will Bruin   F 32 31 2510 12  4   78  35   0   0/0   6   6    0.43 15.4
2      Brad Davis   M 31 28 2523  8 12   53  22   3   3/4   5   3    0.29 15.1
3     Brian Ching   F 30 13 1385  5  5   35  15   1   2/2   2   3    0.32 14.3
4   Boniek Garcia   M 17 17 1530  4  6   30  12   1   0/0   3   1    0.24 13.3
5      Calen Carr   M 26 17 1512  4  2   29  11   2   0/0   3   1    0.24 13.8
6 Macoumba Kandji   F 29 21 1630  4  2   34  16   1   0/0   3   1    0.22 11.8


text:
Q: Changing java version i have a server - client application that runs on java 1.3; i want to change to java 1.6 step by step, meaning first few clients, than rest of the clients and finally server...
i was wondering could you direct me to some common problems that can come along and what should i look after?

A: Off the top of my head, look for the names enum and assert in fields and local variables... These words have become keywords in java 1.4 and 5. The java 6 compiler will mark them as compilation errors if it sees them.
Yuval =8-)

A: Sun keeps a list of incompatibilities that are introduced with each new version of Java.

*

*Java SE 6 Release Notes: Compatibility

*Incompatibilities in J2SE 5.0 (since 1.4.2)

*Java 2 Platform, Standard Edition Version 1.4.2 Compatibility with Previous Releases
The last document for 1.4.2 has links to the compatibility notes back to JDK 1.0.

A: Generally, the backwards compatibility of Sun's JVMs is very good, but not perfect. I've seen three very large applications migrate from 1.3 to 1.5 and encounter only a small number of problems, the biggest of which was one Swing mask going into an endless event handling loop and freezing up the app under 1.4
The server part is unlikely to cause problems, but there have been pretty big under-the-hood changes in Swing, especially between 1.3 and 1.4 - the focus subsystem was completely rewritten, for example.
It's still possible that the app will run without problems, but you definitely should do extensive testing.

A: When I moved from 1.4.2 to 1.5 on a small applet I worked on, lots of things broke: screen refresh got all wonky, elements moved, etc.
Sun's JRE doesn't maintain backward compatibility for everything. Sometimes when items are deprecated, they completely go away after a very short period of time.
We wrote everything with "stock" Java, using Sun's libraries, too.
I've also seen several application written in pure Java that work fine on one or two platforms in the same version of the JRE fail on others with that version (the product I work with now works great on Windows, ok on Mac OS X, decent on Linux, but fails on Solaris - all with the same JRE).
Moving versions is not a simple step, unless the application is really small.

A: Sun tries to keep a high level of backward-compatibility, so you possibly simply can install the new JVM and restart your application with it.
A document describing the backward-incompatibilities from Java 1.6 with earlier version is here. This document links the compatibility-documents for Java 1.5 and Java 1.4 as well. You probably want to read this documents to learn about possible pitfalls.
Java 1.5 and Java 1.6 introduced new class-file-formats. The JVM's will run the old class-files as well, but recompiling your code - especially with JDK 1.6 - will help the new JVM to take advantage of some changes to make your application faster. So you might consider recompiling.
Additionally some new keywords were introduced, namely assert (in 1.4) and enum (in 1.5) (as Yuval already mentioned). If you use these words as identifiers, a recompile will fail, but the old class-files will work. You can provide the switch -source to javac to let it compile: 'javac -source 1.3' will compile the code without assert and enum as a keyword.

A: My experience is that the compatibility is quite high.  I've only found one app ever that I couldn't get to run on a current version.  For whatever reason (not having source, so I didn't dig into it) that one app wouldn't run on anything other than 1.4.2.  Everything else I've ever dealt with (some of them quite sizeable) have come up to 1.6 just fine.  No  modifications required.
YMMV of course, so you'll have to try it and see...


text:
Q: Generate Email Alerts through Perfmon I am using Perfmon to monitor the performance of my application pool. Is there a way I can generate email alerts through Perfmon if my application pool is stopped.

A: Florian Sander's answer is now considered deprecated and setting up that scheduled tasks to send an email natively could or should not be done because its deprecation. Here is another way to send an email through the perfmon application.
What happens when you try to set this task up:

An Error has occured for the tasks {Tasks Name}. Error message: The following error was reported: The tasks definition uses a deprecated feature.

The alternative:
You can achieve similar functionality by going through the steps of Florian's answer but instead of making a tasks that does the "sends out an email" action, select start a program/script. This method would require you to make a small script that would send an email for you. I included an image to help understand what you may have to do.
Here is an image for clarity
To include more information about my process, in my specific case scenario it was easiest to ping a web-app with certain values to email me because my server already had the capabilities to send me an email that way. I already had scripts and tasks that send me email so it was the way I accomplished that tasks. What you have to do is specific to your situation and could be entirely different way of sending the emails.

A: Yes, you can set up email alerts for windows performance counters. There's an instruction available from Microsoft: "How to create performance counter alert and send email when the alert is triggered".
There's also plenty of other tools available for monitoring windows server performance.