问:
pdo variable is undefined in mysql function
I have an index.php which is like:

```<code>require_once("../resources/config.php");
require_once(LIBRARY_PATH . "/mysql.php");
...
if(checkIfMailExists($email)) {
    $error = true;
    $errormsg = "This e-mail is already in use!";
}
</code>```

mysql.php is:

```<code>try {
    $pdo = new PDO('mysql:host=' . $config['db']['db1']['host'] . ';dbname=' . $config['db']['db1']['dbname'], $config['db']['db1']['username'], $config['db']['db1']['password']);
}catch(PDOException $e){
    echo "Cant connect to mysql DB!";
}

function checkIfMailExists($email)  {
    $query = "SELECT * FROM users WHERE email = '".$email."'";
    $num = $pdo->query($query);
    if($num->rowCount() > 0){
        return true;
    }else{
        return false;
    }
}
</code>```

And it appears, that $pdo from function is undefined. Even if i remove try-catch.
The only way i fixed it - i sent $pdo as a parameter to function, but it seems to be wrong. Any suggestions guys?

答:
Sending a PDO connection as a parameter is actually the only sane way to do this. It is indeed good to know that you could use the global keyword, but the optimal way to write code that is possible to maintain is explicitely stating dependencies, and type-hinting them

```<code>function mailExists (PDO $pdo, $email)  {
    $sql = 'SELECT * FROM users WHERE email = :email';
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':email', $email, PDO::PARAM_STR);
    $stmt->execute();
    return $stmt->rowCount() > 0;
}
if (mailExists($pdo, $email) {}
</code>```

Read more here about PDO and prepared statements. Notice how I took advantage of named parameters to ensure that no sql injection is possible from this code.

Body:
I have an index.php which is like:

require_once("../resources/config.php");
require_once(LIBRARY_PATH . "/mysql.php");
...
if(checkIfMailExists($email)) {
    $error = true;
    $errormsg = "This e-mail is already in use!";
}

mysql.php is:

try {
    $pdo = new PDO('mysql:host=' . $config['db']['db1']['host'] . ';dbname=' . $config['db']['db1']['dbname'], $config['db']['db1']['username'], $config['db']['db1']['password']);
}catch(PDOException $e){
    echo "Cant connect to mysql DB!";
}

function checkIfMailExists($email)  {
    $query = "SELECT * FROM users WHERE email = '".$email."'";
    $num = $pdo->query($query);
    if($num->rowCount() > 0){
        return true;
    }else{
        return false;
    }
}

And it appears, that $pdo from function is undefined. Even if i remove try-catch.
The only way i fixed it - i sent $pdo as a parameter to function, but it seems to be wrong. Any suggestions guys?

Body:
Sending a PDO connection as a parameter is actually the only sane way to do this. It is indeed good to know that you could use the global keyword, but the optimal way to write code that is possible to maintain is explicitely stating dependencies, and type-hinting them

function mailExists (PDO $pdo, $email)  {
    $sql = 'SELECT * FROM users WHERE email = :email';
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':email', $email, PDO::PARAM_STR);
    $stmt->execute();
    return $stmt->rowCount() > 0;
}
if (mailExists($pdo, $email) {}

Read more here about PDO and prepared statements. Notice how I took advantage of named parameters to ensure that no sql injection is possible from this code.


来源: stackexchange

问:
Visual studio wont work with "MoveTo" (win32api)
Here's the code below, VS said that on
line 109 ( MoveTo(hdc, x, y);

"MoveTo" is undefined.

Can someone explain me what's wrong ?
This is a win32api application.

```<code>// Win32Project.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "Win32Project4.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

LRESULT CALLBACK ChildWndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int pNum = 0;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
    const WCHAR szAppName[] = L"Third_LAB";
    const WCHAR szChildClass[] = L"Child";

    HWND hwnd;
    MSG msg;
    WNDCLASSEX wndclass;
    wndclass.cbSize = sizeof(wndclass);
    wndclass.style = CS_HREDRAW | CS_VREDRAW;
    wndclass.lpfnWndProc = WndProc;
    wndclass.cbClsExtra = 0;
    wndclass.cbWndExtra = 0;
    wndclass.hInstance = hInstance;
    wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wndclass.hCursor = LoadCursor(NULL, IDC_CROSS);
    wndclass.hbrBackground = (HBRUSH)(NULL_BRUSH);
    wndclass.lpszMenuName = NULL;
    wndclass.lpszClassName = szAppName;
    wndclass.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SMALL));
    RegisterClassEx(&wndclass);
    wndclass.lpfnWndProc = ChildWndProc;
    wndclass.cbWndExtra = sizeof(WORD);
    wndclass.hIcon = NULL;
    wndclass.lpszClassName = szChildClass;
    wndclass.hIconSm = NULL;
    RegisterClassEx(&wndclass);
    hwnd = CreateWindowEx(
        0,
        szAppName, // window class name
        L"Third_LAB", // window caption
        WS_OVERLAPPEDWINDOW | WS_VSCROLL | WS_HSCROLL, // window style
        200, // initial x position
        150, // initial y position
        800, // initial x size
        500, // initial y size
        NULL, // parent window handle
        NULL, // window menu handle
        hInstance, // program instance handle
        NULL
    ); // creation parameters
    ShowWindow(hwnd, iCmdShow);
    UpdateWindow(hwnd);

    while (GetMessage(&msg, 0, 0, 0))
        DispatchMessage(&msg);

    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
    {
        const WCHAR szChildClass[] = L"Child";
        static int cxBlock, cyBlock;
        static HDC hdc;
        static HPEN hPen;
        static BOOL track = FALSE;
        static HWND hwndCH;
        static  int x, y;

        switch (iMsg) {
        case WM_CREATE:
            hdc = GetDC(hwnd);

            hwndCH = CreateWindow(szChildClass, NULL,
                WS_CHILDWINDOW | WS_VISIBLE,
                0, 0, cxBlock / 2 + 3, cyBlock + 3,
                hwnd, NULL,
                (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE),
                NULL);
            MoveWindow(hwndCH, 0, 0, cxBlock / 2 + 3, cyBlock + 3, NULL);
            return 0;

        case WM_SIZE:

            cxBlock = LOWORD(lParam);
            cyBlock = HIWORD(lParam);
            MoveWindow(hwndCH, 0, 0, cxBlock / 2 + 3, cyBlock + 3, NULL);
            return 0;

        case WM_KEYDOWN:
            switch (wParam)
            {
            case (0x51):
                PostQuitMessage(0);
                break;
            }
            return 0;
        case WM_LBUTTONDOWN:
            track = TRUE;
            x = LOWORD(lParam);
            y = HIWORD(lParam);
            MoveTo(hdc, x, y);
            switch (pNum)
            {
            case (1):
                hPen = CreatePen(PS_SOLID, 5, 0);
                SelectObject(hdc, hPen); break;
            case (2):
                hPen = CreatePen(PS_SOLID, 15, 0);
                SelectObject(hdc, hPen); break;
            case (3):
                hPen = CreatePen(PS_SOLID, 25, 0);
                SelectObject(hdc, hPen); break;
            }
            return 0;
        case WM_LBUTTONUP:
            track = FALSE;
            DeleteObject(hPen);
            return 0;
        case WM_MOUSEMOVE:
            if (track)
            {
                x = LOWORD(lParam);
                y = HIWORD(lParam);
                LineTo(hdc, x, y);
                MoveTo(hdc, x, y);
            }
            return 0;
        case WM_DESTROY:
            ReleaseDC(hwnd, hdc);

            PostQuitMessage(0);
            return 0;
        }
        return DefWindowProc(hwnd, iMsg, wParam, lParam);
    }
}
LRESULT CALLBACK ChildWndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
    static HDC hdc;
    PAINTSTRUCT ps;
    static int cxBlock, cyBlock;
    static int x, y;
    static HPEN hPen;
    switch (iMsg)
    {

    case WM_SIZE:
        hdc = GetDC(hwnd);
        cxBlock = LOWORD(lParam);
        cyBlock = HIWORD(lParam);
        InvalidateRect(hwnd, NULL, TRUE);
        ReleaseDC(hwnd, hdc);
        return 0;

    case WM_PAINT:
        hdc = BeginPaint(hwnd, &ps);
        SetROP2(hdc, R2_BLACK);
        Rectangle(hdc, 0, cyBlock / 2 - 100, cxBlock, cyBlock / 2 - 105);
        Rectangle(hdc, 0, cyBlock / 2, cxBlock, cyBlock / 2 - 15);
        Rectangle(hdc, 0, cyBlock / 2 + 100, cxBlock, cyBlock / 2 + 125);
        InvalidateRect(hwnd, NULL, FALSE);
        break;
    case WM_RBUTTONDOWN:
        x = LOWORD(lParam);
        y = HIWORD(lParam);

        if ((y <= (cyBlock / 2 - 100)) && (y >= (cyBlock / 2 - 105)))
            pNum = 1;
        else if ((y <= (cyBlock / 2)) && (y >= (cyBlock / 2 - 15)))
            pNum = 2;
        else if ((y >= (cyBlock / 2 + 100)) && (y <= (cyBlock / 2 + 125)))
            pNum = 3;
        return 0;
    case WM_DESTROY:
        DeleteObject(hPen);
        ReleaseDC(hwnd, hdc);
        DestroyWindow(hwnd);
        return 0;
    }
    return DefWindowProc(hwnd, iMsg, wParam, lParam);
</code>```

Waiting for a fast response, I would be very glad.

答:
MoveTo() is a Windows 3.x function that is no longer supported.  Use MoveToEx() instead, setting the last argument to NULL.  You can define your own MoveTo() to do that, eg:

```<code>#define MoveTo(hdc, x, y) ((void)MoveToEx(hdc, x, y, NULL))
</code>```

Or:

```<code>inline void MoveTo(HDC hdc, int X, int Y) { MoveToEx(hdc, X, Y, NULL); }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here's the code below, VS said that on
line 109 ( MoveTo(hdc, x, y);

"MoveTo" is undefined.

Can someone explain me what's wrong ?
This is a win32api application.

// Win32Project.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "Win32Project4.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

LRESULT CALLBACK ChildWndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int pNum = 0;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
    const WCHAR szAppName[] = L"Third_LAB";
    const WCHAR szChildClass[] = L"Child";

    HWND hwnd;
    MSG msg;
    WNDCLASSEX wndclass;
    wndclass.cbSize = sizeof(wndclass);
    wndclass.style = CS_HREDRAW | CS_VREDRAW;
    wndclass.lpfnWndProc = WndProc;
    wndclass.cbClsExtra = 0;
    wndclass.cbWndExtra = 0;
    wndclass.hInstance = hInstance;
    wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wndclass.hCursor = LoadCursor(NULL, IDC_CROSS);
    wndclass.hbrBackground = (HBRUSH)(NULL_BRUSH);
    wndclass.lpszMenuName = NULL;
    wndclass.lpszClassName = szAppName;
    wndclass.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SMALL));
    RegisterClassEx(&wndclass);
    wndclass.lpfnWndProc = ChildWndProc;
    wndclass.cbWndExtra = sizeof(WORD);
    wndclass.hIcon = NULL;
    wndclass.lpszClassName = szChildClass;
    wndclass.hIconSm = NULL;
    RegisterClassEx(&wndclass);
    hwnd = CreateWindowEx(
        0,
        szAppName, // window class name
        L"Third_LAB", // window caption
        WS_OVERLAPPEDWINDOW | WS_VSCROLL | WS_HSCROLL, // window style
        200, // initial x position
        150, // initial y position
        800, // initial x size
        500, // initial y size
        NULL, // parent window handle
        NULL, // window menu handle
        hInstance, // program instance handle
        NULL
    ); // creation parameters
    ShowWindow(hwnd, iCmdShow);
    UpdateWindow(hwnd);

    while (GetMessage(&msg, 0, 0, 0))
        DispatchMessage(&msg);

    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
    {
        const WCHAR szChildClass[] = L"Child";
        static int cxBlock, cyBlock;
        static HDC hdc;
        static HPEN hPen;
        static BOOL track = FALSE;
        static HWND hwndCH;
        static  int x, y;

        switch (iMsg) {
        case WM_CREATE:
            hdc = GetDC(hwnd);

            hwndCH = CreateWindow(szChildClass, NULL,
                WS_CHILDWINDOW | WS_VISIBLE,
                0, 0, cxBlock / 2 + 3, cyBlock + 3,
                hwnd, NULL,
                (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE),
                NULL);
            MoveWindow(hwndCH, 0, 0, cxBlock / 2 + 3, cyBlock + 3, NULL);
            return 0;

        case WM_SIZE:

            cxBlock = LOWORD(lParam);
            cyBlock = HIWORD(lParam);
            MoveWindow(hwndCH, 0, 0, cxBlock / 2 + 3, cyBlock + 3, NULL);
            return 0;

        case WM_KEYDOWN:
            switch (wParam)
            {
            case (0x51):
                PostQuitMessage(0);
                break;
            }
            return 0;
        case WM_LBUTTONDOWN:
            track = TRUE;
            x = LOWORD(lParam);
            y = HIWORD(lParam);
            MoveTo(hdc, x, y);
            switch (pNum)
            {
            case (1):
                hPen = CreatePen(PS_SOLID, 5, 0);
                SelectObject(hdc, hPen); break;
            case (2):
                hPen = CreatePen(PS_SOLID, 15, 0);
                SelectObject(hdc, hPen); break;
            case (3):
                hPen = CreatePen(PS_SOLID, 25, 0);
                SelectObject(hdc, hPen); break;
            }
            return 0;
        case WM_LBUTTONUP:
            track = FALSE;
            DeleteObject(hPen);
            return 0;
        case WM_MOUSEMOVE:
            if (track)
            {
                x = LOWORD(lParam);
                y = HIWORD(lParam);
                LineTo(hdc, x, y);
                MoveTo(hdc, x, y);
            }
            return 0;
        case WM_DESTROY:
            ReleaseDC(hwnd, hdc);

            PostQuitMessage(0);
            return 0;
        }
        return DefWindowProc(hwnd, iMsg, wParam, lParam);
    }
}
LRESULT CALLBACK ChildWndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
    static HDC hdc;
    PAINTSTRUCT ps;
    static int cxBlock, cyBlock;
    static int x, y;
    static HPEN hPen;
    switch (iMsg)
    {

    case WM_SIZE:
        hdc = GetDC(hwnd);
        cxBlock = LOWORD(lParam);
        cyBlock = HIWORD(lParam);
        InvalidateRect(hwnd, NULL, TRUE);
        ReleaseDC(hwnd, hdc);
        return 0;

    case WM_PAINT:
        hdc = BeginPaint(hwnd, &ps);
        SetROP2(hdc, R2_BLACK);
        Rectangle(hdc, 0, cyBlock / 2 - 100, cxBlock, cyBlock / 2 - 105);
        Rectangle(hdc, 0, cyBlock / 2, cxBlock, cyBlock / 2 - 15);
        Rectangle(hdc, 0, cyBlock / 2 + 100, cxBlock, cyBlock / 2 + 125);
        InvalidateRect(hwnd, NULL, FALSE);
        break;
    case WM_RBUTTONDOWN:
        x = LOWORD(lParam);
        y = HIWORD(lParam);

        if ((y <= (cyBlock / 2 - 100)) && (y >= (cyBlock / 2 - 105)))
            pNum = 1;
        else if ((y <= (cyBlock / 2)) && (y >= (cyBlock / 2 - 15)))
            pNum = 2;
        else if ((y >= (cyBlock / 2 + 100)) && (y <= (cyBlock / 2 + 125)))
            pNum = 3;
        return 0;
    case WM_DESTROY:
        DeleteObject(hPen);
        ReleaseDC(hwnd, hdc);
        DestroyWindow(hwnd);
        return 0;
    }
    return DefWindowProc(hwnd, iMsg, wParam, lParam);

Waiting for a fast response, I would be very glad.

Body:
MoveTo() is a Windows 3.x function that is no longer supported.  Use MoveToEx() instead, setting the last argument to NULL.  You can define your own MoveTo() to do that, eg:

#define MoveTo(hdc, x, y) ((void)MoveToEx(hdc, x, y, NULL))

Or:

inline void MoveTo(HDC hdc, int X, int Y) { MoveToEx(hdc, X, Y, NULL); }


问:
Node.js: how to use proxyquire for replacing neo4j-driver dependency
I must have some fundamental problem understanding of how proxyquire works or doing something wrong.

For a proof of concept I have this original code connecting to neo4j graphnedb in node.js:

```<code>// I am lib/neo4j.js
var neo4j = require('neo4j-driver').v1;

var graphenedbURL = process.env.GRAPHENEDB_BOLT_URL;
var graphenedbUser = process.env.GRAPHENEDB_BOLT_USER;
var graphenedbPass = process.env.GRAPHENEDB_BOLT_PASSWORD;

var driver = neo4j.driver(graphenedbURL, neo4j.auth.basic(graphenedbUser, graphenedbPass));
</code>```

Then I have this test:

```<code>// I am test/neo4j.test.js
'use strict';
const test = require('tap').test;
const proxy = require('proxyquire');
const sinon = require('sinon');

test('Testing connection to Neo4j', (assert) => {
    const driverStub = sinon.stub();
    const testedModule = proxy('../lib/neo4j', {
         'neo4j': {
            'driver': driverStub,
          },
      });
});
</code>```

Test is run as npm tap test/*.test.js --conv

Because npm does not provide access to .env for heroku graphnedb the driver won't have any process.env connection variables which should be ok since my expectation is that proxyquire will replace the driver with above defined stub but that's not happening and the test fails on neo4j.driver missing graphnedebURL. What am I doing wrong please?

答:
You need to proxyquire neo4j the same way you are requiring in the original file, including v1.</p>

```<code> // I am test/neo4j.test.js
 'use strict';
 const test = require('tap').test;
 const proxy = require('proxyquire');
 const sinon = require('sinon');

 test('Testing connection to Neo4j', (assert) => {
    const driverStub = sinon.stub();
    const testedModule = proxy('../lib/neo4j',
    {
        'neo4j-driver': {
            'v1': {
                driver: driverStub
            },
        },
    });
 });
</code>```

Body:
I must have some fundamental problem understanding of how proxyquire works or doing something wrong.

For a proof of concept I have this original code connecting to neo4j graphnedb in node.js:

// I am lib/neo4j.js
var neo4j = require('neo4j-driver').v1;

var graphenedbURL = process.env.GRAPHENEDB_BOLT_URL;
var graphenedbUser = process.env.GRAPHENEDB_BOLT_USER;
var graphenedbPass = process.env.GRAPHENEDB_BOLT_PASSWORD;

var driver = neo4j.driver(graphenedbURL, neo4j.auth.basic(graphenedbUser, graphenedbPass));

Then I have this test:

// I am test/neo4j.test.js
'use strict';
const test = require('tap').test;
const proxy = require('proxyquire');
const sinon = require('sinon');

test('Testing connection to Neo4j', (assert) => {
    const driverStub = sinon.stub();
    const testedModule = proxy('../lib/neo4j', {
         'neo4j': {
            'driver': driverStub,
          },
      });
});

Test is run as npm tap test/*.test.js --conv

Because npm does not provide access to .env for heroku graphnedb the driver won't have any process.env connection variables which should be ok since my expectation is that proxyquire will replace the driver with above defined stub but that's not happening and the test fails on neo4j.driver missing graphnedebURL. What am I doing wrong please?

Body:
You need to proxyquire neo4j the same way you are requiring in the original file, including v1.

 // I am test/neo4j.test.js
 'use strict';
 const test = require('tap').test;
 const proxy = require('proxyquire');
 const sinon = require('sinon');

 test('Testing connection to Neo4j', (assert) => {
    const driverStub = sinon.stub();
    const testedModule = proxy('../lib/neo4j',
    {
        'neo4j-driver': {
            'v1': {
                driver: driverStub
            },
        },
    });
 });


问:
awk: Search missing value in file
awk newbie here! I am asking for help to solve a simple specific task.

Here is file.txt

```<code>1
2
3
5
6
7
8
9
</code>```

As you can see a single number (the number 4) is missing. I would like to print on the console the number 4 that is missing. My idea was to compare the current line number with the entry and whenever they don't match I would print the line number and exit. I tried

```<code>cat file.txt | awk '{ if ($NR != $1) {print $NR; exit 1} }'
</code>```

But it prints only a newline.

I am trying to learn awk via this small exercice. I am therefore mainly interested in solutions using awk. I also welcome an explanation for why my code does not do what I would expect.

答:
Maybe this will help:

```<code>seq $(tail -1 file)|diff - file|grep -Po '.*(?=d)'
4
</code>```

Since I am learning awk as well

```<code>awk 'BEGIN{i=0}{i++;if(i!=$1){print i;i=$1}}' file
4

`awk` explanation read each number from `$1` into array `i` and increment that number list line by line with `i++`, if the number is not sequential, then print it.

cat file
1
2
3
5
6
7
8
9
11
12
13
15

 awk 'BEGIN{i=0}{i++;if(i!=$1){print i;i=$1}}' file
 4
 10
 14
</code>```

Title: awk: Search missing value in file

Body:
awk newbie here! I am asking for help to solve a simple specific task.

Here is file.txt

1
2
3
5
6
7
8
9

As you can see a single number (the number 4) is missing. I would like to print on the console the number 4 that is missing. My idea was to compare the current line number with the entry and whenever they don't match I would print the line number and exit. I tried

cat file.txt | awk '{ if ($NR != $1) {print $NR; exit 1} }'

But it prints only a newline.

I am trying to learn awk via this small exercice. I am therefore mainly interested in solutions using awk. I also welcome an explanation for why my code does not do what I would expect.

Body:
Maybe this will help:

seq $(tail -1 file)|diff - file|grep -Po '.*(?=d)'
4

Since I am learning awk as well

awk 'BEGIN{i=0}{i++;if(i!=$1){print i;i=$1}}' file
4

`awk` explanation read each number from `$1` into array `i` and increment that number list line by line with `i++`, if the number is not sequential, then print it.

cat file
1
2
3
5
6
7
8
9
11
12
13
15

 awk 'BEGIN{i=0}{i++;if(i!=$1){print i;i=$1}}' file
 4
 10
 14


问:
Add variable to the instance of the class
I'm trying to add variable to the instance of the class.

In console, I get this error:

```<code>TypeError: __init__() missing 1 required positional argument: 'view'
</code>```

And here is the code itself:

```<code>import sublime_plugin

class TestMe(sublime_plugin.EventListener):

    def __init__(self, view):
        self.view = view
        self.need_update = False

    def setme():
        need_update = True

    def on_activated(self, view):
        setme()
        if need_update == True:
            print("it works")
</code>```

I spend all day trying to figure out different ways to resolve it. What I'm doing wrong?

答:
It looks like the core of your issue is that you're subclassing EventListener and not ViewEventListener.

The reason you're seeing this error is that the __init__ method of the EventListener class takes no arguments (with the exception of self, which is always present in class methods). When Sublime creates the instance, it doesn't pass in a view, and since your __init__ requires one, you get an error that you're missing a positional parameter.

This is because the events in EventListener all pass in the view that they apply to (if any), so the class doesn't associate with one specific view and thus one is not needed when the listener is created.

In contrast, ViewEventListener offers only a subset of the events that EventListener does, but its instances apply to a specific view, so its constructor is provided with the view that it applies to. In this case the events themselves don't have a view argument because the listener already knows what view it is associated with.

A modified version of your code that takes all of this into account would look like this:

import sublime_plugin

class TestMe(sublime_plugin.ViewEventListener):
    def __init__(self, view):
        super().__init__(view)
        self.need_update = False

    def setme(self):
        self.need_update = True

    def on_activated(self):
        self.setme()
        if self.need_update == True:
            print("it works")
```

Here the super class is ViewEventListener, for which Sublime will pass a view when it is created. This also invokes the super class version of the __init__ method instead of setting self.view to the view passed in, which allows it to do whatever other setup the default class needs to do (in this case none, but better safe than sorry).

Additionally the methods are adjusted a little bit, since in this case every view will have a unique instance of this class created for it:

setme takes a self argument so that it knows what instance it is being called for

on_activated does not take a view argument because it has access to self.view if it needs it

Calls to setme need to be prefixed with self. so that python knows what we're trying to do (this also implicitly passes in the self argument)

All accesses for need_update are prefixed with self. so that each method accesses the version of the variable that is unique to its own instance.

Body:
I'm trying to add variable to the instance of the class.

In console, I get this error:

TypeError: __init__() missing 1 required positional argument: 'view'

And here is the code itself:

import sublime_plugin

class TestMe(sublime_plugin.EventListener):

    def __init__(self, view):
        self.view = view
        self.need_update = False

    def setme():
        need_update = True

    def on_activated(self, view):
        setme()
        if need_update == True:
            print("it works")

I spend all day trying to figure out different ways to resolve it. What I'm doing wrong?

Body:
It looks like the core of your issue is that you're subclassing EventListener and not ViewEventListener.

The reason you're seeing this error is that the __init__ method of the EventListener class takes no arguments (with the exception of self, which is always present in class methods). When Sublime creates the instance, it doesn't pass in a view, and since your __init__ requires one, you get an error that you're missing a positional parameter.

This is because the events in EventListener all pass in the view that they apply to (if any), so the class doesn't associate with one specific view and thus one is not needed when the listener is created.

In contrast, ViewEventListener offers only a subset of the events that EventListener does, but its instances apply to a specific view, so its constructor is provided with the view that it applies to. In this case the events themselves don't have a view argument because the listener already knows what view it is associated with.

A modified version of your code that takes all of this into account would look like this:

import sublime_plugin

class TestMe(sublime_plugin.ViewEventListener):
    def __init__(self, view):
        super().__init__(view)
        self.need_update = False

    def setme(self):
        self.need_update = True

    def on_activated(self):
        self.setme()
        if self.need_update == True:
            print("it works")

Here the super class is ViewEventListener, for which Sublime will pass a view when it is created. This also invokes the super class version of the __init__ method instead of setting self.view to the view passed in, which allows it to do whatever other setup the default class needs to do (in this case none, but better safe than sorry).

Additionally the methods are adjusted a little bit, since in this case every view will have a unique instance of this class created for it:

setme takes a self argument so that it knows what instance it is being called for

on_activated does not take a view argument because it has access to self.view if it needs it

Calls to setme need to be prefixed with self. so that python knows what we're trying to do (this also implicitly passes in the self argument)

All accesses for need_update are prefixed with self. so that each method accesses the version of the variable that is unique to its own instance.


问:
AngularJs OrderBy after push into an array in ng-repeat
I'm trying to sort an array after pushing a new element to it and show changes on my ng-repeat. It isn't working as expected, it looks like my scope is disconnected from the view.

I have a people array shown with a ng-repeater. Then a column header to sort the array by Last Name. Finally a button to add a new person and automatically sort the array by First Name and show it on the view.

This is my HTML code:

(I also have a fiddler here)

Thanks!!

```<code><div ng-app="myApp">
  <div ng-controller='myController'>
    <div>
      <input type="button" value="Filter All" ng-click="filterAll()" />
      <input type="button" value="Add & Filter" ng-click="AddNFilter()" />
    </div><br/>
    <div><a href="" ng-click="orderByField='lname'; reverseSort = !reverseSort">Order by LName</a></div>
    <div ng-repeat="p in person | orderBy:orderByField:reverseSort">
      {{p.name}} {{p.lname}}
    </div>
  </div>
</div>
</code>```

And my javascript:

```<code>var app = angular.module('myApp', []);
app.controller('myController', function ($scope, $filter) {
    var person = [{
            name: "Seimour"
            , lname: "Duncan"
        }
        , {
            name: "Engy"
            , lname: "Wook"
        }
        , {
            name: "Dame"
            , lname: "Eyola"
      }];
    $scope.person = person;
    $scope.filterAll = function () {
        alert('Before filter: ' + $scope.person[0].name);
        var filtered = $filter('orderBy')($scope.person, 'name');
        $scope.person = filtered;
        alert('After filter: ' + $scope.person[0].name);
    }
    $scope.AddNFilter = function () {
        var p = [{
            name: "Ayesha"
            , lname: "Shexper"
        }];
        alert('Length before adding: ' + $scope.person.length);
        $scope.person.push(p);
        var filtered = $filter('orderBy')($scope.person, 'name');
        $scope.person = filtered;
        alert('Length after adding: ' + $scope.person.length);
    }
});
</code>```

答:
First, you must convert your p variable into an object, instead of an array of objects to make your code work:

```<code>var p = {
  name: "Ayesha",
  lname: "Shexper"
};
</code>```

Second, you don't need to sort again your object in the scope. It is enough if you change the variable that you pass to your orderBy filter in order to filter by the right property:

```<code>$scope.orderByField = 'name';
$scope.reverseSort = !$scope.reverseSort; // Optional! Do it if you want to reverse the sorting
</code>```

You should do this in both, filterAll and AddNFilter functions to update the property that your filter by everytime you click any icon. You are doing it good when clicking Order by LName

I updated your fiddle here

Body:
I'm trying to sort an array after pushing a new element to it and show changes on my ng-repeat. It isn't working as expected, it looks like my scope is disconnected from the view.

I have a people array shown with a ng-repeater. Then a column header to sort the array by Last Name. Finally a button to add a new person and automatically sort the array by First Name and show it on the view.

This is my HTML code:

(I also have a fiddler here)

Thanks!!

      <input type="button" value="Filter All" ng-click="filterAll()" />
      <input type="button" value="Add & Filter" ng-click="AddNFilter()" />

Order by LName

      {{p.name}} {{p.lname}}

And my javascript:

var app = angular.module('myApp', []);
app.controller('myController', function ($scope, $filter) {
    var person = [{
            name: "Seimour"
            , lname: "Duncan"
        }
        , {
            name: "Engy"
            , lname: "Wook"
        }
        , {
            name: "Dame"
            , lname: "Eyola"
      }];
    $scope.person = person;
    $scope.filterAll = function () {
        alert('Before filter: ' + $scope.person[0].name);
        var filtered = $filter('orderBy')($scope.person, 'name');
        $scope.person = filtered;
        alert('After filter: ' + $scope.person[0].name);
    }
    $scope.AddNFilter = function () {
        var p = [{
            name: "Ayesha"
            , lname: "Shexper"
        }];
        alert('Length before adding: ' + $scope.person.length);
        $scope.person.push(p);
        var filtered = $filter('orderBy')($scope.person, 'name');
        $scope.person = filtered;
        alert('Length after adding: ' + $scope.person.length);
    }
});

Body:
First, you must convert your p variable into an object, instead of an array of objects to make your code work:

var p = {
  name: "Ayesha",
  lname: "Shexper"
};

Second, you don't need to sort again your object in the scope. It is enough if you change the variable that you pass to your orderBy filter in order to filter by the right property:

$scope.orderByField = 'name';
$scope.reverseSort = !$scope.reverseSort; // Optional! Do it if you want to reverse the sorting

You should do this in both, filterAll and AddNFilter functions to update the property that your filter by everytime you click any icon. You are doing it good when clicking Order by LName

I updated your fiddle here


问:
Wildfly listen on port 8080 and httpd on port 80 and redirect without port number 8080 on URL
AWS CentOS 64b / HTTP / Wildfly 10 / PHPBB php forum / java project

Scenario :

My URL is : www.apisani.org

I have httpd listening on port 80

I have Wildfly listening on port 8080

My needs : I need to type in the browser : www.apisani.org and be redirected to wildfly - java application on port 8080 but dont want to show the port number in the URL.

I need to type in the browser : www.forum.apisani.org and be redirected to httpd on port 80 - phpbb forum website.

I know how to setup wildfly in standalone.xml and welcome-content to redirect www.apisani.org to www.apisani.org/app/indexapp.xhtl but the problem is given above on "My needs" section

[UPDATED BASED ON FISH REPLIES...]

We are almost there !
The <virtualHost> is working like a charm !

:( The ReWriteConde redirects to wildfly URL app instead of forum...

```<code>RewriteCond %{HTTP_HOST} ^www\.forum\.apisani\.org$
RewriteRule (.*) http://apisani.org:80/phpBB3/$1 [P,L]

RewriteCond %{HTTP_HOST} ^forum\.apisani\.org$
RewriteRule (.*) http://apisani.org:80/phpBB3/$1 [P,L]

<VirtualHost *:80>
  Servername www.apisani.org
  ServerAlias apisani.org

  ProxyPreserveHost on
  ProxyPass  / http://apisani.org:8080/app/index
  ProxyPassReverse / http://apisani.org:8080/app/index
</VirtualHost>
</code>```

答:
I'd suggest to use a rewrite and [P] for that:

```<code>RewriteEngine On

RewriteCond %{HTTP_HOST} ^www.apisani.org$
RewriteRule (.*) http://wildfly:8080/$1 [P,L]

RewriteCond %{HTTP_HOST} ^www.forum.apisani.org$
RewriteRule (.*) http://phpbb-forum-website:80/$1 [P,L]
</code>```

$1 refers to (.*) --> the whole URI. If you want to pass that to your application. If not, just lose the brackets and $1

Let us know if that was what you were looking for. And if not, even more, so we can help furthermore ;)

UPDATE

```<code>RewriteCond %{REQUEST_URI} !^/php
RewriteCond %{HTTP_HOST} ^(www\.)?apisani\.org$
RewriteRule ^/(.*)$ apisani.org:8080/<path> [P,L]

RewriteCond %{HTTP_HOST} ^(www\.)?forum\.apisani\.org$
RewriteRule ^/(.*)$ apisani.org/<path> [P,L]
</code>```

Body:
AWS CentOS 64b / HTTP / Wildfly 10 / PHPBB php forum / java project

Scenario :

My URL is : www.apisani.org

I have httpd listening on port 80

I have Wildfly listening on port 8080

My needs : I need to type in the browser : www.apisani.org and be redirected to wildfly - java application on port 8080 but dont want to show the port number in the URL.

I need to type in the browser : www.forum.apisani.org and be redirected to httpd on port 80 - phpbb forum website.

I know how to setup wildfly in standalone.xml and welcome-content to redirect www.apisani.org to www.apisani.org/app/indexapp.xhtl but the problem is given above on "My needs" section

[UPDATED BASED ON FISH REPLIES...]

We are almost there !
The <virtualHost> is working like a charm !

:( The ReWriteConde redirects to wildfly URL app instead of forum...

RewriteCond %{HTTP_HOST} ^www\.forum\.apisani\.org$
RewriteRule (.*) http://apisani.org:80/phpBB3/$1 [P,L]

RewriteCond %{HTTP_HOST} ^forum\.apisani\.org$
RewriteRule (.*) http://apisani.org:80/phpBB3/$1 [P,L]

<VirtualHost *:80>
  Servername www.apisani.org
  ServerAlias apisani.org

  ProxyPreserveHost on
  ProxyPass  / http://apisani.org:8080/app/index
  ProxyPassReverse / http://apisani.org:8080/app/index
</VirtualHost>

Body:
I'd suggest to use a rewrite and [P] for that:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www.apisani.org$
RewriteRule (.*) http://wildfly:8080/$1 [P,L]

RewriteCond %{HTTP_HOST} ^www.forum.apisani.org$
RewriteRule (.*) http://phpbb-forum-website:80/$1 [P,L]

$1 refers to (.*) --> the whole URI. If you want to pass that to your application. If not, just lose the brackets and $1

Let us know if that was what you were looking for. And if not, even more, so we can help furthermore ;)

UPDATE

RewriteCond %{REQUEST_URI} !^/php
RewriteCond %{HTTP_HOST} ^(www\.)?apisani\.org$
RewriteRule ^/(.*)$ apisani.org:8080/<path> [P,L]

RewriteCond %{HTTP_HOST} ^(www\.)?forum\.apisani\.org$
RewriteRule ^/(.*)$ apisani.org/<path> [P,L]


问:
Why does the counter keep counting when i'm using .hasNext in file io in java
Basically, I'm trying to count how many lines in a txt file and then store it to an array as index.

```<code>File file = new java.io.File("number.txt");
Scanner s = new Scanner(file);
int count = 0;
while(s.hasNextLine())
{
    count++;
    System.out.println(count);
}
System.out.println("There is: " + count + " line );
int[] array = new int[count];
</code>```

However, I realize that the "count" go infinity and it never stop counting, but I only have 20 line in my txt file. Why is this happening??

Note: I know how to fix , but i just curious about why it keep counting

答:
Because that is the way it is designed.

public boolean hasNextLine()

Returns true if there is another line in the input of this scanner.
  This method may block while waiting for input. The scanner does not
  advance past any input.

Returns:
      true if and only if this scanner has another line of input
  Blockquote

Throws:
      IllegalStateException - if this scanner is closed

Body:
Basically, I'm trying to count how many lines in a txt file and then store it to an array as index.

File file = new java.io.File("number.txt");
Scanner s = new Scanner(file);
int count = 0;
while(s.hasNextLine())
{
    count++;
    System.out.println(count);
}
System.out.println("There is: " + count + " line );
int[] array = new int[count];

However, I realize that the "count" go infinity and it never stop counting, but I only have 20 line in my txt file. Why is this happening??

Note: I know how to fix , but i just curious about why it keep counting


问:
Replicate Countifs() in pandas with multiple conditions
I have a DataFrame of the form:

What I would like to achieve is a DataFrame that has unique groups and a count of non-zeros for each column 1-9. It would look like the below.

I'm pretty much at a loss on this. I saw the question here, but this doesn't address the grouping aspect. How can I achieve this using pandas?

答:
Using df from @MaxU solution:</p>

```<code>df.pivot_table(index='Group', aggfunc=np.count_nonzero)

        1   2   3   4   5
Group
Group1  1   1   2   1   2
Group2  1   2   2   1   2
Group3  1   1   2   2   2
</code>```

Body:
Using df from @MaxU solution:

df.pivot_table(index='Group', aggfunc=np.count_nonzero)

        1   2   3   4   5
Group
Group1  1   1   2   1   2
Group2  1   2   2   1   2
Group3  1   1   2   2   2


问:
Creating a Function that works for 2 models in Rails
I have two models which need an identical function. I'd like to learn how to make this DRY the right rails way...

For both models I have:

```<code>before_save :assign_uuid
</code>```

Which in each model has:

```<code>  def assign_uuid
    if self.uuid.nil?
      self.uuid = ActiveSupport::SecureRandom.hex(32)
    end
  end
</code>```

Since, assign_uuid lives in both models, Where is the one place I should place this func? Also, in the models, where it say's before_save. How do I call the assign_uuid in the location it is located?

Thanks

答:
I'm no Ruby expert, so I'm not sure if this is frowned upon or not, but if I were you, I'd chuck it in a file in lib/ and whack it straight on ActiveRecord::Base with class_eval.

```<code>ActiveRecord::Base.class_eval do
  def assign_uuid
    if self.uuid.nil?
      self.uuid = ActiveSupport::SecureRandom.hex(32)
    end
  end
end
</code>```

That way, it's available for all your models. Either that, or create a miscellaneous model helpers file and include the module into the models you'd like.

```<code># lib/misc_model_helpers.rb
module MiscModelHelpers
  def assign_uuid
    if self.uuid.nil?
      self.uuid = ActiveSupport::SecureRandom.hex(32)
    end
  end
end

# models/person.rb
class Person < ActiveRecord::Base
  include MiscModelHelpers
  before_save :assign_uuid
end
</code>```

Again, I'm really not 100% on the most rubyish way of doing this. It's probably something completely different. These are just two ways that work for me!

ContentLicense: CC BY-SA 2.5

Body:
I have two models which need an identical function. I'd like to learn how to make this DRY the right rails way...

For both models I have:

before_save :assign_uuid

Which in each model has:

  def assign_uuid
    if self.uuid.nil?
      self.uuid = ActiveSupport::SecureRandom.hex(32)
    end
  end

Since, assign_uuid lives in both models, Where is the one place I should place this func? Also, in the models, where it say's before_save. How do I call the assign_uuid in the location it is located?

Thanks

Body:
I'm no Ruby expert, so I'm not sure if this is frowned upon or not, but if I were you, I'd chuck it in a file in lib/ and whack it straight on ActiveRecord::Base with class_eval.

ActiveRecord::Base.class_eval do
  def assign_uuid
    if self.uuid.nil?
      self.uuid = ActiveSupport::SecureRandom.hex(32)
    end
  end
end

That way, it's available for all your models. Either that, or create a miscellaneous model helpers file and include the module into the models you'd like.

# lib/misc_model_helpers.rb
module MiscModelHelpers
  def assign_uuid
    if self.uuid.nil?
      self.uuid = ActiveSupport::SecureRandom.hex(32)
    end
  end
end

# models/person.rb
class Person < ActiveRecord::Base
  include MiscModelHelpers
  before_save :assign_uuid
end

Again, I'm really not 100% on the most rubyish way of doing this. It's probably something completely different. These are just two ways that work for me!


问:
How to set right spacing between inline-block elements
My example:

Its possilble to set same spacing between div inline elements. Because auto width is not working.
This is what i got so far:

HTML

```<code> <div id="frame">
      <div class="block">1</div>
      <div class="block">2</div>
      <div class="block">3</div>
      <div class="block">4</div>
    </div>
  </div>
</code>```

CSS

```<code>#frame div {
    background-color: brown;
    padding-left: 20%;
    padding-right: 20%;
    width: auto;
    margin: 5px;
    display: inline-block;
}
</code>```

答:
Flexbox may be your best approach, but be aware that older browsers do not support it.

```<code>#frame div {
    background-color: brown;
    width: 20%;
    text-align:center;
}

#frame {
    display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;
  -webkit-justify-content: space-around;
  justify-content: space-around;
}
</code>```

https://jsfiddle.net/02mp1yxv/

Body:
My example:

Its possilble to set same spacing between div inline elements. Because auto width is not working.
This is what i got so far:

HTML

1

2

3

4

CSS

#frame div {
    background-color: brown;
    padding-left: 20%;
    padding-right: 20%;
    width: auto;
    margin: 5px;
    display: inline-block;
}

Body:
Flexbox may be your best approach, but be aware that older browsers do not support it.

#frame div {
    background-color: brown;
    width: 20%;
    text-align:center;
}

#frame {
    display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;
  -webkit-justify-content: space-around;
  justify-content: space-around;
}

https://jsfiddle.net/02mp1yxv/


问:
How to replace numbers in a div?
With the following code, I'm getting the values of "id"(almost 35), and then add 1 to each "id", so 1 will be 2 and so on. Where I'm stock, it is on how to replace that id number in the html.

This is the code that use to get the values of each id, then I push them into an array, then I run another "for loop" to add 1 to each value, but I don't how to return them to the html.

var x = document.getElementsByClassName('p-divs');

var portfolio = new Array;

for (var i = 0; i < x.length; i++)
{
    var y = document.getElementsByClassName('p-divs')[i].getAttribute('id');
    portfolio.push(y);
}

console.log(portfolio);

var portfolio2 = new Array;

for (var i = 0; i<portfolio.length; i++)
{
    var newId;
    newId = parseInt(portfolio[i]) + 1;

    portfolio2.push(newId);
}

console.log(portfolio2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 p-divs" id="1">
  <div class="portfolio">
    <center>
      <img src="images/pace.png" width="230" height="190" alt="" class="img-responsive">
    </center>
  </div>
</div></code>```

答:
Using native javascript, just use  getattribute's opposite: setAttribute

```<code>for (var i = 0; i < x.length; i++)
{
    var y = document.getElementsByClassName('p-divs')[i].getAttribute('id');
    y++;
    document.getElementsByClassName('p-divs')[i].setAttribute("id",y);
}
</code>```

Title: How to replace numbers in a div?

Body:
Using native javascript, just use  getattribute's opposite: setAttribute

for (var i = 0; i < x.length; i++)
{
    var y = document.getElementsByClassName('p-divs')[i].getAttribute('id');
    y++;
    document.getElementsByClassName('p-divs')[i].setAttribute("id",y);
}


问:
Fixed Position Div, displaying on top of following div
I have the following fiddle  https://jsfiddle.net/0vau6psp/  This is the minimum code required to replicated the error.  I am assuming it has something to do with position:fixed but I can not figure it out.

The problem is resulting in my header being display directly on top of the main content which is causing the main content to not be seen,  I would like the content to display underneath the header.

Any help would be appreciated! Below Is my code as well for reference:

HTML:

```<code>    <header class="site-header" >
  <div class="header-main" id="header-flow">
    <div class="container-fluid header-cont-top-nav">
      <div class="row">
        <div class="col-md-5 text-right hidden-xs hidden-sm">
            <ul>
            <li>Link</li>
            <li>Link</li>
            <li>Link</li>
            </ul>
        </div>
      </div>
    </div><!--/.container-->
  </div><!--/.header-main-->
</header>
  <main class="site-main-content" id="mainscrollcontent">
      <p>
       {{ content_for_layout }}
       Test
       Test Content
       Test Content line 4
       </p>
  </main>
</code>```

CSS:

```<code>#header-flow {
    border-bottom: #73b2b2 3px solid;
    z-index: 1000;
    background-color: #fff;
    position: fixed;
    width: 100%;
}
#header-flow li{
display:inline-block;
}
.site-main-content {
    margin-bottom: 0;
    display:block;
}
</code>```

答:
You are setting the header first in HTML, fixing its position and then main , which is coming under.

So u got these options:

Stop Fixing the position of Header. .remove this line.

change the order

position:relative;

Body:
I have the following fiddle  https://jsfiddle.net/0vau6psp/  This is the minimum code required to replicated the error.  I am assuming it has something to do with position:fixed but I can not figure it out.

The problem is resulting in my header being display directly on top of the main content which is causing the main content to not be seen,  I would like the content to display underneath the header.

Any help would be appreciated! Below Is my code as well for reference:

HTML:

Link

Link

Link

       {{ content_for_layout }}
       Test
       Test Content
       Test Content line 4

CSS:

#header-flow {
    border-bottom: #73b2b2 3px solid;
    z-index: 1000;
    background-color: #fff;
    position: fixed;
    width: 100%;
}
#header-flow li{
display:inline-block;
}
.site-main-content {
    margin-bottom: 0;
    display:block;
}


问:
splitting bash string by delimiter (last line with delimiter) into array
I'm having a hard time splitting a string like this:

```<code>444,555,text with, separator
</code>```

into this:

```<code>444
555
text with, separator
</code>```

i.e. into a 3-element array (last element may contain comma)

I tried sed but I end up having 4 elements due to the last comma.

Any ideas?

Thanks,

答:
sed editor allows replacing the number th match of the regexp(i.e. the k-th occurence of the string within a line):

```<code>str="444,555,text with, separator"
sed 's/,/\n/1; s/,/\n/1' <<< $str
</code>```

The output:

```<code>444
555
text with, separator
</code>```

s/,/\n/1 - 1 here is a number flag which points to the first occurrence of , to replace with \n

The following will give the same result(implying the first match on each substitution):

```<code>sed 's/,/\n/; s/,/\n/' <<< $str
</code>```

Two consecutive substitutions will give 3 lines(chunks)

Body:
I'm having a hard time splitting a string like this:

444,555,text with, separator

into this:

444
555
text with, separator

i.e. into a 3-element array (last element may contain comma)

I tried sed but I end up having 4 elements due to the last comma.

Any ideas?

Thanks,

Body:
sed editor allows replacing the number th match of the regexp(i.e. the k-th occurence of the string within a line):

str="444,555,text with, separator"
sed 's/,/\n/1; s/,/\n/1' <<< $str

The output:

444
555
text with, separator

s/,/\n/1 - 1 here is a number flag which points to the first occurrence of , to replace with \n

The following will give the same result(implying the first match on each substitution):

sed 's/,/\n/; s/,/\n/' <<< $str

Two consecutive substitutions will give 3 lines(chunks)


问:
Make error: missing separator
I am getting the following error running make:

```<code>Makefile:168: *** missing separator.  Stop.
</code>```

What is causing this?

答:
My error was on a variable declaration line with a multi-line extension. I have a trailing space after the "\" which made that an invalid line continuation.</p>

```<code>MY_VAR = \
   val1 \ <-- 0x20 there caused the error.
   val2
</code>```

Title: Make error: missing separator

Body:
I am getting the following error running make:

Makefile:168: *** missing separator.  Stop.

What is causing this?

Body:
My error was on a variable declaration line with a multi-line extension. I have a trailing space after the "\" which made that an invalid line continuation.

MY_VAR = \
   val1 \ <-- 0x20 there caused the error.
   val2


问:
How can I extract images from a PDF file?
I need to extract all the images from a PDF file on my server. I don't want the PDF pages, only the images at their original size and resolution.

How could I do this with Perl, PHP or any other UNIX based app (which I would invoke with the exec function from PHP)?

答:
With regards to Perl, have you checked CPAN?

PDF::GetImages - get images from pdf document

PDF::OCR - get ocr and images out of a pdf file

PDF::OCR2 - extract all text and all image ocr from pdf

LastEditorDisplayName: brian d foy

OwnerDisplayName: Kent Fredric


问:
Bash count lines and pipe into less info
Im strugling to get the info i want, we are using a spamfilter which can be monitored thru API calls.

We use PRTG as our monitoring, PRTG is calling a Bash script which calls the API using curl.

The info i need to work with is called by this line.

```<code>queue=$(curl -u USER:PASS -X GET -H "Content-Type: application/http" https://mx10.mailfilter.nl/cgi-bin/api?call=api_delivery_queue&sort_field=domain,server)

OUTPUT:(lines below the domain are associated with te domain)
domain1.TLD
mx10.mailfilter.nl,1csiOn-00012P-QL,2017-03-28 21:08:29
mx20.mailfilter.nl,1csLqx-0004fO-EM,2017-03-28 21:08:29
domain2.TLD
mx10.mailfilter.nl,1csvTq-0007a4-MS,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvhh-0000gI-5s,2017-03-28 21:08:29
mx10.mailfilter.nl,1cswCX-0004bQ-Iz,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvk3-00013I-Rx,2017-03-28 21:08:29
domain3.TLD
mx10.mailfilter.nl,1csbxg-0005sG-Px,2017-03-28 21:08:29
</code>```

I need to break this down to: (where the number is the count of lines associated with the domain)
Expected Output :

```<code>domain1.TLD 2
domain2.TLD 4
domain3.TLD 1

totalcount=$(curl -u USER:PASS -X GET -H "Content-Type: application/http" https://mx10.mailfilter.nl/cgi-bin/api?call=api_get_delivery_queue_count&domain=default)
</code>```

Which at the end echos 0:$totalcount:$queue

EDIT:(29-03)

My example might be not as clear as i ment it to be :)

domain1.TLD
domain2.TLD
..
Are just some examples the variantion of domains is enormous. From a to z. The lines that are static start with mx10 or mx20.

The command from Vipin might do the trick i will try that one tomorrow.

答:
This is one of the many approaches, hope this helps:

```<code>echo -e "$totalcount" | grep -o domain | wc -l
</code>```

grep with -o option means it prints every matched value of "domain" onto a separate output line and then count these newlines with wc -l.

Body:
Im strugling to get the info i want, we are using a spamfilter which can be monitored thru API calls.

We use PRTG as our monitoring, PRTG is calling a Bash script which calls the API using curl.

The info i need to work with is called by this line.

queue=$(curl -u USER:PASS -X GET -H "Content-Type: application/http" https://mx10.mailfilter.nl/cgi-bin/api?call=api_delivery_queue&sort_field=domain,server)

OUTPUT:(lines below the domain are associated with te domain)
domain1.TLD
mx10.mailfilter.nl,1csiOn-00012P-QL,2017-03-28 21:08:29
mx20.mailfilter.nl,1csLqx-0004fO-EM,2017-03-28 21:08:29
domain2.TLD
mx10.mailfilter.nl,1csvTq-0007a4-MS,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvhh-0000gI-5s,2017-03-28 21:08:29
mx10.mailfilter.nl,1cswCX-0004bQ-Iz,2017-03-28 21:08:29
mx10.mailfilter.nl,1csvk3-00013I-Rx,2017-03-28 21:08:29
domain3.TLD
mx10.mailfilter.nl,1csbxg-0005sG-Px,2017-03-28 21:08:29

I need to break this down to: (where the number is the count of lines associated with the domain)
Expected Output :

domain1.TLD 2
domain2.TLD 4
domain3.TLD 1

totalcount=$(curl -u USER:PASS -X GET -H "Content-Type: application/http" https://mx10.mailfilter.nl/cgi-bin/api?call=api_get_delivery_queue_count&domain=default)

Which at the end echos 0:$totalcount:$queue

EDIT:(29-03)

My example might be not as clear as i ment it to be :)

domain1.TLD
domain2.TLD
..
Are just some examples the variantion of domains is enormous. From a to z. The lines that are static start with mx10 or mx20.

The command from Vipin might do the trick i will try that one tomorrow.

Body:
This is one of the many approaches, hope this helps:

echo -e "$totalcount" | grep -o domain | wc -l

grep with -o option means it prints every matched value of "domain" onto a separate output line and then count these newlines with wc -l.


问:
Using Java reflections to get class variables
I have the following class:

```<code>public final class ClassMap {

    public static final Class HELLO = HelloActivity.class;

}
</code>```

I want to be able to access HelloActivity.class knowing the string "HELLO". I've tried the following:

```<code>Field classField = ClassMap.class.getField("HELLO");
</code>```

But that returns a Field object. How can I get a Class object back?

Thanks!

答:
Now that you have the Field object representing the field, ask for the value, i.e. call classField.get(Object obj).

Since your field is static, the obj parameter will be ignored, and you should just give a null value. Javadoc says so:

If the underlying field is a static field, the obj argument is ignored; it may be null.

So, do this:

```<code>Field classField = ClassMap.class.getField("HELLO");
Object value = classField.get(null);
</code>```

Body:
I have the following class:

public final class ClassMap {

    public static final Class HELLO = HelloActivity.class;

}

I want to be able to access HelloActivity.class knowing the string "HELLO". I've tried the following:

Field classField = ClassMap.class.getField("HELLO");

But that returns a Field object. How can I get a Class object back?

Thanks!

Body:
Now that you have the Field object representing the field, ask for the value, i.e. call classField.get(Object obj).

Since your field is static, the obj parameter will be ignored, and you should just give a null value. Javadoc says so:

If the underlying field is a static field, the obj argument is ignored; it may be null.

So, do this:

Field classField = ClassMap.class.getField("HELLO");
Object value = classField.get(null);


问:
Transpose matrix in prolog
I want to transpose a matrix in prolog, so for example
[[1,2,3],[1,2,3],[1,2,3]] should become
[[1,1,1],[2,2,2],[3,3,3]]

Here is what I've done:

```<code>%transpose(M,T)
transpose([],[]).
transpose(M,[H|T]):-row(H,M,M1),transpose(M1,T).

%row(H, M, M1).
row([],[],[]).
row([H|Tt] , [[H|T1]|T] , [T1|Z]) :- row(Tt,T,Z).
</code>```

Where M is to be transposed in T.
Row predicate (not sure for the difference between predicate and function) get the head of each sublist in M, so I can get the entire first row of the new, transposed matrix T.
I tested row separately, and it is giving the proper result. But when I try to transpose, I get only 'false' and nothing happens, no info for the new matrix T is printed.

Can anyone help me? Is the problem in the way I built the program? Or the result I expect is only true/false indeed and if so, how to get the new matrix? Thanks :)

答:
Prolog only has predicates not functions. A predicate defines a relation, and generally isn't thought of as "doing something" as much as it is "defining something. Your row/3 actually defines a relationship between its 3 arguments.  The 3 arguments are related in that the elements of the 1st and 3rd lists are the heads and tails of the arguments of the 2nd list. I'll show 3 different queries that illustrate:

```<code>| ?- row([a,b,c], L, M).

L = [[a|A],[b|B],[c|C]]
M = [A,B,C]

yes
| ?- row(A, [[a,b,c],[d,e,f],[g,h,i]], L).

A = [a,d,g]
L = [[b,c],[e,f],[h,i]] ? ;

no
| ?- row(A, B, [[a,b],[c,d],[e,f]]).

A = [C,D,E]
B = [[C,a,b],[D,c,d],[E,e,f]] ? ;

no
| ?-
</code>```

A function would not behave this way. Also you can see that, knowing the relationship, the name is a bit generic. row doesn't really adequately describe the relationship. Perhaps it could be called heads_and_tails/3, and maybe swap the 1st and 2nd argument.

The reason your transpose/2 predicate is failing is that it recurses down to a list of empty lists ([[], [], []] in the case of a matrix with 3 rows), but your transpose/2 base case is based upon [].

Let's look at substituting, as suggested in the comment, the base case of transpose([], []) with:

```<code>transpose([[] | _], []).
</code>```

The following example queries result:

```<code>| ?- transpose([[a,b,c],[d,e,f]], T).

T = [[a,d],[b,e],[c,f]] ? ;

no
| ?- transpose([[a,b,c],[d,e,f], [a]], T).

no
| ?- transpose(T, [[a,b,c],[d,e,f]]).

T = [[a,d],[b,e|_],[c,f|_]] ? ;

no
</code>```

So incorrect results occur for the second query. One approach to resolve this, following along the logic of this predicate, is to change the base case from transpose([], []) to this:

```<code>transpose(Empty, []) :- maplist(=([]), Empty).
</code>```

This results in a predicate that will give the following results:

```<code>| ?- transpose(T, [[a,b,c],[d,e,f]]).

T = [[a,d],[b,e],[c,f]] ? a

no
| ?- transpose([[a,b,c],[d,e,f]], T).

T = [[a,d],[b,e],[c,f]] ? a

no
</code>```

Title: Transpose matrix in prolog

Body:
I want to transpose a matrix in prolog, so for example
[[1,2,3],[1,2,3],[1,2,3]] should become
[[1,1,1],[2,2,2],[3,3,3]]

Here is what I've done:

%transpose(M,T)
transpose([],[]).
transpose(M,[H|T]):-row(H,M,M1),transpose(M1,T).

%row(H, M, M1).
row([],[],[]).
row([H|Tt] , [[H|T1]|T] , [T1|Z]) :- row(Tt,T,Z).

Where M is to be transposed in T.
Row predicate (not sure for the difference between predicate and function) get the head of each sublist in M, so I can get the entire first row of the new, transposed matrix T.
I tested row separately, and it is giving the proper result. But when I try to transpose, I get only 'false' and nothing happens, no info for the new matrix T is printed.

Can anyone help me? Is the problem in the way I built the program? Or the result I expect is only true/false indeed and if so, how to get the new matrix? Thanks :)

Body:
Prolog only has predicates not functions. A predicate defines a relation, and generally isn't thought of as "doing something" as much as it is "defining something. Your row/3 actually defines a relationship between its 3 arguments.  The 3 arguments are related in that the elements of the 1st and 3rd lists are the heads and tails of the arguments of the 2nd list. I'll show 3 different queries that illustrate:

| ?- row([a,b,c], L, M).

L = [[a|A],[b|B],[c|C]]
M = [A,B,C]

yes
| ?- row(A, [[a,b,c],[d,e,f],[g,h,i]], L).

A = [a,d,g]
L = [[b,c],[e,f],[h,i]] ? ;

no
| ?- row(A, B, [[a,b],[c,d],[e,f]]).

A = [C,D,E]
B = [[C,a,b],[D,c,d],[E,e,f]] ? ;

no
| ?-

A function would not behave this way. Also you can see that, knowing the relationship, the name is a bit generic. row doesn't really adequately describe the relationship. Perhaps it could be called heads_and_tails/3, and maybe swap the 1st and 2nd argument.

The reason your transpose/2 predicate is failing is that it recurses down to a list of empty lists ([[], [], []] in the case of a matrix with 3 rows), but your transpose/2 base case is based upon [].

Let's look at substituting, as suggested in the comment, the base case of transpose([], []) with:

transpose([[] | _], []).

The following example queries result:

| ?- transpose([[a,b,c],[d,e,f]], T).

T = [[a,d],[b,e],[c,f]] ? ;

no
| ?- transpose([[a,b,c],[d,e,f], [a]], T).

no
| ?- transpose(T, [[a,b,c],[d,e,f]]).

T = [[a,d],[b,e|_],[c,f|_]] ? ;

no

So incorrect results occur for the second query. One approach to resolve this, following along the logic of this predicate, is to change the base case from transpose([], []) to this:

transpose(Empty, []) :- maplist(=([]), Empty).

This results in a predicate that will give the following results:

| ?- transpose(T, [[a,b,c],[d,e,f]]).

T = [[a,d],[b,e],[c,f]] ? a

no
| ?- transpose([[a,b,c],[d,e,f]], T).

T = [[a,d],[b,e],[c,f]] ? a

no


问:
Is there any shortcut for array size / length in C?
Is there any way to speed up getting an array size in C?

Typing out sizeof(array)/sizeof(int) every time gets old.  Do any C libraries have something like .length or is there some way I can define sizeof(array)/sizeof(int) as a shorter constant of some sort (possible also using dot notation)?

答:
You could always just write a macro to do it. Note that it won't work as a function, since you'd have to demote the array to a pointer to its first element, so it'd just return sizeof(int *) / sizeof(int).

```<code>#define INTSIZE(array) (sizeof(array) / (sizeof(int))
</code>```

Or, more generally...

```<code>#define SIZE(array, type) (sizeof(array) / (sizeof(type))
</code>```

Wow, downvotes. Okay, this will also work:

```<code>#define SIZE(array) (sizeof(array) / (sizeof((array)[0]))
</code>```

Body:
You could always just write a macro to do it. Note that it won't work as a function, since you'd have to demote the array to a pointer to its first element, so it'd just return sizeof(int *) / sizeof(int).

#define INTSIZE(array) (sizeof(array) / (sizeof(int))

Or, more generally...

#define SIZE(array, type) (sizeof(array) / (sizeof(type))

Wow, downvotes. Okay, this will also work:

#define SIZE(array) (sizeof(array) / (sizeof((array)[0]))


问:
Grafana - Updated all graphs on dashboard from metric selection
I have a prometheus node which collects job data from Jenkins and stores it e.g.:

```<code>jenkins_job_last_completed_build_queuing_duration_seconds{jobname="j1"} 0.01
jenkins_job_last_completed_build_timestamp_seconds{jobname="j1"} 1489006588.334
</code>```

etc.

In grafana I want ot have a dashboard with a bunch of graphs for the different metrics and some way of choosing which job to display on the graphs.

e.g.
I log onto the dashboard and select j1 somehow and all the graphs show the data for j1.
Then I change my selection to j2 and all the graphs update to show j2 data.

I know I can do this on a per graph basis by clicking in the legend, but I want to do them all at once.

Is this possible?

Cheers

答:
Yes!  You can make a template query in grafana that is populated with a label value.  Docs are here: http://docs.grafana.org/features/datasources/prometheus/#templated-queries

We do something similar to select a namespace in a dashboard to see the memory & CPU consumption of the services in that namespace.  Our dashboard looks like this:

And the queries look like:

namespace_name:container_cpu_usage_seconds_total:sum_rate{namespace=\"$namespace\"}

I don't know how to make the variable with the UI, I generate the config with our grafanalib project (https://github.com/weaveworks/grafanalib) and it looks like this:

"templating": {
    "list": [
      {
        "allValue": null,
        "current": {
          "tags": [],
          "text": "default",
          "value": "default"
        },
        "datasource": "Scope-as-a-Service Prometheus",
        "hide": 0,
        "includeAll": false,
        "label": "Namespace",
        "multi": false,
        "name": "namespace",
        "options": [],
        "query": "label_values(k8s_pod_status_ready, namespace)",
        "refresh": 1,
        "regex": "",
        "sort": 1,
        "tagValuesQuery": null,
        "tagsQuery": null,
        "type": "query"
      }
    ]
  },

Body:
I have a prometheus node which collects job data from Jenkins and stores it e.g.:

jenkins_job_last_completed_build_queuing_duration_seconds{jobname="j1"} 0.01
jenkins_job_last_completed_build_timestamp_seconds{jobname="j1"} 1489006588.334

etc.

In grafana I want ot have a dashboard with a bunch of graphs for the different metrics and some way of choosing which job to display on the graphs.

e.g.
I log onto the dashboard and select j1 somehow and all the graphs show the data for j1.
Then I change my selection to j2 and all the graphs update to show j2 data.

I know I can do this on a per graph basis by clicking in the legend, but I want to do them all at once.

Is this possible?

Cheers


答:
Flex makes this easy :

#frame div {
  background-color: brown;
  margin: 5px;
  flex: 1;
  padding:1em;
  color:silver
}

#frame {
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="frame">
  <div class="block">1</div>
  <div class="block">2</div>
  <div class="block">3</div>
  <div class="block">4</div>
</div></code>```

For a single row table does the job too for older browsers :

#frame div {
  background-color: brown;
  display:table-cell;
  padding:1em;
  color:silver
}

#frame {
  display: table;
  width:100%;
  border-spacing: 10px 0;;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="frame">
  <div class="block">1</div>
  <div class="block">2</div>
  <div class="block">3</div>
  <div class="block">4</div>
</div></code>```

or grid for latest browsers (where columns number is known:

#frame div {
  background-color: brown;
  padding: 1em;
  color: silver
}

#frame {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-column-gap: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="frame">
  <div class="block">1</div>
  <div class="block">2</div>
  <div class="block">3</div>
  <div class="block">4</div>
</div></code>```

Title: How to set right spacing between inline-block elements

Body:
Flex makes this easy :

#frame div {
  background-color: brown;
  margin: 5px;
  flex: 1;
  padding:1em;
  color:silver
}

#frame {
  display: flex;
}

<div id="frame">
  <div class="block">1</div>
  <div class="block">2</div>
  <div class="block">3</div>
  <div class="block">4</div>
</div>

For a single row table does the job too for older browsers :

#frame div {
  background-color: brown;
  display:table-cell;
  padding:1em;
  color:silver
}

#frame {
  display: table;
  width:100%;
  border-spacing: 10px 0;;
}

<div id="frame">
  <div class="block">1</div>
  <div class="block">2</div>
  <div class="block">3</div>
  <div class="block">4</div>
</div>

or grid for latest browsers (where columns number is known:

#frame div {
  background-color: brown;
  padding: 1em;
  color: silver
}

#frame {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-column-gap: 10px;
}

<div id="frame">
  <div class="block">1</div>
  <div class="block">2</div>
  <div class="block">3</div>
  <div class="block">4</div>
</div>


问:
Copy all values from fields in one class to another through reflection
I have a class which is basically a copy of another class.

```<code>public class A {
  int a;
  String b;
}

public class CopyA {
  int a;
  String b;
}
</code>```

What I am doing is putting values from class A into CopyA before sending CopyA through a webservice call. Now I would like to create a reflection-method that basically copies all fields that are identical (by name and type) from class A to class CopyA.

How can I do this?

This is what I have so far, but it doesn't quite work. I think the problem here is that I am trying to set a field on the field I am looping through.

```<code>private <T extends Object, Y extends Object> void copyFields(T from, Y too) {

    Class<? extends Object> fromClass = from.getClass();
    Field[] fromFields = fromClass.getDeclaredFields();

    Class<? extends Object> tooClass = too.getClass();
    Field[] tooFields = tooClass.getDeclaredFields();

    if (fromFields != null && tooFields != null) {
        for (Field tooF : tooFields) {
            logger.debug("toofield name #0 and type #1", tooF.getName(), tooF.getType().toString());
            try {
                // Check if that fields exists in the other method
                Field fromF = fromClass.getDeclaredField(tooF.getName());
                if (fromF.getType().equals(tooF.getType())) {
                    tooF.set(tooF, fromF);
                }
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
</code>```

I am sure there must be someone that has already done this somehow

答:
Spring has a built in BeanUtils.copyProperties method. But it doesn't work with classes without getters/setters. JSON serialization/deserialization can be another option for copying fields. Jackson can be used for this purpose. If you are using Spring In most cases Jackson is already in your dependency list.

ObjectMapper mapper     = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Clazz        copyObject = mapper.readValue(mapper.writeValueAsString(sourceObject), Clazz.class);
```

Body:
I have a class which is basically a copy of another class.

public class A {
  int a;
  String b;
}

public class CopyA {
  int a;
  String b;
}

What I am doing is putting values from class A into CopyA before sending CopyA through a webservice call. Now I would like to create a reflection-method that basically copies all fields that are identical (by name and type) from class A to class CopyA.

How can I do this?

This is what I have so far, but it doesn't quite work. I think the problem here is that I am trying to set a field on the field I am looping through.

private <T extends Object, Y extends Object> void copyFields(T from, Y too) {

    Class<? extends Object> fromClass = from.getClass();
    Field[] fromFields = fromClass.getDeclaredFields();

    Class<? extends Object> tooClass = too.getClass();
    Field[] tooFields = tooClass.getDeclaredFields();

    if (fromFields != null && tooFields != null) {
        for (Field tooF : tooFields) {
            logger.debug("toofield name #0 and type #1", tooF.getName(), tooF.getType().toString());
            try {
                // Check if that fields exists in the other method
                Field fromF = fromClass.getDeclaredField(tooF.getName());
                if (fromF.getType().equals(tooF.getType())) {
                    tooF.set(tooF, fromF);
                }
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

I am sure there must be someone that has already done this somehow


答:
If you don't want to use margin-top: or padding: or style the next set of HTML elements underneath your fixed header, you can add a blank div to achieve this.

```<code>.block {
    height: 100px; // customize
    width: 100%;
}
</code>```

Example. & Example.

Title: Fixed Position Div, displaying on top of following div

Body:
If you don't want to use margin-top: or padding: or style the next set of HTML elements underneath your fixed header, you can add a blank div to achieve this.

.block {
    height: 100px; // customize
    width: 100%;
}

Example. & Example.


问:
Why is the __str__ method printing the nodes in an recursive way in a linked list?
Just wondering what's the correct way of showing the next node in the __str__ method. See the following code and the results. It looks like there's some built-in recursive nature chaining the __str__ methods for each node in the list. Could anyone explain why and how I can make it behave normally, like only printing the next node's address. Thanks.

```<code>class Node(object):
    def __init__(self, x):
        self.val = x
        self.next = None
    def __str__(self):
        return "Node {}, next is {}".format(self.val, self.next)

a = Node(1)
b = Node(2)
c = Node(3)
a.next = b
b.next = c
print(a)
Node 1, next is Node 2, next is Node 3, next is None
</code>```

答:
Instead of printing self.next's str representation, try printing its repr instead:

```<code>    return "Node {}, next is {!r}".format(self.val, self.next)
</code>```

Result:

```<code>Node 1, next is <__main__.Node object at 0x7f9f10066630>
</code>```

Body:
Just wondering what's the correct way of showing the next node in the __str__ method. See the following code and the results. It looks like there's some built-in recursive nature chaining the __str__ methods for each node in the list. Could anyone explain why and how I can make it behave normally, like only printing the next node's address. Thanks.

class Node(object):
    def __init__(self, x):
        self.val = x
        self.next = None
    def __str__(self):
        return "Node {}, next is {}".format(self.val, self.next)

a = Node(1)
b = Node(2)
c = Node(3)
a.next = b
b.next = c
print(a)
Node 1, next is Node 2, next is Node 3, next is None

Body:
Instead of printing self.next's str representation, try printing its repr instead:

    return "Node {}, next is {!r}".format(self.val, self.next)

Result:

Node 1, next is <__main__.Node object at 0x7f9f10066630>


问:
Why we need Transient Fault Handling for storage?
I saw some thread said storage library already have retry policy,
So why should us use this :Transient Fault Handling block

Can any one show me some samples about how to use this Transient Fault handling block for myy blob and Table storage properly?
thanks!

答: For tables and blobs you do not need to use any external transient retry blocks afaik. The ones that are implemented within the sdk are fairly robust. If you think you should implement a special retry policy the way to do that is to implement your own retry policy inheriting from Azure Storage IRetryPolicy interface and pass that on to your storage requests as part of the TableRequestOptions.RetryPolicy property.


问:
JSON Array in Newtonsoft using C#
I am pretty new to using JSON and Newtonsoft together and I am trying to replicate this format without success using JArray(). Does anyone have any ideas on how this can be accomplished?</p>

```<code>   "attrList":[
      {
         "name":"Attendee Status",
         "val":"Accepted"
      },
      {
         "name":"Attendee Type",
         "val":"Attendee"
      }
   ]
</code>```

答:
```<code>public class Parent
{
    public List<Attribute> attrList{ get; set; }
}

public class Attribute
{
    public string name{ get; set; }
    public string val{ get; set; }
}

var parsedParent = JsonConvert.DeserializeObject<Parent>(
   "{ 'attrList':[ { 'name':'Attendee Status', 'val':'Accepted' }, { 'name':'Attendee Type', 'val':'Attendee' } ] }"
);
</code>```

Title: JSON Array in Newtonsoft using C#

Body:
I am pretty new to using JSON and Newtonsoft together and I am trying to replicate this format without success using JArray(). Does anyone have any ideas on how this can be accomplished?

   "attrList":[
      {
         "name":"Attendee Status",
         "val":"Accepted"
      },
      {
         "name":"Attendee Type",
         "val":"Attendee"
      }
   ]


问:
"abline" doesn't work after "plot" when inside "with"
I want to create a scatterplot and draw the regression line for a subset of a dataset. To give a reproducible example I'll use the CO2 dataset.

I tried this but the regression line doesn't appear for some reason

```<code>with(subset(CO2,Type=="Quebec"),plot(conc,uptake),abline(lm(uptake~conc)))
</code>```

What is the correct way to give a command like this? Can I do it with a one-liner?

答:
You need to provide both your lines of code as a single R expression. The abline() is being taken as a subsequent argument to with(), which is the ... argument. This is documented a a means to pass arguments on to future methods, but the end result is that it is effectively a black hole for this part of your code.

Two options, i) keep one line but wrap the expression in { and } and separate the two expressions with ;:

```<code>with(subset(CO2,Type=="Quebec"), {plot(conc,uptake); abline(lm(uptake~conc))})
</code>```

Or spread the expression out over two lines, still wrapped in { and }:

```<code>with(subset(CO2,Type=="Quebec"),
     {plot(conc,uptake)
      abline(lm(uptake~conc))})
</code>```

Edit: To be honest, if you are doing things like this you are missing out on the advantages of doing the subsetting via R's model formulae. I would have done this as follows:

```<code>plot(uptake ~ conc, data = CO2, subset = Type == "Quebec")
abline(lm(uptake ~ conc, data = CO2, subset = Type == "Quebec"), col = "red")
</code>```

The with() is just causing you to obfuscate your code with braces and ;.

Body:
I want to create a scatterplot and draw the regression line for a subset of a dataset. To give a reproducible example I'll use the CO2 dataset.

I tried this but the regression line doesn't appear for some reason

with(subset(CO2,Type=="Quebec"),plot(conc,uptake),abline(lm(uptake~conc)))

What is the correct way to give a command like this? Can I do it with a one-liner?

Body:
You need to provide both your lines of code as a single R expression. The abline() is being taken as a subsequent argument to with(), which is the ... argument. This is documented a a means to pass arguments on to future methods, but the end result is that it is effectively a black hole for this part of your code.

Two options, i) keep one line but wrap the expression in { and } and separate the two expressions with ;:

with(subset(CO2,Type=="Quebec"), {plot(conc,uptake); abline(lm(uptake~conc))})

Or spread the expression out over two lines, still wrapped in { and }:

with(subset(CO2,Type=="Quebec"),
     {plot(conc,uptake)
      abline(lm(uptake~conc))})

Edit: To be honest, if you are doing things like this you are missing out on the advantages of doing the subsetting via R's model formulae. I would have done this as follows:

plot(uptake ~ conc, data = CO2, subset = Type == "Quebec")
abline(lm(uptake ~ conc, data = CO2, subset = Type == "Quebec"), col = "red")

The with() is just causing you to obfuscate your code with braces and ;.


问:
sp_executesql Cross Server Insert return Scope_Identity()
I have found answers to my question, they all state that the below syntax should work. It does not work for me. My output variable is always NULL so any help would be appreciated.

```<code>DECLARE @SqlCommand NVARCHAR(1000),
              @ParamDefinition nvarchar(500),
              @Id INT

SET @SqlCommand = N'INSERT INTO [server].db.dbo.table(Title) VALUES(''Insert Into table From othertable Test'')  SELECT @Id = SCOPE_IDENTITY()'
SET @ParamDefinition = N'@Id integer OUTPUT'

EXECUTE sp_executesql @SqlCommand, @ParamDefinition, @Id OUTPUT

Select @Id
</code>```

My Select @Id returns NULL every time, but the row is inserted into the table.

I found four or five results on Stack Overflow that state my code should work and should return the ID. But it does not.

I am working on a third party server, is there a chance that an error is being thrown that I am not seeing.

Thanks for any help.

Note: The statement below returns the value of the Scope_Identity(). Problem is I have no idea how to catch that value in a variable.

```<code>EXEC [Server].[db].[dbo].sp_executesql N'
     INSERT INTO [server].db.dbo.table(Title) VALUES(''Test Title Insert'')
     SELECT SCOPE_IDENTITY()'
</code>```

I have tried the syntax below with no luck

```<code>DECLARE @Id INT

EXEC @Id = [Server].[db].[dbo].sp_executesql N'
     INSERT INTO [server].db.dbo.table(Title) VALUES(''Test Title Insert'')
     SELECT SCOPE_IDENTITY()'
</code>```

Select @Id - @Id Is always NULL.

答:
Your parameter definition in the first snippet should use int rather than integer.

In addition, you could try using the OUTPUT keyword as explained in this question.

Body:
I have found answers to my question, they all state that the below syntax should work. It does not work for me. My output variable is always NULL so any help would be appreciated.

DECLARE @SqlCommand NVARCHAR(1000),
              @ParamDefinition nvarchar(500),
              @Id INT

SET @SqlCommand = N'INSERT INTO [server].db.dbo.table(Title) VALUES(''Insert Into table From othertable Test'')  SELECT @Id = SCOPE_IDENTITY()'
SET @ParamDefinition = N'@Id integer OUTPUT'

EXECUTE sp_executesql @SqlCommand, @ParamDefinition, @Id OUTPUT

Select @Id

My Select @Id returns NULL every time, but the row is inserted into the table.

I found four or five results on Stack Overflow that state my code should work and should return the ID. But it does not.

I am working on a third party server, is there a chance that an error is being thrown that I am not seeing.

Thanks for any help.

Note: The statement below returns the value of the Scope_Identity(). Problem is I have no idea how to catch that value in a variable.

EXEC [Server].[db].[dbo].sp_executesql N'
     INSERT INTO [server].db.dbo.table(Title) VALUES(''Test Title Insert'')
     SELECT SCOPE_IDENTITY()'

I have tried the syntax below with no luck

DECLARE @Id INT

EXEC @Id = [Server].[db].[dbo].sp_executesql N'
     INSERT INTO [server].db.dbo.table(Title) VALUES(''Test Title Insert'')
     SELECT SCOPE_IDENTITY()'

Select @Id - @Id Is always NULL.


问:
How to shift iframe towards right side?
I'm currently working on the feature in which whenever a user hovers over a link, instant preview is shown below the link. Like this -

What I wanted to do is, whenever a user hovers over a link, iframe should shift towards right, just like in Google Instant preview.

```<code><div class="title" (mouseover)="overTitle()" (mouseleave)="overTitle()">
                    <a href="{{item.link}}">{{item.title}}</a>
                    <div class="box">
                        <iframe width="400px" height="400px" [src]="myUrlList[i]"></iframe>
                    </div>
                </div>
</code>```

CSS file -

```<code> .box {
      display: none;
      width: 100%;
    }

    a:hover + .box, .box:hover{
      display:block;
      position: absolute;
      z-index:100;
    }
</code>```

I tried using align="right" in div tag, but nothing happens. Also in .box class in CSS, I tried using float: right;, but nothing happens. It will be very much helpful if someone can help me. :)

答:
Check something like that, without JS, pure CSS.
https://jsfiddle.net/fxdhcrxj/2/

I just use opacity and visibilityto animate fade in and out, you can use any other methods, like JS fade In out etc.

In CSS if you want catch next element use ~

CSS:

```<code>.title{
    // for proper position absolute element inside
    position: relative;
}

// We catch nexy element .box, and when some one hover over box
.title a:hover ~.box, .title .box:hover{
    //display: inline;
  visibility: visible;
  opacity: 1;
}
// As i use element to bottom 0, I must translated it 100% below of his height.
.title .box{
    //display: none;
  visibility: hidden;
  opacity: 0;
  transition: visibility 0.2s ease-in-out, opacity 0.2s ease-in-out;
  position: absolute;
  z-index: 10;
  background: #fff;
  bottom:0;
  left:0;
  transform: translateY(100%);
}
</code>```

HTML:

```<code><div class="title" >
    <a href="#">TITL0E</a>
    <div class="box">
        <iframe width="400px" height="400px" src="https://www.w3schools.com"></iframe>
    </div>
</div>
</code>```

Important Note:

If you want put lot of Iframes, on page use Lazy load on them.
Simply just replace src attr when someone hover over title or use scripts e.g
http://dinbror.dk/blog/blazy/ otherwise your page will load really slow and make lot of freezes etc.

For better mobile support you may also use focus on element, not only hover

Title: How to shift iframe towards right side?

Body:
I'm currently working on the feature in which whenever a user hovers over a link, instant preview is shown below the link. Like this -

What I wanted to do is, whenever a user hovers over a link, iframe should shift towards right, just like in Google Instant preview.

                    {{item.title}}

CSS file -

 .box {
      display: none;
      width: 100%;
    }

    a:hover + .box, .box:hover{
      display:block;
      position: absolute;
      z-index:100;
    }

I tried using align="right" in div tag, but nothing happens. Also in .box class in CSS, I tried using float: right;, but nothing happens. It will be very much helpful if someone can help me. :)

Body:
Check something like that, without JS, pure CSS.
https://jsfiddle.net/fxdhcrxj/2/

I just use opacity and visibilityto animate fade in and out, you can use any other methods, like JS fade In out etc.

In CSS if you want catch next element use ~

CSS:

.title{
    // for proper position absolute element inside
    position: relative;
}

// We catch nexy element .box, and when some one hover over box
.title a:hover ~.box, .title .box:hover{
    //display: inline;
  visibility: visible;
  opacity: 1;
}
// As i use element to bottom 0, I must translated it 100% below of his height.
.title .box{
    //display: none;
  visibility: hidden;
  opacity: 0;
  transition: visibility 0.2s ease-in-out, opacity 0.2s ease-in-out;
  position: absolute;
  z-index: 10;
  background: #fff;
  bottom:0;
  left:0;
  transform: translateY(100%);
}

HTML:

<div class="title" >
    <a href="#">TITL0E</a>
    <div class="box">
        <iframe width="400px" height="400px" src="https://www.w3schools.com"></iframe>
    </div>
</div>

Important Note:

If you want put lot of Iframes, on page use Lazy load on them.
Simply just replace src attr when someone hover over title or use scripts e.g
http://dinbror.dk/blog/blazy/ otherwise your page will load really slow and make lot of freezes etc.

For better mobile support you may also use focus on element, not only hover


问:
Normalize data frame by levels
Good evening,

I am still new to R, so sorry in advance if this question seems obvious to you.
I am currently working on a drug screening protocol and I created .csv table in Excel with the output of my analysis. I imported it as data frame as raw.data into R with the following structure:

```<code>| Sample        | Group | Parameter Drug 1 | Parameter Drug 2 | Time Parameter Drug 1 (ms) |
|---------------|-------|------------------|------------------|----------------------------|
| Heart_Sample1 | Heart | 2.4              | 9.0              | 1.5                        |
| Heart_Sample1 | Heart | 2.29             | 22.2             | 3.4                        |
| Heart_Sample1 | Heart | 3.4              | 3.5              | 4.5                        |
| Heart_Sample1 | Heart | 5.2              | 8.4              | 6.5                        |
| Heart_Sample1 | Heart | 2.3              | 34.1             | 7.8                        |
| ...           | Organ | value            | value            | time                       |
| Heart_Sample2 | Heart | 10.4             | 10.2             | 1.5                        |
| Heart_Sample2 | Heart | 8.4              | 2.45             | 3.6                        |
| ...           | Organ | value            | value            | time                       |
| Liver_Sample1 | Liver | 13.4             | 44.5             | 2.8                        |
| ...           | Organ | 2.3              | value            | time                       |
</code>```

Parameter indicates the value of a certain parameter I am experimentally measuring (e.g. neuronal spikes). Time of Parameter indicates the time of the recording at which the spikes occur.

I transformed raw.data into mod.data with gather with the following formula:

```<code>  mod.data <- gather(raw.data, `Parameter Drug 1`, `Parameter Drug 2`, `Parameter Drug 3`, key = "Drug", value = "value")

| Sample        | Group | Time Parameter Drug 1 (ms) | Drug            | value |
|---------------|-------|----------------------------|-----------------|-------|
| Heart_Sample1 | Heart |                            | Baseline        |       |
| Heart_Sample1 | Heart |                            | Baseline        |       |
| Heart_Sample1 | Heart |                            | Concentration 1 |       |
| Heart_Sample1 | Heart |                            | Concentration 1 |       |
| Heart_Sample1 | Heart |                            | Concentration 2 |       |
</code>```

Then I generated the plots, separated by Sample and , in order to have a clear overview of what is happening to the parameter, over time, in all the samples. The results is a huge plot array, with ~200 plots.

Since different organs have different values, and also within the same organ I can find very different values, the scales have to be matched within each Sample to clearly understand what is going in the sample.

I then tried to normalize with the following function:

```<code>    normalize <- function(x){
  (x - min(x))/(max(x)-min(x))
  }
</code>```

Where x is my parameter of interest. Unfortunately, it takes as min and max the respective min and max of the whole Parameter, regardless of the Sample and the Group. I also try to subset, but it would mean to create a single subset for each Sample and then merge them together in a figure. I also try with group_by(Sample, Group), as described in the RStudio cheatsheet, but I was not able to apply the normalize function to the generated data frame.

tl;dr My question is: how can I normalize, from 0 to 1, within each Sample, my values?

Thank you in advance for the answers.

Regards

Title: Normalize data frame by levels

Body:
Good evening,

I am still new to R, so sorry in advance if this question seems obvious to you.
I am currently working on a drug screening protocol and I created .csv table in Excel with the output of my analysis. I imported it as data frame as raw.data into R with the following structure:

| Sample        | Group | Parameter Drug 1 | Parameter Drug 2 | Time Parameter Drug 1 (ms) |
|---------------|-------|------------------|------------------|----------------------------|
| Heart_Sample1 | Heart | 2.4              | 9.0              | 1.5                        |
| Heart_Sample1 | Heart | 2.29             | 22.2             | 3.4                        |
| Heart_Sample1 | Heart | 3.4              | 3.5              | 4.5                        |
| Heart_Sample1 | Heart | 5.2              | 8.4              | 6.5                        |
| Heart_Sample1 | Heart | 2.3              | 34.1             | 7.8                        |
| ...           | Organ | value            | value            | time                       |
| Heart_Sample2 | Heart | 10.4             | 10.2             | 1.5                        |
| Heart_Sample2 | Heart | 8.4              | 2.45             | 3.6                        |
| ...           | Organ | value            | value            | time                       |
| Liver_Sample1 | Liver | 13.4             | 44.5             | 2.8                        |
| ...           | Organ | 2.3              | value            | time                       |

Parameter indicates the value of a certain parameter I am experimentally measuring (e.g. neuronal spikes). Time of Parameter indicates the time of the recording at which the spikes occur.

I transformed raw.data into mod.data with gather with the following formula:

  mod.data <- gather(raw.data, `Parameter Drug 1`, `Parameter Drug 2`, `Parameter Drug 3`, key = "Drug", value = "value")

| Sample        | Group | Time Parameter Drug 1 (ms) | Drug            | value |
|---------------|-------|----------------------------|-----------------|-------|
| Heart_Sample1 | Heart |                            | Baseline        |       |
| Heart_Sample1 | Heart |                            | Baseline        |       |
| Heart_Sample1 | Heart |                            | Concentration 1 |       |
| Heart_Sample1 | Heart |                            | Concentration 1 |       |
| Heart_Sample1 | Heart |                            | Concentration 2 |       |

Then I generated the plots, separated by Sample and , in order to have a clear overview of what is happening to the parameter, over time, in all the samples. The results is a huge plot array, with ~200 plots.

Since different organs have different values, and also within the same organ I can find very different values, the scales have to be matched within each Sample to clearly understand what is going in the sample.

I then tried to normalize with the following function:

    normalize <- function(x){
  (x - min(x))/(max(x)-min(x))
  }

Where x is my parameter of interest. Unfortunately, it takes as min and max the respective min and max of the whole Parameter, regardless of the Sample and the Group. I also try to subset, but it would mean to create a single subset for each Sample and then merge them together in a figure. I also try with group_by(Sample, Group), as described in the RStudio cheatsheet, but I was not able to apply the normalize function to the generated data frame.

tl;dr My question is: how can I normalize, from 0 to 1, within each Sample, my values?

Thank you in advance for the answers.

Regards

Body:
Here's another approach using dplyr and your normalize function. I had no issues applying it to the toy data I created.

library(dplyr)

set.seed(123)

df <- data.frame(Sample = sample(c("Sample1", "Sample2"), 20, replace = T),
                 Group = sample(c("Heart", "Liver"), 20, replace = T),
                 Time = sample(100:500, 20),
                 Value = sample(1000:5000, 20))

normalize <- function(x){
  (x - min(x))/(max(x)-min(x))
}

df %>%
  group_by(Sample, Group) %>%
  mutate(Time_std = normalize(Time),
         Value_std = normalize(Value)) %>%
  arrange(Sample, Group, Time_std)

  #  Sample  Group  Time Value   Time_std  Value_std
  # Sample1  Heart   317  2895 0.00000000 0.47500000
  # Sample1  Heart   389  3441 0.57600000 1.00000000
  # Sample1  Heart   436  2755 0.95200000 0.34038462
  # Sample1  Heart   442  2401 1.00000000 0.00000000
  # Sample1  Liver   149  2513 0.00000000 0.00000000
  # Sample1  Liver   154  2792 0.01428571 0.24303136
  # Sample1  Liver   157  3661 0.02285714 1.00000000
  # Sample1  Liver   272  3510 0.35142857 0.86846690
  # Sample1  Liver   499  2535 1.00000000 0.01916376
  # Sample2  Heart   179  1877 0.00000000 0.15939905
  # Sample2  Heart   204  4171 0.39062500 1.00000000
  # Sample2  Heart   243  1442 1.00000000 0.00000000
  # Sample2  Liver   117  4011 0.00000000 0.92470805
  # Sample2  Liver   147  1002 0.10238908 0.00000000
  # Sample2  Liver   160  4256 0.14675768 1.00000000
  # Sample2  Liver   192  4236 0.25597270 0.99385372
  # Sample2  Liver   246  2096 0.44027304 0.33620160
  # Sample2  Liver   265  1379 0.50511945 0.11585741
  # Sample2  Liver   283  4244 0.56655290 0.99631223
  # Sample2  Liver   410  3832 1.00000000 0.86969883