问:
Is there memory area called 'stack' in C++ to store automatic variables
Is there a specific area in memory called stack in C++ where automatic variables are getting stored.</p>

答:
This question seems to have generated a debate about whether the correct answer is what is defined by the standard, or what is actually done in most if not all implementations. Rather than continuing to snipe with comments, let me give a long answer.

A simple analogy: Suppose that you were trying to teach someone beginning geography. At one point the student asks, "Is France in Europe?" What would you consider the correct answer to such a question?

(a) No. The French Constitution does not specify the borders of the country. Therefore, it is impossible to say where France is.

(b) No. It is possible that someday in the future the Earth will be destroyed and French refugees will settle on another planet and reconstitute their nation there. Or there may be alternative universes in which France is located in a different place. Therefore, we cannot say where France is.

(c) Yes. France is in Europe.

(d) Basically yes. The central government and the bulk of the population of France is in Europe, though they do control territories elsewhere, like French Guiana in South America and Reunion Island in the Indian Ocean.

I would give answer (c) if the question was being asked in a general way or by a beginning student, or (d) if the context indicated that a more precise answer was called for. Apparently some of the posters here insist that the correct answer is (a) or (b). They say that it is literally WRONG to look at the world as it actually is, and that the only correct answer to a question is to look for some document that describes the world as some authority declares it ought to be.

If you think this analogy is strained and you want a more purely IT discussion, let me offer a closer analogy. Suppose you are teaching a class on web design and a student asks, "How can I express complex mathematical formulas in a web page?"

Would you say that the correct answer is, "Use the <MATH> tag, and it's associated tags like ABOVE and BELOW and ROOT and ARRAY, as defined in the HTML 3.2 standard."

Such an answer would be absolutely true in the sense that the HTML 3.2 standard does include such tags. Unfortunately, no major browser implements these tags. The fact that it is in a standard is not of much practical use.

I could say the same about many features of IT products. "How do I limit the number of rows of output from a SQL query?" The real answer depends on which database engine you are using. Off the top of my head I don't know what the SQL standard says, if it provides any means at all, and I don't care, because it doesn't matter. In real life I do not run the ANSI SQL standard on my database server, I run Postgres or Oracle or MySQL or some other actual product.

I'm not saying that standards don't matter in general. OF COURSE we should have good standards, and products should comply with them to the maximum extent possible. But in the real world, what ultimately matters is implementation.

To insist that it doesn't matter how the computer ACTUALLY works in real life, but that we can ONLY consider how someone said he thought it should work, is not useful to someone trying to write programs that run on real computers.

(Yes, there is a practical case to be made for writing programs that will work with any standards-compliant compiler, if you're interested in cross-platform compatibility and upwards compatibility. We could certainly debate the wisdom of using tricks that depend on a specific implementation: when is performance or coding convenience outweighed by the fragility of a non-standard implementation?)

Frankly, I think this sort of answer is a pedantry that just confuses the beginning student. When the beginning student asks what continent France is on, he doesn't want or need a long string of hypotheticals, theoreticals, and special cases. He needs a simple and direct answer. Same thing with when he asks, "Are my function variables stored on a stack?" or "Is my program loaded into RAM at run time?"


来源: stackexchange

问:
daemonic processes are not allowed to have children
I know it's a common question, and related question like this, but I want to ask for best way to fit my scenario because I haven't used celery now.

My service scenario will use multiprocessing.Process to create multi-campaign order, in each campaign order, it still use multiprocessing.Process to create multi-ad (campaign and ad are 1toM relationship).

As you know, if I set multi-process on both campaign and ad creation part, it will fail with "daemonic processes are not allowed to have children", I think celery may meet similar problem even though I haven't used it now.

My question is, what is the general way to solve this kind of problem? should I use celery still, or any way to work around it?

Thanks a lot

答:
1. General Good Workaround

You should use a message queue to decouple

For example,

main program, create task , push to queue_1

multi-campaign worker get task from queue_1, process,  and push some multi-ad task to queue_2

multi-ad worker get task from queue_2 , process ,  done.

The logic is simple, easy to implement by yourself. Also there are some existing libs for such stuff, such as  rq/celery.

2. Simple Workaround

If get AssertionError , use thread instead

```<code>def run_in_subprocess(func, *args, **kwargs):
    from multiprocessing import Process
    thread = Process(target=func, args=args, kwargs=kwargs)
    thread.daemon = True
    thread.start()
    return thread

def run_in_thread(func, *args, **kwargs):
    from threading import Thread
    thread = Thread(target=func, args=args, kwargs=kwargs)
    thread.daemon = True
    thread.start()
    return thread

def run_task(config):
    try:
        run_in_subprocess(xxxx_task, config)
    except AssertionError:
        print('daemonic processes are not allowed to have children, use thread')
        run_in_thread(xxxx_task, config)
</code>```

I use this code in some demo app, but I don't recommend use in production.

ContentLicense: CC BY-SA 3.0

Body:
1. General Good Workaround

You should use a message queue to decouple

For example,

main program, create task , push to queue_1

multi-campaign worker get task from queue_1, process,  and push some multi-ad task to queue_2

multi-ad worker get task from queue_2 , process ,  done.

The logic is simple, easy to implement by yourself. Also there are some existing libs for such stuff, such as  rq/celery.

2. Simple Workaround

If get AssertionError , use thread instead

def run_in_subprocess(func, *args, **kwargs):
    from multiprocessing import Process
    thread = Process(target=func, args=args, kwargs=kwargs)
    thread.daemon = True
    thread.start()
    return thread

def run_in_thread(func, *args, **kwargs):
    from threading import Thread
    thread = Thread(target=func, args=args, kwargs=kwargs)
    thread.daemon = True
    thread.start()
    return thread

def run_task(config):
    try:
        run_in_subprocess(xxxx_task, config)
    except AssertionError:
        print('daemonic processes are not allowed to have children, use thread')
        run_in_thread(xxxx_task, config)

I use this code in some demo app, but I don't recommend use in production.


问:
Twitter login page comes up even though user denies to give access to Twitter from App
When I am trying to login to my App in iOS 11 using Twitter, sometimes I am getting an alertview-style popup saying “ wants to open twitter”, with the options "cancel" and "open". If I tap on "open", it is the normal login flow for twitter.

However, if I tap on cancel, then what I want is for the whole login attempt to be cancelled. Instead, the app redirects me to the webview which opens twitter login page and again I need to cancel that dismiss the page saying “Error during login”. Could anyone able to simulate it?

答: Looks like it might be related to a known issue that Twitter is trying to fix? See https://twittercommunity.com/t/bug-twitter-kit-ios-3-0-4-login-sometimes-fails-to-redirect-back-to-host-app/89618/24</p>


问:
How can I automatically update data in pyqtgraph?
I'm trying to plot candlesticks. I referred to this question and answer( The fastest way to add a new data bar with pyqtgraph )

I want my program to update and plot new candlesticks by receiving new values from a server, through calling update().

A problem that I have is that this example doesn't work without using QtCore.QTimer(). For example, if I manually call update() on the prompt or by apscheduler, candlesticks show no difference, but once I select the plot window, it shows new candlesticks at the same time. I don't understand why this happens.

Could anyone try testing this and tell me how to fix this problem?

```<code>import pyqtgraph as pg
from pyqtgraph import QtCore, QtGui
import random
import numpy as np
from apscheduler.schedulers.background import BackgroundScheduler

class CandlestickItem(pg.GraphicsObject):
    def __init__(self):
        pg.GraphicsObject.__init__(self)
        self.flagHasData = False

    def set_data(self, data):
        self.data = data
        self.flagHasData = True
        self.generatePicture()
        self.informViewBoundsChanged()

    def generatePicture(self):
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen('w'))
        w = (self.data[1][0] - self.data[0][0]) / 3.
        for (t, open, close, min, max) in self.data:
            p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
            if open > close:
                p.setBrush(pg.mkBrush('r'))
            else:
                p.setBrush(pg.mkBrush('g'))
            p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
        p.end()

    def paint(self, p, *args):
        if self.flagHasData:
            p.drawPicture(0, 0, self.picture)

    def boundingRect(self):
        return QtCore.QRectF(self.picture.boundingRect())

app = QtGui.QApplication([])

data = [
    [1., 10, 13, 5, 15],
    [2., 13, 17, 9, 20],
    [3., 17, 14, 11, 23],
    [4., 14, 15, 5, 19],
    [5., 15, 9, 8, 22],
    [6., 9, 15, 8, 16],
]
item = CandlestickItem()
item.set_data(data)

plt = pg.plot()
plt.addItem(item)
plt.setWindowTitle('pyqtgraph example: customGraphicsItem')

def update():
    global item, data
    data_len = len(data)
    rand = random.randint(0, len(data)-1)
    new_bar = data[rand][:]
    new_bar[0] = data_len
    data.append(new_bar)
    item.set_data(data)
    app.processEvents()

## DOESN'T SHOW NEW CANDLESTICKS UNLESS YOU SELECT THE PLOT WINDOW
#sched = BackgroundScheduler()
#sched.start()
#sched.add_job(update, trigger='cron', second='*/1')

## WORKS FINE WITH THIS PARAGRAPH.
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(1000)

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
</code>```

答:
Many times non-native elements for Qt generate that behavior, Qt is a framework that has libraries for many tasks like the ones you want to do, a Qt-style solution would be to use QThreads and in that case we would use signals to update the data, but another solution but it is simple to use QRunnable and QThreadPool as I show below:</p>

```<code>class PlotRunnable(QtCore.QRunnable):
    def __init__(self, it):
        QtCore.QRunnable.__init__(self)
        self.it = it

    def run(self):
        while True:
            data = self.it.data
            data_len = len(data)
            rand = random.randint(0, len(data)-1)
            new_bar = data[rand][:]
            new_bar[0] = data_len
            data.append(new_bar)

            QtCore.QMetaObject.invokeMethod(self.it, "set_data",
                                     QtCore.Qt.QueuedConnection,
                                     QtCore.Q_ARG(list, data))
            QtCore.QThread.msleep(1000)

class CandlestickItem(pg.GraphicsObject):
    def __init__(self):
        pg.GraphicsObject.__init__(self)
        self.flagHasData = False

    @QtCore.pyqtSlot(list)
    def set_data(self, data):
        self.data = data
        self.flagHasData = True
        self.generatePicture()
        self.informViewBoundsChanged()

    def generatePicture(self):
        [...]

app = QtGui.QApplication([])

data = [
    [1., 10, 13, 5, 15],
    [2., 13, 17, 9, 20],
    [3., 17, 14, 11, 23],
    [4., 14, 15, 5, 19],
    [5., 15, 9, 8, 22],
    [6., 9, 15, 8, 16],
]
item = CandlestickItem()
item.set_data(data)

plt = pg.plot()
plt.addItem(item)
plt.setWindowTitle('pyqtgraph example: customGraphicsItem')

runnable = PlotRunnable(item)
QtCore.QThreadPool.globalInstance().start(runnable)

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
</code>```

Body:
I'm trying to plot candlesticks. I referred to this question and answer( The fastest way to add a new data bar with pyqtgraph )

I want my program to update and plot new candlesticks by receiving new values from a server, through calling update().

A problem that I have is that this example doesn't work without using QtCore.QTimer(). For example, if I manually call update() on the prompt or by apscheduler, candlesticks show no difference, but once I select the plot window, it shows new candlesticks at the same time. I don't understand why this happens.

Could anyone try testing this and tell me how to fix this problem?

import pyqtgraph as pg
from pyqtgraph import QtCore, QtGui
import random
import numpy as np
from apscheduler.schedulers.background import BackgroundScheduler

class CandlestickItem(pg.GraphicsObject):
    def __init__(self):
        pg.GraphicsObject.__init__(self)
        self.flagHasData = False

    def set_data(self, data):
        self.data = data
        self.flagHasData = True
        self.generatePicture()
        self.informViewBoundsChanged()

    def generatePicture(self):
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen('w'))
        w = (self.data[1][0] - self.data[0][0]) / 3.
        for (t, open, close, min, max) in self.data:
            p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
            if open > close:
                p.setBrush(pg.mkBrush('r'))
            else:
                p.setBrush(pg.mkBrush('g'))
            p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
        p.end()

    def paint(self, p, *args):
        if self.flagHasData:
            p.drawPicture(0, 0, self.picture)

    def boundingRect(self):
        return QtCore.QRectF(self.picture.boundingRect())

app = QtGui.QApplication([])

data = [
    [1., 10, 13, 5, 15],
    [2., 13, 17, 9, 20],
    [3., 17, 14, 11, 23],
    [4., 14, 15, 5, 19],
    [5., 15, 9, 8, 22],
    [6., 9, 15, 8, 16],
]
item = CandlestickItem()
item.set_data(data)

plt = pg.plot()
plt.addItem(item)
plt.setWindowTitle('pyqtgraph example: customGraphicsItem')

def update():
    global item, data
    data_len = len(data)
    rand = random.randint(0, len(data)-1)
    new_bar = data[rand][:]
    new_bar[0] = data_len
    data.append(new_bar)
    item.set_data(data)
    app.processEvents()

## DOESN'T SHOW NEW CANDLESTICKS UNLESS YOU SELECT THE PLOT WINDOW
#sched = BackgroundScheduler()
#sched.start()
#sched.add_job(update, trigger='cron', second='*/1')

## WORKS FINE WITH THIS PARAGRAPH.
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(1000)

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

Body:
Many times non-native elements for Qt generate that behavior, Qt is a framework that has libraries for many tasks like the ones you want to do, a Qt-style solution would be to use QThreads and in that case we would use signals to update the data, but another solution but it is simple to use QRunnable and QThreadPool as I show below:

class PlotRunnable(QtCore.QRunnable):
    def __init__(self, it):
        QtCore.QRunnable.__init__(self)
        self.it = it

    def run(self):
        while True:
            data = self.it.data
            data_len = len(data)
            rand = random.randint(0, len(data)-1)
            new_bar = data[rand][:]
            new_bar[0] = data_len
            data.append(new_bar)

            QtCore.QMetaObject.invokeMethod(self.it, "set_data",
                                     QtCore.Qt.QueuedConnection,
                                     QtCore.Q_ARG(list, data))
            QtCore.QThread.msleep(1000)

class CandlestickItem(pg.GraphicsObject):
    def __init__(self):
        pg.GraphicsObject.__init__(self)
        self.flagHasData = False

    @QtCore.pyqtSlot(list)
    def set_data(self, data):
        self.data = data
        self.flagHasData = True
        self.generatePicture()
        self.informViewBoundsChanged()

    def generatePicture(self):
        [...]

app = QtGui.QApplication([])

data = [
    [1., 10, 13, 5, 15],
    [2., 13, 17, 9, 20],
    [3., 17, 14, 11, 23],
    [4., 14, 15, 5, 19],
    [5., 15, 9, 8, 22],
    [6., 9, 15, 8, 16],
]
item = CandlestickItem()
item.set_data(data)

plt = pg.plot()
plt.addItem(item)
plt.setWindowTitle('pyqtgraph example: customGraphicsItem')

runnable = PlotRunnable(item)
QtCore.QThreadPool.globalInstance().start(runnable)

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()


问:
How to exit while loop on certain condition and exception handling for invalid values
This is homework, so I'm just looking for some guidance. I have my code working to return a value in an array[10] based on an index value given by the user.

What isn't working is that I need to stop the program when "99" is entered, a value that also triggers the try-catch IndexOutOfRangeException. I can't get the program to recognize the difference between "99" and any other out of range value. I did try it with an if-else, but "99" still threw the IndexOutOfRangeException and it wouldn't loop. An attempt at do-while also didn't work.

Code is below. Thanks in advance.

```<code>using System;
using static System.Console;

class SubscriptExceptionTest
{
static void Main()
{
    double[] array = {20.3, 44.6, 32.5, 46.7, 89.6, 67.5, 12.3, 14.6, 22.1, 13.6};

    int i = 0;

    while (i != 99)
        try
        {

            Write("Enter a number to see the value in that position. Type 99 to stop: ");
            i = Convert.ToInt32(ReadLine());

            double arrayVal = array[i];
            WriteLine("The value at index {0} is {1}", i, arrayVal);
            ReadLine();
        }
        catch (FormatException fe)
        {
            throw new FormatException("You did not enter an integer.");
        }
        catch (IndexOutOfRangeException ie)
        {
            throw new IndexOutOfRangeException("Index was outside the bounds of the array.");
        }
        catch (Exception ex)
        {
            throw new Exception("Error: " + ex.Message);
        }
    }
}
</code>```

答:
As a rule, Try/Catch's and Exception Handlers should only be used Exceptionally. They are expensive. Let me show you how to handle these issues using defensive programming.

I think using the Array.Length to check the Array Bounds if any other out of range value is the answer you want.

```<code>static void Main()
{
double[] array = {20.3, 44.6, 32.5, 46.7, 89.6,67.5, 12.3, 14.6, 22.1, 13.6};

int i = 0;

while (i != 99)
{
        Write("Enter a number to see the value in that position. Type 99 to stop: ");

        var result = ReadLine();

        bool isInteger = int.TryParse(result, out i);

        if (isInteger == false) throw new FormatException("You did not enter an integer.");

        if (i == 99) Environment.Exit(0);

        if (i < 0 || i > array.Length) throw new IndexOutOfRangeException("Index was outside the bounds of the array.");

        double arrayVal = array[i];

        WriteLine("The value at index {0} is {1}", i, arrayVal);

        ReadLine();
}
</code>```

Body:
This is homework, so I'm just looking for some guidance. I have my code working to return a value in an array[10] based on an index value given by the user.

What isn't working is that I need to stop the program when "99" is entered, a value that also triggers the try-catch IndexOutOfRangeException. I can't get the program to recognize the difference between "99" and any other out of range value. I did try it with an if-else, but "99" still threw the IndexOutOfRangeException and it wouldn't loop. An attempt at do-while also didn't work.

Code is below. Thanks in advance.

using System;
using static System.Console;

class SubscriptExceptionTest
{
static void Main()
{
    double[] array = {20.3, 44.6, 32.5, 46.7, 89.6, 67.5, 12.3, 14.6, 22.1, 13.6};

    int i = 0;

    while (i != 99)
        try
        {

            Write("Enter a number to see the value in that position. Type 99 to stop: ");
            i = Convert.ToInt32(ReadLine());

            double arrayVal = array[i];
            WriteLine("The value at index {0} is {1}", i, arrayVal);
            ReadLine();
        }
        catch (FormatException fe)
        {
            throw new FormatException("You did not enter an integer.");
        }
        catch (IndexOutOfRangeException ie)
        {
            throw new IndexOutOfRangeException("Index was outside the bounds of the array.");
        }
        catch (Exception ex)
        {
            throw new Exception("Error: " + ex.Message);
        }
    }
}

Body:
As a rule, Try/Catch's and Exception Handlers should only be used Exceptionally. They are expensive. Let me show you how to handle these issues using defensive programming.

I think using the Array.Length to check the Array Bounds if any other out of range value is the answer you want.

static void Main()
{
double[] array = {20.3, 44.6, 32.5, 46.7, 89.6,67.5, 12.3, 14.6, 22.1, 13.6};

int i = 0;

while (i != 99)
{
        Write("Enter a number to see the value in that position. Type 99 to stop: ");

        var result = ReadLine();

        bool isInteger = int.TryParse(result, out i);

        if (isInteger == false) throw new FormatException("You did not enter an integer.");

        if (i == 99) Environment.Exit(0);

        if (i < 0 || i > array.Length) throw new IndexOutOfRangeException("Index was outside the bounds of the array.");

        double arrayVal = array[i];

        WriteLine("The value at index {0} is {1}", i, arrayVal);

        ReadLine();
}


问:
Converting autocall libraries to stored compiled macros
We have hundreds of macros across several autocall libraries that I'd like to compile using the MSTORE facility.

The problem is that some of those libraries are used on other sites - and we don't want to add /STORE to every definition, as then it is required to use the MSTORED option.

I guess the answer is to add /* /STORE */ at the end of every %macro statement, so that the .sas program files can be updated with a regular expression (or some other text replacement technique) on every redeploy, but this seems like a messy workaround.

Is it possible / in some way supported, to compile regular (unmodified) autocall macros and store the definitions?  Eg by %inc'ing each one and saving the work macro catalog, or something like that?

答:
What is the problem that you had?

First compile all of your autocall macros. Say you have a fileref named MYMACS that points to the directory with the source code.

```<code>%include mymacs(macro1,macro2,.....);
</code>```

You might use a program to search for all of the source files so that you could automate generating the %include statement(s).  Or you could use a datastep and copy all of the source files into a single temporary file and include that.

```<code>filename src temp;
data _null_;
  infile "&inpath\*.sas" ;
  file src ;
  input;
  put _infile_;
run;
%inc src ;
</code>```

Then copy the WORK catalog to you a new location.  Note that the name is different if you are running SAS on an application server. In that case try copying from WORK.SASMAC1 instead of WORK.SASMACR.

```<code>libname out base "&path";
proc catalog cat=work.sasmacr et=macro ;
  copy out=out.sasmacr ;
  run;
quit;
</code>```

You can test if it worked by clearing your current work macro catalog, so you know SAS is not finding the macro there, and setting options to point to the new catalog of compiled macros.

```<code>proc catalog cat=work.sasmacr kill force ;
quit;
options mrecall mstored sasmstore=out ;
</code>```

Then trying to run one of the copied compiled macros.

Now start up a new session and try using the compiled macros in that session.

Body:
What is the problem that you had?

First compile all of your autocall macros. Say you have a fileref named MYMACS that points to the directory with the source code.

%include mymacs(macro1,macro2,.....);

You might use a program to search for all of the source files so that you could automate generating the %include statement(s).  Or you could use a datastep and copy all of the source files into a single temporary file and include that.

filename src temp;
data _null_;
  infile "&inpath\*.sas" ;
  file src ;
  input;
  put _infile_;
run;
%inc src ;

Then copy the WORK catalog to you a new location.  Note that the name is different if you are running SAS on an application server. In that case try copying from WORK.SASMAC1 instead of WORK.SASMACR.

libname out base "&path";
proc catalog cat=work.sasmacr et=macro ;
  copy out=out.sasmacr ;
  run;
quit;

You can test if it worked by clearing your current work macro catalog, so you know SAS is not finding the macro there, and setting options to point to the new catalog of compiled macros.

proc catalog cat=work.sasmacr kill force ;
quit;
options mrecall mstored sasmstore=out ;

Then trying to run one of the copied compiled macros.

Now start up a new session and try using the compiled macros in that session.


问:
AppInventor - Getting user review in Play Store from created app?
Does anyone know if there is a way to get the user of an app created in AppInventor to review/rate the app in the Play Store?

I mean like, is there a way to use something like the Activity Starter to link directly to the Google Play Store "Write A Review" option?

答: How to launch Google Play from within your app


问:
Swift 2.2 - Value of type ViewController has no member action
I have been getting the error "Value of type 'ViewController' has no member 'action'"

(action being the function)

Here is the code I am using for the function and Gesture Recogniser

```<code>   let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(self.action))

    uilpgr.minimumPressDuration = 2

    Map.addGestureRecognizer(uilpgr)

    func action(gestureRecogniser: UIGestureRecognizer) {

        print("Gesture Recognised")

    }
</code>```

let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(self.action))

This is where the error occurs at self.action

What am I doing wrong and how do I fix it?

答:
the accepted Blake Lockley's answer was right before Swift 4; however in Swift 4, the code need to be changed to the following in order to be compiled correctly (add the @objc marker to the target function):</p>

```<code>override func viewDidLoad() {

  super.viewDidLoad()

  let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.action))
}

@objc func action(gesture:UIGestureRecognizer){

  print("receives gesture")

}
</code>```

Body:
I have been getting the error "Value of type 'ViewController' has no member 'action'"

(action being the function)

Here is the code I am using for the function and Gesture Recogniser

   let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(self.action))

    uilpgr.minimumPressDuration = 2

    Map.addGestureRecognizer(uilpgr)

    func action(gestureRecogniser: UIGestureRecognizer) {

        print("Gesture Recognised")

    }

let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(self.action))

This is where the error occurs at self.action

What am I doing wrong and how do I fix it?

Body:
the accepted Blake Lockley's answer was right before Swift 4; however in Swift 4, the code need to be changed to the following in order to be compiled correctly (add the @objc marker to the target function):

override func viewDidLoad() {

  super.viewDidLoad()

  let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.action))
}

@objc func action(gesture:UIGestureRecognizer){

  print("receives gesture")

}


问:
The overload is ambigous
I am doing some C++ interview questions (for fun). I found the following:

According to C++11 standard, what is the output of this program?

```<code>#include <iostream>

void f(int){std::cout << 1;}
void f(unsigned){std::cout << 2;}

int main()
{
 f(-2.5);
}
</code>```

The answer is that there is a compilation error, because the overload is ambigous.

But why? Is it not clear for the compiler that -2.5 is a signed int, so it outputs 1?

答:
Well . You are trying to call the function with a floating point number ...
try using integer values...
The Program would work if you used f(-2) instead of f(-2.5) but as @Mark Ranson pointed out " An integer literal is always int unless you add additional qualifiers".
What he meant was that even if you used f(-2) it would give the same result as f(2).. which obviously renders the overload useless.

Title: The overload is ambigous

Body:
I am doing some C++ interview questions (for fun). I found the following:

According to C++11 standard, what is the output of this program?

#include <iostream>

void f(int){std::cout << 1;}
void f(unsigned){std::cout << 2;}

int main()
{
 f(-2.5);
}

The answer is that there is a compilation error, because the overload is ambigous.

But why? Is it not clear for the compiler that -2.5 is a signed int, so it outputs 1?


问:
How to solve Android Update with Different Database
I develop an application that already live on GooglePlay,
Now I need to modify some parts that need more column in the database.
But I got problem, The problem is when I post the new APK with more column to playstore, I can't found those new column in the database, but when I uninstall it first, then I install the new APK, the problem is gone,

How to fix this bug?

答:
you have to use onUpgrade() method to reflect changes in local and live application.

onUpgrade() is only called when the database file exists but the stored version number is lower than requested in constructor. The onUpgrade() should update the table schema to the requested version.

When changing the table schema in code (onCreate()), you should make sure the database is updated. Two main approaches:

Delete the old database file so that onCreate() is run again. This is often preferred at development time where you have control over the installed versions and data loss is not an issue. Some ways to to delete the database file:

Uninstall the application. Use the application manager or adb uninstall your.package.name from shell.

Clear application data. Use the application manager.

Increment the database version so that onUpgrade() is invoked. This is slightly more complicated as more code is needed.

For development time schema upgrades where data loss is not an issue, you can just use execSQL("DROP TABLE IF EXISTS <tablename>") in to remove your existing tables and call onCreate() to recreate the database.

For released versions, you should implement data migration in onUpgrade() so your users don't lose their data.

```<code>@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch(oldVersion){
        case 1:
            db.execSQL("ALTER TABLE " + DATABASE_TABLE + " ADD COLUMN " + NEW_COLUMN_NAME + TYPE);
    }
}
</code>```

Check SqlLiteOpenHelper and this explanation

Body:
you have to use onUpgrade() method to reflect changes in local and live application.

onUpgrade() is only called when the database file exists but the stored version number is lower than requested in constructor. The onUpgrade() should update the table schema to the requested version.

When changing the table schema in code (onCreate()), you should make sure the database is updated. Two main approaches:

Delete the old database file so that onCreate() is run again. This is often preferred at development time where you have control over the installed versions and data loss is not an issue. Some ways to to delete the database file:

Uninstall the application. Use the application manager or adb uninstall your.package.name from shell.

Clear application data. Use the application manager.

Increment the database version so that onUpgrade() is invoked. This is slightly more complicated as more code is needed.

For development time schema upgrades where data loss is not an issue, you can just use execSQL("DROP TABLE IF EXISTS <tablename>") in to remove your existing tables and call onCreate() to recreate the database.

For released versions, you should implement data migration in onUpgrade() so your users don't lose their data.

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch(oldVersion){
        case 1:
            db.execSQL("ALTER TABLE " + DATABASE_TABLE + " ADD COLUMN " + NEW_COLUMN_NAME + TYPE);
    }
}

Check SqlLiteOpenHelper and this explanation


问:
How can I keep track of subscribers if they unsubscribe
When someone wants to receive sms message updates, they can subscribe on my website.

If they reply STOP on any of my messages, twilio will then stop sending them messages.

Is there a webhook where twilio can send me a notification that someone has unsubscribed?

答:
Twilio developer evangelist here.

There is no webhook to say that a user has unsubscribed. However you will get the regular webhook with the message they sent.

So, you can look for messages that only contain "STOP", "STOPALL", "UNSUBSCRIBE", "CANCEL", "END", and "QUIT" and update your database, or whatever you need, at that point.


问:
When jquery.delegate call the event handler?
Recently , Ive been using .delegate and .live a lot.They have a subtle difference when it comes to event capturing I guess.
When using live for link clicks like $('a').live("click",... , the links which had an image as their html content, ended up with the click handler getting the target as the image instead of the link.
Whereas with delegation ,it seems that it the link which is passed as the target.

What is the catch here?

Also, when exactly is a click handler called for .delegate, while the capturing phase or the bubbling phase?

答:
The main difference between .live and .delegate is, that .delegate() uses a context. In other words, .delegate() is actually a wrapper for .live(), but instead watching the document root for bubbling events, it'll just watch a given root node.

For instance

```<code>$('a').live('click', function() {
});
</code>```

will create an event handler attached to your document.body. This will catch absolutly all anchors-clicks that occur on your site.

```<code>$('#someDiv').delegate('a', 'click', function() {
});
</code>```

will only "watch" all anchors which are childnodes from #someDiv.

It's unlikely that a delegated event by .live() have another target. Both .live() and .delegate() pass in the event object into the handler. It should make no difference at all, the event.target should always be the node of invocation.

Ref.: .live(), .delegate()

ContentLicense: CC BY-SA 2.5

Body:
The main difference between .live and .delegate is, that .delegate() uses a context. In other words, .delegate() is actually a wrapper for .live(), but instead watching the document root for bubbling events, it'll just watch a given root node.

For instance

$('a').live('click', function() {
});

will create an event handler attached to your document.body. This will catch absolutly all anchors-clicks that occur on your site.

$('#someDiv').delegate('a', 'click', function() {
});

will only "watch" all anchors which are childnodes from #someDiv.

It's unlikely that a delegated event by .live() have another target. Both .live() and .delegate() pass in the event object into the handler. It should make no difference at all, the event.target should always be the node of invocation.

Ref.: .live(), .delegate()


问:
How can I get the serializer-fields in APIView?
How can I get the  serializer-fields  in APIView?

In the document, it only say how to add serializer-fields in serializers, but did not state how to get the serializer-fields in the  APIView.

I add so many serializer-fields in the CloudServerCreateSerializer:

```<code>class CloudServerCreateSerializer(ModelSerializer):

    cpu = serializers.IntegerField()  # eg:1,2,4,
    ram = serializers.IntegerField()  # eg: 1,2,4,
    os = serializers.DictField()  # eg: {"os_big":"Linux", "os_detail":"CentOS7.2"}

    disk_os = serializers.DictField()  # {"disk_type":"SSD", "disk_size":"50"}
    disk_store = serializers.ListField()  # [{"disk_type":"SSD", "disk_size":"50"}, {"disk_type":"SSD", "disk_size":"50"}]

    class Meta:
        model = CloudServer
        exclude = ['expiration_time']
</code>```

but I do not know how to get these values in the views:

```<code>class CloudServerCreateAPIView(CreateAPIView):
    serializer_class = CloudServerCreateSerializer
    permission_classes = []
    queryset = CloudServer.objects.all()

    def post(self, request, *args, **kwargs):

        print(*args, **kwargs)

        #serializer.save()
        return Response(data="创建成功", status=HTTP_200_OK, exception=None)
</code>```

How to get the serializer-fields in rest framework views?

答:
You are writing an APIView derived class, which is just a basic class based view.  API Views are intended to handle the framework tasks of auth, content type negotiation, and so on, leaving all request processing logic to you.  They do not know about serializer_class or queryset, those are part of the ModelViewSet.

Thankfully, it is quite easy to run the serializer manually and get the data you want.  You can even have it raise 400 errors for you.

```<code>def post(self, request, *args, **kwargs):
    ser = CloudServerCreateSerializer(
        data=request.data,
        context={'request': request}
    )
    ser.is_valid(raise_exception=True)
    data = ser.validated_data
    # use the data somehow
</code>```

Some notes:

The context param contains extra data the serializer can use.  For example, the request to use to find the host-name for making url fields.  You may be able to ignore this.

is_valid(True) will raise all serializer errors back to the client, such as 400 or any that you throw.  You don't have to revalidate the data inside afterwards.

*ars, **kwargs will be empty unless your URL specifies path paramters, e.g. /users/(?<username>\w+)/details/

If you want to serialize a model to json using this, then you would pass the instance parameter:

```<code>data = MySerializer(instance=MyModel.objects.first()).data
</code>```

If you are trying to make a ViewSet to fully handle the model (get, create, list, delete, ...), then you want to use ModelViewSet

```<code>class CloudServerViewSet(ModelViewSet):
    serializer_class = CloudServerCreateSerializer
    permission_classes = []
    queryset = CloudServer.objects.all()

 router.register(r'clouds', CloudServerViewSet, base_name='clouds')
 # this will give you
 # POST  /prefix/clouds/      # create
 # GET   /prefix/clouds/      # list
 # GET   /prefix/clonds/:pk/  # details
 # PATCH /prefix/clonds/:pk/  # update
</code>```

Body:
How can I get the  serializer-fields  in APIView?

In the document, it only say how to add serializer-fields in serializers, but did not state how to get the serializer-fields in the  APIView.

I add so many serializer-fields in the CloudServerCreateSerializer:

class CloudServerCreateSerializer(ModelSerializer):

    cpu = serializers.IntegerField()  # eg:1,2,4,
    ram = serializers.IntegerField()  # eg: 1,2,4,
    os = serializers.DictField()  # eg: {"os_big":"Linux", "os_detail":"CentOS7.2"}

    disk_os = serializers.DictField()  # {"disk_type":"SSD", "disk_size":"50"}
    disk_store = serializers.ListField()  # [{"disk_type":"SSD", "disk_size":"50"}, {"disk_type":"SSD", "disk_size":"50"}]

    class Meta:
        model = CloudServer
        exclude = ['expiration_time']

but I do not know how to get these values in the views:

class CloudServerCreateAPIView(CreateAPIView):
    serializer_class = CloudServerCreateSerializer
    permission_classes = []
    queryset = CloudServer.objects.all()

    def post(self, request, *args, **kwargs):

        print(*args, **kwargs)

        #serializer.save()
        return Response(data="创建成功", status=HTTP_200_OK, exception=None)

How to get the serializer-fields in rest framework views?

Body:
You are writing an APIView derived class, which is just a basic class based view.  API Views are intended to handle the framework tasks of auth, content type negotiation, and so on, leaving all request processing logic to you.  They do not know about serializer_class or queryset, those are part of the ModelViewSet.

Thankfully, it is quite easy to run the serializer manually and get the data you want.  You can even have it raise 400 errors for you.

def post(self, request, *args, **kwargs):
    ser = CloudServerCreateSerializer(
        data=request.data,
        context={'request': request}
    )
    ser.is_valid(raise_exception=True)
    data = ser.validated_data
    # use the data somehow

Some notes:

The context param contains extra data the serializer can use.  For example, the request to use to find the host-name for making url fields.  You may be able to ignore this.

is_valid(True) will raise all serializer errors back to the client, such as 400 or any that you throw.  You don't have to revalidate the data inside afterwards.

*ars, **kwargs will be empty unless your URL specifies path paramters, e.g. /users/(?<username>\w+)/details/

If you want to serialize a model to json using this, then you would pass the instance parameter:

data = MySerializer(instance=MyModel.objects.first()).data

If you are trying to make a ViewSet to fully handle the model (get, create, list, delete, ...), then you want to use ModelViewSet

class CloudServerViewSet(ModelViewSet):
    serializer_class = CloudServerCreateSerializer
    permission_classes = []
    queryset = CloudServer.objects.all()

 router.register(r'clouds', CloudServerViewSet, base_name='clouds')
 # this will give you
 # POST  /prefix/clouds/      # create
 # GET   /prefix/clouds/      # list
 # GET   /prefix/clonds/:pk/  # details
 # PATCH /prefix/clonds/:pk/  # update


问:
Firebase RT database child not updating from httpPostJson
I'm trying to log an event that happens with a Smartthings device into a Firebase database. The function in my Smartthings app is:

```<code>def reportSwitchOnHandler(evt){
log.debug "reportSwitchOnHandler called: $evt"

def params = [
    uri: "https://<project-id>.firebaseio.com/switchStateData/params.json?auth=<key>",

    body: [
            switchState: "test"
        ]
]

try {
    httpPostJson(params) { resp ->
        resp.headers.each {
            log.debug "${it.name} : ${it.value}"
        }
        log.debug "DEBUG (POST FIREBASE): response contentType: ${resp.    contentType}"
    }
} catch (e) {
    log.debug "something went wrong: $e"
}
</code>```

My "params" database structure returned json is:

```<code>{"lights":0,"switchState":"off"}
</code>```

I'm only wanting to update the switchState.

So with that said, when I run the above code, under the "params" structure, rather than updates the switchState child, it creates a new child with some random value like "-Kyn_TIEItKNNACLuEk5" and under that switchState is there with the "test" value.

```<code>{"-Kyn_TIEItKNNACLuEk5":{"switchState":"test"},"lights":0,"state":"off"}
</code>```

Any ideas what I'm missing for it to actually update the original switchState child and not be creating a new sub child (-Kyn_TIEItKNNACLuEk5)?

答:
Using POST pushes data to a location, you need to use PATCH to update the data without overwriting keys that are missing.

```<code>curl -X PATCH -d '{"last":"Jones"}' \
'https://[PROJECT_ID].firebaseio.com/users/jack/name/.json'
</code>```

You can update specific children at a location without overwriting existing data using a PATCH request. Named children in the data being written with PATCH are overwritten, but omitted children are not deleted.

https://firebase.google.com/docs/reference/rest/database/#section-patch

Body:
I'm trying to log an event that happens with a Smartthings device into a Firebase database. The function in my Smartthings app is:

def reportSwitchOnHandler(evt){
log.debug "reportSwitchOnHandler called: $evt"

def params = [
    uri: "https://<project-id>.firebaseio.com/switchStateData/params.json?auth=<key>",

    body: [
            switchState: "test"
        ]
]

try {
    httpPostJson(params) { resp ->
        resp.headers.each {
            log.debug "${it.name} : ${it.value}"
        }
        log.debug "DEBUG (POST FIREBASE): response contentType: ${resp.    contentType}"
    }
} catch (e) {
    log.debug "something went wrong: $e"
}

My "params" database structure returned json is:

{"lights":0,"switchState":"off"}

I'm only wanting to update the switchState.

So with that said, when I run the above code, under the "params" structure, rather than updates the switchState child, it creates a new child with some random value like "-Kyn_TIEItKNNACLuEk5" and under that switchState is there with the "test" value.

{"-Kyn_TIEItKNNACLuEk5":{"switchState":"test"},"lights":0,"state":"off"}

Any ideas what I'm missing for it to actually update the original switchState child and not be creating a new sub child (-Kyn_TIEItKNNACLuEk5)?

Body:
Using POST pushes data to a location, you need to use PATCH to update the data without overwriting keys that are missing.

curl -X PATCH -d '{"last":"Jones"}' \
'https://[PROJECT_ID].firebaseio.com/users/jack/name/.json'

You can update specific children at a location without overwriting existing data using a PATCH request. Named children in the data being written with PATCH are overwritten, but omitted children are not deleted.

https://firebase.google.com/docs/reference/rest/database/#section-patch


问:
Creating a Google map in iOS that doesn't fit the whole screen
I'm using the Google Maps SDK to generate a map in my UIViewController but it's generating a map on the whole screen. I only need it to create a map on half the screen. How do I accomplish that?    </p>

```<code>class MapViewController: UIViewController,CLLocationManagerDelegate{
    var locationManager = CLLocationManager()
    var mapView = GMSMapView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // User Location
        locationManager.delegate = self
        //locationManager.requestWhenInUseAuthorization()
        locationManager.requestAlwaysAuthorization()
        view.backgroundColor = UIColor.gray

        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation = locations.last
        let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)

        let camera = GMSCameraPosition.camera(withLatitude: userLocation!.coordinate.latitude,
                                              longitude: userLocation!.coordinate.longitude, zoom: 9.1)

        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        mapView.isMyLocationEnabled = true
        self.view = mapView

        locationManager.stopUpdatingLocation()
    }
}
</code>```

答:
Here is the main issue

```<code>self.view = mapView
</code>```

You are setting your mapView as self.view which means full Size of view that appear on Screen

instead do like in didLoad

```<code>self.view.addSubview(mapView)
</code>```

and set it frame in willAppear or didAppear

```<code>mapView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width , height: self.view.frame.size.height/2)
</code>```

Body:
I'm using the Google Maps SDK to generate a map in my UIViewController but it's generating a map on the whole screen. I only need it to create a map on half the screen. How do I accomplish that?

class MapViewController: UIViewController,CLLocationManagerDelegate{
    var locationManager = CLLocationManager()
    var mapView = GMSMapView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // User Location
        locationManager.delegate = self
        //locationManager.requestWhenInUseAuthorization()
        locationManager.requestAlwaysAuthorization()
        view.backgroundColor = UIColor.gray

        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation = locations.last
        let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)

        let camera = GMSCameraPosition.camera(withLatitude: userLocation!.coordinate.latitude,
                                              longitude: userLocation!.coordinate.longitude, zoom: 9.1)

        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        mapView.isMyLocationEnabled = true
        self.view = mapView

        locationManager.stopUpdatingLocation()
    }
}

Body:
Here is the main issue

self.view = mapView

You are setting your mapView as self.view which means full Size of view that appear on Screen

instead do like in didLoad

self.view.addSubview(mapView)

and set it frame in willAppear or didAppear

mapView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width , height: self.view.frame.size.height/2)


问:
Load chart data into a webapp from google datastore
I've got a google app engine application that loads time series data real-time into a google datastore nosql style table. I was hoping to get some feedback around the right type of architecture to pull this data into a web application style chart (and ideally something I could also plug into a content management system like Word Press).

Most of my server-side code is python. What's a reasonable client-server setup to pull the data from the datastore database and display into my webpage? Ideally I'd have something that scales and doesn't cause an unnecessary number of reads on my database (potentially using google-app-engine's built in caching/etc).

I'm guessing this is a common use-case but I'd like to get an idea of what might be some best practices around this. I've seen some examples using client web side javascript/ajax with server side php to read the DB- is this really the best way?

答:
Welcome to "it depends".

You have some choices. Imagine the classic four-quadrant chart. Along one axis is data size, along the other is staleness/freshness.

If your time-series data changes rapidly but is small enough to safely be retrieved within a request, you can query for it on demand, convert it to JSON, and squirt it to the browser to be rendered by the JavaScript charting package of your choice. If the data is large, your app will need to do some sort of server-side pre-processing so that when the data is needed, it can be retrieved in sufficiently fewer requests that that the request won't time out. This might involve something data dependent like pre-bucketing the time series.

If the data changes slowly, you have the option of generating your chart on the server side, perhaps using matplotlib. When new data is ingested, or perhaps at intervals, spawn off a task to generate and cache the chart (or JSON to hand to the front-end) as a blob in the datastore. If the data is sufficiently large that a task will timeout, you might need to use a backend process. If the data is sufficiently large and you don't pre-process, you're in the quadrant of unhappiness.

In my experience, GAE memcache is best for caching data between requests where the time between requests is very short. Don't rely on generating artifacts, stuff them in memcache and hoping that they'll be there a few minutes later. I've rarely seen that work.


问:
Click on element after fading in on hover
I have a paragraph and an anchor, when i hover into the paragraph, the anchor fades in, how can I keep it for a little while so I can click on it? because when I move the mouse away from the p element it disappears and I cant click on it, here is my code:

$(function() {
  $('p').hover(function() {
    $('a').fadeIn();
  }, function() {
    $('a').css('display','none');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a{
  display: none;
}</code>```

Show anchor

Hi```

答:
You can do it in many ways like animation and delay. there I am using delay to overcome your issue may this help you.

```<code>$(function() {
   $('p').hover(function() {
        $('a').fadeIn();
    }, function() {

       $('a').delay(800).queue(function (next) {

            $(this).css('display', 'none');
         next();
      });

    });
    });
});
</code>```

Body:
I have a paragraph and an anchor, when i hover into the paragraph, the anchor fades in, how can I keep it for a little while so I can click on it? because when I move the mouse away from the p element it disappears and I cant click on it, here is my code:

$(function() {
  $('p').hover(function() {
    $('a').fadeIn();
  }, function() {
    $('a').css('display','none');
  });
});

a{
  display: none;
}

Show anchor

Hi

Body:
You can do it in many ways like animation and delay. there I am using delay to overcome your issue may this help you.

$(function() {
   $('p').hover(function() {
        $('a').fadeIn();
    }, function() {

       $('a').delay(800).queue(function (next) {

            $(this).css('display', 'none');
         next();
      });

    });
    });
});


问:
using setInterval for keep scrolling in nightwatch js
i have a nightwatch js script that will run scrolling in my webpage
this is my custom commands script

```<code>'use strict'

exports.command = function (param) {
    this.execute(function (param) {
        $(window).scrollTop(param)
    }, [param])
}
</code>```

and then from my testing file i call that scrolling script. this is my script

```<code>module.exports = {
    'Scrolling testing': function (client) {
        client.url('http://localhost:1200/').waitForElementVisible('div.user-item', 5000);
        let i = 50
        setInterval(function () {
            console.log(i)
            client.scrollTo(i)
            i += 50
        }, 500)
    }
};
</code>```

i just wanna make scrolling action every 500ms with setInterval, but the browser just scroll only once (but the console log keep runing). can anyone solve this..

sorry for bad english :(

答:
There are a some options that I will do to get the behavior you want but I dont know which one will satisfy you:

Use perform (See documentation here)

perform command enables you to execute some code, it can be asynchronous so you can do something like the example # 1 (for some reason if I put the code below it wont be formatted)

Use executeAsync (See documentation here) instead of execute:

execute command runs synchronous, so maybe after the first execution it continues with the test and then it finishes. So instead, use executeAsync  and move the whole setInterval function inside it so you dont need the custom command (imho, I will delete it since doesnt do so much thing). See example # 2

Example # 1

```<code>client
    .url('http://localhost:1200/')
    .waitForElementVisible('div.user-item', 5000)
    .perform(function(client, done){
        let i = 50, maxExecutions = 10, intervalTime = 0;
        intervalTime = setInterval(function () {
            console.log(i);
            client.scrollTo(i);
            i += 50;
            maxExecutions++;
            if(maxExecutions===10) {
                clearInterval(intervalTime); //to prevent an infinite loop
                done();
            }
        }, 500)
    })
</code>```

Example # 2

```<code>module.exports = {
    'Scrolling testing': function (client) {
        client
            .url('http://localhost:1200/')
            .waitForElementVisible('div.user-item', 5000)
            .executeAsync(function (param, done) {
                let i = 50, maxExecutions = 10, intervalTime = 0;
                intervalTime = setInterval(function () {
                    maxExecutions++;
                    console.log(i);//will be logged on browser console
                    $(window).scrollTop(param);
                    i += 50
                    if(maxExecutions===10){
                        clearInterval(intervalTime);
                        done(/*you can send some data here*/)
                    }
                }, 500)
            }, [], function(/*the data that you have send*/){
                //do something
            })
    }
};
</code>```

Body:
i have a nightwatch js script that will run scrolling in my webpage
this is my custom commands script

'use strict'

exports.command = function (param) {
    this.execute(function (param) {
        $(window).scrollTop(param)
    }, [param])
}

and then from my testing file i call that scrolling script. this is my script

module.exports = {
    'Scrolling testing': function (client) {
        client.url('http://localhost:1200/').waitForElementVisible('div.user-item', 5000);
        let i = 50
        setInterval(function () {
            console.log(i)
            client.scrollTo(i)
            i += 50
        }, 500)
    }
};

i just wanna make scrolling action every 500ms with setInterval, but the browser just scroll only once (but the console log keep runing). can anyone solve this..

sorry for bad english :(

Body:
There are a some options that I will do to get the behavior you want but I dont know which one will satisfy you:

Use perform (See documentation here)

perform command enables you to execute some code, it can be asynchronous so you can do something like the example # 1 (for some reason if I put the code below it wont be formatted)

Use executeAsync (See documentation here) instead of execute:

execute command runs synchronous, so maybe after the first execution it continues with the test and then it finishes. So instead, use executeAsync  and move the whole setInterval function inside it so you dont need the custom command (imho, I will delete it since doesnt do so much thing). See example # 2

Example # 1

client
    .url('http://localhost:1200/')
    .waitForElementVisible('div.user-item', 5000)
    .perform(function(client, done){
        let i = 50, maxExecutions = 10, intervalTime = 0;
        intervalTime = setInterval(function () {
            console.log(i);
            client.scrollTo(i);
            i += 50;
            maxExecutions++;
            if(maxExecutions===10) {
                clearInterval(intervalTime); //to prevent an infinite loop
                done();
            }
        }, 500)
    })

Example # 2

module.exports = {
    'Scrolling testing': function (client) {
        client
            .url('http://localhost:1200/')
            .waitForElementVisible('div.user-item', 5000)
            .executeAsync(function (param, done) {
                let i = 50, maxExecutions = 10, intervalTime = 0;
                intervalTime = setInterval(function () {
                    maxExecutions++;
                    console.log(i);//will be logged on browser console
                    $(window).scrollTop(param);
                    i += 50
                    if(maxExecutions===10){
                        clearInterval(intervalTime);
                        done(/*you can send some data here*/)
                    }
                }, 500)
            }, [], function(/*the data that you have send*/){
                //do something
            })
    }
};


问:
C# How to sort int when value is too large
```<code>8
723
77715926535897932384626433832795
</code>```

Usually I will place them into Array and using Sort method to sort them numerically.

However, the above value is too huge to be place into Int64 and if using string array, its gonna give unexpected outcome which 8 comes after 77715926535897932384626433832795. How to sort such large value?

Body:
8
723
77715926535897932384626433832795

Usually I will place them into Array and using Sort method to sort them numerically.

However, the above value is too huge to be place into Int64 and if using string array, its gonna give unexpected outcome which 8 comes after 77715926535897932384626433832795. How to sort such large value?

Body:
You can always sort by length and then by value:

var numbers = new []
{
    "8",
    "77715926535897932384626433832795",
    "723",
};

var sorted =
    numbers
        .OrderBy(n => n.Length)
        .ThenBy(n => n)
        .ToArray();

That gives:

8
723
77715926535897932384626433832795


问:
How to move a div's border "up" one pixel with css
I have a div, which I have given a border on top. The border needs to be shifted one pixel higher. Is this possible with CSS.</p>

答:
You can accomplish this with a negative top margin

```<code>{ margin-top: -1px; }
</code>```

very basic example: http://jsfiddle.net/zW6yD/

Body:
You can accomplish this with a negative top margin

{ margin-top: -1px; }

very basic example: http://jsfiddle.net/zW6yD/


问:
Fetching return value from async function
I am trying to capture the response of two service calls within a function. Got to know that async and await will solve this purpose and tried below. Here inside async function ex - I am making a call to users, companies end point and console log is displaying perfect, but while retrieving the same value by calling the async function is giving Promise Pending. I tried two options 1. by simply calling the async function - giving Promise Pending 2. by calling with await prefixed - giving await is a reserved word.

Please let me know how to capture the response from this...

```<code>const service = {
        getUsers: () => axios.get(`http://localhost:3000/users`),
        getCompanies: () => axios.get('http://localhost:3000/companies')
      };

      let ex = async () => {
        let users = {};
        let companies = {};
        try {
           users =   await service.getUsers()
           companies = await  service.getCompanies()

          console.log('Example ', {
            users: users.data,
            companies: companies.data
          })

        } catch (err) {
          console.log(err);
        }
        return  [{ users, companies}];
      };
      //let resp = await ex(); - giving await is a reserved word
      // let resp = ex(); - giving Promise is pending..
      console.log(resp);
</code>```

答:
All async functions will always return a promise. If you return nothing, the function will return a promise for undefined. Whatever you return will get wrapped up in a promise, which you need to await or call then on to access the value inside.

```<code>resp.then(console.log)
</code>```

Body:
I am trying to capture the response of two service calls within a function. Got to know that async and await will solve this purpose and tried below. Here inside async function ex - I am making a call to users, companies end point and console log is displaying perfect, but while retrieving the same value by calling the async function is giving Promise Pending. I tried two options 1. by simply calling the async function - giving Promise Pending 2. by calling with await prefixed - giving await is a reserved word.

Please let me know how to capture the response from this...

const service = {
        getUsers: () => axios.get(`http://localhost:3000/users`),
        getCompanies: () => axios.get('http://localhost:3000/companies')
      };

      let ex = async () => {
        let users = {};
        let companies = {};
        try {
           users =   await service.getUsers()
           companies = await  service.getCompanies()

          console.log('Example ', {
            users: users.data,
            companies: companies.data
          })

        } catch (err) {
          console.log(err);
        }
        return  [{ users, companies}];
      };
      //let resp = await ex(); - giving await is a reserved word
      // let resp = ex(); - giving Promise is pending..
      console.log(resp);

Body:
All async functions will always return a promise. If you return nothing, the function will return a promise for undefined. Whatever you return will get wrapped up in a promise, which you need to await or call then on to access the value inside.

resp.then(console.log)


问:
Are there any drawback of using output buffer on do_action function?
I have a function where I need to use apply_filter and couple of action in between. Are there any drawbacks of using this approach? Are there alternatives?</p>

```<code>$form = array ('choice1', 'choice2', 'choice3')
$content= "";
foreach ($form as $choice ) {

    ob_start();
    do_action( 'before_choice', $form_id, $choice );
    $content .= ob_get_clean();

    $content .='<div class="choice-container">'. $choice .'</div>';

    ob_start();
    do_action( 'after_choice', $form_id, $choice );
    $content .= ob_get_clean();

}
$content = apply_filters( 'change_choices_layout', $content, $form  );
echo $content;
</code>```

答: If it's static content my alternative would be to use transients which are much faster to render on screen.  The issue with ob_start() is that if you or someone else modified the action 'before_choice' and put another call to ob_start() within it then it makes it difficult to troubleshoot what's going on as the content would disappear.  I would also change your do_action to apply_filters, rewrite your 'before_choice' hook to be an add_filter instead of an add_action hook as filters will return a value by default so you don't need to use ob_start() anymore.

Body:
I have a function where I need to use apply_filter and couple of action in between. Are there any drawbacks of using this approach? Are there alternatives?

$form = array ('choice1', 'choice2', 'choice3')
$content= "";
foreach ($form as $choice ) {

    ob_start();
    do_action( 'before_choice', $form_id, $choice );
    $content .= ob_get_clean();

    $content .='
'. $choice .'
';

    ob_start();
    do_action( 'after_choice', $form_id, $choice );
    $content .= ob_get_clean();

}
$content = apply_filters( 'change_choices_layout', $content, $form  );
echo $content;


问:
Exclude certain taxonomy from function
I need a help with a WordPress code.
On this page https://developer.wordpress.org/reference/functions/get_the_terms/ I got a code that returns my taxonomies and their terms.

But I'd like a certain taxonomy called "Ad Type" to be excluded from this list.

I managed to exclude some terms from "Ad Type" using this code...

```<code>// An array of IDs to ignore / exclude
$ excluded_ids = array (1, 2, 3, 4);

foreach ($ terms as $ term) {
// Only proceed if the term_id is NOT in the $ excluded_ids array
   if (! in_array ($ term-> term_id, $ excluded_ids)) {
   $ out. = '<li> <a href="' .get_term_link($term-> slug, $ taxonomy).' '>'. $ term-> name. '</a> </ li>';
}
}
</code>```

But what I want is that the "Ad Type" taxonomy does not appear at all.
Because with the code above the Title of "Ad Type" is still appearing on the terms list retrieved.
What i want is to totally exlcude this taxonomy from being retrieved on that part of my wordpress template.

Here is the code:

```<code>function wpdocs_custom_taxonomies_terms_links() {
// Get post by post ID.
$post = get_post( $post->ID );

// Get post type by post.
$post_type = $post->post_type;

// Get post type taxonomies.
$taxonomies = get_object_taxonomies( $post_type, 'objects' );

$out = array();

foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){

    // Get the terms related to post.
    $terms = get_the_terms( $post->ID, $taxonomy_slug );

    if ( ! empty( $terms ) ) {

        $out[] = "<h6>" . $taxonomy->label . ":</h6>\n<ul>";
        foreach ( $terms as $term ) {
            $out[] = sprintf( '<li>%2$s</li> - ',
                esc_url( get_term_link( $term->slug, $taxonomy_slug ) ),
                esc_html( $term->name )
            );
        }
        $out[] = "</ul>\n";
    }
}

return implode( '', $out );
}
</code>```

And here is how i retrieve it on my template page:

```<code><?php echo wpdocs_custom_taxonomies_terms_links(); ?>
</code>```

Is there a way to do this?
can anybody help me?

Thanks

答:
I don't know if I am comparing it right but you can check if current taxonomy is not Ad Type only then get terms

```<code>foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){

    if ($taxonomy_slug !== 'ad_type') :
        // Get the terms related to post.
        $terms = get_the_terms( $post->ID, $taxonomy_slug );

        if ( ! empty( $terms ) ) {

            $out[] = "<h6>" . $taxonomy->label . ":</h6>\n<ul>";
            foreach ( $terms as $term ) {
                $out[] = sprintf( '<li>%2$s</li> - ',
                    esc_url( get_term_link( $term->slug, $taxonomy_slug ) ),
                    esc_html( $term->name )
                );
            }
            $out[] = "</ul>\n";
        }
    endif;
}
</code>```

Title: Exclude certain taxonomy from function

Body:
I need a help with a WordPress code.
On this page https://developer.wordpress.org/reference/functions/get_the_terms/ I got a code that returns my taxonomies and their terms.

But I'd like a certain taxonomy called "Ad Type" to be excluded from this list.

I managed to exclude some terms from "Ad Type" using this code...

// An array of IDs to ignore / exclude
$ excluded_ids = array (1, 2, 3, 4);

foreach ($ terms as $ term) {
// Only proceed if the term_id is NOT in the $ excluded_ids array
   if (! in_array ($ term-> term_id, $ excluded_ids)) {
   $ out. = '
  slug, $ taxonomy).' '>'. $ term-> name. '
';
}
}

But what I want is that the "Ad Type" taxonomy does not appear at all.
Because with the code above the Title of "Ad Type" is still appearing on the terms list retrieved.
What i want is to totally exlcude this taxonomy from being retrieved on that part of my wordpress template.

Here is the code:

function wpdocs_custom_taxonomies_terms_links() {
// Get post by post ID.
$post = get_post( $post->ID );

// Get post type by post.
$post_type = $post->post_type;

// Get post type taxonomies.
$taxonomies = get_object_taxonomies( $post_type, 'objects' );

$out = array();

foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){

    // Get the terms related to post.
    $terms = get_the_terms( $post->ID, $taxonomy_slug );

    if ( ! empty( $terms ) ) {

        $out[] = "
" . $taxonomy->label . ":
\n
";
        foreach ( $terms as $term ) {
            $out[] = sprintf( '
%2$s
 - ',
                esc_url( get_term_link( $term->slug, $taxonomy_slug ) ),
                esc_html( $term->name )
            );
        }
        $out[] = "
\n";
    }
}

return implode( '', $out );
}

And here is how i retrieve it on my template page:

<?php echo wpdocs_custom_taxonomies_terms_links(); ?>

Is there a way to do this?
can anybody help me?

Thanks

Body:
I don't know if I am comparing it right but you can check if current taxonomy is not Ad Type only then get terms

foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){

    if ($taxonomy_slug !== 'ad_type') :
        // Get the terms related to post.
        $terms = get_the_terms( $post->ID, $taxonomy_slug );

        if ( ! empty( $terms ) ) {

            $out[] = "<h6>" . $taxonomy->label . ":</h6>\n<ul>";
            foreach ( $terms as $term ) {
                $out[] = sprintf( '<li>%2$s</li> - ',
                    esc_url( get_term_link( $term->slug, $taxonomy_slug ) ),
                    esc_html( $term->name )
                );
            }
            $out[] = "</ul>\n";
        }
    endif;
}


问:
Get mouse position in world space
I'm making a game using Unity and I have a little issue, I need to know the mouse position in world space, for that I try to set a GameObject at the mouse position using this code :

```<code>    Vector3 p = Input.mousePosition;
    Vector3 pos = Camera.main.ScreenToWorldPoint( p);
    testGameObject.transform.position = pos;
</code>```

It works like a charm in Editor but in exe / apk, the GameObject dosn't follow the mouse:

Example 1

Example 2

The GameObject that is supposed to follow the mouse is the "1" inside a circle

答:
If it's works in editor like a charm, then it should in build to.

I see it already working in build, maybe what you want is to exactly place yor object to match the screen click point, but your object is far too close to the camera so that you can't see it.

maybe there's a problem with the depth of the position from the camera.
try adding something like

```<code>Vector3 p = Input.mousePosition;
p.z = 20;
Vector3 pos = Camera.main.ScreenToWorldPoint(p);
testGameObject.transform.position = pos;
</code>```

To add depth to the mouse position. try to change 20 to -20 if it's still doesn't work

Title: Get mouse position in world space

Body:
I'm making a game using Unity and I have a little issue, I need to know the mouse position in world space, for that I try to set a GameObject at the mouse position using this code :

    Vector3 p = Input.mousePosition;
    Vector3 pos = Camera.main.ScreenToWorldPoint( p);
    testGameObject.transform.position = pos;

It works like a charm in Editor but in exe / apk, the GameObject dosn't follow the mouse:

Example 1

Example 2

The GameObject that is supposed to follow the mouse is the "1" inside a circle

Body:
If it's works in editor like a charm, then it should in build to.

I see it already working in build, maybe what you want is to exactly place yor object to match the screen click point, but your object is far too close to the camera so that you can't see it.

maybe there's a problem with the depth of the position from the camera.
try adding something like

Vector3 p = Input.mousePosition;
p.z = 20;
Vector3 pos = Camera.main.ScreenToWorldPoint(p);
testGameObject.transform.position = pos;

To add depth to the mouse position. try to change 20 to -20 if it's still doesn't work


问:
How do you do an incremental search across multiple files in VIM?
Vim already does incremental search within the currently open file but can you do
an incremental search across multiple files?</p>

答: AFAIK this is not possible. However you can start to type a word that is in an opened buffer and hit ctrl-xctrl-n to start searching for such a word in all opened buffers.


问:
ValueError: Only call `softmax_cross_entropy_with_logits` with named arguments (labels=..., logits=..., ...)
Can you guide how to fix this?

```<code>with tf.name_scope('loss'):
    #cross_entropy = None
    val = tf.nn.softmax_cross_entropy_with_logits(y_conv, y_)
    cross_entropy = tf.reduce_mean(val)

with tf.name_scope('adam_optimizer'):
    #train_step = None
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
</code>```

I get this error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-40-f67d0aecc114> in <module>()
      1 with tf.name_scope('loss'):
      2     #cross_entropy = None
----> 3     val = tf.nn.softmax_cross_entropy_with_logits(y_conv, y_)
      4     cross_entropy = tf.reduce_mean(val)
      5

~/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py in softmax_cross_entropy_with_logits(_sentinel, labels, logits, dim, name)
   1576   """
   1577   _ensure_xent_args("softmax_cross_entropy_with_logits", _sentinel,
-> 1578                     labels, logits)
   1579
   1580   # TODO(pcmurray) Raise an error when the labels do not sum to 1. Note: This

~/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py in _ensure_xent_args(name, sentinel, labels, logits)
   1531   if sentinel is not None:
   1532     raise ValueError("Only call `%s` with "
-> 1533                      "named arguments (labels=..., logits=..., ...)" % name)
   1534   if labels is None or logits is None:
   1535     raise ValueError("Both labels and logits must be provided.")

ValueError: Only call `softmax_cross_entropy_with_logits` with named arguments (labels=..., logits=..., ...)
</code>```

Also, tf.__version__ returns '1.0.0'
and I have Anaconda Python 3.6.2 on OSX Sierra.

答:
This is an easy fix: softmax_cross_entropy_with_logits() has three key arguments: _sentinel, labels, and logits. The sentinel must be empty, requiring the use of named arguments.

Fixed (although I'm not sure if y_conv or y_ is the label or logit in this case, so you may have to swap them):

```<code>with tf.name_scope('loss'):
    #cross_entropy = None
    val = tf.nn.softmax_cross_entropy_with_logits(labels = y_conv, logits=y_)
    cross_entropy = tf.reduce_mean(val)

with tf.name_scope('adam_optimizer'):
    #train_step = None
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
</code>```

Body:
Can you guide how to fix this?

with tf.name_scope('loss'):
    #cross_entropy = None
    val = tf.nn.softmax_cross_entropy_with_logits(y_conv, y_)
    cross_entropy = tf.reduce_mean(val)

with tf.name_scope('adam_optimizer'):
    #train_step = None
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

I get this error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-40-f67d0aecc114> in <module>()
      1 with tf.name_scope('loss'):
      2     #cross_entropy = None
----> 3     val = tf.nn.softmax_cross_entropy_with_logits(y_conv, y_)
      4     cross_entropy = tf.reduce_mean(val)
      5

~/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py in softmax_cross_entropy_with_logits(_sentinel, labels, logits, dim, name)
   1576   """
   1577   _ensure_xent_args("softmax_cross_entropy_with_logits", _sentinel,
-> 1578                     labels, logits)
   1579
   1580   # TODO(pcmurray) Raise an error when the labels do not sum to 1. Note: This

~/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py in _ensure_xent_args(name, sentinel, labels, logits)
   1531   if sentinel is not None:
   1532     raise ValueError("Only call `%s` with "
-> 1533                      "named arguments (labels=..., logits=..., ...)" % name)
   1534   if labels is None or logits is None:
   1535     raise ValueError("Both labels and logits must be provided.")

ValueError: Only call `softmax_cross_entropy_with_logits` with named arguments (labels=..., logits=..., ...)

Also, tf.__version__ returns '1.0.0'
and I have Anaconda Python 3.6.2 on OSX Sierra.

Body:
This is an easy fix: softmax_cross_entropy_with_logits() has three key arguments: _sentinel, labels, and logits. The sentinel must be empty, requiring the use of named arguments.

Fixed (although I'm not sure if y_conv or y_ is the label or logit in this case, so you may have to swap them):

with tf.name_scope('loss'):
    #cross_entropy = None
    val = tf.nn.softmax_cross_entropy_with_logits(labels = y_conv, logits=y_)
    cross_entropy = tf.reduce_mean(val)

with tf.name_scope('adam_optimizer'):
    #train_step = None
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

ContentLicense: CC BY-SA 4.0


问:
How do I print everything separately? What will be the loop?
Make two new dictionaries representing different people, and store all three
dictionaries in a list called people. Loop through your list of people. As you
loop through the list, print everything you know about each person.

```<code>person_1 = {'first_name':'shamol',
      'last_name': 'kabir',
      'age': '25',
      'city': 'jessore'}
person_2 = {'first_name':'shorif',
        'last_name':'jaman',
        'age':'28',
        'city':'khulna'}
person_3= {'first_name':'mizan',
       'last_name':'rahman',
       'age':'25',
       'city':'jessore'}
people= [person_1,person_2,person_3]
</code>```

what will be the next few lines??

答:
please first try your self. And this question is pretty simple to find answer.</p>

```<code>for d in people:
    for key, value in d.items():
        print(key, value)
</code>```

Body:
Make two new dictionaries representing different people, and store all three
dictionaries in a list called people. Loop through your list of people. As you
loop through the list, print everything you know about each person.

person_1 = {'first_name':'shamol',
      'last_name': 'kabir',
      'age': '25',
      'city': 'jessore'}
person_2 = {'first_name':'shorif',
        'last_name':'jaman',
        'age':'28',
        'city':'khulna'}
person_3= {'first_name':'mizan',
       'last_name':'rahman',
       'age':'25',
       'city':'jessore'}
people= [person_1,person_2,person_3]

what will be the next few lines??

Body:
please first try your self. And this question is pretty simple to find answer.

for d in people:
    for key, value in d.items():
        print(key, value)


问:
AngularJS and IE compatibility mode
I have angularJS(AngularJS v1.3.0-beta.3) application that crashes in IE10 compatibility mode. It works fine in FF, Chrome and IE11. Here is what I get as an error in console:

```<code>Multiple directives [login, login] asking for 'login' controller on: <div>
</code>```

to set state of application, I create a  node:

```<code>link: function ($scope, $element, $attrs) {
    ....
$element.html('<login></login>');
    $compile($element.contents())($scope); // crash happens here
    ....
}
</code>```

Here is my login directive:

```<code>widgets.directive('login', ['$compile', '$http', 'resourceLoader', function ($compile, $http, resourceLoader) {
    return {
        restrict: 'AE',
        replace: true,
        template: '<div></div>',
        controller: function ($scope, $element) {
            $scope.user.isLogged = false;
            $scope.user.password = undefined;

            $scope.submitLogin = function () {
                // code that goes to server
            };
        },
        link: function ($scope, $element, $attrs) {
            resourceLoader.get('templates', 'profile', 'unlogged/login', 'jquery.min', function (template) {
                $element.html(template);
                $compile($element.contents())($scope);
            });
        }
    };
}]);
</code>```

Any ideas? Thanx.

答:
Adding below line in index.html's head section solved my problem:

```<code> <meta http-equiv="x-ua-compatible" content="IE=edge">
</code>```

For more info : https://stackoverflow.com/a/46489212/698127

Title: AngularJS and IE compatibility mode

Body:
I have angularJS(AngularJS v1.3.0-beta.3) application that crashes in IE10 compatibility mode. It works fine in FF, Chrome and IE11. Here is what I get as an error in console:

Multiple directives [login, login] asking for 'login' controller on:

to set state of application, I create a  node:

link: function ($scope, $element, $attrs) {
    ....
$element.html('<login></login>');
    $compile($element.contents())($scope); // crash happens here
    ....
}

Here is my login directive:

widgets.directive('login', ['$compile', '$http', 'resourceLoader', function ($compile, $http, resourceLoader) {
    return {
        restrict: 'AE',
        replace: true,
        template: '

',
        controller: function ($scope, $element) {
            $scope.user.isLogged = false;
            $scope.user.password = undefined;

            $scope.submitLogin = function () {
                // code that goes to server
            };
        },
        link: function ($scope, $element, $attrs) {
            resourceLoader.get('templates', 'profile', 'unlogged/login', 'jquery.min', function (template) {
                $element.html(template);
                $compile($element.contents())($scope);
            });
        }
    };
}]);

Any ideas? Thanx.

Body:
Adding below line in index.html's head section solved my problem:

 <meta http-equiv="x-ua-compatible" content="IE=edge">

For more info : https://stackoverflow.com/a/46489212/698127


问:
gvim: passing the visually-selected text to the command line
I use gvim to store recipes of commands that I will execute, depending on output. Currently, I select the text in gvim and paste the commands into a terminal console, but I bet there's a way I can pass the visually selected range into a command-line for execution.</p>

答:
Assuming you mean the Vim command line:

(if you mean the OS command line, see below).

For parts of lines (i.e. no end of line character), you could do something like this:

```<code>" Visually select lines, then:
y:<C-R>"<ENTER>
</code>```

where <C-R> means press Ctrl+R.  The y 'yanks' the selected text, the : enters command mode, <C-R>" pulls the contents of the " (last yanked text) register onto the command line and <ENTER> (obviously) runs the command.

If you want to do line-wise stuff, it's a bit more complicated (as the command line doesn't like ^Ms in the command).  I'd recommend something like this in your vimrc:

```<code>function! RunCommands()
    exe getline('.')
endfunction
command -range RunCommands <line1>,<line2>call RunCommands()
vmap ,r :RunCommands<CR>
</code>```

Select the lines (after restarting vim) and press ,r.

Another way that you may find useful is to copy the lines you want, hit q: to open the command line window and paste the lines you want into there and then move the cursor over the line you want and press ENTER.  This has the advantage that you can edit the command before pressing ENTER.  It'll only run one command at a time.

If you mean an (e.g.) Windows or Linux command line:

Use the function I listed above, but instead of:

```<code>exe getline('.')
</code>```

use

```<code>call system(getline('.'))
</code>```

or, if you want to see the result:

```<code>echo system(getline('.'))
</code>```

or

```<code>echomsg system(getline('.'))
</code>```

For more information:

```<code>:help :echo
:help :echomsg
:help :messages

:help :vmap
:help :command-range
:help :command
:help :function

:help c_CTRL-R
:help :exe
:help getline()
:help system()
</code>```

Body:
Assuming you mean the Vim command line:

(if you mean the OS command line, see below).

For parts of lines (i.e. no end of line character), you could do something like this:

" Visually select lines, then:
y:<C-R>"<ENTER>

where <C-R> means press Ctrl+R.  The y 'yanks' the selected text, the : enters command mode, <C-R>" pulls the contents of the " (last yanked text) register onto the command line and <ENTER> (obviously) runs the command.

If you want to do line-wise stuff, it's a bit more complicated (as the command line doesn't like ^Ms in the command).  I'd recommend something like this in your vimrc:

function! RunCommands()
    exe getline('.')
endfunction
command -range RunCommands <line1>,<line2>call RunCommands()
vmap ,r :RunCommands<CR>

Select the lines (after restarting vim) and press ,r.

Another way that you may find useful is to copy the lines you want, hit q: to open the command line window and paste the lines you want into there and then move the cursor over the line you want and press ENTER.  This has the advantage that you can edit the command before pressing ENTER.  It'll only run one command at a time.

If you mean an (e.g.) Windows or Linux command line:

Use the function I listed above, but instead of:

exe getline('.')

use

call system(getline('.'))

or, if you want to see the result:

echo system(getline('.'))

or

echomsg system(getline('.'))

For more information:

:help :echo
:help :echomsg
:help :messages

:help :vmap
:help :command-range
:help :command
:help :function

:help c_CTRL-R
:help :exe
:help getline()
:help system()


问:
Why cant I draw to a texture in SDL2?
So my main goal is to read the pixel data of a given texture, so to test this, i've created a new texture with target access then drawn it red.

The problem is that when I access the pixel data, SDL_RenderReadPixels() says the pitch is 0, and all the pixel data is 0. Also when I try to draw the new texture, it comes out black.

```<code>SDL_Texture* tempChar = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, 3, 5);

if (SDL_SetRenderTarget(renderer, tempChar) != 0) {
    cout << "SDL_SetRenderTarget() Error! " << SDL_GetError() << endl;
} else {
    cout << "SDL_SetRenderTarget() success" << endl;
}

if (SDL_RenderClear(renderer) != 0) {
    cout << "SDL_RenderClear() Error! " << SDL_GetError() << endl;
} else {
    cout << "SDL_RenderClear() success" << endl;
}

if (SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255) != 0) {
    cout << "SDL_SetRenderDrawColor() Error! " << SDL_GetError() << endl;
} else {
    cout << "SDL_SetRenderDrawColor() success" << endl;
}

if (SDL_RenderFillRect(renderer, NULL) != 0) {
    cout << "SDL_RenderClear() Error! " << SDL_GetError() << endl;
} else {
    cout << "SDL_RenderClear() success" << endl;
}

int w;
int h;
Uint32 format;
int access;

if (SDL_QueryTexture(tempChar, &format, &access, &w, &h) != 0) {
    cout << "SDL_QueryTexture() ERROR : " << SDL_GetError() << endl;
} else {
    cout << "SDL_QueryTexture() no error" << endl;
}

cout << "width is : " << w << " height is : " << h << endl;

if (access == SDL_TEXTUREACCESS_TARGET) {
    cout << "TARGET" << endl;
}

if (format == SDL_PIXELFORMAT_RGBA8888) {
    cout << "format is : SDL_PIXELFORMAT_RGBA8888" << endl;
}

void* readPixels = NULL;
int pitch;

if (SDL_RenderReadPixels(renderer, NULL, 0, readPixels, pitch) != 0) {//12 pitch, 3x4bytes
    //an error occurred
    cout << "SDL_RenderReadPixels() Error, text probably wont work... :-/\n" << SDL_GetError() << endl;
} else {
    cout << "SDL_RenderReadPixels() success" << endl;
}

cout << "pitch returned : " << pitch << endl;

menuMouse = tempChar;

for (int i = 0; i < 5; i++) {
    cout << "i is : " << i << endl;
    char* rowStart = ((char*) readPixels) + i * pitch;
    cout << "pix data is : " << int(rowStart) << endl;
}
</code>```

答:
For some reason you assume that SDL_RenderReadPixels allocates pixels array and returns resulting pitch; it does neither. Calling side passes pixels array big enough to hold data, and its correct pitch, e.g.:

```<code>Uint32 pixels[3*5];
int pitch = sizeof(Uint32)*3;
</code>```

In C/C++, functions does not modify input parameters directly, unless parameter is a reference type (in C++), or value is modified indirectly through pointer, so if function takes int - it is clearly input parameter, not output. E.g. take a look at SDL_CreateWindowAndRenderer, which outputs window and renderer pointers and hence its parameter types are pointer-to-pointer.

Title: Why cant I draw to a texture in SDL2?

Body:
So my main goal is to read the pixel data of a given texture, so to test this, i've created a new texture with target access then drawn it red.

The problem is that when I access the pixel data, SDL_RenderReadPixels() says the pitch is 0, and all the pixel data is 0. Also when I try to draw the new texture, it comes out black.

SDL_Texture* tempChar = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, 3, 5);

if (SDL_SetRenderTarget(renderer, tempChar) != 0) {
    cout << "SDL_SetRenderTarget() Error! " << SDL_GetError() << endl;
} else {
    cout << "SDL_SetRenderTarget() success" << endl;
}

if (SDL_RenderClear(renderer) != 0) {
    cout << "SDL_RenderClear() Error! " << SDL_GetError() << endl;
} else {
    cout << "SDL_RenderClear() success" << endl;
}

if (SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255) != 0) {
    cout << "SDL_SetRenderDrawColor() Error! " << SDL_GetError() << endl;
} else {
    cout << "SDL_SetRenderDrawColor() success" << endl;
}

if (SDL_RenderFillRect(renderer, NULL) != 0) {
    cout << "SDL_RenderClear() Error! " << SDL_GetError() << endl;
} else {
    cout << "SDL_RenderClear() success" << endl;
}

int w;
int h;
Uint32 format;
int access;

if (SDL_QueryTexture(tempChar, &format, &access, &w, &h) != 0) {
    cout << "SDL_QueryTexture() ERROR : " << SDL_GetError() << endl;
} else {
    cout << "SDL_QueryTexture() no error" << endl;
}

cout << "width is : " << w << " height is : " << h << endl;

if (access == SDL_TEXTUREACCESS_TARGET) {
    cout << "TARGET" << endl;
}

if (format == SDL_PIXELFORMAT_RGBA8888) {
    cout << "format is : SDL_PIXELFORMAT_RGBA8888" << endl;
}

void* readPixels = NULL;
int pitch;

if (SDL_RenderReadPixels(renderer, NULL, 0, readPixels, pitch) != 0) {//12 pitch, 3x4bytes
    //an error occurred
    cout << "SDL_RenderReadPixels() Error, text probably wont work... :-/\n" << SDL_GetError() << endl;
} else {
    cout << "SDL_RenderReadPixels() success" << endl;
}

cout << "pitch returned : " << pitch << endl;

menuMouse = tempChar;

for (int i = 0; i < 5; i++) {
    cout << "i is : " << i << endl;
    char* rowStart = ((char*) readPixels) + i * pitch;
    cout << "pix data is : " << int(rowStart) << endl;
}

Body:
For some reason you assume that SDL_RenderReadPixels allocates pixels array and returns resulting pitch; it does neither. Calling side passes pixels array big enough to hold data, and its correct pitch, e.g.:

Uint32 pixels[3*5];
int pitch = sizeof(Uint32)*3;

In C/C++, functions does not modify input parameters directly, unless parameter is a reference type (in C++), or value is modified indirectly through pointer, so if function takes int - it is clearly input parameter, not output. E.g. take a look at SDL_CreateWindowAndRenderer, which outputs window and renderer pointers and hence its parameter types are pointer-to-pointer.


问:
How to change the height of a TextBox?
I am currently learning C# and XAML for UWP apps and have a problem with my TextBoxes.

How do I get the TextBox smaller? Adjusting the font size alone is not enough, even setting the height doesn't bring about any changes. What I noticed is that the Clear button doesn't get smaller, also the X in it doesn't get smaller with the FontSize. And that's probably the problem, because the TextBox probably doesn't want to cut the Clear button and therefore retains the default size, because you can make the box bigger without any problems, but not smaller.

I might add that I use Visual Studio Community 2017 and the TextBox from the existing ToolBox there.

Could someone help me with that? All I've found so far is how to add such a clear button and only on WPF apps.

答:
As jsmyth886 said the MinHeight property will limit the minimum height you can set. If you want to make smaller TextBox, you could create custom style for TextBox like following

```<code><Style TargetType="TextBox" x:Key="MyTextBoxStyle">
    <Setter Property="MinHeight" Value="20"/>
</Style>
</code>```

When you set the Height property to more than the MinHeight, it will take effect.

```<code><TextBox x:Name="MyTextBox" Text="This text box" Style="{StaticResource MyTextBoxStyle}" Height="21" />
</code>```

The above operation is also suitable to MinWidth property.

Title: How to change the height of a TextBox?

Body:
As jsmyth886 said the MinHeight property will limit the minimum height you can set. If you want to make smaller TextBox, you could create custom style for TextBox like following

<Style TargetType="TextBox" x:Key="MyTextBoxStyle">
    <Setter Property="MinHeight" Value="20"/>
</Style>

When you set the Height property to more than the MinHeight, it will take effect.

<TextBox x:Name="MyTextBox" Text="This text box" Style="{StaticResource MyTextBoxStyle}" Height="21" />

The above operation is also suitable to MinWidth property.


问:
How to apply style on svg path in d3js
As I am trying to create horizon chart based on multi year data. I have a query regarding "how to apply style on svg path in d3js to control color based on data?

Fiddle is shared at http://jsfiddle.net/pjrc0yy3/1/

Here, I am able to apply colors on svg but I want to apply actual on path using g element.

May be like below code:

```<code>path.enter().append("path")
            .transition()
            .style("fill", function(d) { return color(d); })
            .attr("transform", t0)
            .attr("d", d0);
</code>```

答:
Change the code to:

```<code>  lineGraph
    .data([newValue])
    .transition()
    .duration(1500)
    .attr('fill', function(d) { return color(d); })
</code>```

Now only the color of the path is changing, if that was your question

Title: How to apply style on svg path in d3js

Body:
As I am trying to create horizon chart based on multi year data. I have a query regarding "how to apply style on svg path in d3js to control color based on data?

Fiddle is shared at http://jsfiddle.net/pjrc0yy3/1/

Here, I am able to apply colors on svg but I want to apply actual on path using g element.

May be like below code:

path.enter().append("path")
            .transition()
            .style("fill", function(d) { return color(d); })
            .attr("transform", t0)
            .attr("d", d0);

Body:
Change the code to:

  lineGraph
    .data([newValue])
    .transition()
    .duration(1500)
    .attr('fill', function(d) { return color(d); })

Now only the color of the path is changing, if that was your question