问:
libusb can't claim device
I'm trying to using the libusb-1.0 and QtUsb library for USB Device access. Its simple a bulk-device thats works before I did make a few updates.
Currently I use

```<code>Linux nadhh.fritz.box 4.11.8-200.fc25.x86_64 #1 SMP Thu Jun 29 16:13:56 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
</code>```

It doesn't matter if I run as user or root because the device will be set to group users and permission 666 by udev

```<code>[timestamp] [threadID] facility level [function call] <message>
--------------------------------------------------------------------------------
[ 0.012281] [00000fc6] libusb: error [op_get_configuration] device unconfigured
Type:1, cat:default, file:../src/qlibusb.cpp, line:114, f:virtual qint32 QUsbDevice::open(), msg:Cannot Claim Interface
Type:1, cat:default, file:../src/qlibusb.cpp, line:168, f:void QUsbDevice::printUsbError(int), msg:libusb Error: Entity not found
[ 0.951403] [00000fc6] libusb: warning [libusb_exit] application left some devices open
</code>```

It doesn't matter if I run as user or root because the device will be set to group users and permission 666 by udev
Any hints are welcome

Sincerely Jürgen

The Code

Taken from

QtUsb

A Cross-platform USB Library for Qt.
Relies on libusb-1.0.

Features

Bulk transfer

Device insertion/removal detection

Device search

TODO

Interrupt transfer

isochronous transfer

Usage

Documentation is not complete yet, you can have a look at the examples in the meanwhile.

Documentation

Doxygen documentation can be found here: http://fpoussin.github.io/doxygen/qtusb/

Downloads

Ubuntu PPA: https://launchpad.net/~fpoussin/+archive/ubuntu/ppa
Windows libraries are coming soon.

header

```<code>    #ifndef USBEXAMPLE_H
    #define USBEXAMPLE_H

    #include <QObject>
    #include <QUsb>

    const quint8 USB_PIPE_IN = 0x81;   /* Bulk output endpoint for responses */
    const quint8 USB_PIPE_OUT = 0x01;      /* Bulk input endpoint for commands */
    const quint16 USB_TIMEOUT_MSEC = 300;

    const quint16 vendor_id = 0x04e3;
    const quint16 product_id= 0x0001;

    class UsbExample : public QObject
    {
        Q_OBJECT
    public:
        explicit UsbExample(QObject *parent = 0);
        ~UsbExample(void);
        void setupDevice(void);
        bool openDevice(void);
        bool closeDevice(void);
        void read(QByteArray *buf);
        void write(QByteArray *buf);

    signals:

    public slots:

    private:
        QUsbManager mUsbManager;
        QUsbDevice* mUsbDev;

        QtUsb::DeviceFilter mFilter;
        QtUsb::DeviceConfig mConfig;
    };

    #endif // USBEXAMPLE_H
</code>```

cpp

```<code>    #include <iostream>
    #include "usbexample.h"

    using namespace std;

    #ifdef interface
    #undef interface
    #endif

    UsbExample::UsbExample(QObject *parent) : QObject(parent) {
      this->setupDevice();

      QByteArray send, recv;

      send.append(".[]=R00[]=R01[]=R02$");

      if (this->openDevice()) {
        cerr << "Device open!" << endl;
        this->write(&send);
        this->read(&recv);
      }
    }

    UsbExample::~UsbExample() { delete mUsbDev; }

    void UsbExample::setupDevice() {
      /* There are 2 ways of identifying devices depending on the platform.
       * You can use both methods, only one will be taken into account.
       */

      mUsbDev = new QUsbDevice();
      mUsbDev->setDebug(true);

    #if 1
      // Bus 003 Device 004: ID 04e3:0001 Zilog, Inc.
      mFilter.pid = 0x0001;
      mFilter.vid = 0x04E3;
    #else
      mFilter.vid = 0x0c4b;
      mFilter.pid = 0x0400;
    #endif

      //
      mConfig.alternate = 0;
      mConfig.config = 0;
      mConfig.interface = 0;
      mConfig.readEp = 0x81;
      mConfig.writeEp = 0x02;
    }

    bool UsbExample::openDevice() {
      cerr << "Opening" << endl;

      QtUsb::DeviceStatus ds;

      ds = mUsbManager.openDevice(mUsbDev, mFilter, mConfig);

      if (ds == QtUsb::deviceOK) {
        // Device is open
        return true;
      }
      return false;
    }

    bool UsbExample::closeDevice() {
      cerr << "Closing" << endl;
      mUsbManager.closeDevice(mUsbDev);
      return false;
    }

    void UsbExample::read(QByteArray *buf) { mUsbDev->read(buf, 1); }

    void UsbExample::write(QByteArray *buf) { mUsbDev->write(buf, buf->size()); }

    #include "usbexample.h"
    #include <QCoreApplication>
    #include <QTimer>
    #include <iostream>

    void customLogHandler(QtMsgType type, const QMessageLogContext& context,
                          const QString& msg)
    {
       // send the data to log file via the other thread
       // emit writeToFile(type, context, msg);

       // now output to debugger console
    #ifdef Q_OS_WIN
        OutputDebugString(text.toStdWString().c_str());
    #else
        std::cerr << "Type:" << type << ", cat:" << context.category << ", file:" << context.file
                      << ", line:" << context.line
                      << ", f:" << context.function << ", msg:" << msg.toStdString() << std::endl;
    #endif
    }

    int main(int argc, char *argv[]) {
        qInstallMessageHandler(&customLogHandler);
      QCoreApplication a(argc, argv);
      QTimer timer;

      QObject::connect(&timer, SIGNAL(timeout()), &a, SLOT(quit()));

      timer.setInterval(1000);
      timer.setSingleShot(true);
      timer.start();

      UsbExample example;

      return a.exec();
    }
</code>```

答:
this is a problem with the configuration. in USB you have to obey the hierarchy

device descriptor - configuration descriptor - interface descriptor - endpoint descriptor

( http://www.beyondlogic.org/usbnutshell/usb1.shtml )

if there is an error on configuration level all other levels also fail

very likely the error is in this code :

```<code>  mConfig.alternate = 0;
  mConfig.config = 0;
  mConfig.interface = 0;
  mConfig.readEp = 0x81;
  mConfig.writeEp = 0x02;
</code>```

the problem is that i do not know the structure of the USB tree of your device so you have to do this. you can get the structure by lsusb -v or usb-devices and search your device for the structural ordering 'device - configuration - interface - endpoint'

if you have the information you have to modify the above code (i.e. changing interface index, alternate setting ,...)

the critical part of the source code is

```<code>int conf;
  libusb_get_configuration(mDevHandle, &conf);

  if (conf != mConfig.config) {
    if (mDebug) qDebug("Configuration needs to be changed");
    rc = libusb_set_configuration(mDevHandle, mConfig.config);
    if (rc != 0) {
      qWarning("Cannot Set Configuration");
      this->printUsbError(rc);
      return -3;
    }
  }
  rc = libusb_claim_interface(mDevHandle, mConfig.interface);
  if (rc != 0) {
    qWarning("Cannot Claim Interface");
    this->printUsbError(rc);
    return -4;
}
</code>```

source: https://github.com/fpoussin/QtUsb/blob/master/src/qlibusb.cpp

this is where the 'Cannot Claim Interface' error message comes from because there is a problem with setting the accurate configuration. as said try lsusb -v or usb-devices to get the correct information ...

Title: libusb can't claim device

Body:
I'm trying to using the libusb-1.0 and QtUsb library for USB Device access. Its simple a bulk-device thats works before I did make a few updates.
Currently I use

Linux nadhh.fritz.box 4.11.8-200.fc25.x86_64 #1 SMP Thu Jun 29 16:13:56 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

It doesn't matter if I run as user or root because the device will be set to group users and permission 666 by udev

[timestamp] [threadID] facility level [function call] <message>
--------------------------------------------------------------------------------
[ 0.012281] [00000fc6] libusb: error [op_get_configuration] device unconfigured
Type:1, cat:default, file:../src/qlibusb.cpp, line:114, f:virtual qint32 QUsbDevice::open(), msg:Cannot Claim Interface
Type:1, cat:default, file:../src/qlibusb.cpp, line:168, f:void QUsbDevice::printUsbError(int), msg:libusb Error: Entity not found
[ 0.951403] [00000fc6] libusb: warning [libusb_exit] application left some devices open

It doesn't matter if I run as user or root because the device will be set to group users and permission 666 by udev
Any hints are welcome

Sincerely Jürgen

The Code

Taken from

QtUsb

A Cross-platform USB Library for Qt.
Relies on libusb-1.0.

Features

Bulk transfer

Device insertion/removal detection

Device search

TODO

Interrupt transfer

isochronous transfer

Usage

Documentation is not complete yet, you can have a look at the examples in the meanwhile.

Documentation

Doxygen documentation can be found here: http://fpoussin.github.io/doxygen/qtusb/

Downloads

Ubuntu PPA: https://launchpad.net/~fpoussin/+archive/ubuntu/ppa
Windows libraries are coming soon.

header

    #ifndef USBEXAMPLE_H
    #define USBEXAMPLE_H

    #include <QObject>
    #include <QUsb>

    const quint8 USB_PIPE_IN = 0x81;   /* Bulk output endpoint for responses */
    const quint8 USB_PIPE_OUT = 0x01;      /* Bulk input endpoint for commands */
    const quint16 USB_TIMEOUT_MSEC = 300;

    const quint16 vendor_id = 0x04e3;
    const quint16 product_id= 0x0001;

    class UsbExample : public QObject
    {
        Q_OBJECT
    public:
        explicit UsbExample(QObject *parent = 0);
        ~UsbExample(void);
        void setupDevice(void);
        bool openDevice(void);
        bool closeDevice(void);
        void read(QByteArray *buf);
        void write(QByteArray *buf);

    signals:

    public slots:

    private:
        QUsbManager mUsbManager;
        QUsbDevice* mUsbDev;

        QtUsb::DeviceFilter mFilter;
        QtUsb::DeviceConfig mConfig;
    };

    #endif // USBEXAMPLE_H

cpp

    #include <iostream>
    #include "usbexample.h"

    using namespace std;

    #ifdef interface
    #undef interface
    #endif

    UsbExample::UsbExample(QObject *parent) : QObject(parent) {
      this->setupDevice();

      QByteArray send, recv;

      send.append(".[]=R00[]=R01[]=R02$");

      if (this->openDevice()) {
        cerr << "Device open!" << endl;
        this->write(&send);
        this->read(&recv);
      }
    }

    UsbExample::~UsbExample() { delete mUsbDev; }

    void UsbExample::setupDevice() {
      /* There are 2 ways of identifying devices depending on the platform.
       * You can use both methods, only one will be taken into account.
       */

      mUsbDev = new QUsbDevice();
      mUsbDev->setDebug(true);

    #if 1
      // Bus 003 Device 004: ID 04e3:0001 Zilog, Inc.
      mFilter.pid = 0x0001;
      mFilter.vid = 0x04E3;
    #else
      mFilter.vid = 0x0c4b;
      mFilter.pid = 0x0400;
    #endif

      //
      mConfig.alternate = 0;
      mConfig.config = 0;
      mConfig.interface = 0;
      mConfig.readEp = 0x81;
      mConfig.writeEp = 0x02;
    }

    bool UsbExample::openDevice() {
      cerr << "Opening" << endl;

      QtUsb::DeviceStatus ds;

      ds = mUsbManager.openDevice(mUsbDev, mFilter, mConfig);

      if (ds == QtUsb::deviceOK) {
        // Device is open
        return true;
      }
      return false;
    }

    bool UsbExample::closeDevice() {
      cerr << "Closing" << endl;
      mUsbManager.closeDevice(mUsbDev);
      return false;
    }

    void UsbExample::read(QByteArray *buf) { mUsbDev->read(buf, 1); }

    void UsbExample::write(QByteArray *buf) { mUsbDev->write(buf, buf->size()); }

    #include "usbexample.h"
    #include <QCoreApplication>
    #include <QTimer>
    #include <iostream>

    void customLogHandler(QtMsgType type, const QMessageLogContext& context,
                          const QString& msg)
    {
       // send the data to log file via the other thread
       // emit writeToFile(type, context, msg);

       // now output to debugger console
    #ifdef Q_OS_WIN
        OutputDebugString(text.toStdWString().c_str());
    #else
        std::cerr << "Type:" << type << ", cat:" << context.category << ", file:" << context.file
                      << ", line:" << context.line
                      << ", f:" << context.function << ", msg:" << msg.toStdString() << std::endl;
    #endif
    }

    int main(int argc, char *argv[]) {
        qInstallMessageHandler(&customLogHandler);
      QCoreApplication a(argc, argv);
      QTimer timer;

      QObject::connect(&timer, SIGNAL(timeout()), &a, SLOT(quit()));

      timer.setInterval(1000);
      timer.setSingleShot(true);
      timer.start();

      UsbExample example;

      return a.exec();
    }

Body:
this is a problem with the configuration. in USB you have to obey the hierarchy

device descriptor - configuration descriptor - interface descriptor - endpoint descriptor

( http://www.beyondlogic.org/usbnutshell/usb1.shtml )

if there is an error on configuration level all other levels also fail

very likely the error is in this code :

  mConfig.alternate = 0;
  mConfig.config = 0;
  mConfig.interface = 0;
  mConfig.readEp = 0x81;
  mConfig.writeEp = 0x02;

the problem is that i do not know the structure of the USB tree of your device so you have to do this. you can get the structure by lsusb -v or usb-devices and search your device for the structural ordering 'device - configuration - interface - endpoint'

if you have the information you have to modify the above code (i.e. changing interface index, alternate setting ,...)

the critical part of the source code is

int conf;
  libusb_get_configuration(mDevHandle, &conf);

  if (conf != mConfig.config) {
    if (mDebug) qDebug("Configuration needs to be changed");
    rc = libusb_set_configuration(mDevHandle, mConfig.config);
    if (rc != 0) {
      qWarning("Cannot Set Configuration");
      this->printUsbError(rc);
      return -3;
    }
  }
  rc = libusb_claim_interface(mDevHandle, mConfig.interface);
  if (rc != 0) {
    qWarning("Cannot Claim Interface");
    this->printUsbError(rc);
    return -4;
}

source: https://github.com/fpoussin/QtUsb/blob/master/src/qlibusb.cpp

this is where the 'Cannot Claim Interface' error message comes from because there is a problem with setting the accurate configuration. as said try lsusb -v or usb-devices to get the correct information ...


来源: stackexchange

问:
Tkinter Canvas Collision Detection?
I'm currently trying to make a self-scrolling adventure game, where you have to kill enemies. But for killing them, I need to know how to do collision detection. Most things I found online didn't work, my own attempts neither.
(I'm not gonna use Pygame)

Thanks for you help in advance.

答:
Thank you all for your help, but I've found an answer myself:</p>

```<code>a = canvas.bbox(object)
b = canvas.bbox(object2)
if b[0] in range(a[0],a[2]) or b[2] in range(a[0],a[2]) and b[1] in range(a[1],a[3]) or b[3] in range(a[1],a[3]):
    pass #collision
</code>```

ContentLicense: CC BY-SA 3.0

Title: Tkinter Canvas Collision Detection?

Body:
Thank you all for your help, but I've found an answer myself:

a = canvas.bbox(object)
b = canvas.bbox(object2)
if b[0] in range(a[0],a[2]) or b[2] in range(a[0],a[2]) and b[1] in range(a[1],a[3]) or b[3] in range(a[1],a[3]):
    pass #collision


问:
Chat client in iPhone App
If I create an application for iPhone, how can I get notified of chat messages I receive? Does receiving messages from the server happens through Push notification or Application has to poll to server in a regular time interval.

I guess that for each time a new message comes the server would send a notification to the app, and once the app receives the notification, the app pulls the message from the server.

Is my understanding correct?

答:
look up XMPP protocol/servers :) therein lies your answer.

Theres a iPhone framework called XMPPFramework which will help.

ContentLicense: CC BY-SA 2.5

Title: Chat client in iPhone App


问:
ImportError: No module named http in odoo
error in odoo 10 when i try to write  basic controller for web

```<code>from odoo import http
</code>```

show error

```<code>2017-07-09 13:20:10,128 9183 ERROR ? werkzeug: Error on request:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 177, in run_wsgi
    execute(self.server.app)
  File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 165, in execute
    application_iter = app(environ, start_response)
  File "/odoo/odoo-server/odoo/service/server.py", line 250, in app
    return self.app(e, s)
  File "/odoo/odoo-server/odoo/service/wsgi_server.py", line 184, in application
    return application_unproxied(environ, start_response)
  File "/odoo/odoo-server/odoo/service/wsgi_server.py", line 170, in application_unproxied
    result = handler(environ, start_response)
  File "/odoo/odoo-server/odoo/http.py", line 1307, in __call__
    self.load_addons()
  File "/odoo/odoo-server/odoo/http.py", line 1328, in load_addons
    m = __import__('odoo.addons.' + module)
  File "/odoo/odoo-server/odoo/modules/module.py", line 81, in load_module
    execfile(modfile, new_mod.__dict__)
  File "/odoo/odoo-server/addons/web_printscreen_zb/__init__.py", line 25, in <module>
    import controllers
  File "/odoo/odoo-server/addons/web_printscreen_zb/controllers.py", line 28, in <module>
    import openerp.addons.web.http as openerpweb
  File "/odoo/odoo-server/odoo/modules/module.py", line 109, in load_module
    mod = importlib.import_module(canonical)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named http
</code>```

i read the documentation of odoo to write web controller but same result.

and
i have tried to

from odoo.addons.web import http

same result

答:
the problem has been solved
by move the code from controller.py to another file file.py
i don't know why this ..!</p>

Body:
error in odoo 10 when i try to write  basic controller for web

from odoo import http

show error

2017-07-09 13:20:10,128 9183 ERROR ? werkzeug: Error on request:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 177, in run_wsgi
    execute(self.server.app)
  File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 165, in execute
    application_iter = app(environ, start_response)
  File "/odoo/odoo-server/odoo/service/server.py", line 250, in app
    return self.app(e, s)
  File "/odoo/odoo-server/odoo/service/wsgi_server.py", line 184, in application
    return application_unproxied(environ, start_response)
  File "/odoo/odoo-server/odoo/service/wsgi_server.py", line 170, in application_unproxied
    result = handler(environ, start_response)
  File "/odoo/odoo-server/odoo/http.py", line 1307, in __call__
    self.load_addons()
  File "/odoo/odoo-server/odoo/http.py", line 1328, in load_addons
    m = __import__('odoo.addons.' + module)
  File "/odoo/odoo-server/odoo/modules/module.py", line 81, in load_module
    execfile(modfile, new_mod.__dict__)
  File "/odoo/odoo-server/addons/web_printscreen_zb/__init__.py", line 25, in <module>
    import controllers
  File "/odoo/odoo-server/addons/web_printscreen_zb/controllers.py", line 28, in <module>
    import openerp.addons.web.http as openerpweb
  File "/odoo/odoo-server/odoo/modules/module.py", line 109, in load_module
    mod = importlib.import_module(canonical)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named http

i read the documentation of odoo to write web controller but same result.

and
i have tried to

from odoo.addons.web import http

same result


问:
subtracting RGB values from an Image in Python
I'm working in a project where I need to subtract the RGB values from an Image. In example I want to subtract the BLUE channel from RED, so RED gets the difference value of the subtraction.

I have the next properties of the image:

Dimension:1456x2592,
bpp:3

The image I'm using gives me the following arrays:

```<code> [[[ 63  58  60]
     [ 63  58  60]
     [ 64  59  61]
      ...,
     [155 155 161]
     [155 155 161]
     [155 155 161]]

     [[ 58  53  55]
      [ 60  55  57]
      [ 62  57  59]
       ...,
      [157 157 163]
      [157 157 163]
      [158 158 164]]
</code>```

I know those are the values(RGB) from the image, so now I move on to do the code (I based on this code)

```<code>import cv2
import numpy as np
from PIL import Image

# read image into matrix.
m =  cv2.imread("ITESO.jpeg")

# get image properties.
h,w,bpp = np.shape(m)

# iterate over the entire image.
# BLUE = 0, GREEN = 1, RED = 2.

for py in range(0,h):
    for px in range(0,w):
        #m[py][px][2] = 2
        n = m[py][px][2]                //n takes the value of RED
        Y = [n, 0, 0]                   //I create an array with [RED, 0, 0]
        m, Y = np.array(m), np.array(Y)
        m =  np.absolute(m - Y)       //Get the matriz with the substraction

y = 1
x = 1
print (m)
print (m[x][y])

#display image
#cv2.imshow('matrix', m)
#cv2.waitKey(0)
cv2.imwrite('new.jpeg',m)
img = Image.open('new.jpeg')
img.show()

img = Image.open('new.jpeg').convert('L')
img.save('new_gray_scale.jpg')
img.show()
</code>```

When I print the J matrix it gives the following arrays:

B,G,R

Blue = BLUE - RED

```<code>[[[  3  58  60]
  [  3  58  60]
  [  4  59  61]
  ...,
 [ 95 155 161]
 [ 95 155 161]
 [ 95 155 161]]

[[  2  53  55]
 [  0  55  57]
 [  2  57  59]
 ...,
 [ 97 157 163]
 [ 97 157 163]
 [ 98 158 164]]
</code>```

But I'm not able to open the new image and if I set one RGB channel to one value it shows me the image. I use the next lines for that:

```<code>import cv2
import numpy as np

# read image into matrix.
m =  cv2.imread("python.png")

# get image properties.
h,w,bpp = np.shape(m)

# iterate over the entire image.
for py in range(0,h):
    for px in range(0,w):
        m[py][px][0] = 0 //setting channel Blue to values of 0

# display image
cv2.imshow('matrix', m)
cv2.waitKey(0)
</code>```

How can I subtract the RGB channels from each other?

PS: In MatLab it works like a charm, but I'm not able to do it in python.

答:
Pay attention that this operation is changing the dtype of the matrix (image) from uint8 to int32, and this can cause other problems. A better way (and more efficient) to do this, IMO, is this:

```<code>import cv2
import numpy as np

img =  cv2.imread('image.png').astype(np.float)  # BGR, float
img[:, :, 2] = np.absolute(img[:, :, 2] - img[:, :, 0])  # R = |R - B|
img = img.astype(np.uint8)  # convert back to uint8
cv2.imwrite('new-image.png', img)  # save the image
cv2.imshow('img', img)
cv2.waitKey()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working in a project where I need to subtract the RGB values from an Image. In example I want to subtract the BLUE channel from RED, so RED gets the difference value of the subtraction.

I have the next properties of the image:

Dimension:1456x2592,
bpp:3

The image I'm using gives me the following arrays:

 [[[ 63  58  60]
     [ 63  58  60]
     [ 64  59  61]
      ...,
     [155 155 161]
     [155 155 161]
     [155 155 161]]

     [[ 58  53  55]
      [ 60  55  57]
      [ 62  57  59]
       ...,
      [157 157 163]
      [157 157 163]
      [158 158 164]]

I know those are the values(RGB) from the image, so now I move on to do the code (I based on this code)

import cv2
import numpy as np
from PIL import Image

# read image into matrix.
m =  cv2.imread("ITESO.jpeg")

# get image properties.
h,w,bpp = np.shape(m)

# iterate over the entire image.
# BLUE = 0, GREEN = 1, RED = 2.

for py in range(0,h):
    for px in range(0,w):
        #m[py][px][2] = 2
        n = m[py][px][2]                //n takes the value of RED
        Y = [n, 0, 0]                   //I create an array with [RED, 0, 0]
        m, Y = np.array(m), np.array(Y)
        m =  np.absolute(m - Y)       //Get the matriz with the substraction

y = 1
x = 1
print (m)
print (m[x][y])

#display image
#cv2.imshow('matrix', m)
#cv2.waitKey(0)
cv2.imwrite('new.jpeg',m)
img = Image.open('new.jpeg')
img.show()

img = Image.open('new.jpeg').convert('L')
img.save('new_gray_scale.jpg')
img.show()

When I print the J matrix it gives the following arrays:

B,G,R

Blue = BLUE - RED

[[[  3  58  60]
  [  3  58  60]
  [  4  59  61]
  ...,
 [ 95 155 161]
 [ 95 155 161]
 [ 95 155 161]]

[[  2  53  55]
 [  0  55  57]
 [  2  57  59]
 ...,
 [ 97 157 163]
 [ 97 157 163]
 [ 98 158 164]]

But I'm not able to open the new image and if I set one RGB channel to one value it shows me the image. I use the next lines for that:

import cv2
import numpy as np

# read image into matrix.
m =  cv2.imread("python.png")

# get image properties.
h,w,bpp = np.shape(m)

# iterate over the entire image.
for py in range(0,h):
    for px in range(0,w):
        m[py][px][0] = 0 //setting channel Blue to values of 0

# display image
cv2.imshow('matrix', m)
cv2.waitKey(0)

How can I subtract the RGB channels from each other?

PS: In MatLab it works like a charm, but I'm not able to do it in python.

Body:
Pay attention that this operation is changing the dtype of the matrix (image) from uint8 to int32, and this can cause other problems. A better way (and more efficient) to do this, IMO, is this:

import cv2
import numpy as np

img =  cv2.imread('image.png').astype(np.float)  # BGR, float
img[:, :, 2] = np.absolute(img[:, :, 2] - img[:, :, 0])  # R = |R - B|
img = img.astype(np.uint8)  # convert back to uint8
cv2.imwrite('new-image.png', img)  # save the image
cv2.imshow('img', img)
cv2.waitKey()


问:
How to display Splash Screen in android
I want to display splash screen in android app. But I want to execute onCreate() method of MainActivity behind the splash screen. because i am doing huge work in this method. Anyone can tel me how to do that.

答:
Basically you want to do some work in background while user is shown some splash screen, right ? What you need is an Async Task or a Loader kind of thing.

Step 1: Display the splash screen.
Step 2: Start an Async task and do all your heavy processing in the doInBackground method of Async Task
Step 3: Update the UI using the onPostExecute method of Async Task. In this method, first close the timer to splash screen. Then send the intent to start another screen with the data of the heavy processed result of Async task. Display it on UI thread.

Only Showing Splash screen is very simple. This code creates a splash screen of 3 seconds and then sends an Intent to another activity.

```<code>public class SplashScreenActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        CountDownTimer cdt1 = new CountDownTimer(3000, 1000) {

            Boolean checkInternetConnection = false;

            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {

          //Send Intent here
             Intent i = new Intent(getApplicationContext(),
                         anotherActivity.class);
                startActivity(i);
            }
        }.start();

    }
</code>```

PS- Dont forget to make the activity with this code as launcher activity  from manifest file.

Title: How to display Splash Screen in android

Body:
Basically you want to do some work in background while user is shown some splash screen, right ? What you need is an Async Task or a Loader kind of thing.

Step 1: Display the splash screen.
Step 2: Start an Async task and do all your heavy processing in the doInBackground method of Async Task
Step 3: Update the UI using the onPostExecute method of Async Task. In this method, first close the timer to splash screen. Then send the intent to start another screen with the data of the heavy processed result of Async task. Display it on UI thread.

Only Showing Splash screen is very simple. This code creates a splash screen of 3 seconds and then sends an Intent to another activity.

public class SplashScreenActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        CountDownTimer cdt1 = new CountDownTimer(3000, 1000) {

            Boolean checkInternetConnection = false;

            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {

          //Send Intent here
             Intent i = new Intent(getApplicationContext(),
                         anotherActivity.class);
                startActivity(i);
            }
        }.start();

    }

PS- Dont forget to make the activity with this code as launcher activity  from manifest file.


问:
Is there a Java equivalent for Python's map function?
I would like to easily transform a collection (list) of objects of class A to a collection of objects of class B, just as Python's map function does it. Is there any "well-known" implementation of this (some kind of library)? I've already searched for it in Apache's commons-lang but with no luck. </p>

答:
still not exist

functional programming features will be added in Java 8 - Project Lambda

I think Google Guava is best for your needs now


问:
Opening existing PowerPoint from a directory with Python 3.5
Open an existing PowerPoint Presentation from a directory
Example from here: Charts from Excel to PowerPoint with Python

My situation is different - the link showed how to to open a new presentation not a saved existing one.

error message:

module None.

答:
You can call out to the open cmd and pass the filename to be opened as the only parameter. It will query the registry to find the program that should be used as default to open such a file, how to do it, and then do it.

This should work, did not check though

```<code>subprocess.run(['open', 'the file to be opened.pptx'])
</code>```

Update: There is also https://docs.python.org/3/library/os.html#os.startfile

Body:
You can call out to the open cmd and pass the filename to be opened as the only parameter. It will query the registry to find the program that should be used as default to open such a file, how to do it, and then do it.

This should work, did not check though

subprocess.run(['open', 'the file to be opened.pptx'])

Update: There is also https://docs.python.org/3/library/os.html#os.startfile


问:
Convert List<V> in Map<K,V> with stream Java 8
I have a these model classes:

```<code>public class Student extends Person;

public class Professor extends Person;

public class University {
    private long id;
    private String name;
    private List<Person> employers;
....
}
</code>```

I have a List of University and I want to convert it into a Map; Person is an abstract class and has implemented hashCode and equals method.
This is an implementation with a for iteration:

```<code>Map<Person, University> mapList = new HashMap<Person, University>();
for (University u : universities) {
    for (Person p : u.getEmployers()) {
       mapList.put(p,u);
    }
}
mapList.forEach((k,v) -> System.out.println(k.toString() + v.getName()));
</code>```

I am not so familiar with Java 8 stream, but how can I covert this code with lambda expression?

答:
I have probably not the best solution, so I would stick with java 7 approach. But here is my solution with Stream API

```<code>    Map<Person, University> mapList = universities.stream()
            .flatMap(university -> university.getEmployers().stream()
                    .map(employer -> new Tuple<>(employer, university)))
            .collect(Collectors.toMap(Tuple::getV1, Tuple::getV2));
</code>```

You also need for this approach some kind of holder class

```<code>class Tuple<T, V> {
    private final T v1;
    private final V v2;

    public Tuple(T v1, V v2) {
        this.v1 = v1;
        this.v2 = v2;
    }

    public T getV1() {
        return v1;
    }

    public V getV2() {
        return v2;
    }
}
</code>```

Body:
I have a these model classes:

public class Student extends Person;

public class Professor extends Person;

public class University {
    private long id;
    private String name;
    private List<Person> employers;
....
}

I have a List of University and I want to convert it into a Map; Person is an abstract class and has implemented hashCode and equals method.
This is an implementation with a for iteration:

Map<Person, University> mapList = new HashMap<Person, University>();
for (University u : universities) {
    for (Person p : u.getEmployers()) {
       mapList.put(p,u);
    }
}
mapList.forEach((k,v) -> System.out.println(k.toString() + v.getName()));

I am not so familiar with Java 8 stream, but how can I covert this code with lambda expression?

Body:
I have probably not the best solution, so I would stick with java 7 approach. But here is my solution with Stream API

    Map<Person, University> mapList = universities.stream()
            .flatMap(university -> university.getEmployers().stream()
                    .map(employer -> new Tuple<>(employer, university)))
            .collect(Collectors.toMap(Tuple::getV1, Tuple::getV2));

You also need for this approach some kind of holder class

class Tuple<T, V> {
    private final T v1;
    private final V v2;

    public Tuple(T v1, V v2) {
        this.v1 = v1;
        this.v2 = v2;
    }

    public T getV1() {
        return v1;
    }

    public V getV2() {
        return v2;
    }
}


问:
C - What's wrong with mystrtok() function?
I'm trying to create a function that'll do the same work as strtok() function does in C.  Below is my code, but the problem is that every time I run this program, it shows only the first tokenized string, then the program stops and Windows shows a pop-up saying "..... has stopped working......" & then then Code::Blocks returns  -1073741819 (0XC0000005). I don't know why this is happening — can you explain?

My code:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char a[1000],b[50];
int i=0;

char *mystrtok(char a[],char b[])
{
    char c[1000];
    char *ptr = malloc(1000*sizeof(c));
    ptr = c;
    c[0] = '\0';

    if(a == NULL)
        ++i;
    else
        i=0;

    /*printf("i is = %d\n",i);
    free(ptr);*/

    //printf("len of c is%d",strlen(c));
    int j=0,flag;

    //ptr = realloc(ptr,sizeof(c));
    for(i=i;a[i] != '\0';i++)
    {
        for(j=0;b[j] != '\0';j++)
        {
            if(a[i] == b[j])
            {
                c[i] = '\0';
                return ptr;
            }
            else
            {
                flag = 0;
                c[i] = a[i];
                continue;
            }
        }
    }
    /*if(!flag)
        c[i] = '\0';*/
    return ptr;
}

int main()
{
    int k;
    printf("Enter a big string: ");
    gets(a);
    printf("Enter a token: ");
    gets(b);

    char *tokenized;
    tokenized = mystrtok(a,b);
    puts(tokenized);

    while(tokenized)
    {
        tokenized = mystrtok(NULL, b);
        puts(tokenized);
    }
}
</code>```

I've spent much time on finding what's problem with my code, and I've searched through Google & Stack Overflow help, but nothing helps me exactly.

答:
You have a few bugs.  Right off the top, you allocate memory for ptr, then lose the reference to it by overwriting it with c.  That's a memory leak (and also because you never free it).

The main problem I think is that when the second call passes NULL, you lost the reference to the string you're supposed to be searching from the previous call.  You have to have some memory that persists between function calls.  static variables are perfect for this.

And lastly, the loop in main has the statements in the reverse order.

```<code>#include <stdio.h>

char *mystrtok(char *str, const char *delim) {
  int i = 0, j;
  static char *ptr = "";
  int found;

  // new str, new search
  if(str != NULL) {
    ptr = str;
  }

  // skip delims
  while(ptr[i] != '\0') {
    found = 1;
    for(j = 0; delim[j] != '\0'; j++) {
      if(ptr[i] == delim[j]) {
        found = 0;
        break;
      }
    }

    if(found) {
      break;
    }

    i++;
  }

  if(ptr[i] == '\0') {
    return NULL;
  } else {
    ptr += i;
  }

  // find next delim
  found = 0;
  while(ptr[i] != '\0') {
    for(j = 0; delim[j] != '\0'; j++) {
      if(ptr[i] == delim[j]) {
        ptr[i] = '\0';
        found = 1;
        break;
      }
    }

    if(found) {
      break;
    }

    i++;
  }

  // record start, advance ptr
  str = ptr;
  ptr += i;

  // only skip delims
  if(found) {
    ptr++;
  }

  return str;
}

int main() {
  char a[1000];
  char b[50];

  printf("Enter a big string: ");
  gets(a);

  printf("Enter a token: ");
  gets(b);

  char *tokenized = mystrtok(a, b);

  while(tokenized != NULL) {
    puts(tokenized);
    tokenized = mystrtok(NULL, b);
  }

  return 0;
}
</code>```

Body:
I'm trying to create a function that'll do the same work as strtok() function does in C.  Below is my code, but the problem is that every time I run this program, it shows only the first tokenized string, then the program stops and Windows shows a pop-up saying "..... has stopped working......" & then then Code::Blocks returns  -1073741819 (0XC0000005). I don't know why this is happening — can you explain?

My code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char a[1000],b[50];
int i=0;

char *mystrtok(char a[],char b[])
{
    char c[1000];
    char *ptr = malloc(1000*sizeof(c));
    ptr = c;
    c[0] = '\0';

    if(a == NULL)
        ++i;
    else
        i=0;

    /*printf("i is = %d\n",i);
    free(ptr);*/

    //printf("len of c is%d",strlen(c));
    int j=0,flag;

    //ptr = realloc(ptr,sizeof(c));
    for(i=i;a[i] != '\0';i++)
    {
        for(j=0;b[j] != '\0';j++)
        {
            if(a[i] == b[j])
            {
                c[i] = '\0';
                return ptr;
            }
            else
            {
                flag = 0;
                c[i] = a[i];
                continue;
            }
        }
    }
    /*if(!flag)
        c[i] = '\0';*/
    return ptr;
}

int main()
{
    int k;
    printf("Enter a big string: ");
    gets(a);
    printf("Enter a token: ");
    gets(b);

    char *tokenized;
    tokenized = mystrtok(a,b);
    puts(tokenized);

    while(tokenized)
    {
        tokenized = mystrtok(NULL, b);
        puts(tokenized);
    }
}

I've spent much time on finding what's problem with my code, and I've searched through Google & Stack Overflow help, but nothing helps me exactly.

Body:
You have a few bugs.  Right off the top, you allocate memory for ptr, then lose the reference to it by overwriting it with c.  That's a memory leak (and also because you never free it).

The main problem I think is that when the second call passes NULL, you lost the reference to the string you're supposed to be searching from the previous call.  You have to have some memory that persists between function calls.  static variables are perfect for this.

And lastly, the loop in main has the statements in the reverse order.

#include <stdio.h>

char *mystrtok(char *str, const char *delim) {
  int i = 0, j;
  static char *ptr = "";
  int found;

  // new str, new search
  if(str != NULL) {
    ptr = str;
  }

  // skip delims
  while(ptr[i] != '\0') {
    found = 1;
    for(j = 0; delim[j] != '\0'; j++) {
      if(ptr[i] == delim[j]) {
        found = 0;
        break;
      }
    }

    if(found) {
      break;
    }

    i++;
  }

  if(ptr[i] == '\0') {
    return NULL;
  } else {
    ptr += i;
  }

  // find next delim
  found = 0;
  while(ptr[i] != '\0') {
    for(j = 0; delim[j] != '\0'; j++) {
      if(ptr[i] == delim[j]) {
        ptr[i] = '\0';
        found = 1;
        break;
      }
    }

    if(found) {
      break;
    }

    i++;
  }

  // record start, advance ptr
  str = ptr;
  ptr += i;

  // only skip delims
  if(found) {
    ptr++;
  }

  return str;
}

int main() {
  char a[1000];
  char b[50];

  printf("Enter a big string: ");
  gets(a);

  printf("Enter a token: ");
  gets(b);

  char *tokenized = mystrtok(a, b);

  while(tokenized != NULL) {
    puts(tokenized);
    tokenized = mystrtok(NULL, b);
  }

  return 0;
}


问:
IBM Watson visual recognition c#
I'm trying to develop an ASP.Net app ( software app or the web) in visual studio 2013 OR 2015 that uses IBM Watson Visual Recognition service.

I have seen the examples for QA service but it is outdated with the Watson credentials and functionality.
the example: (it requires username and password as credentials, which are not supplied anymore when creating a service):

http://www.nechai.net/2016/07/05/invoking-the-web-api-of-ibm-watsons-speech-to-text-service-from-net/

This example that I have found looks updated to today's credentials ( the API Key instead of username and pass) but I can't import, open or use the sub projects inside it, visual studio does not know how to recognize it)
"https://github.com/watson-developer-cloud/visual-recognition-aspnet"

the two inner projects that the project rely on are VisualRecognition and WatsonServices projects in the main project.
They have a project file with the xproj extension file, which visual studio 2013 AND 2015 seems to not recognize so I can't try it or reuse its code in my test app.

the above example project is too complicated to just grab the code and try it (after failing to import and making it work on VS 2013)

Is there a very simple example on how to connect to a watson service using this type of credentials? :

"credentials": {
"url": "https://gateway-a.watsonplatform.net/visual-recognition/api",
"note": "It may take up to 5 minutes for this key to become active",
"api_key": "********************************************************"
}

I have also tried to install the Watson services SDK by Nuget and by downloading the source and opening it in VS (for visual recognition specifically and the whole services option as well) but with no luck as well.
When opening the source code in VS, it says "incompatible" with all the files.
"https://github.com/watson-developer-cloud/dotnet-standard-sdk"

When trying to install with Nuget I get Errors:
in VS2013:
Install-Package: Could not install package 'IBM.WatsonDeveloperCloud.VisualRecognition.v3 1.0.0'. You are trying to install this package into a project that targets '.NETFram
ework,Version=v4.6', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
At line:1 char:1
+ Install-Package IBM.WatsonDeveloperCloud.VisualRecognition.v3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
+ FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

in VS 2015:
Install-Package : An error occurred while retrieving package metadata for 'Newtonsoft.Json.10.0.3' from source 'd:\Users*****\Documents\Visual Studio 2015\Projects\FaceDetection\packages'.
At line:1 char:1
+ Install-Package IBM.WatsonDeveloperCloud.VisualRecognition.v3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Install-Package], Exception
+ FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

There is no example on how to use or install the SDKs except for using Nuget so I'm lost here.

答:
The Watson Developer Cloud .NET Standard SDK has been updated to 1.1.0. Please try to update the packages. You can see examples of how to invoke the service in the readme for the service.

Additionally, there is an example file of how to invoke the service in the examples directory of the github repo.

Basically you instantiate the service

```<code>private VisualRecognitionService _visualRecognition = new VisualRecognitionService();
</code>```

Set the credentials

```<code>_visualRecognition.SetCredential(apikey);
</code>```

And call the API (classify in this example)

```<code>var result = _visualRecognition.Classify(<image-url>);
</code>```

You should be able to traverse the result object to get the classification results

```<code>if (result != null)
{
    foreach (ClassifyTopLevelSingle image in result.Images)
        foreach (ClassifyPerClassifier classifier in image.Classifiers)
            foreach (ClassResult classResult in classifier.Classes)
                Console.WriteLine(string.Format("class: {0} | score: {1} | type hierarchy: {2}", classResult._Class, classResult.Score, classResult.TypeHierarchy));
}
</code>```

You can also see the result in json format by serializing the result object

```<code>Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
</code>```

Title: IBM Watson visual recognition c#

Body:
The Watson Developer Cloud .NET Standard SDK has been updated to 1.1.0. Please try to update the packages. You can see examples of how to invoke the service in the readme for the service.

Additionally, there is an example file of how to invoke the service in the examples directory of the github repo.

Basically you instantiate the service

private VisualRecognitionService _visualRecognition = new VisualRecognitionService();

Set the credentials

_visualRecognition.SetCredential(apikey);

And call the API (classify in this example)

var result = _visualRecognition.Classify(<image-url>);

You should be able to traverse the result object to get the classification results

if (result != null)
{
    foreach (ClassifyTopLevelSingle image in result.Images)
        foreach (ClassifyPerClassifier classifier in image.Classifiers)
            foreach (ClassResult classResult in classifier.Classes)
                Console.WriteLine(string.Format("class: {0} | score: {1} | type hierarchy: {2}", classResult._Class, classResult.Score, classResult.TypeHierarchy));
}

You can also see the result in json format by serializing the result object

Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));


问:
What grayscale conversion algorithm does OpenCV cvtColor() use?
When converting an image in OpenCV from color to grayscale, what conversion algorithm is used? I tried to look this up in the source code on GitHub, but I did not have any success.

The lightness method averages the most prominent and least prominent colors:

```<code>  (max(R, G, B) + min(R, G, B)) / 2.
</code>```

The average method simply averages the values:

```<code>  (R + G + B) / 3.
</code>```

The luminosity method is a more sophisticated version of the average method. It also averages the values, but it forms a weighted average to account for human perception. We’re more sensitive to green than other colors, so green is weighted most heavily.

```<code>    The formula for luminosity is 0.21 R + 0.72 G + 0.07 B.
</code>```

Here is an example of some conversion algorithms:
http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/

答:
Just wanted to point out that:

```<code>img = cv2.imread(rgbImageFileName)
b1 = img[:,:,0] # Gives **Blue**
b2 = img[:,:,1] # Gives Green
b3 = img[:,:,2] # Gives **Red**
</code>```

On the other hand, loading it as a numeric array works fine:

```<code>imgArray= gdalnumeric.LoadFile(rgbImageFileName)
Red = imgArray[0, :, :].astype('float32')
Green = imgArray[1, :, :].astype('float32')
Blue = imgArray[2, :, :].astype('float32')
</code>```

So just watch out for these oddities.

But when converting to Grayscale cv2.cvtColor uses the the bands correctly.
I compared pixel values using Matlab's rgb2gray.

Cheers

Body:
When converting an image in OpenCV from color to grayscale, what conversion algorithm is used? I tried to look this up in the source code on GitHub, but I did not have any success.

The lightness method averages the most prominent and least prominent colors:

  (max(R, G, B) + min(R, G, B)) / 2.

The average method simply averages the values:

  (R + G + B) / 3.

The luminosity method is a more sophisticated version of the average method. It also averages the values, but it forms a weighted average to account for human perception. We’re more sensitive to green than other colors, so green is weighted most heavily.

    The formula for luminosity is 0.21 R + 0.72 G + 0.07 B.

Here is an example of some conversion algorithms:
http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/

Body:
Just wanted to point out that:

img = cv2.imread(rgbImageFileName)
b1 = img[:,:,0] # Gives **Blue**
b2 = img[:,:,1] # Gives Green
b3 = img[:,:,2] # Gives **Red**

On the other hand, loading it as a numeric array works fine:

imgArray= gdalnumeric.LoadFile(rgbImageFileName)
Red = imgArray[0, :, :].astype('float32')
Green = imgArray[1, :, :].astype('float32')
Blue = imgArray[2, :, :].astype('float32')

So just watch out for these oddities.

But when converting to Grayscale cv2.cvtColor uses the the bands correctly.
I compared pixel values using Matlab's rgb2gray.

Cheers


问:
Working with bitstrings and big.Int in Go
I'm new to Go and I'm working on a few exercises to get up to speed. How can I convert a string representing a sequence of bits to the appropriate datatype in Go?

For eg, I see that if its a bitstring representing a 64-bit number, I can do :-

```<code>val, err := strconv.ParseInt(bitstring, 2, 64)
</code>```

However, if the bitstring represents a larger number(say 1024 or 2048 bits), how can I go about converting that number to the appropriate type in Go? I believe the type for managing big integers in Go is big.Int.

答:
Yes, you may use the big.Int type, and its Int.SetString() method, passing 2 as the base.

Example:

```<code>i := big.NewInt(0)
if _, ok := i.SetString("10101010101010101010101010101010101010101010101010101010101010101010101010", 2); !ok {
    fmt.Println("Invalid number!")
} else {
    fmt.Println(i)
}
</code>```

Output (try it on the Go playground):

```<code>12592977287652387236522
</code>```

Body:
I'm new to Go and I'm working on a few exercises to get up to speed. How can I convert a string representing a sequence of bits to the appropriate datatype in Go?

For eg, I see that if its a bitstring representing a 64-bit number, I can do :-

val, err := strconv.ParseInt(bitstring, 2, 64)

However, if the bitstring represents a larger number(say 1024 or 2048 bits), how can I go about converting that number to the appropriate type in Go? I believe the type for managing big integers in Go is big.Int.

Body:
Yes, you may use the big.Int type, and its Int.SetString() method, passing 2 as the base.

Example:

i := big.NewInt(0)
if _, ok := i.SetString("10101010101010101010101010101010101010101010101010101010101010101010101010", 2); !ok {
    fmt.Println("Invalid number!")
} else {
    fmt.Println(i)
}

Output (try it on the Go playground):

12592977287652387236522


问:
Why the dip in speed increase for generating 400,000,000 random numbers?
I'm generating around 400,000,000 (400 million) random numbers in parallel on an Intel i7 with 4 cores (8 threads hyperthreaded) on macOS with 8 GB RAM.

However, I'm also generating 400,000,000 random numbers on a DigitalOcean server with 20 cores on Debian with 64 GB RAM.

Here's the code:

```<code>import multiprocessing
import random

rangemin = 1
rangemax = 9

def randomGenPar_backend(backinput):
    return random.randint(rangemin, rangemax)

def randomGenPar(num):
    pool = multiprocessing.Pool()
    return pool.map(randomGenPar_backend, range(0, num))

randNum = 400000000

random.seed(999)
randomGenPar(randNum)
</code>```

These are the results of the benchmark:

```<code>5,000,000 Random Numbers:
1 Core: 5.984
8 Core: 1.982

50,000,000 Random Numbers:
1 Core: 57.28
8 Core: 19.799
20 Core: 18.257
Times Benefit (20 core vs. 8 core) = 1.08

100,000,000 Random Numbers:
1 Core: 115
8 Core: 40.434
20 Core: 31.652
Times Benefit (20 core vs. 8 core) = 1.28

200,000,000 Random Numbers:
8 Core: 87
20 Core: 60
Times Benefit (20 core vs. 8 core) = 1.45

300,000,000 Random Numbers:
8 Core: 157
20 Core: 88
Times Benefit (20 core vs. 8 core) = 1.78

400,000,000 Random Numbers:
8 Core: 202
20 Core: 139
Times Benefit (20 core vs. 8 core) = 1.45 (DIP!)

500,000,000 Random Numbers:
8 Core: 280
20 Core: 171
Times Benefit (20 core vs. 8 core) = 1.64 (INCREASE!)

600,000,000 Random Numbers:
8 Core: 342
20 Core: 198
Times Benefit (20 core vs. 8 core) = 1.73

700,000,000 Random Numbers:
8 Core: 410
20 Core: 206
Times Benefit (20 core vs. 8 core) = 1.99

800,000,000 Random Numbers:
8 Core: 482
20 Core: 231
Times Benefit (20 core vs. 8 core) = 2.09
</code>```

Usually, the more random numbers that are generated, the more the parallelism of the 20 core CPU can be used. Therefore, the "times increase" of speed from 8 core to 20 core increases over time.

However, after 300 million random numbers, this decreases, and increases again until 800 million (I haven't tested further).

Why is this? Is there a specific reason? Was it just random? (I've repeated this twice, and gotten the same result both times)

EDIT: If it makes any difference, I'm using the time function to time the execution of the script. Also, the OS isn't the same on both machines (8 core - macOS, 20 core - Debian).

答:
Two possible explanations come to mind.

This could be an artifact of garbage collection kicking in.  An easy experiment would be to shut-off GC and see if the "dip" persists:

```<code>>>> import gc
>>> gc.disable()
</code>```

Another possibility is that this is an artifact of list growth using realloc() under-the-hood.  Lists implemented are fixed length arrays of pointers.  When map() grows the list with append(), the C function call realloc() is called periodically to resize the array of pointers.  Often, this call is very cheap because none of the data has to be moved.  However, if even a single byte in memory "obstructs" the resize, then all of the data has to be relocated.  This is very expensive and could cause your the "dip" if at that point in execution multiprocessing is creating an obstructing byte.

To test this hypothesis, you could use imap() instead of map() and feed the results into collections.deque() instead of a list().  The deque implementation does not use relloc so its performance is consistent in the face of fragmented memory (internally, it just makes repeated calls to malloc() to obtained fixed length memory blocks).

Body:
I'm generating around 400,000,000 (400 million) random numbers in parallel on an Intel i7 with 4 cores (8 threads hyperthreaded) on macOS with 8 GB RAM.

However, I'm also generating 400,000,000 random numbers on a DigitalOcean server with 20 cores on Debian with 64 GB RAM.

Here's the code:

import multiprocessing
import random

rangemin = 1
rangemax = 9

def randomGenPar_backend(backinput):
    return random.randint(rangemin, rangemax)

def randomGenPar(num):
    pool = multiprocessing.Pool()
    return pool.map(randomGenPar_backend, range(0, num))

randNum = 400000000

random.seed(999)
randomGenPar(randNum)

These are the results of the benchmark:

5,000,000 Random Numbers:
1 Core: 5.984
8 Core: 1.982

50,000,000 Random Numbers:
1 Core: 57.28
8 Core: 19.799
20 Core: 18.257
Times Benefit (20 core vs. 8 core) = 1.08

100,000,000 Random Numbers:
1 Core: 115
8 Core: 40.434
20 Core: 31.652
Times Benefit (20 core vs. 8 core) = 1.28

200,000,000 Random Numbers:
8 Core: 87
20 Core: 60
Times Benefit (20 core vs. 8 core) = 1.45

300,000,000 Random Numbers:
8 Core: 157
20 Core: 88
Times Benefit (20 core vs. 8 core) = 1.78

400,000,000 Random Numbers:
8 Core: 202
20 Core: 139
Times Benefit (20 core vs. 8 core) = 1.45 (DIP!)

500,000,000 Random Numbers:
8 Core: 280
20 Core: 171
Times Benefit (20 core vs. 8 core) = 1.64 (INCREASE!)

600,000,000 Random Numbers:
8 Core: 342
20 Core: 198
Times Benefit (20 core vs. 8 core) = 1.73

700,000,000 Random Numbers:
8 Core: 410
20 Core: 206
Times Benefit (20 core vs. 8 core) = 1.99

800,000,000 Random Numbers:
8 Core: 482
20 Core: 231
Times Benefit (20 core vs. 8 core) = 2.09

Usually, the more random numbers that are generated, the more the parallelism of the 20 core CPU can be used. Therefore, the "times increase" of speed from 8 core to 20 core increases over time.

However, after 300 million random numbers, this decreases, and increases again until 800 million (I haven't tested further).

Why is this? Is there a specific reason? Was it just random? (I've repeated this twice, and gotten the same result both times)

EDIT: If it makes any difference, I'm using the time function to time the execution of the script. Also, the OS isn't the same on both machines (8 core - macOS, 20 core - Debian).

Body:
Two possible explanations come to mind.

This could be an artifact of garbage collection kicking in.  An easy experiment would be to shut-off GC and see if the "dip" persists:

>>> import gc
>>> gc.disable()

Another possibility is that this is an artifact of list growth using realloc() under-the-hood.  Lists implemented are fixed length arrays of pointers.  When map() grows the list with append(), the C function call realloc() is called periodically to resize the array of pointers.  Often, this call is very cheap because none of the data has to be moved.  However, if even a single byte in memory "obstructs" the resize, then all of the data has to be relocated.  This is very expensive and could cause your the "dip" if at that point in execution multiprocessing is creating an obstructing byte.

To test this hypothesis, you could use imap() instead of map() and feed the results into collections.deque() instead of a list().  The deque implementation does not use relloc so its performance is consistent in the face of fragmented memory (internally, it just makes repeated calls to malloc() to obtained fixed length memory blocks).


问:
Why is this UrlFetch function not working properly?
This is the function I'm trying to run through the JavaScript Tool on my Google Spreadsheet chart, the function is currently working on 4 different websites, where in this example:

$id is the imported value from my spreadsheet cell (belacoin)

```<code>function CoinmarketcapPrice($id) {
  var response = UrlFetchApp.fetch("https://api.coinmarketcap.com/v1/ticker/" + $id);
  var html = JSON.parse(response.getContentText());
  try
  {
    return parseFloat(html["price_btc"]);
  }
  catch(err)
  {
    return null;
  }
}
</code>```

this is what that UrlFetch returns:

```<code>[
    {
        "id": "belacoin",
        "name": "BelaCoin",
        "symbol": "BELA",
        "rank": "176",
        "price_usd": "0.212823",
        "price_btc": "0.00008400",
        "24h_volume_usd": "534995.0",
        "market_cap_usd": "7694903.0",
        "available_supply": "36156350.0",
        "total_supply": "36156350.0",
        "percent_change_1h": "0.63",
        "percent_change_24h": "1.88",
        "percent_change_7d": "-17.03",
        "last_updated": "1499549044"
    }
]
</code>```

答:
It looks like that endpoint is returning an array of objects, so if you want to access the first item in the array change your try block to:</p>

```<code>try {
  return parseFloat(html[0]["price_btc"]);
}
</code>```

Body:
This is the function I'm trying to run through the JavaScript Tool on my Google Spreadsheet chart, the function is currently working on 4 different websites, where in this example:

$id is the imported value from my spreadsheet cell (belacoin)

function CoinmarketcapPrice($id) {
  var response = UrlFetchApp.fetch("https://api.coinmarketcap.com/v1/ticker/" + $id);
  var html = JSON.parse(response.getContentText());
  try
  {
    return parseFloat(html["price_btc"]);
  }
  catch(err)
  {
    return null;
  }
}

this is what that UrlFetch returns:

[
    {
        "id": "belacoin",
        "name": "BelaCoin",
        "symbol": "BELA",
        "rank": "176",
        "price_usd": "0.212823",
        "price_btc": "0.00008400",
        "24h_volume_usd": "534995.0",
        "market_cap_usd": "7694903.0",
        "available_supply": "36156350.0",
        "total_supply": "36156350.0",
        "percent_change_1h": "0.63",
        "percent_change_24h": "1.88",
        "percent_change_7d": "-17.03",
        "last_updated": "1499549044"
    }
]

Body:
It looks like that endpoint is returning an array of objects, so if you want to access the first item in the array change your try block to:

try {
  return parseFloat(html[0]["price_btc"]);
}


问:
why do tensorflow compute Sigmoid's output again when compute the gradient of Sigmod?
Reading the source code of the tensorflow I found the Sigmoid Gradient Computation is defined below.

```<code>Status SigmoidGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
return GradForUnaryCwise(g, {
  {{"y"}, "Sigmoid", {"x"}},
  FDH::Const("const", 1.0f),
  {{"one"}, "Cast", {"const"}, {{"SrcT", DT_FLOAT}, {"DstT", "$T"}}},
  {{"a"}, "Sub", {"one", "y"}, {}, {"dy"}},
  {{"b"}, "Mul", {"y", "a"}},             // y * (1 - y)
  {{"dx"}, "Mul", {"dy", "b"}},           // dy * y * (1 - y)
});
// clang-format on
}
</code>```

My question is, why do tensorflow recompute the Sigmoid's output for computing it's gradient. Isn't it stored in the op's context??

The code piece comes from github

答:
Why do tensorflow recompute the Sigmoid's output for its gradient?

It does not — that's the beauty of frameworks such as tensorflow. Tensorflow will reuse nodes that can be reused. So the sigmoid node in the gradient will automagically reuse the sigmoid computation.

Note that node reuse is much more powerful than a per-op optimization, because the optimization can happen anywhere in the graph, between different operations.

Body:
Reading the source code of the tensorflow I found the Sigmoid Gradient Computation is defined below.

Status SigmoidGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
return GradForUnaryCwise(g, {
  {{"y"}, "Sigmoid", {"x"}},
  FDH::Const("const", 1.0f),
  {{"one"}, "Cast", {"const"}, {{"SrcT", DT_FLOAT}, {"DstT", "$T"}}},
  {{"a"}, "Sub", {"one", "y"}, {}, {"dy"}},
  {{"b"}, "Mul", {"y", "a"}},             // y * (1 - y)
  {{"dx"}, "Mul", {"dy", "b"}},           // dy * y * (1 - y)
});
// clang-format on
}

My question is, why do tensorflow recompute the Sigmoid's output for computing it's gradient. Isn't it stored in the op's context??

The code piece comes from github


问:
how to get the values of a entire table having text and checkbox fields jsp to servlet
I have a jsp which iterates through a list printing the first name, last name and Paid (Checkbox). All these values come from oracle DB. Paid checkbox is editable (So, the user can check/uncheck the checkbox). I'm having a problem in getting all the updated values from jsp to servlet. I need to know how to get the entire list back in servlet with the checkbox updated values. Please let me know.

JSP Code snippet.

```<code><c:forEach items="${nameList}" var="nameObj">
  <tr>
    <td><label>${nameObj.firstName}</label></td>
    <td><label>${nameObj.lastName}</label></td>
    <c:if test="${nameObj.paid}">
        <td><input type="checkbox" name="paid" id="paid" checked ></td>
  </c:if>
  </tr>
</c:forEach>
</code>```

答:
You use this code as</p>

```<code>  <c:forEach items="${nameList}" var="nameObj">
       <tr>
      `<td><label>`FirstName`</label><input type="text" name="firstName" value="${nameObj.firstName}"/></td>`
      `<td><label>`LastName:`</label><input type="text" name="lastName" value="${nameObj.lastName}"/></td>`

  <c:if test="${nameObj.paid}">
       <td><input type="checkbox" name="paid" id="paid" checked /></td>
    </c:if>
    </tr>
</code>```

Body:
I have a jsp which iterates through a list printing the first name, last name and Paid (Checkbox). All these values come from oracle DB. Paid checkbox is editable (So, the user can check/uncheck the checkbox). I'm having a problem in getting all the updated values from jsp to servlet. I need to know how to get the entire list back in servlet with the checkbox updated values. Please let me know.

JSP Code snippet.

<c:forEach items="${nameList}" var="nameObj">

    ${nameObj.firstName}
    ${nameObj.lastName}
    <c:if test="${nameObj.paid}">
        <input type="checkbox" name="paid" id="paid" checked >
  </c:if>

</c:forEach>

Body:
You use this code as

  <c:forEach items="${nameList}" var="nameObj">
       <tr>
      `<td><label>`FirstName`</label><input type="text" name="firstName" value="${nameObj.firstName}"/></td>`
      `<td><label>`LastName:`</label><input type="text" name="lastName" value="${nameObj.lastName}"/></td>`

  <c:if test="${nameObj.paid}">
       <td><input type="checkbox" name="paid" id="paid" checked /></td>
    </c:if>
    </tr>


问:
setElevation() not working on AppBarLayout
I have a AppBarLayout, in which I wish to programatically set the elevation to 0 in the onCreate() method. If I have an example onCreate() like this..

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(_toolbar);
    _appBar.setElevation(0);
}
</code>```

The AppBarLayout elevation does NOT change.

However if I add a delay, for say, 400milliseconds, the AppBarLayout elevation DOES change.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(_toolbar);
        Observable.just(_appBar)
        .delay(400, TimeUnit.MILLISECONDS)
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<AppBarLayout>() {
            @Override
            public void accept(AppBarLayout appBarLayout) throws Exception {
                appBarLayout.setElevation(0);
            }
        });
}
</code>```

Can anyone explain why this is happening? and how I can fix this without a delay. I have also tried using getSupportActionBar().setElevation(0); as well, and using API 24

答:
Solved! instead of set elevation, I use:

```<code>StateListAnimator stateListAnimator = new StateListAnimator();
stateListAnimator.addState(new int[0], ObjectAnimator.ofFloat(view, "elevation", 0));
appBarLayout.setStateListAnimator(stateListAnimator);
</code>```

Please see the following answer for a more detailed explanation:

How to set the elevation of an AppBarLayout programmatically in the Android Support Library v24.0.0?

Body:
I have a AppBarLayout, in which I wish to programatically set the elevation to 0 in the onCreate() method. If I have an example onCreate() like this..

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(_toolbar);
    _appBar.setElevation(0);
}

The AppBarLayout elevation does NOT change.

However if I add a delay, for say, 400milliseconds, the AppBarLayout elevation DOES change.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(_toolbar);
        Observable.just(_appBar)
        .delay(400, TimeUnit.MILLISECONDS)
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<AppBarLayout>() {
            @Override
            public void accept(AppBarLayout appBarLayout) throws Exception {
                appBarLayout.setElevation(0);
            }
        });
}

Can anyone explain why this is happening? and how I can fix this without a delay. I have also tried using getSupportActionBar().setElevation(0); as well, and using API 24

Body:
Solved! instead of set elevation, I use:

StateListAnimator stateListAnimator = new StateListAnimator();
stateListAnimator.addState(new int[0], ObjectAnimator.ofFloat(view, "elevation", 0));
appBarLayout.setStateListAnimator(stateListAnimator);

Please see the following answer for a more detailed explanation:

How to set the elevation of an AppBarLayout programmatically in the Android Support Library v24.0.0?


问:
Yii2 query for posts in a space
I had a DB with a post table, a content table, and a space table.

A post is a type of content, and a space is a container for many posts. I want to get all posts within a space.

Post:

```<code>id   object_id
--------------
1    22
</code>```

Content (object_id --> post.id):

```<code>id   space_id
------------------------
22   3
</code>```

Space (id --> content.space_id):

```<code>id
--------------
3
</code>```

To get posts within a space, the controller function looked like this:

```<code>$posts = Post::find()
  ->joinWith('content', false)
  ->where(['{{content}}.space_id' => $space_id])
  ->all();
</code>```

And the Post model had this function to get the content object for a post:

```<code>public function getContent() {
   return $this->hasOne(Content::className(), ['object_id' => 'id'])->andOnCondition(['{{content}}.object_model' => 'humhub\modules\post\models\Post']);
}
</code>```

This worked perfectly until the database schema changed.

Now there is no longer a space_id column in the content table. Instead, there is a new table contentcontainer with a pk field which replaces space_id, and a class field (i.e. space class) to identify that the PK is for a space( there is also a class in the table).

The tables/relationships are now:

Post Table:

```<code>id   object_id
--------------
1    22
</code>```

Content table (object_id --> post.id):

```<code>id   contentcontainer_id
------------------------
22   5
</code>```

Contentcontainer Table (id --> content.contentcontainer_id)

```<code>id   pk   class
---------------
5    3    //Space
</code>```

Space (id --> contentcontainer):

```<code>id
--------------
3
</code>```

To get all posts within a space, I now have to link 3 tables: post,content,contentcontainer.

Do I add the contentcontainer relationship to the Post model? Or modify the content model relationship in the Post model? Not sure how best to tackle without writing a big sloppy query.

I changed the controller function to this:

```<code>$posts = Post::find()
  ->where(['{{contentcontainer}}.pk' => $space_id])
  ->andWhere(['{{contentcontainer}}.class' => 'humhub\modules\space\models\Space'])
</code>```

Not sure this is right and I am stuck setting up the contentcontainer relationship in the Post model.

答:
Here''s how I solved this (results are pulled from Content model, not Post model):</p>

```<code>    $content = Content::find()
     ->joinWith('contentContainer')
     ->andWhere(['{{contentcontainer}}.pk' => $space_id])
     ->andWhere(['{{contentcontainer}}.class' => 'humhub\modules\space\models\Space'])
     ->andWhere(['{{content}}.object_model' => 'humhub\modules\post\models\Post'])
     ->asArray()
     ->all();
</code>```

Title: Yii2 query for posts in a space

Body:
I had a DB with a post table, a content table, and a space table.

A post is a type of content, and a space is a container for many posts. I want to get all posts within a space.

Post:

id   object_id
--------------
1    22

Content (object_id --> post.id):

id   space_id
------------------------
22   3

Space (id --> content.space_id):

id
--------------
3

To get posts within a space, the controller function looked like this:

$posts = Post::find()
  ->joinWith('content', false)
  ->where(['{{content}}.space_id' => $space_id])
  ->all();

And the Post model had this function to get the content object for a post:

public function getContent() {
   return $this->hasOne(Content::className(), ['object_id' => 'id'])->andOnCondition(['{{content}}.object_model' => 'humhub\modules\post\models\Post']);
}

This worked perfectly until the database schema changed.

Now there is no longer a space_id column in the content table. Instead, there is a new table contentcontainer with a pk field which replaces space_id, and a class field (i.e. space class) to identify that the PK is for a space( there is also a class in the table).

The tables/relationships are now:

Post Table:

id   object_id
--------------
1    22

Content table (object_id --> post.id):

id   contentcontainer_id
------------------------
22   5

Contentcontainer Table (id --> content.contentcontainer_id)

id   pk   class
---------------
5    3    //Space

Space (id --> contentcontainer):

id
--------------
3

To get all posts within a space, I now have to link 3 tables: post,content,contentcontainer.

Do I add the contentcontainer relationship to the Post model? Or modify the content model relationship in the Post model? Not sure how best to tackle without writing a big sloppy query.

I changed the controller function to this:

$posts = Post::find()
  ->where(['{{contentcontainer}}.pk' => $space_id])
  ->andWhere(['{{contentcontainer}}.class' => 'humhub\modules\space\models\Space'])

Not sure this is right and I am stuck setting up the contentcontainer relationship in the Post model.

Body:
Here''s how I solved this (results are pulled from Content model, not Post model):

    $content = Content::find()
     ->joinWith('contentContainer')
     ->andWhere(['{{contentcontainer}}.pk' => $space_id])
     ->andWhere(['{{contentcontainer}}.class' => 'humhub\modules\space\models\Space'])
     ->andWhere(['{{content}}.object_model' => 'humhub\modules\post\models\Post'])
     ->asArray()
     ->all();


问:
replace the menu and stick it to top on scroll
I want to replace my navigation menu by another one on scroll and stick the new one on the top of the page.

For the sticky menu part I used this JavaScript code :

```<code> // Create a clone of the menu, right next to original.
$('.panel_menu').addClass('original').clone().insertAfter('.panel_menu').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeClass('original').hide();

scrollIntervalID = setInterval(stickIt, 10);

function stickIt() {

  var orgElementPos = $('.original').offset();
  orgElementTop = orgElementPos.top;

  if ($(window).scrollTop() >= (orgElementTop)) {

    // scrolled past the original position; now only show the cloned, sticky element.

    // Cloned element should always have same left position and width as original element.
    orgElement = $('.original');
    coordsOrgElement = orgElement.offset();
    leftOrgElement = coordsOrgElement.left;
    widthOrgElement = orgElement.css('width');
    $('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement).show();
    $('.original').css('visibility','hidden');
    $(".cloned").css('background-color', '#2f3a54');

  } else {
    // not scrolled past the menu; only show the original menu.
    $('.cloned').hide();

    $('.original').css('visibility','visible');
  }
};
</code>```

but I don't know how to perform the replacement part.. thank you

Edit  (Answer) :
So I slightly modified the answer of KLAJDI and here is the code :

```<code>$(function(){
     // Check the initial Poistion of the Sticky Header
     var stickyHeaderTop = $('.panel_menu').offset().top;

     $(window).scroll(function(){
             if( $(window).scrollTop() > stickyHeaderTop ) {
                     orgElement = $('.panel_menu');
                     widthOrgElement = orgElement.css('width');
                     $('.panel_menu_clone').css({position: 'fixed', top: '0px'});
                     $('.panel_menu_clone').css('width',widthOrgElement).show();
                     $(".panel_menu_clone").css('background-color', '#2f3a54');
             } else {
                     $('.panel_menu').show();
                     $('.panel_menu_clone').css('display', 'none');
             }
     });
});
</code>```

答:
You mean sth like this:

$(function(){
        // Check the initial Poistion of the Sticky Header
        var stickyHeaderTop = $('#stickyheader').offset().top;

        $(window).scroll(function(){
                if( $(window).scrollTop() > stickyHeaderTop ) {
                        $('#stickyheader').css({position: 'fixed', top: '0px'});
                        $('#stickyalias').css('display', 'block');
                } else {
                        $('#stickyheader').css({position: 'static', top: '0px'});
                        $('#stickyalias').css('display', 'none');
                }
        });
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>        table { background: black; color: white;}
                body, td {
                        font: 13px sans-serif;
                }
                #stickyheader {
                        width: 100%;
                        height: 10px;
                }
                #stickyalias {
                  display: none;
                  height: 10px;
                }
                #unstickyheader {
                  margin-bottom: 15px;
                }
                #othercontent {
                  margin-top: 20px;
                }</code>```

This is some text that comes before our Sticky
    Header

        Sticky Text 1

        Sticky Text 2

        Sticky Text 3

        Sticky Text 4

        Sticky Text 5

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

Content Here

```

Body:
I want to replace my navigation menu by another one on scroll and stick the new one on the top of the page.

For the sticky menu part I used this JavaScript code :

 // Create a clone of the menu, right next to original.
$('.panel_menu').addClass('original').clone().insertAfter('.panel_menu').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeClass('original').hide();

scrollIntervalID = setInterval(stickIt, 10);

function stickIt() {

  var orgElementPos = $('.original').offset();
  orgElementTop = orgElementPos.top;

  if ($(window).scrollTop() >= (orgElementTop)) {

    // scrolled past the original position; now only show the cloned, sticky element.

    // Cloned element should always have same left position and width as original element.
    orgElement = $('.original');
    coordsOrgElement = orgElement.offset();
    leftOrgElement = coordsOrgElement.left;
    widthOrgElement = orgElement.css('width');
    $('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement).show();
    $('.original').css('visibility','hidden');
    $(".cloned").css('background-color', '#2f3a54');

  } else {
    // not scrolled past the menu; only show the original menu.
    $('.cloned').hide();

    $('.original').css('visibility','visible');
  }
};

but I don't know how to perform the replacement part.. thank you

Edit  (Answer) :
So I slightly modified the answer of KLAJDI and here is the code :

$(function(){
     // Check the initial Poistion of the Sticky Header
     var stickyHeaderTop = $('.panel_menu').offset().top;

     $(window).scroll(function(){
             if( $(window).scrollTop() > stickyHeaderTop ) {
                     orgElement = $('.panel_menu');
                     widthOrgElement = orgElement.css('width');
                     $('.panel_menu_clone').css({position: 'fixed', top: '0px'});
                     $('.panel_menu_clone').css('width',widthOrgElement).show();
                     $(".panel_menu_clone").css('background-color', '#2f3a54');
             } else {
                     $('.panel_menu').show();
                     $('.panel_menu_clone').css('display', 'none');
             }
     });
});

Body:
You mean sth like this:

$(function(){
        // Check the initial Poistion of the Sticky Header
        var stickyHeaderTop = $('#stickyheader').offset().top;

        $(window).scroll(function(){
                if( $(window).scrollTop() > stickyHeaderTop ) {
                        $('#stickyheader').css({position: 'fixed', top: '0px'});
                        $('#stickyalias').css('display', 'block');
                } else {
                        $('#stickyheader').css({position: 'static', top: '0px'});
                        $('#stickyalias').css('display', 'none');
                }
        });
  });

        table { background: black; color: white;}
                body, td {
                        font: 13px sans-serif;
                }
                #stickyheader {
                        width: 100%;
                        height: 10px;
                }
                #stickyalias {
                  display: none;
                  height: 10px;
                }
                #unstickyheader {
                  margin-bottom: 15px;
                }
                #othercontent {
                  margin-top: 20px;
                }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="unstickyheader">
    <p>This is some text that comes before our <strong>Sticky
    Header</strong></p>
  </div>

  <div id="stickyheader">
    <table width="100%">
      <tr>
        <td>Sticky Text 1</td>

        <td>Sticky Text 2</td>

        <td>Sticky Text 3</td>

        <td>Sticky Text 4</td>

        <td>Sticky Text 5</td>
      </tr>
    </table>
  </div>

  <div id="stickyalias"></div>

  <div id="othercontent">
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
    <p>Content Here<p>
  </div>


问:
Package Manager Console Automation using DTE in Visual Studio
I am trying to automate the Package Manager Console window in Visual Studio 2012. I am DTE object to achieve the same. By using below code line I am able to open the Package Manager Console window.

DTE.ExecuteCommand("View.PackageManagerConsole");

Now I want to pass few parameter to this window. Basically below parameter
 I want to pass

add-migration 'migrationName'

I also want to pass the default project name to the PMC window.

Please help me to achieve this functionality.

Thanks!

答:
The best way for running a script in package manager console is parameter passing into it.</p>

```<code>var script = "function global:SaveAll {write-host \"All files saved.\"} SaveAll";
_ObjDTE.ExecuteCommand("View.PackageManagerConsole", script);
</code>```

Body:
The best way for running a script in package manager console is parameter passing into it.

var script = "function global:SaveAll {write-host \"All files saved.\"} SaveAll";
_ObjDTE.ExecuteCommand("View.PackageManagerConsole", script);


问:
is it possible to create object for interface without implementing this by any of the classes in java?
Itest is an Interface. here i mentioned like new Itest(). Then is it means that i can create object for interface?

```<code>public interface Itest {

}
static final Itest s = new Itest(){
};
</code>```

It is just like, we could create object for interface without any class implement the interface.

答:
```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    interface ISampleInterface
    {
        void SampleMethod();
    }

    class ImplementationClass : ISampleInterface
    {
        // Explicit interface member implementation:
       public void SampleMethod()
        {
            // Method implementation.
            Console.Write("Interface implements");
        }

        static void Main(string[] args)
        {
            // Declare an interface instance.
            ISampleInterface obj = new ImplementationClass();

            // Call the member.
            obj.SampleMethod();
            ImplementationClass a = new ImplementationClass();
            a.SampleMethod();
            ISampleInterface b = (ISampleInterface)a;
        }
    }
}
</code>```

Body:
Itest is an Interface. here i mentioned like new Itest(). Then is it means that i can create object for interface?

public interface Itest {

}
static final Itest s = new Itest(){
};

It is just like, we could create object for interface without any class implement the interface.


问:
How do I load bootstrap using npm?
I have a npm project that uses jquery.

var $ = require('jquery');

I also have an index html file that references bootstrap.

```<code><link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet"/>

<script type="text/javascript" src="my-script.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
</code>```

Now do I need to a separate load for jquery for bootstrap as it depends on it?  I was recently using jqueryify instead of jquery and I did not need the separate load.

Can anyone recommend a loading pattern for bootstrap with use with require?

答:
```<code>yarn add bootstrap-sass
yarn add jquery
</code>```

For style, I use gulp sass which need to include Paths for bootstrap

```<code>@import "bootstrap-sprockets";
@import "bootstrap";

var sass = require('gulp-sass');

pipe(sass({includePaths: ['node_modules/bootstrap-sass/assets/stylesheets']}).on('error', sass.logError))
</code>```

For JavaScript, I assign jquery to window.jQuery as bootstrap-sass needed:

```<code>window.jQuery = require('jquery');
require('bootstrap-sass');
</code>```

Title: How do I load bootstrap using npm?

Body:
I have a npm project that uses jquery.

var $ = require('jquery');

I also have an index html file that references bootstrap.

<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet"/>

Now do I need to a separate load for jquery for bootstrap as it depends on it?  I was recently using jqueryify instead of jquery and I did not need the separate load.

Can anyone recommend a loading pattern for bootstrap with use with require?

Body:
yarn add bootstrap-sass
yarn add jquery

For style, I use gulp sass which need to include Paths for bootstrap

@import "bootstrap-sprockets";
@import "bootstrap";

var sass = require('gulp-sass');

pipe(sass({includePaths: ['node_modules/bootstrap-sass/assets/stylesheets']}).on('error', sass.logError))

For JavaScript, I assign jquery to window.jQuery as bootstrap-sass needed:

window.jQuery = require('jquery');
require('bootstrap-sass');


问:
CSS: Set background-size: cover property to cover div instead of whole screen
I understand that the background-size: cover property in CSS makes the background image as large as possible so that it covers the entire screen. However, because this can distort the image on larger screens, I want to be able to make the background image cover the width and height of the div container that it's in, rather than the width of the whole screen. I'm not sure how to do this. Even when placing my image inside a div in my HTML, the background-size: cover property still expands the image to the whole screen.

My CSS is:

```<code>.main {
  height: 30vh;
  text-align: center;
  background: url("https://i.imgur.com/6FYizew.jpg");
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover
}
</code>```

My HTML is:

```<code><div class = "container" style = "padding-top: 5vh">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#myCarousel" data-slide-to="0" class = "active hidden-xs"></li>
  </ol>
  <div class="carousel-inner">
<div class="item main active">
    <div class = "hidden-xs" style = "width: 80%; max-width: 1200px; margin: auto; position: relative; top: 15%; padding-top: 30px; padding-bottom: 40px; background-color: rgba(255, 255, 255, 0.8);">
        <h1 class = "hidden-xs" style = "font-size: 5em; font-weight: normal; color: #0b3c5d; font-weight: bold">TITLE</h1>
        <hr class = "intro-divider hidden-xs" style = "width: 550px; background-color: #232f3f">
        <h4 class = "hidden-xs" style = "margin-top: 15px; font-size: 1.5em; color: #232f3f"><em>SUBTITLE</em></h4>
    </div>
</div>
</code>```

Please let me know how I can set cover to cover just a container instead of the entire screen. Thanks!

答:
you didn't set width... add width size and it will only cover .main div

if you didn't set width in div then it's use auto width property which means your div cover whole  remaining place ...currently your main div cover whole pages that is why you see background image on whole page

Body:
I understand that the background-size: cover property in CSS makes the background image as large as possible so that it covers the entire screen. However, because this can distort the image on larger screens, I want to be able to make the background image cover the width and height of the div container that it's in, rather than the width of the whole screen. I'm not sure how to do this. Even when placing my image inside a div in my HTML, the background-size: cover property still expands the image to the whole screen.

My CSS is:

.main {
  height: 30vh;
  text-align: center;
  background: url("https://i.imgur.com/6FYizew.jpg");
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover
}

My HTML is:

TITLE

SUBTITLE

Please let me know how I can set cover to cover just a container instead of the entire screen. Thanks!


问:
How to not run an example using roxygen2?
I'm writing a geocoding function right now that relies on having a Bing Maps Key.  Obviously I'd rather not publish mine, and the examples fail without one.

How do I include an example for users to run manually, but not have it executed during R CMD check?

答:
You can use \donttest{} to your example. The snippet will be provided in your documentation, but won't get tested with the R CMD Check.

For more info --> ?example

```<code>#' @example
\donttest{
    2^2
    }
</code>```

This 2^2 won't get run when you run devtools::check()

EDIT

Per the latest release notes or NEWS for R 4.0.0, examples within \donttest{} will now be tested by default. This can, however, be overridden by setting environment variable _R_CHECK_DONTTEST_EXAMPLES_ to FALSE.

R CMD check --as-cran now runs \donttest examples (which are run by example()) instead of instructing the tester to do so. This can be temporarily circumvented during development by setting environment variable R_CHECK_DONTTEST_EXAMPLES to a false value.

According to this GitHub issues discussion (credited here), Hadley Wickham noted that

Generally, now if you don't want to run tests on CRAN \dontrun{} is more likely to work, but using \dontrun{} may cause initial submission to fail.

There are other ways as well that will let you continue to use donttest{}, refer the aforementioned discussions for the workarounds.

Body:
You can use \donttest{} to your example. The snippet will be provided in your documentation, but won't get tested with the R CMD Check.

For more info --> ?example

#' @example
\donttest{
    2^2
    }

This 2^2 won't get run when you run devtools::check()

EDIT

Per the latest release notes or NEWS for R 4.0.0, examples within \donttest{} will now be tested by default. This can, however, be overridden by setting environment variable _R_CHECK_DONTTEST_EXAMPLES_ to FALSE.

R CMD check --as-cran now runs \donttest examples (which are run by example()) instead of instructing the tester to do so. This can be temporarily circumvented during development by setting environment variable R_CHECK_DONTTEST_EXAMPLES to a false value.

According to this GitHub issues discussion (credited here), Hadley Wickham noted that

Generally, now if you don't want to run tests on CRAN \dontrun{} is more likely to work, but using \dontrun{} may cause initial submission to fail.

There are other ways as well that will let you continue to use donttest{}, refer the aforementioned discussions for the workarounds.


问:
How to compare today date is greater than or equals to another
compare 2 dates
if (from_date >= today && totime < = today)
 i tried with this</p>

```<code>NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
NSString * TodayDate = [dateFormatter stringFromDate:[NSDate date]];

if ([displayList.fromTime compare:TodayDate] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");

} else if ([displayList.toTime compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");

} else {
    NSLog(@"dates are the same");

}
</code>```

答:
You're not saying what class of object fromDate is, but since you're comparing it to TodayDate, which is a string, I'm assuming all of your dates are strings when you compare them? If so, that's a bad choice. Date comparison and string comparison are not the same and will yield different results.

Instead of turning today's date into a string, you should turn fromDate into an NSDate, and then compare those.

If, OTOH, fromDate is not a string, then that's your error. Just because two objects result in the same text being NSLogged doesn't mean they're the same type and can be compared, so make sure they're all the same type (NSDate) and then compare those.

Body:
compare 2 dates
if (from_date >= today && totime < = today)
 i tried with this

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
NSString * TodayDate = [dateFormatter stringFromDate:[NSDate date]];

if ([displayList.fromTime compare:TodayDate] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");

} else if ([displayList.toTime compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");

} else {
    NSLog(@"dates are the same");

}


问:
how to remove all characters except for those enclosed by parentheses
Suppose you have a text file like this below

```<code>I have apples, bananas, ( some pineapples over 4 ), and cherries ( coconuts with happy face :D ) and so on. You may help yourself except for cherries ( they are for my parents sorry ;C ) . I feel like I can run a fruit business.
</code>```

What I aim to do is to erase all characters except for those enclosed by parentheses. Please keep in mind that the characters in a pair of parentheses can be varied ranging from English to other characters but no other punctuations may play a role as enclosing characters: only parentheses can be allowed to do.

I think I should utilize gsub but not sure.

This is what I want to have as a result.

```<code>( some pineapples over 4 ) ( coconuts with happy face :D ) ( they are for my parents sorry ;C )
</code>```

Whether using a way of removing or extracting, I hope to get the result above.

答:
We can do this by extracting the substring within the brackets and paste it together

```<code>library(stringr)
paste(str_extract_all(str1, "\\([^)]*\\)")[[1]], collapse=' ')
#[1] "( some pineapples over 4 ) ( coconuts with happy face :D ) ( they are for my parents sorry ;C )"
</code>```

Or we can use a gsub based solution

```<code>trimws(gsub("\\s+\\([^)]*\\)(*SKIP)(*FAIL)|.", "", str1, perl = TRUE))
#[1] "( some pineapples over 4 ) ( coconuts with happy face :D ) ( they are for my parents sorry ;C )"
</code>```

data

```<code>str1 <- "I have apples, bananas, ( some pineapples over 4 ), and cherries ( coconuts with happy face :D ) and so on. You may help yourself except for cherries ( they are for my parents sorry ;C ) . I feel like I can run a fruit business."
</code>```

Body:
Suppose you have a text file like this below

I have apples, bananas, ( some pineapples over 4 ), and cherries ( coconuts with happy face :D ) and so on. You may help yourself except for cherries ( they are for my parents sorry ;C ) . I feel like I can run a fruit business.

What I aim to do is to erase all characters except for those enclosed by parentheses. Please keep in mind that the characters in a pair of parentheses can be varied ranging from English to other characters but no other punctuations may play a role as enclosing characters: only parentheses can be allowed to do.

I think I should utilize gsub but not sure.

This is what I want to have as a result.

( some pineapples over 4 ) ( coconuts with happy face :D ) ( they are for my parents sorry ;C )

Whether using a way of removing or extracting, I hope to get the result above.

Body:
We can do this by extracting the substring within the brackets and paste it together

library(stringr)
paste(str_extract_all(str1, "\\([^)]*\\)")[[1]], collapse=' ')
#[1] "( some pineapples over 4 ) ( coconuts with happy face :D ) ( they are for my parents sorry ;C )"

Or we can use a gsub based solution

trimws(gsub("\\s+\\([^)]*\\)(*SKIP)(*FAIL)|.", "", str1, perl = TRUE))
#[1] "( some pineapples over 4 ) ( coconuts with happy face :D ) ( they are for my parents sorry ;C )"

data

str1 <- "I have apples, bananas, ( some pineapples over 4 ), and cherries ( coconuts with happy face :D ) and so on. You may help yourself except for cherries ( they are for my parents sorry ;C ) . I feel like I can run a fruit business."