问:
how to start the appium 1.6.5 by using .bat file
When I am executing the following .bat file it runs the appium 1.4.16 server.

```<code>cd \
"C:/Program Files/Appium/node.exe" "C:/Program Files/Appium/node_modules/appium/bin/Appium.js" --address 127.0.0.1 --chromedriver-port 9516 --bootstrap-port 4725 --selendroid-port 8082 --no-reset --local-timezone
</code>```

Then how to run the 1.6.5 batch file using .bat file

答:
Now it have been solved,

Create the bat file contents as follow:

```<code>cd \
appium --udid T2334RS23 --port 4725 --address 127.0.0.1 --chromedriver-port 9516 --bootstrap-port 4725 --selendroid-port 8082 --no-reset --local-timezone
</code>```

Body:
When I am executing the following .bat file it runs the appium 1.4.16 server.

cd \
"C:/Program Files/Appium/node.exe" "C:/Program Files/Appium/node_modules/appium/bin/Appium.js" --address 127.0.0.1 --chromedriver-port 9516 --bootstrap-port 4725 --selendroid-port 8082 --no-reset --local-timezone

Then how to run the 1.6.5 batch file using .bat file

Body:
Now it have been solved,

Create the bat file contents as follow:

cd \
appium --udid T2334RS23 --port 4725 --address 127.0.0.1 --chromedriver-port 9516 --bootstrap-port 4725 --selendroid-port 8082 --no-reset --local-timezone


来源: stackexchange

问:
Get Index of an Item in a List of Class Items with Timer Member
I am trying to find the index of the Triggered Timer.

I created a list of Class Entry here in Program.cs

```<code>static public List<Entry> Table = new List<Entry>();
</code>```

This is the class called "Entry" with its constructors in Entry.cs

```<code>public class Entry
    {
        public int pktID;

        public Timer pktTimer= new Timer();
    }

public Entry()
      {
      }

public Entry(int _pktID, Boolean idleTimeOutStart)
        {
            this.pktID = _pktID;

            if (idleTimeOutStart == true)
            {
                pktTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf());

                pktTimer.Interval = 10000; // 10000 ms is 10 seconds
                pktTimer.Start();

            }

        }

static void CallDeleteEntry(object sender, System.Timers.ElapsedEventArgs e, int pktIndex)
        {
            Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index
            Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry
        }
</code>```

The items in the list are created randomly. Now each Timer in the List (List Index) will start and then after 10000 msecs, CallDeleteEntry shall be called.

What I need to do is the pass the Index of the Timer when it elapses 10000msec to CallDeleteEntry, so it can remove that item row for the list.

I think something must be modified here to make it work.

```<code>idleTimeOutTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf());
</code>```

The List will look like this

ListIndex | Entry Item

    0     |  pkt | pktTimer

    1     |  pkt | pktTimer

    2     |  pkt | pktTimer

    3     |  pkt | pktTimer

    4     |  pkt | pktTimer

答:
Your pretty close IndexOf requires the item you're trying to get the index of. in this case the Entry class you're trying to get the index of. I believe in your case it would be the key word this, so IndexOf(this).

https://msdn.microsoft.com/en-us/library/8bd0tetb(v=vs.110).aspx

ContentLicense: CC BY-SA 3.0

Body:
I am trying to find the index of the Triggered Timer.

I created a list of Class Entry here in Program.cs

static public List<Entry> Table = new List<Entry>();

This is the class called "Entry" with its constructors in Entry.cs

public class Entry
    {
        public int pktID;

        public Timer pktTimer= new Timer();
    }

public Entry()
      {
      }

public Entry(int _pktID, Boolean idleTimeOutStart)
        {
            this.pktID = _pktID;

            if (idleTimeOutStart == true)
            {
                pktTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf());

                pktTimer.Interval = 10000; // 10000 ms is 10 seconds
                pktTimer.Start();

            }

        }

static void CallDeleteEntry(object sender, System.Timers.ElapsedEventArgs e, int pktIndex)
        {
            Program.Table.RemoveAt(pktIndex); //Removes Entry at this Index
            Program.Table[pktIndex].idleTimeOutTimer.Stop(); //Stops idleTimeOutTimer of This Entry
        }

The items in the list are created randomly. Now each Timer in the List (List Index) will start and then after 10000 msecs, CallDeleteEntry shall be called.

What I need to do is the pass the Index of the Timer when it elapses 10000msec to CallDeleteEntry, so it can remove that item row for the list.

I think something must be modified here to make it work.

idleTimeOutTimer.Elapsed += (sender, e) => CallDeleteEntry(sender, e, Program.Table.IndexOf());

The List will look like this

ListIndex | Entry Item

    0     |  pkt | pktTimer

    1     |  pkt | pktTimer

    2     |  pkt | pktTimer

    3     |  pkt | pktTimer

    4     |  pkt | pktTimer


问:
How to calculate errors on slopes of linear fits when y-errors are asymmetric
I have a data set with values that can be plotted as x-values against y-values.
Data on the y-axis have asymmetric errors, i.e.,

I want to fit these data with a linear function.
I can do this fit in a number of way in python, but all of them have the same problem, that is, how to get the errors of the fit parameters too.

Very related to this, but impossible (or at least, not straightforward) to use scipy.optimize.curve_fit since my data have asymmetric errors on the ordinate (y-axis) in order to get the slope error as well.

Then, how can I calculate errors on slopes of linear fits when y-error bars are asymmetric?

Is there any python function for this?

答:
There's a paper by Barlow+04 https://arxiv.org/abs/physics/0406120 on finding the mean of variables with asymmetric error bars. You could perhaps use these techniques.

The brute force route that I take is to draw many realisations of the variable from a split-normal distribution (https://en.wikipedia.org/wiki/Split_normal_distribution) and store the best-fitting polynomial parameters for them. I then compute the median and 1-sigma upper/lower error bars (from the 84th and 16th percentile from the median, respectively) for each polynomial parameter.

The code below, in Python 2.7.9, does this. There's a function for computing a split-normal value, the errors from the percentiles and fitting a polynomial.

Hope this helps.

```<code>#! /bin/python

from random import choice, gauss
from numpy import polyfit

def split_normal(mus, sigmas_u68, sigmas_l68):
    """
    RET: A split-normal value.
    """

    split_normal = []

    for mu, sigma_u68, sigma_l68 in zip(mus, sigmas_u68, sigmas_l68):

        sigma = choice([sigma_u68, -sigma_l68])
        g = abs(gauss(0.0, 1.0)) * sigma + mu
        split_normal.append(g)

    return split_normal

def errors_84_16(x):
    """
    RET: 1-sigma upper/lower error bars from the 84/16th percentile
         from the median.
    """

    n = len(x)

    index_med = n / 2 # median.
    index_84 = int(round(n * 0.84135)) # 84th percentile from median.
    index_16 = int(round(n * 0.15865))

    x_sorted = sorted(x)
    x_med = x_sorted[index_med]
    x_u68 = x_sorted[index_84] - x_med # 1-sigma upper error.
    x_l68 = x_med - x_sorted[index_16] # 1-sigma lower error.

    return x_med, x_u68, x_l68

def assymetric_polyfit(x, y, y_u68, y_l68, n_mc=500):
    """
    DES: Solves y = a + b * x for assymentric y error bars.
    RET: [a, a_u68, a_l68, b, b_u68, b_l68].
    """

    a_mc = []
    b_mc = []

    for i in xrange(0, n_mc):
        y_mc = split_normal(y, y_u68, y_l68)
        pars = polyfit(x, y_mc, 2)
        a_mc.append(pars[2])
        b_mc.append(pars[1])

    a, a_u68, a_l68 = errors_84_16(a_mc)
    b, b_u68, b_l68 = errors_84_16(b_mc)

    return a, a_u68, a_l68, b, b_u68, b_l68

def example():
    """
    """

    x = [1.0, 2.0, 3.0, 4.0, 5.0]
    y = [5.0, 8.0, 11.0, 14.0, 17.0] # 2 + 3x
    y_u68 = [0.5, 0.5, 0.5, 0.5, 0.5]
    y_l68 = [1.5, 1.5, 1.5, 1.5, 1.5]

    pars = assymetric_polyfit(x, y, y_u68, y_l68)
    print(pars)

if __name__ == '__main__':

    example()
</code>```

Body:
There's a paper by Barlow+04 https://arxiv.org/abs/physics/0406120 on finding the mean of variables with asymmetric error bars. You could perhaps use these techniques.

The brute force route that I take is to draw many realisations of the variable from a split-normal distribution (https://en.wikipedia.org/wiki/Split_normal_distribution) and store the best-fitting polynomial parameters for them. I then compute the median and 1-sigma upper/lower error bars (from the 84th and 16th percentile from the median, respectively) for each polynomial parameter.

The code below, in Python 2.7.9, does this. There's a function for computing a split-normal value, the errors from the percentiles and fitting a polynomial.

Hope this helps.

#! /bin/python

from random import choice, gauss
from numpy import polyfit

def split_normal(mus, sigmas_u68, sigmas_l68):
    """
    RET: A split-normal value.
    """

    split_normal = []

    for mu, sigma_u68, sigma_l68 in zip(mus, sigmas_u68, sigmas_l68):

        sigma = choice([sigma_u68, -sigma_l68])
        g = abs(gauss(0.0, 1.0)) * sigma + mu
        split_normal.append(g)

    return split_normal

def errors_84_16(x):
    """
    RET: 1-sigma upper/lower error bars from the 84/16th percentile
         from the median.
    """

    n = len(x)

    index_med = n / 2 # median.
    index_84 = int(round(n * 0.84135)) # 84th percentile from median.
    index_16 = int(round(n * 0.15865))

    x_sorted = sorted(x)
    x_med = x_sorted[index_med]
    x_u68 = x_sorted[index_84] - x_med # 1-sigma upper error.
    x_l68 = x_med - x_sorted[index_16] # 1-sigma lower error.

    return x_med, x_u68, x_l68

def assymetric_polyfit(x, y, y_u68, y_l68, n_mc=500):
    """
    DES: Solves y = a + b * x for assymentric y error bars.
    RET: [a, a_u68, a_l68, b, b_u68, b_l68].
    """

    a_mc = []
    b_mc = []

    for i in xrange(0, n_mc):
        y_mc = split_normal(y, y_u68, y_l68)
        pars = polyfit(x, y_mc, 2)
        a_mc.append(pars[2])
        b_mc.append(pars[1])

    a, a_u68, a_l68 = errors_84_16(a_mc)
    b, b_u68, b_l68 = errors_84_16(b_mc)

    return a, a_u68, a_l68, b, b_u68, b_l68

def example():
    """
    """

    x = [1.0, 2.0, 3.0, 4.0, 5.0]
    y = [5.0, 8.0, 11.0, 14.0, 17.0] # 2 + 3x
    y_u68 = [0.5, 0.5, 0.5, 0.5, 0.5]
    y_l68 = [1.5, 1.5, 1.5, 1.5, 1.5]

    pars = assymetric_polyfit(x, y, y_u68, y_l68)
    print(pars)

if __name__ == '__main__':

    example()


问:
What's a a good way to stop a pool of threads from running?
I've been working on a project lately, and i need to manage a pair of thread pools.
What the worker threads in the pools do is basically execute some kind of pop operation to each respective queue, eventually wait on a condition variable (pthread_cond_t) if there is no available value in the queue, and once they get an item, parse it and execute operations accordingly.
What i'm concerned about is the fact that i want to have no memory leaks, and to achieve that i noticed that calling a pthread_cancel on each thread when the main process is exiting is definitely a bad idea, as it leaves a lot of garbage around.
The point is, my first thought was to use a exit flag which i can set when the threads need to exit, so that they can easily free memory and call a pthread_exit...
I guess i should set this flag, then send a broadcast signal to the threads waiting on the condition variable and check the flag right after the pop operation...

Is this really the correct way to implement a good thread pool termination? I don't feel that much confident about this...
I'm writing some pseudo-code here to explain what i'm talking about

Each pool thread will run some code structured like this:

```<code>/* Worker thread (which will run on each pool thread) */
{ /* Thread initialization */ ... }
loop {
   value = pop();
   { /* Mutex lock because of the shared flag */ ... }
   if (flag) {{ /* Free memory and unlock mutex */ ... } pthread_exit(); }
   { /* Unlock the mutex */ ... }
   { /* Elaborate value */ ... }
}
return NULL;
</code>```

And there will be some kind of pool_stopRunning() function which will look like:

```<code>/* pool_stopRunning() function code */
{ /* Acquire flag mutex */ ... }
setFlag(flag);
{ /* Unlock flag mutex */ ... }
{ /* Acquire queue mutex */ ... }
pthread_cond_broadcast(...);
{ /* Unlock queue mutex */ ... }
</code>```

Thanks in advance, i just need to be sure that there isn't a fancy-er way to stop a thread pool... (or get to know a better way, by any chance)
As always, i'm sorry if there is any typo, i'm not and english speaker and it's kind of late right now >:

答:
What you are describing will work, but I would suggest a different approach...

You already have a mechanism for assigning tasks to threads, complete with all appropriate synchronization. So instead of complicating the design with some new parallel mechanism, just define a new type of task called "STOP". If there are N threads servicing a queue and you want to terminate them, push N STOP tasks onto the queue. Then just wait for all of the threads to terminate. (This last can be done via "join", so it should not require any new mechanism, either.)

No muss, no fuss.

ContentLicense: CC BY-SA 4.0

Body:
I've been working on a project lately, and i need to manage a pair of thread pools.
What the worker threads in the pools do is basically execute some kind of pop operation to each respective queue, eventually wait on a condition variable (pthread_cond_t) if there is no available value in the queue, and once they get an item, parse it and execute operations accordingly.
What i'm concerned about is the fact that i want to have no memory leaks, and to achieve that i noticed that calling a pthread_cancel on each thread when the main process is exiting is definitely a bad idea, as it leaves a lot of garbage around.
The point is, my first thought was to use a exit flag which i can set when the threads need to exit, so that they can easily free memory and call a pthread_exit...
I guess i should set this flag, then send a broadcast signal to the threads waiting on the condition variable and check the flag right after the pop operation...

Is this really the correct way to implement a good thread pool termination? I don't feel that much confident about this...
I'm writing some pseudo-code here to explain what i'm talking about

Each pool thread will run some code structured like this:

/* Worker thread (which will run on each pool thread) */
{ /* Thread initialization */ ... }
loop {
   value = pop();
   { /* Mutex lock because of the shared flag */ ... }
   if (flag) {{ /* Free memory and unlock mutex */ ... } pthread_exit(); }
   { /* Unlock the mutex */ ... }
   { /* Elaborate value */ ... }
}
return NULL;

And there will be some kind of pool_stopRunning() function which will look like:

/* pool_stopRunning() function code */
{ /* Acquire flag mutex */ ... }
setFlag(flag);
{ /* Unlock flag mutex */ ... }
{ /* Acquire queue mutex */ ... }
pthread_cond_broadcast(...);
{ /* Unlock queue mutex */ ... }

Thanks in advance, i just need to be sure that there isn't a fancy-er way to stop a thread pool... (or get to know a better way, by any chance)
As always, i'm sorry if there is any typo, i'm not and english speaker and it's kind of late right now >:


问:
MVC5 how to find root path in code?
I have some helper methods to build Html output but it only comes out correct on my local dev and not my staging server. The ~ doesn't work since this is not Razor.

My local site path is http://localhost/testSite

My staging path is http://192.168.1.2/

On my local this produces
    src="/testSite/images.test.jpg"

On my staging instance it produces src="//images.test.jpg"

```<code>var baseUrl = HttpRuntime.AppDomainAppPath;
var tb = new TagBuilder("img");
tb.MergeAttribute("title", "Main Image");
tb.MergeAttribute("src", baseUrl +"\images\test.jpg");
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
</code>```

I'm sure there is a method built in to do this on the code side

答:
Hi you can try also with Using double dot notation in URL link

ex:

../file would mean to look in the parent directory for file. If you had just file it would look in the current directory.

Thanks

Title: MVC5 how to find root path in code?

Body:
I have some helper methods to build Html output but it only comes out correct on my local dev and not my staging server. The ~ doesn't work since this is not Razor.

My local site path is http://localhost/testSite

My staging path is http://192.168.1.2/

On my local this produces
    src="/testSite/images.test.jpg"

On my staging instance it produces src="//images.test.jpg"

var baseUrl = HttpRuntime.AppDomainAppPath;
var tb = new TagBuilder("img");
tb.MergeAttribute("title", "Main Image");
tb.MergeAttribute("src", baseUrl +"\images\test.jpg");
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));

I'm sure there is a method built in to do this on the code side


问:
Build a Queue with a limitation of Array of size 5 - but queue can grow
Question: Build a queue class with the enqueue and dequeue methods. However, the language you are using has a bug which does not allow arrays to store more than 5 elements, how would you build that?

I wrote the below code and I was rejected, curious to understand what is the issue and why I was rejected, fyi - this is in technical phone screen.

```<code>static LinkedList<Queue<Integer>> list = new LinkedList<Queue<Integer>>();

public static void enQueue(Integer element){

    //iterating the linkedlist....
    while(true){ //todo
        Queue<Integer> curr;
        if(list.size() > 0)
            curr = list.getLast();
        else{
            curr = new LinkedList<Integer>();
            list.add(curr);
        }
        if(curr.size() < 5){
            curr.add(element);
            System.out.println("enqueued:" + element);
            break;
        } else{
            Queue<Integer> newQueue = new LinkedList<Integer>();
            newQueue.add(element);
            list.add(newQueue); //adding the new Queue of size(5) to the list
            break;
        }
    }
}

public static Integer deQueue(){
    LinkedList<Queue<Integer>> node = list;
    if(!isEmpty()){
        Integer retValue = 0;
        while(list.size() > 0){
            Queue<Integer> q = node.getFirst();
            if(!q.isEmpty()){
                retValue =  q.poll();
                break;
            }else{
                node.removeFirst();
            }
        }
        return retValue;
    }else{
        System.out.println("No such element found");
        return -1; //throw new NoSuchElementException("no element found");
    }
}

public static boolean isEmpty(){
    return list.size() == 0;
}
</code>```

答:
I guess the question is to check on your implementation of queue data structure  with arrays, which cannot be more than size of 5.

I would have something like

```<code>Class Queue {

int[][] data;
int maxSize = 25; //5 * 5
int[] front;
int[] rear;

Enqeue(int element) {
   //Check for queue full
   //Increment front last index, if it crosses 5. Increment previous index
   //Use the front index identify data element
   //Put the data
}

Dequeue() {
   //Check for queue empty

   //Use the rear index identify data element
   //get the data
   //Increment rear last index, if it crosses 5. Increment previous index
   //Return the data

}

}
</code>```

The queue size can be easily scaled to big numbers.

Hope it helps!

Body:
Question: Build a queue class with the enqueue and dequeue methods. However, the language you are using has a bug which does not allow arrays to store more than 5 elements, how would you build that?

I wrote the below code and I was rejected, curious to understand what is the issue and why I was rejected, fyi - this is in technical phone screen.

static LinkedList<Queue<Integer>> list = new LinkedList<Queue<Integer>>();

public static void enQueue(Integer element){

    //iterating the linkedlist....
    while(true){ //todo
        Queue<Integer> curr;
        if(list.size() > 0)
            curr = list.getLast();
        else{
            curr = new LinkedList<Integer>();
            list.add(curr);
        }
        if(curr.size() < 5){
            curr.add(element);
            System.out.println("enqueued:" + element);
            break;
        } else{
            Queue<Integer> newQueue = new LinkedList<Integer>();
            newQueue.add(element);
            list.add(newQueue); //adding the new Queue of size(5) to the list
            break;
        }
    }
}

public static Integer deQueue(){
    LinkedList<Queue<Integer>> node = list;
    if(!isEmpty()){
        Integer retValue = 0;
        while(list.size() > 0){
            Queue<Integer> q = node.getFirst();
            if(!q.isEmpty()){
                retValue =  q.poll();
                break;
            }else{
                node.removeFirst();
            }
        }
        return retValue;
    }else{
        System.out.println("No such element found");
        return -1; //throw new NoSuchElementException("no element found");
    }
}

public static boolean isEmpty(){
    return list.size() == 0;
}

Body:
I guess the question is to check on your implementation of queue data structure  with arrays, which cannot be more than size of 5.

I would have something like

Class Queue {

int[][] data;
int maxSize = 25; //5 * 5
int[] front;
int[] rear;

Enqeue(int element) {
   //Check for queue full
   //Increment front last index, if it crosses 5. Increment previous index
   //Use the front index identify data element
   //Put the data
}

Dequeue() {
   //Check for queue empty

   //Use the rear index identify data element
   //get the data
   //Increment rear last index, if it crosses 5. Increment previous index
   //Return the data

}

}

The queue size can be easily scaled to big numbers.

Hope it helps!


问:
How to make a column autowrap when using data grid
I have some long string in the column. How to make a column auto-wrapping?</p>

答:
For a DataGridTextColumn you can use this</p>

```<code><DataGridTextColumn ...>
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="TextBlock">
            <Setter Property="TextWrapping" Value="Wrap"/>
        </Style>
    </DataGridTextColumn.ElementStyle>
    <DataGridTextColumn.EditingElementStyle>
        <Style TargetType="TextBox">
            <Setter Property="TextWrapping" Value="Wrap"/>
        </Style>
    </DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
For a DataGridTextColumn you can use this

<DataGridTextColumn ...>
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="TextBlock">
            <Setter Property="TextWrapping" Value="Wrap"/>
        </Style>
    </DataGridTextColumn.ElementStyle>
    <DataGridTextColumn.EditingElementStyle>
        <Style TargetType="TextBox">
            <Setter Property="TextWrapping" Value="Wrap"/>
        </Style>
    </DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>


问:
error installing glove-python : 'cl.exe' failed with exit status 2
I am trying to install glove-python package on python3.5 (x64) and I got errors as it is shown below.

Note that I have TDM-GCC-64, MinGW32,  MinGW64  ,Cygwin, microsot visual c++ for python 2.7 , microsoft visual 2008 (x64) and  microsoft visual c++ 2015 (x64) Redistributable installed on my windows 10 to try to solve the problem.

I tried many solutions like creating distutils.cfg file to build package using mingw32/cygwin/mingw64 but all my trials gave me different errors! so I deleted the distutils.cfg file at all , But also this gives me an error as it is shown below .

Note: the path written in the error is for microsoft visual c++ for python 2.7 (but I am using python35) so this may be the cause of the error ?

Also I feel that the error may be due to Cython not running . I installed Cython 0.25.2 using pip install .But when I run pycharm debugger it gives me a warning that debugger speedups using cython not found.Also I got errors (during my trials to install the package by different ways) when building "glove.glove_cython".

Here is the error :

```<code>C:\Users\ESCA>pip3 install glove-python
Collecting glove-python
Using cached glove_python-0.1.0.tar.gz
Requirement already satisfied: numpy in c:\users\esca\appdata\local\programs\python\python35\lib\site-packages (from glove-python)
Requirement already satisfied: scipy in c:\users\esca\appdata\local\programs\python\python35\lib\site-packages (from glove-python)
Building wheels for collected packages: glove-python
Running setup.py bdist_wheel for glove-python ... error
Complete output from command c:\users\esca\appdata\local\programs\python\python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ESCA\\AppData\\Local\\Temp\\pip-build-4tm726dc\\glove-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\ESCA\AppData\Local\Temp\tmp0war2fdwpip-wheel- --python-tag cp35:
running bdist_wheel
running build
running build_py
creating build
creating build\lib.win-amd64-3.5
creating build\lib.win-amd64-3.5\glove
copying glove\corpus.py -> build\lib.win-amd64-3.5\glove
copying glove\glove.py -> build\lib.win-amd64-3.5\glove
copying glove\__init__.py -> build\lib.win-amd64-3.5\glove
running build_ext
building 'glove.glove_cython' extension
creating build\temp.win-amd64-3.5
creating build\temp.win-amd64-3.5\Release
creating build\temp.win-amd64-3.5\Release\glove
C:\Users\ESCA\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\bin\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Ic:\users\esca\appdata\local\programs\python\python35\include -Ic:\users\esca\appdata\local\programs\python\python35\include /Tcglove/glove_cython.c /Fobuild\temp.win-amd64-3.5\Release\glove/glove_cython.obj -fopenmp -ffast-math -march=native
 cl : Command line warning D9002 : ignoring unknown option '-fopenmp'
 cl : Command line warning D9002 : ignoring unknown option '-ffast-math'
 cl : Command line warning D9002 : ignoring unknown option '-march=native'
 glove_cython.c
 c:\users\esca\appdata\local\programs\python\python35\include\pyconfig.h(68) : fatal error C1083: Cannot open include file: 'io.h': No such file or directory
error: command 'C:\\Users\\ESCA\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\bin\\cl.exe' failed with exit status 2

----------------------------------------
Failed building wheel for glove-python
Running setup.py clean for glove-python
Complete output from command c:\users\esca\appdata\local\programs\python\python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ESCA\\AppData\\Local\\Temp\\pip-build-4tm726dc\\glove-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" clean --all:
usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
 or: -c --help [cmd1 cmd2 ...]
 or: -c --help-commands
 or: -c cmd --help

error: option --all not recognized

----------------------------------------
Failed cleaning build dir for glove-python
Failed to build glove-python
Installing collected packages: glove-python
Running setup.py install for glove-python ... error
Complete output from command c:\users\esca\appdata\local\programs\python\python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ESCA\\AppData\\Local\\Temp\\pip-build-4tm726dc\\glove-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\ESCA\AppData\Local\Temp\pip-gs05_i6s-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
running build_ext
building 'glove.glove_cython' extension
C:\Users\ESCA\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\bin\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Ic:\users\esca\appdata\local\programs\python\python35\include -Ic:\users\esca\appdata\local\programs\python\python35\include /Tcglove/glove_cython.c /Fobuild\temp.win-amd64-3.5\Release\glove/glove_cython.obj -fopenmp -ffast-math -march=native
cl : Command line warning D9002 : ignoring unknown option '-fopenmp'
cl : Command line warning D9002 : ignoring unknown option '-ffast-math'
cl : Command line warning D9002 : ignoring unknown option '-march=native'
glove_cython.c
c:\users\esca\appdata\local\programs\python\python35\include\pyconfig.h(68) : fatal error C1083: Cannot open include file: 'io.h': No such file or directory
error: command 'C:\\Users\\ESCA\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\bin\\cl.exe' failed with exit status 2

----------------------------------------
Command "c:\users\esca\appdata\local\programs\python\python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ESCA\\AppData\\Local\\Temp\\pip-build-4tm726dc\\glove-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\ESCA\AppData\Local\Temp\pip-gs05_i6s-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\ESCA\AppData\Local\Temp\pip-build-4tm726dc\glove-python\
</code>```

答:
Try out this setup.py instead when you're compiling, works on the default install directories in Windows x64 machines:

```<code>from Cython.Distutils import build_ext
import numpy as np
import os

try:
    from setuptools import setup
    from setuptools import Extension
except ImportError:
    from distutils.core import setup
    from distutils.extension import Extension

module = 'mymodule'

ext_modules = [Extension(module, sources=[module + '.pyx'],
              include_dirs=['C://Program Files (x86)//Windows Kits//10//Include//10.0.10240.0//ucrt','C://Program Files (x86)//Microsoft Visual Studio 14.0//VC//include','C://Program Files (x86)//Windows Kits//8.1//Include//shared'],
              library_dirs=['C://Program Files (x86)//Windows Kits//8.1//bin//x64', 'C://Windows//System32', 'C://Program Files (x86)//Microsoft Visual Studio 14.0//VC//lib//amd64', 'C://Program Files (x86)//Windows Kits//8.1//Lib//winv6.3//um//x64', 'C://Program Files (x86)//Windows Kits//10//Lib//10.0.10240.0//ucrt//x64'],
              extra_compile_args=['/Ot', '/favor:INTEL64', '/EHsc', '/GA', '/openmp'],
              language='c++')]

setup(
    name = module,
    ext_modules = ext_modules,
    cmdclass = {'build_ext': build_ext},
    include_dirs = [np.get_include(), os.path.join(np.get_include(), 'numpy')]
    )
</code>```

Note the above may need some serious editing for your paths to each include directory, as well as for the package you're installing.  You're better off with Python 3.5 on Windows x64 to install Visual Studio 2015 Community then doing the python setup.py install from a VS command prompt that sets up all the include directories for you, either the VS2015 x64 native tools or MSBuild command prompt for VS2015 which appear after installing Community.  Note that the VS2015 versions require Community at least to build Python modules as they got rid of the prior ability to compile via Microsoft redistributables.

Body:
I am trying to install glove-python package on python3.5 (x64) and I got errors as it is shown below.

Note that I have TDM-GCC-64, MinGW32,  MinGW64  ,Cygwin, microsot visual c++ for python 2.7 , microsoft visual 2008 (x64) and  microsoft visual c++ 2015 (x64) Redistributable installed on my windows 10 to try to solve the problem.

I tried many solutions like creating distutils.cfg file to build package using mingw32/cygwin/mingw64 but all my trials gave me different errors! so I deleted the distutils.cfg file at all , But also this gives me an error as it is shown below .

Note: the path written in the error is for microsoft visual c++ for python 2.7 (but I am using python35) so this may be the cause of the error ?

Also I feel that the error may be due to Cython not running . I installed Cython 0.25.2 using pip install .But when I run pycharm debugger it gives me a warning that debugger speedups using cython not found.Also I got errors (during my trials to install the package by different ways) when building "glove.glove_cython".

Here is the error :

C:\Users\ESCA>pip3 install glove-python
Collecting glove-python
Using cached glove_python-0.1.0.tar.gz
Requirement already satisfied: numpy in c:\users\esca\appdata\local\programs\python\python35\lib\site-packages (from glove-python)
Requirement already satisfied: scipy in c:\users\esca\appdata\local\programs\python\python35\lib\site-packages (from glove-python)
Building wheels for collected packages: glove-python
Running setup.py bdist_wheel for glove-python ... error
Complete output from command c:\users\esca\appdata\local\programs\python\python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ESCA\\AppData\\Local\\Temp\\pip-build-4tm726dc\\glove-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\ESCA\AppData\Local\Temp\tmp0war2fdwpip-wheel- --python-tag cp35:
running bdist_wheel
running build
running build_py
creating build
creating build\lib.win-amd64-3.5
creating build\lib.win-amd64-3.5\glove
copying glove\corpus.py -> build\lib.win-amd64-3.5\glove
copying glove\glove.py -> build\lib.win-amd64-3.5\glove
copying glove\__init__.py -> build\lib.win-amd64-3.5\glove
running build_ext
building 'glove.glove_cython' extension
creating build\temp.win-amd64-3.5
creating build\temp.win-amd64-3.5\Release
creating build\temp.win-amd64-3.5\Release\glove
C:\Users\ESCA\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\bin\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Ic:\users\esca\appdata\local\programs\python\python35\include -Ic:\users\esca\appdata\local\programs\python\python35\include /Tcglove/glove_cython.c /Fobuild\temp.win-amd64-3.5\Release\glove/glove_cython.obj -fopenmp -ffast-math -march=native
 cl : Command line warning D9002 : ignoring unknown option '-fopenmp'
 cl : Command line warning D9002 : ignoring unknown option '-ffast-math'
 cl : Command line warning D9002 : ignoring unknown option '-march=native'
 glove_cython.c
 c:\users\esca\appdata\local\programs\python\python35\include\pyconfig.h(68) : fatal error C1083: Cannot open include file: 'io.h': No such file or directory
error: command 'C:\\Users\\ESCA\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\bin\\cl.exe' failed with exit status 2

----------------------------------------
Failed building wheel for glove-python
Running setup.py clean for glove-python
Complete output from command c:\users\esca\appdata\local\programs\python\python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ESCA\\AppData\\Local\\Temp\\pip-build-4tm726dc\\glove-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" clean --all:
usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
 or: -c --help [cmd1 cmd2 ...]
 or: -c --help-commands
 or: -c cmd --help

error: option --all not recognized

----------------------------------------
Failed cleaning build dir for glove-python
Failed to build glove-python
Installing collected packages: glove-python
Running setup.py install for glove-python ... error
Complete output from command c:\users\esca\appdata\local\programs\python\python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ESCA\\AppData\\Local\\Temp\\pip-build-4tm726dc\\glove-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\ESCA\AppData\Local\Temp\pip-gs05_i6s-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
running build_ext
building 'glove.glove_cython' extension
C:\Users\ESCA\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\bin\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Ic:\users\esca\appdata\local\programs\python\python35\include -Ic:\users\esca\appdata\local\programs\python\python35\include /Tcglove/glove_cython.c /Fobuild\temp.win-amd64-3.5\Release\glove/glove_cython.obj -fopenmp -ffast-math -march=native
cl : Command line warning D9002 : ignoring unknown option '-fopenmp'
cl : Command line warning D9002 : ignoring unknown option '-ffast-math'
cl : Command line warning D9002 : ignoring unknown option '-march=native'
glove_cython.c
c:\users\esca\appdata\local\programs\python\python35\include\pyconfig.h(68) : fatal error C1083: Cannot open include file: 'io.h': No such file or directory
error: command 'C:\\Users\\ESCA\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\bin\\cl.exe' failed with exit status 2

----------------------------------------
Command "c:\users\esca\appdata\local\programs\python\python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ESCA\\AppData\\Local\\Temp\\pip-build-4tm726dc\\glove-python\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\ESCA\AppData\Local\Temp\pip-gs05_i6s-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\ESCA\AppData\Local\Temp\pip-build-4tm726dc\glove-python\

Body:
Try out this setup.py instead when you're compiling, works on the default install directories in Windows x64 machines:

from Cython.Distutils import build_ext
import numpy as np
import os

try:
    from setuptools import setup
    from setuptools import Extension
except ImportError:
    from distutils.core import setup
    from distutils.extension import Extension

module = 'mymodule'

ext_modules = [Extension(module, sources=[module + '.pyx'],
              include_dirs=['C://Program Files (x86)//Windows Kits//10//Include//10.0.10240.0//ucrt','C://Program Files (x86)//Microsoft Visual Studio 14.0//VC//include','C://Program Files (x86)//Windows Kits//8.1//Include//shared'],
              library_dirs=['C://Program Files (x86)//Windows Kits//8.1//bin//x64', 'C://Windows//System32', 'C://Program Files (x86)//Microsoft Visual Studio 14.0//VC//lib//amd64', 'C://Program Files (x86)//Windows Kits//8.1//Lib//winv6.3//um//x64', 'C://Program Files (x86)//Windows Kits//10//Lib//10.0.10240.0//ucrt//x64'],
              extra_compile_args=['/Ot', '/favor:INTEL64', '/EHsc', '/GA', '/openmp'],
              language='c++')]

setup(
    name = module,
    ext_modules = ext_modules,
    cmdclass = {'build_ext': build_ext},
    include_dirs = [np.get_include(), os.path.join(np.get_include(), 'numpy')]
    )

Note the above may need some serious editing for your paths to each include directory, as well as for the package you're installing.  You're better off with Python 3.5 on Windows x64 to install Visual Studio 2015 Community then doing the python setup.py install from a VS command prompt that sets up all the include directories for you, either the VS2015 x64 native tools or MSBuild command prompt for VS2015 which appear after installing Community.  Note that the VS2015 versions require Community at least to build Python modules as they got rid of the prior ability to compile via Microsoft redistributables.


问:
How can I fix Visual Studio 2015 exception Microsoft.vshup.server.httphostx64.exe has stopped working when run project
I installed Visual Studio Community 2015 and I created a project, but when I run the project I get this exception:

Microsoft.vshup.server.httphostx64.exe has stopped working

I am using Windows 8.

I would appreciate it if you could help me.

答:
I had the same issue due to corrupted drivers but it happened while debugging, I fixed it by
unchecking "use hardware graphic acceleration " from Tools > options > environment
and followed the steps in this post:

https://thomas-barthelemy.github.io/2015/05/01/visual-studio-vshub/

Navigate to

"C:\Program Files (x86)\Common Files\Microsoft Shared\VsHub\1.0.0.0"

Stop Visual Studio if started

rename Microsoft.VsHub.Server.HttpHostx64.exe to Microsoft.VsHub.Server.HttpHostx64.exe.bak

Create a copy of Microsoft.VsHub.Server.HttpHost.exe and rename it Microsoft.VsHub.Server.HttpHostx64.exe

Re-start Visual Studio


问:
LayerDrawable programmatically
Since my application's color theme is dynamic i can only create background drawables using colors and shapedrawables,
i want to build a edittext background drawable with colors and shapes as shown below.
But i want to do this programatically

How to build this same drawable programatically?

```<code><item>
    <shape>
        <solid android:color="@android:color/yellow" />
    </shape>
</item>

<!-- main color -->
<item
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp">
    <shape>
        <solid android:color="@android:color/white" />
    </shape>
</item>

<!-- draw another block to cut-off the left and right bars -->
<item android:bottom="10dp">
    <shape>
        <solid android:color="@android:color/white" />
    </shape>
</item>
</code>```

this is what i tried....

```<code>    GradientDrawable border = new GradientDrawable();
    border.setShape(GradientDrawable.RECTANGLE);
    border.setColor(Color.WHITE);

    GradientDrawable background = new GradientDrawable();
    background.setShape(GradientDrawable.RECTANGLE);
    background.setColor(Color.YELLOW);

    GradientDrawable clip = new GradientDrawable();
    clip.setShape(GradientDrawable.RECTANGLE);
    border.setColor(Color.WHITE);

    Drawable[] layers = {background, border, clip};
    LayerDrawable layerDrawable = new LayerDrawable(layers);

    layerDrawable.setLayerInset(0, 0, 0, 0, 0);
    layerDrawable.setLayerInset(1, 1, 0, 1, 1);
    layerDrawable.setLayerInset(2, 0, 0, 0, 10);
</code>```

but the result is different....please help....!

答:
This also works with Gradient Drawables:</p>

```<code>GradientDrawable border = new GradientDrawable();
border.setColor(Color.White);

GradientDrawable background = new GradientDrawable();
background.setColor(Color.Black);

GradientDrawable clip = new GradientDrawable();
clip.setColor(Color.White);

GradientDrawable[] layers = {background, border, clip};
LayerDrawable layerDrawable = new LayerDrawable(layers);

layerDrawable.setLayerInset(0, 0, 0, 0, 0);
layerDrawable.setLayerInset(1, 1, 0, 1, 1);
layerDrawable.setLayerInset(2, 0, 0, 0, 10);
</code>```

Title: LayerDrawable programmatically

Body:
Since my application's color theme is dynamic i can only create background drawables using colors and shapedrawables,
i want to build a edittext background drawable with colors and shapes as shown below.
But i want to do this programatically

How to build this same drawable programatically?

<item>
    <shape>
        <solid android:color="@android:color/yellow" />
    </shape>
</item>

<item
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp">
    <shape>
        <solid android:color="@android:color/white" />
    </shape>
</item>

<item android:bottom="10dp">
    <shape>
        <solid android:color="@android:color/white" />
    </shape>
</item>

this is what i tried....

    GradientDrawable border = new GradientDrawable();
    border.setShape(GradientDrawable.RECTANGLE);
    border.setColor(Color.WHITE);

    GradientDrawable background = new GradientDrawable();
    background.setShape(GradientDrawable.RECTANGLE);
    background.setColor(Color.YELLOW);

    GradientDrawable clip = new GradientDrawable();
    clip.setShape(GradientDrawable.RECTANGLE);
    border.setColor(Color.WHITE);

    Drawable[] layers = {background, border, clip};
    LayerDrawable layerDrawable = new LayerDrawable(layers);

    layerDrawable.setLayerInset(0, 0, 0, 0, 0);
    layerDrawable.setLayerInset(1, 1, 0, 1, 1);
    layerDrawable.setLayerInset(2, 0, 0, 0, 10);

but the result is different....please help....!

Body:
This also works with Gradient Drawables:

GradientDrawable border = new GradientDrawable();
border.setColor(Color.White);

GradientDrawable background = new GradientDrawable();
background.setColor(Color.Black);

GradientDrawable clip = new GradientDrawable();
clip.setColor(Color.White);

GradientDrawable[] layers = {background, border, clip};
LayerDrawable layerDrawable = new LayerDrawable(layers);

layerDrawable.setLayerInset(0, 0, 0, 0, 0);
layerDrawable.setLayerInset(1, 1, 0, 1, 1);
layerDrawable.setLayerInset(2, 0, 0, 0, 10);


问:
MVC IAuthenticationFilter Windows Authentication Overwriting principal and caching
Sorry in advance for the essay.

I have an MVC application which uses windows authentication.
A number of roles and 'system actions' have been stored in a database.
I've created a custom principal which has a base of ClaimsPrincipal.
I've also created an AuthenticationFilter which implements IAuthenticationFilter.
In the filter, i create a new instance of my custom principal, add the roles and 'system actions' as claims, and then assign it to the filter.Principal.

From there i have a custom AuthorizationAttribute which will make use of these roles and system actions. (i.e. each controller/action will have a [CustomAuthorizationAttribute(Roles = "blah", SystemActions = "blah")])

Additionally - i have a disclaimer page - which when the user agrees, needs to store a claim in my CustomPrincipal. my custom authorization attribute then checks to see if that claim exists.

Now that the background is out of the way;
The issue is that i need to cache this principal somehow - so that i don't have to hit the database on every request.
Am i best to store it in session? Or a cookie? Or is there some other way to do it?
What are the pros and cons of each?
I was leaning towards using a cookie - although this decision is not made with much knowledge of the pros/cons of each (hence the above question).
How would i go about implementing the cookie?

From the disclaimer page, i would then need to add my 'DisclaimerAccepted' claim, and update the cache.

AuthFilter code for reference:

```<code>public class AuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
        var principal = new CustomPrincipal(filterContext.Principal);

        var roles = GetRolesForUser(principal.Identity.Name);
        var systemActions = new List<SystemAction>();

        foreach (var role in roles)
        {
            principal.AddRole(role.Name);
            systemActions.AddRange(GetSystemActionsForRole(role.Id));
        }

        principal.AddSystemActions(systemActions.Select(a => a.Name));

        filterContext.Principal = principal;
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            filterContext.Result = new HttpUnauthorizedResult();
    }
}
</code>```

答:
The issue is that i need to cache this principal somehow - so that i
  don't have to hit the database on every request. Am i best to store it
  in session?

You can use OWIN Cookie middleware in which we store claims inside cookie so that we only query database once.

On subsequent request, OWIN Cookie Middleware retrieves the claims from the cookie, and add those to Principle object.

Additionally - i have a disclaimer page - which when the user agrees,
  needs to store a claim in my CustomPrincipal.

If you want to add new claims, you will need to call authenticationManager.SignIn(identity); again.

Startup.cs

Configure OWIN Cookie Middleware at startup.

```<code>[assembly: OwinStartup(typeof(YourApplication.Startup))]
namespace YourApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/Account/Login")
            });
        }
    }
}
</code>```

OwinAuthenticationService

```<code>public class OwinAuthenticationService : IAuthenticationService
{
    private readonly HttpContextBase _context;
    private const string AuthenticationType = "ApplicationCookie";

    public OwinAuthenticationService(HttpContextBase context)
    {
        _context = context;
    }

    public void SignIn(User user)
    {
        IList<Claim> claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.GivenName, user.FirstName),
            new Claim(ClaimTypes.Surname, user.LastName),
        };

        ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);

        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;

        authenticationManager.SignIn(identity);
    }

    public void SignOut()
    {
        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;

        authenticationManager.SignOut(AuthenticationType);
    }
}
</code>```

You can look at my working sample project at GitHub.

Body:
Sorry in advance for the essay.

I have an MVC application which uses windows authentication.
A number of roles and 'system actions' have been stored in a database.
I've created a custom principal which has a base of ClaimsPrincipal.
I've also created an AuthenticationFilter which implements IAuthenticationFilter.
In the filter, i create a new instance of my custom principal, add the roles and 'system actions' as claims, and then assign it to the filter.Principal.

From there i have a custom AuthorizationAttribute which will make use of these roles and system actions. (i.e. each controller/action will have a [CustomAuthorizationAttribute(Roles = "blah", SystemActions = "blah")])

Additionally - i have a disclaimer page - which when the user agrees, needs to store a claim in my CustomPrincipal. my custom authorization attribute then checks to see if that claim exists.

Now that the background is out of the way;
The issue is that i need to cache this principal somehow - so that i don't have to hit the database on every request.
Am i best to store it in session? Or a cookie? Or is there some other way to do it?
What are the pros and cons of each?
I was leaning towards using a cookie - although this decision is not made with much knowledge of the pros/cons of each (hence the above question).
How would i go about implementing the cookie?

From the disclaimer page, i would then need to add my 'DisclaimerAccepted' claim, and update the cache.

AuthFilter code for reference:

public class AuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
        var principal = new CustomPrincipal(filterContext.Principal);

        var roles = GetRolesForUser(principal.Identity.Name);
        var systemActions = new List<SystemAction>();

        foreach (var role in roles)
        {
            principal.AddRole(role.Name);
            systemActions.AddRange(GetSystemActionsForRole(role.Id));
        }

        principal.AddSystemActions(systemActions.Select(a => a.Name));

        filterContext.Principal = principal;
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            filterContext.Result = new HttpUnauthorizedResult();
    }
}

Body:
The issue is that i need to cache this principal somehow - so that i
  don't have to hit the database on every request. Am i best to store it
  in session?

You can use OWIN Cookie middleware in which we store claims inside cookie so that we only query database once.

On subsequent request, OWIN Cookie Middleware retrieves the claims from the cookie, and add those to Principle object.

Additionally - i have a disclaimer page - which when the user agrees,
  needs to store a claim in my CustomPrincipal.

If you want to add new claims, you will need to call authenticationManager.SignIn(identity); again.

Startup.cs

Configure OWIN Cookie Middleware at startup.

[assembly: OwinStartup(typeof(YourApplication.Startup))]
namespace YourApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/Account/Login")
            });
        }
    }
}

OwinAuthenticationService

public class OwinAuthenticationService : IAuthenticationService
{
    private readonly HttpContextBase _context;
    private const string AuthenticationType = "ApplicationCookie";

    public OwinAuthenticationService(HttpContextBase context)
    {
        _context = context;
    }

    public void SignIn(User user)
    {
        IList<Claim> claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.GivenName, user.FirstName),
            new Claim(ClaimTypes.Surname, user.LastName),
        };

        ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);

        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;

        authenticationManager.SignIn(identity);
    }

    public void SignOut()
    {
        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;

        authenticationManager.SignOut(AuthenticationType);
    }
}

You can look at my working sample project at GitHub.


问:
Concatenate multiple instances of complex data structure in python
To give some background: often in experimental science we have a set of probes at different locations that record some variables (temperature and velocity here) in time. These probes may be interrupted at certain times and so what we are left with are chunks of restart data that just continue where the previous data set ended. I have created an example data set to show this, and now the only thing is to find an elegant way of concatenating the "chunks" of data collected:

```<code>import pandas as pd
import numpy as np

dimS = 1  # dimension of a scalar variable
dimV = 3  # dimension of a vector variable
Np = 3    # number of measurement locations
Nt = 10   # time samples

def create_single_probe(Nt):
    """
    Create fictitious data for a probe
    """
    probe = {}
    probe["temp"] = np.random.rand(dimS*Nt).reshape(dimS,Nt)
    probe["velo"] = np.random.rand(dimV*Nt).reshape(dimV,Nt)
    probe["loc"] = np.random.rand(3)
    return probe

def create_multiple_probes(Np,Nt):
    """
    Gather mutliple probes into dict
    """
    probes = []

    for i in range(Np):
        probes.append(create_single_probe(Nt))

    data = {}
    data["time"] = range(Nt)
    data["probes"] = probes

    return data

# Create data that we want to concatenate
restarts = [create_multiple_probes(Np,Nt) for i in range(3)]

# Now we want to concatenate the entries of restarts

def concat_complex_dict(restarts):

   # Solution here...

   return concat_data
</code>```

in this example the location of the probe for each restart location will change with the new restart data, but this is not the case in reality.

After concatenation I expect the following:

concat_data["time"] to be a list or array of length 30

concat_data["probes"] to be a list of length 3 (since there are three probe locations) where each entry is a dictionary such that the ith entry we have

concat_data["probes"][i]["temp"] is an array length 30 and
concat_data["probes"][i]["velo"] is an array length 3x30

I can make a very laborious solution whereby I go through all the elements of my dictionary that I want concatenate with a bunch of lists but I am wondering if there is a more elegant way maybe using pandas...

I hope it makes sense what I want to do and any suggestions would be helpful.

答:
Here is my solution which should work. However it is tremendously ugly, and difficult to follow...</p>

```<code>def concat_complex_dict(lst):

    cdata = {}

    # Concatenate the time data
    first = True
    for x in lst:
        time = x["time"]
    if first:
        ctime = time
        first = False
    else:
        ctime = np.concatenate((ctime,time))

    cdata["time"] = ctime

    cdata["probes"] = []

    # Concatenate the probe data

    nLoc = len(lst[0]["probes"])
    for i in range(nLoc):
    dic = lst[0]["probes"][i]
    cprobe = {}
    for key, _ in dic.iteritems():
        first = True
        for j in range(len(lst)):
            if first:
            cprobe[key] = np.atleast_2d(lst[j]["probes"][i][key])
            first = False
            else:
            if key == "loc":
            break # dont concatenate the location as it doesnt change
            cprobe[key] = np.concatenate((cprobe[key],lst[j]["probes"][i][key]),axis=1)

        cdata["probes"].append(cprobe)

    return cdata
</code>```

Body:
To give some background: often in experimental science we have a set of probes at different locations that record some variables (temperature and velocity here) in time. These probes may be interrupted at certain times and so what we are left with are chunks of restart data that just continue where the previous data set ended. I have created an example data set to show this, and now the only thing is to find an elegant way of concatenating the "chunks" of data collected:

import pandas as pd
import numpy as np

dimS = 1  # dimension of a scalar variable
dimV = 3  # dimension of a vector variable
Np = 3    # number of measurement locations
Nt = 10   # time samples

def create_single_probe(Nt):
    """
    Create fictitious data for a probe
    """
    probe = {}
    probe["temp"] = np.random.rand(dimS*Nt).reshape(dimS,Nt)
    probe["velo"] = np.random.rand(dimV*Nt).reshape(dimV,Nt)
    probe["loc"] = np.random.rand(3)
    return probe

def create_multiple_probes(Np,Nt):
    """
    Gather mutliple probes into dict
    """
    probes = []

    for i in range(Np):
        probes.append(create_single_probe(Nt))

    data = {}
    data["time"] = range(Nt)
    data["probes"] = probes

    return data

# Create data that we want to concatenate
restarts = [create_multiple_probes(Np,Nt) for i in range(3)]

# Now we want to concatenate the entries of restarts

def concat_complex_dict(restarts):

   # Solution here...

   return concat_data

in this example the location of the probe for each restart location will change with the new restart data, but this is not the case in reality.

After concatenation I expect the following:

concat_data["time"] to be a list or array of length 30

concat_data["probes"] to be a list of length 3 (since there are three probe locations) where each entry is a dictionary such that the ith entry we have

concat_data["probes"][i]["temp"] is an array length 30 and
concat_data["probes"][i]["velo"] is an array length 3x30

I can make a very laborious solution whereby I go through all the elements of my dictionary that I want concatenate with a bunch of lists but I am wondering if there is a more elegant way maybe using pandas...

I hope it makes sense what I want to do and any suggestions would be helpful.

Body:
Here is my solution which should work. However it is tremendously ugly, and difficult to follow...

def concat_complex_dict(lst):

    cdata = {}

    # Concatenate the time data
    first = True
    for x in lst:
        time = x["time"]
    if first:
        ctime = time
        first = False
    else:
        ctime = np.concatenate((ctime,time))

    cdata["time"] = ctime

    cdata["probes"] = []

    # Concatenate the probe data

    nLoc = len(lst[0]["probes"])
    for i in range(nLoc):
    dic = lst[0]["probes"][i]
    cprobe = {}
    for key, _ in dic.iteritems():
        first = True
        for j in range(len(lst)):
            if first:
            cprobe[key] = np.atleast_2d(lst[j]["probes"][i][key])
            first = False
            else:
            if key == "loc":
            break # dont concatenate the location as it doesnt change
            cprobe[key] = np.concatenate((cprobe[key],lst[j]["probes"][i][key]),axis=1)

        cdata["probes"].append(cprobe)

    return cdata


问:
Error installing eZ publish platform
I am trying to install ezpublish platform 15.05.02. When i run composer update i get the following error

```<code>[Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException]
The service "ezplatform.installer.install_command" has a dependency on a non-existent parameter "search_engine". Di
d you mean one of these: "ezpublish.api.search_engine.class", "ezpublish.api.search_engine.factory.class", "ezpubli
sh.api.search_engine.default"?
</code>```

答:
Just a note here, you can now use eZ Launchpad to bootstrap your project on top of Docker very easily.
https://ezsystems.github.io/launchpad/</p>

Title: Error installing eZ publish platform

Body:
I am trying to install ezpublish platform 15.05.02. When i run composer update i get the following error

[Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException]
The service "ezplatform.installer.install_command" has a dependency on a non-existent parameter "search_engine". Di
d you mean one of these: "ezpublish.api.search_engine.class", "ezpublish.api.search_engine.factory.class", "ezpubli
sh.api.search_engine.default"?


问:
Teradata / SQL join data conversion
This has been racking my brain for the entire afternoon, and I feel like I am missing something obvious. Thanks in advance.

I have two table, A and B. Table A has a column called A_id, and it has type DECIMAL(16,0). Table B has a column called B_id, and it has type varchar(100). I am trying to an inner join, ideally from A to B. After that, I also need to filter the result with a where clause, such as A = 12345. So far, I have tried below things.

```<code>select A.A_id, B.B_id
from A
join B on B.B_id = cast(cast(A.A_id as bigint) as archer(100))
where A_id = '12345';
</code>```

(I also tried cast A,A_id directly to varchar)

This doesn't produce any error, but it returns no result. I know they are same A_id and B_ids.

Furthermore, below code works and return good result

```<code>select A.A_id, B.B_id
from B
join a on B.B_id = A.A_id
where B_id = '12345';
</code>```

If I take out the where clause, then sql will return error message (2620) suggesting that I have bad character. Similarly, if I don't do any casting, sql will return error message. I assume there are some sort of implicit casting going on that made the second chunk of code work.

I really need help on how to make the first chunk of code work. So, how to cast A.A_id correctly so the join will actually work.

答:
```<code>create table A
(
a_id decimal (16,0)
);

create table B
(
b_id varchar(10)
);

insert into A select 12345;
insert into B select '12345';

-- produces result
select A.a_id, B.b_id from A join B on a.a_id=b.b_id;

--produces the same result, although I don't understand the reason for intra-casting
select A.A_id, B.B_id from A
  join B on B.B_id = cast(cast(A.A_id as bigint) as varchar(100))
where A_id = '12345';
</code>```

The reason it didn't produce the result for you may be because you inserted an extra, let's say, blank character into table B's id, and that doesn't compare correctly. Id est: ' 12345'<>'12345'

Title: Teradata / SQL join data conversion

Body:
This has been racking my brain for the entire afternoon, and I feel like I am missing something obvious. Thanks in advance.

I have two table, A and B. Table A has a column called A_id, and it has type DECIMAL(16,0). Table B has a column called B_id, and it has type varchar(100). I am trying to an inner join, ideally from A to B. After that, I also need to filter the result with a where clause, such as A = 12345. So far, I have tried below things.

select A.A_id, B.B_id
from A
join B on B.B_id = cast(cast(A.A_id as bigint) as archer(100))
where A_id = '12345';

(I also tried cast A,A_id directly to varchar)

This doesn't produce any error, but it returns no result. I know they are same A_id and B_ids.

Furthermore, below code works and return good result

select A.A_id, B.B_id
from B
join a on B.B_id = A.A_id
where B_id = '12345';

If I take out the where clause, then sql will return error message (2620) suggesting that I have bad character. Similarly, if I don't do any casting, sql will return error message. I assume there are some sort of implicit casting going on that made the second chunk of code work.

I really need help on how to make the first chunk of code work. So, how to cast A.A_id correctly so the join will actually work.

Body:
create table A
(
a_id decimal (16,0)
);

create table B
(
b_id varchar(10)
);

insert into A select 12345;
insert into B select '12345';

-- produces result
select A.a_id, B.b_id from A join B on a.a_id=b.b_id;

--produces the same result, although I don't understand the reason for intra-casting
select A.A_id, B.B_id from A
  join B on B.B_id = cast(cast(A.A_id as bigint) as varchar(100))
where A_id = '12345';

The reason it didn't produce the result for you may be because you inserted an extra, let's say, blank character into table B's id, and that doesn't compare correctly. Id est: ' 12345'<>'12345'


问:
Recursive Fibonacci in Ruby
This week is my first time doing recursion. One of the problems I was able to solve was Fibonacci's sequence to the nth number; it wasn't hard after messing with it for 5 minutes.

However, I am having trouble understanding why this works with the current return statement.

```<code>return array if num == 2
</code>```

If I push to array, it doesn't work, if I make a new variable sequence and push to that, it returns the correct answer. I am cool with that, but my base case says return array, not sequence. I initially pushed the sequence to the array, the result was not fibs sequence. I only solved the problem when I tried seeing what would happen if I pushed to the sequence array.

Instead of just making it work I was hoping someone could explain what was happening under the hood, what the stacks might be and how the problem works.

I understand recursion to an extent and somehow intuitively can make it work by assuming things, but I feel funny not actually knowing all the whys behind it.

```<code>def fib_seq(num)
  return [0] if num == 1
  return [] if num == 0

  array = [0, 1]
  return array if num <= 2

  seq = fib_seq(num - 1)
  seq << seq[-2] + seq[-1]
end
</code>```

答:
Recursive functions need to have an exit condition to prevent them from running forever. The main part of your recursive method is the following:

```<code>seq = fib_seq(num - 1)
seq << seq[-2] + seq[-1]
</code>```

In Ruby, the last expression of a method is considered to be the return value of that method, so the lines above are equivalent to:

```<code>seq = fib_seq(num - 1)
seq << seq[-2] + seq[-1]
return seq
</code>```

Let's run down what would happen if the method only contained these two lines, with num = 4:

```<code>call fib_seq(4)
  call fib_seq(3)
    call fib_seq(2)
      call fib_seq(1)
        call fib_seq(0)
          call fib_seq(-1)
            ...
</code>```

Obviously this results in an infinite loop, since we have no exit condition. We always call fib_seq again on the first line, so the code has no chance of ever reaching the return statement at the end. To fix the problem, let's add in these two lines at the beginning:

```<code>array = [0, 1]
return array if num <= 2
</code>```

These can be simplified down to just:

```<code>return [0, 1] if num <= 2
</code>```

Now let's see what happens when we call the method with num = 4:

```<code>call fib_seq(4)
  4 > 2, exit condition not triggered, calling fib_seq(n - 1)
  call fib_seq(3)
    3 > 2, exit condition not triggered, calling fib_seq(n - 1)
    call fib_seq(2)
    2 == 2, exit condition triggered, returning [0, 1]!
  fib_seq(2) returned with seq = [0, 1]
  add 0 + 1 together, push new value to seq
  seq is now [0, 1, 1]
  return seq
fib_seq(3) returned with seq = [0, 1, 1]
add 1 + 1 together, push new value to seq
seq is now [0, 1, 1, 2]
return seq
FINAL RESULT: [0, 1, 1, 2]
</code>```

So it looks like this method is working for values of num that are >= 2:

```<code>def fib_seq(num)
  return [0, 1] if num <= 2

  seq = fib_seq(num - 1)
  seq << seq[-2] + seq[-1]
end
</code>```

There is one bug left: num = 0 and num = 1 both return [0, 1]. Let's fix that:

```<code>def fib_seq(num)
  return [] if num == 0
  return [0] if num == 1
  return [0, 1] if num == 2

  seq = fib_seq(num - 1)
  seq << seq[-2] + seq[-1]
end
</code>```

Clean it up a little:

```<code>def fib_seq(num)
  return [0, 1].first(num) if num <= 2
  seq = fib_seq(num - 1)
  seq << seq[-2] + seq[-1]
end
</code>```

Title: Recursive Fibonacci in Ruby

Body:
This week is my first time doing recursion. One of the problems I was able to solve was Fibonacci's sequence to the nth number; it wasn't hard after messing with it for 5 minutes.

However, I am having trouble understanding why this works with the current return statement.

return array if num == 2

If I push to array, it doesn't work, if I make a new variable sequence and push to that, it returns the correct answer. I am cool with that, but my base case says return array, not sequence. I initially pushed the sequence to the array, the result was not fibs sequence. I only solved the problem when I tried seeing what would happen if I pushed to the sequence array.

Instead of just making it work I was hoping someone could explain what was happening under the hood, what the stacks might be and how the problem works.

I understand recursion to an extent and somehow intuitively can make it work by assuming things, but I feel funny not actually knowing all the whys behind it.

def fib_seq(num)
  return [0] if num == 1
  return [] if num == 0

  array = [0, 1]
  return array if num <= 2

  seq = fib_seq(num - 1)
  seq << seq[-2] + seq[-1]
end

Body:
Recursive functions need to have an exit condition to prevent them from running forever. The main part of your recursive method is the following:

seq = fib_seq(num - 1)
seq << seq[-2] + seq[-1]

In Ruby, the last expression of a method is considered to be the return value of that method, so the lines above are equivalent to:

seq = fib_seq(num - 1)
seq << seq[-2] + seq[-1]
return seq

Let's run down what would happen if the method only contained these two lines, with num = 4:

call fib_seq(4)
  call fib_seq(3)
    call fib_seq(2)
      call fib_seq(1)
        call fib_seq(0)
          call fib_seq(-1)
            ...

Obviously this results in an infinite loop, since we have no exit condition. We always call fib_seq again on the first line, so the code has no chance of ever reaching the return statement at the end. To fix the problem, let's add in these two lines at the beginning:

array = [0, 1]
return array if num <= 2

These can be simplified down to just:

return [0, 1] if num <= 2

Now let's see what happens when we call the method with num = 4:

call fib_seq(4)
  4 > 2, exit condition not triggered, calling fib_seq(n - 1)
  call fib_seq(3)
    3 > 2, exit condition not triggered, calling fib_seq(n - 1)
    call fib_seq(2)
    2 == 2, exit condition triggered, returning [0, 1]!
  fib_seq(2) returned with seq = [0, 1]
  add 0 + 1 together, push new value to seq
  seq is now [0, 1, 1]
  return seq
fib_seq(3) returned with seq = [0, 1, 1]
add 1 + 1 together, push new value to seq
seq is now [0, 1, 1, 2]
return seq
FINAL RESULT: [0, 1, 1, 2]

So it looks like this method is working for values of num that are >= 2:

def fib_seq(num)
  return [0, 1] if num <= 2

  seq = fib_seq(num - 1)
  seq << seq[-2] + seq[-1]
end

There is one bug left: num = 0 and num = 1 both return [0, 1]. Let's fix that:

def fib_seq(num)
  return [] if num == 0
  return [0] if num == 1
  return [0, 1] if num == 2

  seq = fib_seq(num - 1)
  seq << seq[-2] + seq[-1]
end

Clean it up a little:

def fib_seq(num)
  return [0, 1].first(num) if num <= 2
  seq = fib_seq(num - 1)
  seq << seq[-2] + seq[-1]
end


问:
How to change Firebase user login identity from command line (CLI)?
I'm trying to login to Firebase using login credentials of, let's say, User-Alice.

But when I go through the authorization procedure I get a message saying I'm logged in as User-Bob. This is not mentioned anywhere in the documentation nor does it explain how to change the user I'm logged in as.

How can I change the Firebase logged in user from User-Bob to User-Alice?

Thank you.

答:
use this

```<code>firebase login --reauth
</code>```

then you can change account

Body:
use this

firebase login --reauth

then you can change account


问:
How can I read this xml?
could you help me?

I need to read this file:

I Tried this way:

$xml = simplexml_load_file('http://api.crossref.org/works/10.18468/pracs.2016v9n3.p99-119/transform/application/vnd.crossref.unixsd+xml');

echo $xml->journal_metadata->full_title;

I don´t know how to get the value of a specific tag.

I need read this:Click to see

答:
First you load the file from the distant server :

```<code>$file = @file_get_contents('http://api.crossref.org/works/10.18468/pracs.2016v9n3.p99-119/transform/application/vnd.crossref.unixsd+xml');
if ($file===FALSE)
{
    die ("error getting the content of the file");
}
</code>```

Then, you parse the xml and extract it into an object using  simplexml :

```<code>$o= simplexml_load_string ($file);
</code>```

Finally, you move through your object tree until you reach the intended destination

```<code>echo "```";
$intended_obj = $o->query_result->body->query->doi_record->crossref->journal->journal_article->doi_data;
print_r($intended_obj->resource);
print_r($intended_obj->collection);
echo "```";
</code>```

That should output :

```<code>   SimpleXMLElement Object
(
    [0] => https://periodicos.unifap.br/index.php/pracs/article/view/2791
)
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [property] => crawler-based
        )
    [item] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [crawler] => iParadigms
                )
            [resource] => https://periodicos.unifap.br/index.php/pracs/article/viewFile/2791/haliadorav9n3.pdf
        )
)
</code>```

Good luck,

Title: How can I read this xml?

Body:
First you load the file from the distant server :

$file = @file_get_contents('http://api.crossref.org/works/10.18468/pracs.2016v9n3.p99-119/transform/application/vnd.crossref.unixsd+xml');
if ($file===FALSE)
{
    die ("error getting the content of the file");
}

Then, you parse the xml and extract it into an object using  simplexml :

$o= simplexml_load_string ($file);

Finally, you move through your object tree until you reach the intended destination

echo "<pre>";
$intended_obj = $o->query_result->body->query->doi_record->crossref->journal->journal_article->doi_data;
print_r($intended_obj->resource);
print_r($intended_obj->collection);
echo "</pre>";

That should output :

   SimpleXMLElement Object
(
    [0] => https://periodicos.unifap.br/index.php/pracs/article/view/2791
)
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [property] => crawler-based
        )
    [item] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [crawler] => iParadigms
                )
            [resource] => https://periodicos.unifap.br/index.php/pracs/article/viewFile/2791/haliadorav9n3.pdf
        )
)

Good luck,


问:
Robust selector to find all elements of class
How can I get all elements who have a class that begins with vd-? My code below works for most cases except for the following:

```<code>class="foo vd-bar"
</code>```

It works for these cases:

```<code>class="vd-bar foo"
</code>```

Here is my selector, will it work if the HTML markup uses single quotation marks? For eg; class='vd-foo'?

```<code>$('[class^="vd-"]', myElement).each(function(index, ele) {

});
</code>```

答:
You need to use the contains selector (*), not the start with selector (^). Other than that, it doesn't really matter whether you use single or double quotes as long as you match them correctly. Here is an example:

$("[class*='vd-']").css("border", "1px solid #f00");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo vd-bar">first div</div>
<div class='vd-bar foo'>second div</div>
<div class='fvd-bar foo'>third div</div></code>```

Note: As you can see, the code above will select everything that contains "vd-". That should be fine for most cases because usually class prefixes don't occur in the middle of the class name. If they do, that's considered a bad design. If you want to only select elements with classes that start with "vd-", that cannot be done in a simple selector, so you'll have to use two selectors like randomir's answer below. That has a performance cost in big documents, so it is better to avoid it unless it is necessary. Here is a jQuery example:

$("[class*=' vd-'],[class^='vd-']").css("border", "1px solid #f00");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo vd-bar">first div</div>
<div class='vd-bar foo'>second div</div>
<div class='fvd-bar foo'>third div</div></code>```

Body:
How can I get all elements who have a class that begins with vd-? My code below works for most cases except for the following:

class="foo vd-bar"

It works for these cases:

class="vd-bar foo"

Here is my selector, will it work if the HTML markup uses single quotation marks? For eg; class='vd-foo'?

$('[class^="vd-"]', myElement).each(function(index, ele) {

});

Body:
You need to use the contains selector (*), not the start with selector (^). Other than that, it doesn't really matter whether you use single or double quotes as long as you match them correctly. Here is an example:

$("[class*='vd-']").css("border", "1px solid #f00");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo vd-bar">first div</div>
<div class='vd-bar foo'>second div</div>
<div class='fvd-bar foo'>third div</div>

Note: As you can see, the code above will select everything that contains "vd-". That should be fine for most cases because usually class prefixes don't occur in the middle of the class name. If they do, that's considered a bad design. If you want to only select elements with classes that start with "vd-", that cannot be done in a simple selector, so you'll have to use two selectors like randomir's answer below. That has a performance cost in big documents, so it is better to avoid it unless it is necessary. Here is a jQuery example:

$("[class*=' vd-'],[class^='vd-']").css("border", "1px solid #f00");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo vd-bar">first div</div>
<div class='vd-bar foo'>second div</div>
<div class='fvd-bar foo'>third div</div>


问:
Can I fill a parameter dropdown based on a dataset used for an actual report in SQL Server Reporting Services (SSRS)?
Is it possible, using SQL Server Reporting Services (SSRS) 2008 R2, to somehow use the dataset that is used for the actual list of data for the report for a report parameter dropdown?

Explanation: Let's say I have a dataset with products and their respective prices. Now I'd like to be able to filter the dataset on the different kinds of product contained in that very dataset. I can of course set up another dataset containing just the products, but this approach has the problem that
- I have two different datasets
- I have dependencies between them, e.g. if I decide to change the WHERE condition in the datasource providing my products and prices I also have to change the same things for my second dataset that I use for the parameter dropdown
- I have performance drawbacks

I know that one could also argue that indeed there are good reasons to have two datasets for my problem described above, however, unfortunately I wasn't able to find a definitive answer to it, so I am still looking for some help regarding this issue.

答:
I've been searching for a solution to the same problem. It would be great if you could create a DataSet based on a query/filter on an existing DataSet. Unfortunately this isn't possible in the lastest edition of SSRS (2008RC2).

For now you have to rely on SSRS's ability to cache your reports/DataSets and the caching in SQL Server Database Engine to keep your performance within your requirements. You can setup caching for your report in your administration environment: http://[reportserver]/Reports

Regards
Alex


问:
Recyclerview within a Scrollview dont coordinate
I have this activity design, which shows a card view inside a scrollView, But under that cardview I need to put a listview or recyclerview. The problem is that I need the scroll of that list to coordinate with the main scroll. Osea that when lower in the content the cardview will disappear and the list of the recyclerview or listview will be crossed.

I need all the content to respond to the main scroll to show up and disappear after titlebar, Which should I change or redesign?

```<code>        <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        app:cardElevation="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CoordinatorLayout
            android:id="@+id/post_coordinator"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/post_bg"
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:scaleType="fitXY"
                android:src="@drawable/default_profile" />

            <android.support.design.widget.FloatingActionButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:fabSize="normal"
                android:src="@drawable/ic_hot_black"
                app:layout_anchorGravity="bottom"
                android:layout_marginLeft="16dp"
                app:layout_anchor="@id/post_bg"
                android:tint="#FFF"
                />

            <com.mikhaellopez.circularimageview.CircularImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                app:layout_anchor="@id/post_bg"
                app:layout_anchorGravity="center_horizontal|bottom"
                android:src="@drawable/profile"
                app:civ_border_color="#FFF"
                app:civ_border_width="3dp"
                />

            <android.support.design.widget.FloatingActionButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:fabSize="normal"
                android:src="@drawable/ic_hot_black"
                app:layout_anchorGravity="bottom|end"
                android:layout_marginRight="16dp"
                app:layout_anchor="@id/post_bg"
                android:tint="#FFF"
                />

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_marginTop="205dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:paddingBottom="50dp"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Prepare your Anus Cersei Lanister, You Gonna Die"
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                    android:textColor="#2d2d2d"
                    android:textAlignment="center"
                    />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:text="@string/emilia"
                    android:textColor="@color/secondary_text"
                    android:layout_marginTop="10dp"
                    />

            </LinearLayout>

        </android.support.design.widget.CoordinatorLayout>

    </android.support.v7.widget.CardView>

    <ListView
        android:id="@+id/post_comments"
        android:layout_marginTop="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
    </ListView>

    </LinearLayout>
</ScrollView>
</code>```

答:
Add your recyclerview inside NestedScrollview.
Also add recyclerview.setNestedScrollingEnabled(false);</p>

Body:
I have this activity design, which shows a card view inside a scrollView, But under that cardview I need to put a listview or recyclerview. The problem is that I need the scroll of that list to coordinate with the main scroll. Osea that when lower in the content the cardview will disappear and the list of the recyclerview or listview will be crossed.

I need all the content to respond to the main scroll to show up and disappear after titlebar, Which should I change or redesign?

        <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        app:cardElevation="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CoordinatorLayout
            android:id="@+id/post_coordinator"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/post_bg"
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:scaleType="fitXY"
                android:src="@drawable/default_profile" />

            <android.support.design.widget.FloatingActionButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:fabSize="normal"
                android:src="@drawable/ic_hot_black"
                app:layout_anchorGravity="bottom"
                android:layout_marginLeft="16dp"
                app:layout_anchor="@id/post_bg"
                android:tint="#FFF"
                />

            <com.mikhaellopez.circularimageview.CircularImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                app:layout_anchor="@id/post_bg"
                app:layout_anchorGravity="center_horizontal|bottom"
                android:src="@drawable/profile"
                app:civ_border_color="#FFF"
                app:civ_border_width="3dp"
                />

            <android.support.design.widget.FloatingActionButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:fabSize="normal"
                android:src="@drawable/ic_hot_black"
                app:layout_anchorGravity="bottom|end"
                android:layout_marginRight="16dp"
                app:layout_anchor="@id/post_bg"
                android:tint="#FFF"
                />

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_marginTop="205dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:paddingBottom="50dp"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Prepare your Anus Cersei Lanister, You Gonna Die"
                    android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                    android:textColor="#2d2d2d"
                    android:textAlignment="center"
                    />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:text="@string/emilia"
                    android:textColor="@color/secondary_text"
                    android:layout_marginTop="10dp"
                    />

            </LinearLayout>

        </android.support.design.widget.CoordinatorLayout>

    </android.support.v7.widget.CardView>

    <ListView
        android:id="@+id/post_comments"
        android:layout_marginTop="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
    </ListView>

    </LinearLayout>
</ScrollView>


问:
How do I correctly add the file input stream to my Firebase JSON file
My JSON file resides in the projects root folder, I have correctly set up the dependencies and now I'm trying to add the JSON file Using the instructions as provided by Firebse themselves here.

Here is the code from my main java file:

```<code>import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseCredentials;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.management.RuntimeMXBean;
import java.io.*;
import java.net.*;
import java.util.*;
import java.io.LineNumberReader;
import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;
import java.util.Random;

 public class Climate {
    public static void main(String [] args){
          FileInputStream serviceAccount = new FileInputStream("serviceAccountKey.json");

          FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
                .setDatabaseUrl("https://*retracted*.firebaseio.com/")
                .build();

          FirebaseApp.initializeApp(options);
    }
 }
</code>```

this is how it look in the IDE

and this is the message under next to it:

It says file not found but the file is there i assure you, am I being really dumb here, please excuse my incompetence I'm new to firebase... any help would be much appreciated.

答:
You need to surround that statement by "try and catch" or use throws exceptions.</p>

```<code> public class Climate {
    public static void main(String [] args){
          FileInputStream serviceAccount = null;
        try {
            serviceAccount = new FileInputStream("serviceAccountKey.json");
            FirebaseOptions options = new FirebaseOptions.Builder()
                    .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
                    .setDatabaseUrl("https://*retracted*.firebaseio.com/")
                    .build();
            FirebaseApp.initializeApp(options);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Climate.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                serviceAccount.close();
            } catch (IOException ex) {
                Logger.getLogger(Climate.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
 }
</code>```

Body:
My JSON file resides in the projects root folder, I have correctly set up the dependencies and now I'm trying to add the JSON file Using the instructions as provided by Firebse themselves here.

Here is the code from my main java file:

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseCredentials;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.management.RuntimeMXBean;
import java.io.*;
import java.net.*;
import java.util.*;
import java.io.LineNumberReader;
import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;
import java.util.Random;

 public class Climate {
    public static void main(String [] args){
          FileInputStream serviceAccount = new FileInputStream("serviceAccountKey.json");

          FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
                .setDatabaseUrl("https://*retracted*.firebaseio.com/")
                .build();

          FirebaseApp.initializeApp(options);
    }
 }

this is how it look in the IDE

and this is the message under next to it:

It says file not found but the file is there i assure you, am I being really dumb here, please excuse my incompetence I'm new to firebase... any help would be much appreciated.

Body:
You need to surround that statement by "try and catch" or use throws exceptions.

 public class Climate {
    public static void main(String [] args){
          FileInputStream serviceAccount = null;
        try {
            serviceAccount = new FileInputStream("serviceAccountKey.json");
            FirebaseOptions options = new FirebaseOptions.Builder()
                    .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
                    .setDatabaseUrl("https://*retracted*.firebaseio.com/")
                    .build();
            FirebaseApp.initializeApp(options);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Climate.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                serviceAccount.close();
            } catch (IOException ex) {
                Logger.getLogger(Climate.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
 }


问:
Need to change UIImageView with a Int generated by a button Swift
I'm creating an app that will control climate. The value changes, however, I cannot get different (Guage) images to display based on value. please help!

Here is my code

```<code> /* Fan Output Up */

@IBAction func FanOutputUpBtn(_ sender: Any) {

    let name = "Fan Position\(fanCounter)"
    /* Setting the name of the fan position image including the variable fanCounter */

    fanPositionImage.image = UIImage(named: "fanPosition \(fanCounter)")
    /* Setting the name of the fan position image including the variable fanCounter */

    if fanCounter == 5 {
        /* Set maximum value */
    } else {

    fanCounter += 1
        /* Increase the fan counter position by 1 */

    TestFanCounter.text = String(Int(self.fanCounter))
        /* Display the counter image */

        self.fanPositionImage.image = UIImage(named: name)
        /* Display image for fan position based on fan counter */

}
</code>```

Update

Now It's random images displaying on tap however the TestFanCounter.text = String(Int(self.fanCounter)) is displaying completly fine

```<code>   /* Fan Output Up */

@IBAction func FanOutputUpBtn(_ sender: Any) {

    let name = "Fan Position \(fanCounter)"
    // Setting the name of the fan position image including the variable fanCounter

    if fanCounter == 4 {
        // Set maximum value
    } else {

    fanCounter += 1
        // Increase the fan counter position by 1

    TestFanCounter.text = String(Int(self.fanCounter))
        // Display the counter image

        self.fanPositionImage.image = UIImage(named: name)
        /* Display image for fan position based on fan counter */

    }
</code>```

}

答: You are incrementing the fanCounter after you set the name. When you display the counter, it will be one higher than when you assigned the name, which you are using to set an image. Are those values supposed to be equal?</p>

Body:
I'm creating an app that will control climate. The value changes, however, I cannot get different (Guage) images to display based on value. please help!

Here is my code

 /* Fan Output Up */

@IBAction func FanOutputUpBtn(_ sender: Any) {

    let name = "Fan Position\(fanCounter)"
    /* Setting the name of the fan position image including the variable fanCounter */

    fanPositionImage.image = UIImage(named: "fanPosition \(fanCounter)")
    /* Setting the name of the fan position image including the variable fanCounter */

    if fanCounter == 5 {
        /* Set maximum value */
    } else {

    fanCounter += 1
        /* Increase the fan counter position by 1 */

    TestFanCounter.text = String(Int(self.fanCounter))
        /* Display the counter image */

        self.fanPositionImage.image = UIImage(named: name)
        /* Display image for fan position based on fan counter */

}

Update

Now It's random images displaying on tap however the TestFanCounter.text = String(Int(self.fanCounter)) is displaying completly fine

   /* Fan Output Up */

@IBAction func FanOutputUpBtn(_ sender: Any) {

    let name = "Fan Position \(fanCounter)"
    // Setting the name of the fan position image including the variable fanCounter

    if fanCounter == 4 {
        // Set maximum value
    } else {

    fanCounter += 1
        // Increase the fan counter position by 1

    TestFanCounter.text = String(Int(self.fanCounter))
        // Display the counter image

        self.fanPositionImage.image = UIImage(named: name)
        /* Display image for fan position based on fan counter */

    }

}