问:
How to communicate RabbitMQ(Pika library) in tornado application
Pika library support tornado adapter, here is an example about how to publish message using Asynchronous adapter.

I want use pika in tornado application, just an example, I want put tornado request data to RabbitMQ, But don't know how to do it.

Two question don't know how to solve.

1 Pika use tornado adapter has its own ioloop,

self._connection = pika.SelectConnection(pika.URLParameters(self._url),
                                         self.on_connection_open)
self._connection.ioloop.start()
```

<p>Tornado application has its own ioloop,
</p>

```tornado.ioloop.IOLoop.instance().start()
```

How to combine those two ioloop?

2 The Pika example publish same message again and again, but I want to publish request data, how to pass request data to publish method?

答:
Finally,i figure out it!
the previous solution is outdated for the newest pika component!

1.my pika Version is 1.0.1.
warning :
TornadoConnection Class has changed is package by the newest push request.

```<code>from pika.adapters import tornado_connection
</code>```

2.there is an example:  log() and config() should ignore(delete it)

```<code>import tornado.web

from handlers.notify import NotifyHandler
from function.function import config
from utils.utils import log

import pika
from pika.adapters import tornado_connection

HANDLERS = [(r'/notify', NotifyHandler)]

class PikaClient():
    def __init__(self, io_loop):
        self.io_loop = io_loop
        self.connected = False
        self.connecting = False
        self.connection = None
        self.channel = None
        self.message_count = 9

    def connect(self):
        if self.connecting:
            return
        self.connecting = True
        cred = pika.PlainCredentials('guest', 'guest')
        param = pika.ConnectionParameters(host="10.xxx.xxx.75", credentials=cred)
        self.connection = tornado_connection.TornadoConnection(param, custom_ioloop = self.io_loop, on_open_callback = self.on_connected)
        self.connection.add_on_open_error_callback(self.err)
        self.connection.add_on_close_callback(self.on_closed)

    def err(self, conn):
        log('socket error', conn)
        pass

    def on_connected(self, conn):
        log('connected')
        self.connected = True
        self.connection = conn
        self.connection.channel(channel_number = 1, on_open_callback = self.on_channel_open)

    def on_message(self, channel, method, properties, body):
        log(body)
        print('body : ', body)
        pass

    def on_channel_open(self, channel):
        self.channel = channel
        channel.basic_consume(on_message_callback = self.on_message, queue='hello', auto_ack=True)
        return

    def on_closed(self, conn, c):
        log('pika close!')
        self.io_loop.stop()
        pass

def main():
    port = 3002
    is_debug = config('sys', 'debug')
    print('DEBUG', is_debug)
    app = tornado.web.Application(
            HANDLERS,
            debug = is_debug,
            )
    io_loop = tornado.ioloop.IOLoop.instance()
    app.pc = PikaClient(io_loop)
    app.pc.connect()
    http_server = tornado.httpserver.HTTPServer(app)
    app.listen(port)
    io_loop.start()
    print('listen {}'.format(port))

if __name__ == '__main__':
    main()

</code>```

Body:
Pika library support tornado adapter, here is an example about how to publish message using Asynchronous adapter.

I want use pika in tornado application, just an example, I want put tornado request data to RabbitMQ, But don't know how to do it.

Two question don't know how to solve.

1 Pika use tornado adapter has its own ioloop,

self._connection = pika.SelectConnection(pika.URLParameters(self._url),
                                         self.on_connection_open)
self._connection.ioloop.start()

Tornado application has its own ioloop,

tornado.ioloop.IOLoop.instance().start()

How to combine those two ioloop?

2 The Pika example publish same message again and again, but I want to publish request data, how to pass request data to publish method?

Body:
Finally,i figure out it!
the previous solution is outdated for the newest pika component!

1.my pika Version is 1.0.1.
warning :
TornadoConnection Class has changed is package by the newest push request.

from pika.adapters import tornado_connection

2.there is an example:  log() and config() should ignore(delete it)

import tornado.web

from handlers.notify import NotifyHandler
from function.function import config
from utils.utils import log

import pika
from pika.adapters import tornado_connection

HANDLERS = [(r'/notify', NotifyHandler)]

class PikaClient():
    def __init__(self, io_loop):
        self.io_loop = io_loop
        self.connected = False
        self.connecting = False
        self.connection = None
        self.channel = None
        self.message_count = 9

    def connect(self):
        if self.connecting:
            return
        self.connecting = True
        cred = pika.PlainCredentials('guest', 'guest')
        param = pika.ConnectionParameters(host="10.xxx.xxx.75", credentials=cred)
        self.connection = tornado_connection.TornadoConnection(param, custom_ioloop = self.io_loop, on_open_callback = self.on_connected)
        self.connection.add_on_open_error_callback(self.err)
        self.connection.add_on_close_callback(self.on_closed)

    def err(self, conn):
        log('socket error', conn)
        pass

    def on_connected(self, conn):
        log('connected')
        self.connected = True
        self.connection = conn
        self.connection.channel(channel_number = 1, on_open_callback = self.on_channel_open)

    def on_message(self, channel, method, properties, body):
        log(body)
        print('body : ', body)
        pass

    def on_channel_open(self, channel):
        self.channel = channel
        channel.basic_consume(on_message_callback = self.on_message, queue='hello', auto_ack=True)
        return

    def on_closed(self, conn, c):
        log('pika close!')
        self.io_loop.stop()
        pass

def main():
    port = 3002
    is_debug = config('sys', 'debug')
    print('DEBUG', is_debug)
    app = tornado.web.Application(
            HANDLERS,
            debug = is_debug,
            )
    io_loop = tornado.ioloop.IOLoop.instance()
    app.pc = PikaClient(io_loop)
    app.pc.connect()
    http_server = tornado.httpserver.HTTPServer(app)
    app.listen(port)
    io_loop.start()
    print('listen {}'.format(port))

if __name__ == '__main__':
    main()


来源: stackexchange

问:
jQuery - exclude inputs with certain value from selector
I would like to select all inputs in my div and set them new value but also I want to exclude inputs with certain value
something like this:

```<code>$('#mydiv input:not(val("100")').val(myvariable);
</code>```

how to do that, is it possible in simple selector?
thanks

答:
You need to use the attribute not equal selector.

```<code>$('#mydiv input[value!="100"]').val(myvariable);
</code>```

jsFiddle

ContentLicense: CC BY-SA 3.0

Body:
I would like to select all inputs in my div and set them new value but also I want to exclude inputs with certain value
something like this:

$('#mydiv input:not(val("100")').val(myvariable);

how to do that, is it possible in simple selector?
thanks

Body:
You need to use the attribute not equal selector.

$('#mydiv input[value!="100"]').val(myvariable);

jsFiddle


问:
Remove a list of provided letters from the start of the string
I have a dataframe-df with column "Names" as below :

```<code>Names
AL GHAITHA & AL MOOSA
AL ASEEL ELECTRONICS T
SUNRISE SUPERMARKET-QU
EMARAT-AL SAFIYAH(6735
LULU CENTRE LLC EFT TE
THE MAX
</code>```

Code :

```<code>remove_letters = ['AL ', 'THE ']

# my function below :

def remove_start_words(df, col, letters):
    for l in letters:
        for i in df.index:
            x = df.at[i, col]
            if x.startswith(l):
                df.at[i, col] = x[len(l):]
            else:
                df.at[i, col] = x

def remove_strings(self, df, col):
    for i in df.index:
        x = df.at[i, col]
        x = x.split(' ')
        if len(x) > 1:
            if len(x[1]) > 2:
                x[1] = ''.join(e for e in x[1] if e.isalnum())
                x = ' '.join(x[0:2])
                df.at[i, col] = x
            else:
                df.at[i, col] = x[0]
        else:
            df.at[i, col] = df.at[i, col]

def remove_end_digits(self, df, col):
    for i in df.index:
        x = df.at[i, col]
        df.at[i, col] = x.rstrip(string.digits)

# calling my function
remove_start_words(df=df, col='Names',
                          letters=remove_letters)

remove_strings(df=df, col='Names')
remove_end_digits(df=df, col='Names')
</code>```

Now the problem is i have a dataframe of more than 1 million column values.
My code is not well optimized ? How to get a optimized solution ?

Issue 1 :
I can understand i have used 2 loops ( 1 for remove_letters and other for all the column values) that is causing slowness.

Is there a better way ? where i can check if the column values start with the letters mentioned in remove_letters list and strip them at one shot ?

Issue 2 & 3 :
What is objective of the function - "remove_strings" :
Get only the 2 strings from the column names. For eg : ASEEL ELECTRONICS T
output will be : ASEEL ELECTRONICS

Is there a faster way for the functions : remove_strings,remove_end_digits

Main issue : Can all this 3 functions can be done at one shot all together ?

Expected dataframe:

```<code>Names
GHAITHA
ASEEL ELECTRONICS
SUNRISE SUPERMARKET
EMARAT-AL SAFIYAH
LULU CENTRE
MAX
</code>```

NOTE : The function "remove_start_words" should check if any of the mentioned letters are starting in the "Names" if so, remove them.
For eg : "AL THEMAX" should be "THEMAX" not as "MAX" (removing both AL and THE)

Thanks in advance.

答:
Since you said you only wanted the words removed from the beginning of the sentence, you could use regular expression :

```<code>import pandas as pd

file_path = 'file3.xlsx'

df = pd.read_excel(file_path)

words_to_remove = ["THE", "AL"]
regular_expression = '^' + '|'.join(words_to_remove)

df.Names = df.Names.apply(lambda x : re.sub(regular_expression, "", x))
</code>```

the regular_expression expression variable would contain ^THE|AL in this case meaning THE or AL at the beginning of the string.

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe-df with column "Names" as below :

Names
AL GHAITHA & AL MOOSA
AL ASEEL ELECTRONICS T
SUNRISE SUPERMARKET-QU
EMARAT-AL SAFIYAH(6735
LULU CENTRE LLC EFT TE
THE MAX

Code :

remove_letters = ['AL ', 'THE ']

# my function below :

def remove_start_words(df, col, letters):
    for l in letters:
        for i in df.index:
            x = df.at[i, col]
            if x.startswith(l):
                df.at[i, col] = x[len(l):]
            else:
                df.at[i, col] = x

def remove_strings(self, df, col):
    for i in df.index:
        x = df.at[i, col]
        x = x.split(' ')
        if len(x) > 1:
            if len(x[1]) > 2:
                x[1] = ''.join(e for e in x[1] if e.isalnum())
                x = ' '.join(x[0:2])
                df.at[i, col] = x
            else:
                df.at[i, col] = x[0]
        else:
            df.at[i, col] = df.at[i, col]

def remove_end_digits(self, df, col):
    for i in df.index:
        x = df.at[i, col]
        df.at[i, col] = x.rstrip(string.digits)

# calling my function
remove_start_words(df=df, col='Names',
                          letters=remove_letters)

remove_strings(df=df, col='Names')
remove_end_digits(df=df, col='Names')

Now the problem is i have a dataframe of more than 1 million column values.
My code is not well optimized ? How to get a optimized solution ?

Issue 1 :
I can understand i have used 2 loops ( 1 for remove_letters and other for all the column values) that is causing slowness.

Is there a better way ? where i can check if the column values start with the letters mentioned in remove_letters list and strip them at one shot ?

Issue 2 & 3 :
What is objective of the function - "remove_strings" :
Get only the 2 strings from the column names. For eg : ASEEL ELECTRONICS T
output will be : ASEEL ELECTRONICS

Is there a faster way for the functions : remove_strings,remove_end_digits

Main issue : Can all this 3 functions can be done at one shot all together ?

Expected dataframe:

Names
GHAITHA
ASEEL ELECTRONICS
SUNRISE SUPERMARKET
EMARAT-AL SAFIYAH
LULU CENTRE
MAX

NOTE : The function "remove_start_words" should check if any of the mentioned letters are starting in the "Names" if so, remove them.
For eg : "AL THEMAX" should be "THEMAX" not as "MAX" (removing both AL and THE)

Thanks in advance.

Body:
Since you said you only wanted the words removed from the beginning of the sentence, you could use regular expression :

import pandas as pd

file_path = 'file3.xlsx'

df = pd.read_excel(file_path)

words_to_remove = ["THE", "AL"]
regular_expression = '^' + '|'.join(words_to_remove)

df.Names = df.Names.apply(lambda x : re.sub(regular_expression, "", x))

the regular_expression expression variable would contain ^THE|AL in this case meaning THE or AL at the beginning of the string.


问:
How make case when in WHERE clause for MS SQL
I use a case when it works perfectly fine on MySQL but not MS SQL please help.

It seems the equal is not accepted -- if not what then will work

```<code>SELECT A FROM TABLE A
WHERE
CASE WHEN COUNT = 2 THEN GOAL = 2 ELSE GOAL = 3 END
</code>```

Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword
  'CASE'.

答:
You need to change your query to WHERE columnName = value.

The following query is what you are expecting:

```<code>SELECT A.*
FROM TABLE A
WHERE GOAL = CASE WHEN COUNT = 2 THEN 2 ELSE 3 END
</code>```

Body:
I use a case when it works perfectly fine on MySQL but not MS SQL please help.

It seems the equal is not accepted -- if not what then will work

SELECT A FROM TABLE A
WHERE
CASE WHEN COUNT = 2 THEN GOAL = 2 ELSE GOAL = 3 END

Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword
  'CASE'.

Body:
You need to change your query to WHERE columnName = value.

The following query is what you are expecting:

SELECT A.*
FROM TABLE A
WHERE GOAL = CASE WHEN COUNT = 2 THEN 2 ELSE 3 END


问:
How to remove products from cart in Django?
I am writing code for removing product from cart but i am facing a few problems.First is when i click on remove the product is not deleted from cart and the second is that, in my urls.py, i have added regex on id for removing product from cart.But when i click on remove, the id isn't displayed in the url.

Views.py

```<code>def remove_from_cart(request,id):
try:
    the_id=request.session['cart_id']
    cart = Cart.objects.get(id=the_id)
except:
   return HttpResponseRedirect(reverse("cart"))
cartitem=CartItem.objects.get(id=id)

cartitem.cart=None
cartitem.save()
return HttpResponseRedirect(reverse("cart"))
</code>```

models.py

```<code>class CartItem(models.Model):
    cart=models.ForeignKey('Cart',on_delete=models.SET_NULL,null=True,blank=True)
    product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True,blank=True)
    accessory = models.ForeignKey(Accessories,on_delete=models.SET_NULL,null=True,blank=True)
    quantity=models.IntegerField(default=1)
    updated  = models.DateTimeField(auto_now_add=True,auto_now=False)
    line_total=models.DecimalField(default=10.99,max_digits=1000,decimal_places=2)
timestamp = models.DateTimeField(auto_now_add=True,auto_now=False)
   def __unicode__(self):
        try:
           return str(self.cart.id)
        except:
            return self.product.title
</code>```

urls.py

```<code>url(r'^cart/(?P<id>\d+)/$', remove_from_cart, name='remove_from_cart'),
</code>```

template.html

```<code><td><a href="{% url 'remove_from_cart' item.id %}">Remove</a></td>
</code>```

Please if any one can help it would be really appreciated?

Note: I have searched different links on stackoverflow but none helped.

答:
What query you send to template, can you provide it?</p>

```<code>def remove_from_cart(request, id):
    the_id = request.session['cart_id']
    card = Cart.objects.filter(id=the_id)
    if card.exists():
        cartitem = CartItem.objects.filter(card_id=card.first().id)
        if cartitem.exists():
            cartitem.delete()
        return HttpResponseRedirect(reverse("cart"))
    return HttpResponseRedirect(reverse("cart"))
</code>```

Body:
I am writing code for removing product from cart but i am facing a few problems.First is when i click on remove the product is not deleted from cart and the second is that, in my urls.py, i have added regex on id for removing product from cart.But when i click on remove, the id isn't displayed in the url.

Views.py

def remove_from_cart(request,id):
try:
    the_id=request.session['cart_id']
    cart = Cart.objects.get(id=the_id)
except:
   return HttpResponseRedirect(reverse("cart"))
cartitem=CartItem.objects.get(id=id)

cartitem.cart=None
cartitem.save()
return HttpResponseRedirect(reverse("cart"))

models.py

class CartItem(models.Model):
    cart=models.ForeignKey('Cart',on_delete=models.SET_NULL,null=True,blank=True)
    product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True,blank=True)
    accessory = models.ForeignKey(Accessories,on_delete=models.SET_NULL,null=True,blank=True)
    quantity=models.IntegerField(default=1)
    updated  = models.DateTimeField(auto_now_add=True,auto_now=False)
    line_total=models.DecimalField(default=10.99,max_digits=1000,decimal_places=2)
timestamp = models.DateTimeField(auto_now_add=True,auto_now=False)
   def __unicode__(self):
        try:
           return str(self.cart.id)
        except:
            return self.product.title

urls.py

url(r'^cart/(?P<id>\d+)/$', remove_from_cart, name='remove_from_cart'),

template.html

Remove

Please if any one can help it would be really appreciated?

Note: I have searched different links on stackoverflow but none helped.

Body:
What query you send to template, can you provide it?

def remove_from_cart(request, id):
    the_id = request.session['cart_id']
    card = Cart.objects.filter(id=the_id)
    if card.exists():
        cartitem = CartItem.objects.filter(card_id=card.first().id)
        if cartitem.exists():
            cartitem.delete()
        return HttpResponseRedirect(reverse("cart"))
    return HttpResponseRedirect(reverse("cart"))


问:
Calling addEventListener or using onscroll handler?
I have two approaches making my element scroll on the window which both work but what are the two differences and which one is a better approach. Thanks!

First approach

```<code>window.onscroll = function() {rotate()};

function rotate(){
}
</code>```

Second approach

```<code>window.addEventListener('scroll', rotate);

function rotate(){
}
</code>```

答:
You can add more that one handler with addEventListener, where as assigning onscroll you can only have one handler at a time.

For example if you have two sections of code that need to listen to a scroll event, they can't both set onscroll, as the first one will be overwritten. So instead both can call addEventListener and each receive the event.

Body:
I have two approaches making my element scroll on the window which both work but what are the two differences and which one is a better approach. Thanks!

First approach

window.onscroll = function() {rotate()};

function rotate(){
}

Second approach

window.addEventListener('scroll', rotate);

function rotate(){
}


问:
React Router with Path Params Not working
I have a react BrowserRouter with the following configuration.

```<code><BrowserRouter>
        <div>
            <Switch>
                <Route path={`/`} component={Home} exact/>
                <Route path={`/about`} render={(props) => <About {...props}/>} exact/>
                <Route path={`/products/:id/:slug`} render={(props) => <Products {...props}/>} exact/>
            </Switch>
        </div>
</code>```

In the About Page there are products with the following  tag. If I click a link, the url changes and Product page is getting rendered correctly.

```<code><Link to={'/products/' + product.id + '/' + product.slug>{product.name }</Link>
</code>```

But when I directly Land to Product page using the exact URL. rendering won't work.

```<code> e.g localhost:3000/products/123/books
</code>```

Any idea what's causing the issue?

答:
To make 'client-side, virtual' routes working from any url you need a server side support - f.e. apache mod-rewrite.

Already ansered here

Body:
I have a react BrowserRouter with the following configuration.

<BrowserRouter>

            <Switch>
                <Route path={`/`} component={Home} exact/>
                <Route path={`/about`} render={(props) => <About {...props}/>} exact/>
                <Route path={`/products/:id/:slug`} render={(props) => <Products {...props}/>} exact/>
            </Switch>

In the About Page there are products with the following  tag. If I click a link, the url changes and Product page is getting rendered correctly.

<Link to={'/products/' + product.id + '/' + product.slug>{product.name }</Link>

But when I directly Land to Product page using the exact URL. rendering won't work.

 e.g localhost:3000/products/123/books

Any idea what's causing the issue?


问:
?!Have an issue on table using html, css
1.) Im having a problem to my table. How can i merge this table into 1? they are separated . see my image below:

css, html

.no-bottom-border{
    border: 1px solid black;
    border-radius: 5px;
    width:100%;

}
```

<p>HTML:</p>

<pre class="lang-html prettyprint-override"><code><table class="no-bottom-border">
                    <tr>
                        <td><b>Drop</b> : {{$value['sequence_id']}}</td>
                        <td><b>Route Code</b> : {{$value['route_no']}}</td>
                        <td><b>Route Name</b> : {{$route_name}}</td>
                        </tr>
                        <?php
                    $getVsr = \App\Modules\Entities\VSR\VSR::where('route_no',$value['route_no'])->get();
                    // dd($getVsr);
                ?>
                        <tr>
                        <td colspan="3">
                        <table>
                            <tr>
                        <th>                </th>
                        <th>ENV</th>
                        <th>VSR NO.</th>
                        <th>BOX/BDL</th>
                        <th>SEAL NO.</th>
                        <th>PADLOCK NO.</th>
                        <th>DEST-ATA</th>
                        <th>DEST-ATD</th>
                        <th>REMARKS</th>
                        <th>RECEIVED BY/DATE</th>
                    </tr>
                @foreach($getVsr as $vsrVal)
                    <tr>
                        <td></td>
                        <td>{{$vsrVal['env']}}</td>
                        <td>{{$vsrVal['vsr_no']}}</td>
                        <td>{{$vsrVal['vsr_no']}}</td>
                        <td>{{$vsrVal['seal_no']}}</td>
                        <td>{{$vsrVal['padlock_no']}}</td>
                        <td>__________</td>
                        <td>__________</td>
                        <td>__________</td>
                        <td>__________</td>
                    </tr>
                @endforeach
                </table>
</code>```

any idea? suggestion . much appreciate
2.) i cant fix my table and having a problem to merge it into 1 table only

答:
You have a second
 tag inside your table right below the

If you only want to have one table, remove the second tag.

Body:
1.) Im having a problem to my table. How can i merge this table into 1? they are separated . see my image below:

css, html

.no-bottom-border{
    border: 1px solid black;
    border-radius: 5px;
    width:100%;

}

HTML:

                        Drop : {{$value['sequence_id']}}
                        Route Code : {{$value['route_no']}}
                        Route Name : {{$route_name}}

                        <?php
                    $getVsr = \App\Modules\Entities\VSR\VSR::where('route_no',$value['route_no'])->get();
                    // dd($getVsr);
                ?>

                        ENV
                        VSR NO.
                        BOX/BDL
                        SEAL NO.
                        PADLOCK NO.
                        DEST-ATA
                        DEST-ATD
                        REMARKS
                        RECEIVED BY/DATE

                @foreach($getVsr as $vsrVal)

                        {{$vsrVal['env']}}
                        {{$vsrVal['vsr_no']}}
                        {{$vsrVal['vsr_no']}}
                        {{$vsrVal['seal_no']}}
                        {{$vsrVal['padlock_no']}}
                        __________
                        __________
                        __________
                        __________

                @endforeach

any idea? suggestion . much appreciate
2.) i cant fix my table and having a problem to merge it into 1 table only

Body:
You have a second <table> tag inside your table right below the <td colspan="3">

If you only want to have one table, remove the second tag.


问:
How can I transpose a part of a data frame?
Suppose I have a data frame as follows :

```<code>ID  DOMAIN.x  VISIT.x  DAY     DOMAIN.y   VISIT.y
1     A        C1D1     30        B         C2D1
</code>```

Now I want to get another data with a row for .y variables.

```<code>ID  DOMAIN   VISIT    DAY
1     A       C1D1    30
2     B       C2D1    30
</code>```

答:
Youc an do this:</p>

```<code>df <- read.table(text = "
ID  DOMAIN.x  VISIT.x  DAY     DOMAIN.y   VISIT.y
1     A        C1D1     30        B         C2D1 ", header = T)

reshape(df, direction = "long", varying = list(domain = c(2,5), visit = c(3,6)),
        idvar = "ID", v.names = c("DOMAIN", "VISIT"), timevar = "ID", times = c(1,2))

    ID DAY DOMAIN VISIT
1.1  1  30      A  C1D1
1.2  2  30      B  C2D1

</code>```

Body:
Suppose I have a data frame as follows :

ID  DOMAIN.x  VISIT.x  DAY     DOMAIN.y   VISIT.y
1     A        C1D1     30        B         C2D1

Now I want to get another data with a row for .y variables.

ID  DOMAIN   VISIT    DAY
1     A       C1D1    30
2     B       C2D1    30

Body:
Youc an do this:

df <- read.table(text = "
ID  DOMAIN.x  VISIT.x  DAY     DOMAIN.y   VISIT.y
1     A        C1D1     30        B         C2D1 ", header = T)

reshape(df, direction = "long", varying = list(domain = c(2,5), visit = c(3,6)),
        idvar = "ID", v.names = c("DOMAIN", "VISIT"), timevar = "ID", times = c(1,2))

    ID DAY DOMAIN VISIT
1.1  1  30      A  C1D1
1.2  2  30      B  C2D1


问:
how to make http://abcd.com/../../xyz/a.do work
I tried to run something like this http://abcd.com/../../xyz/a.do via browser.But it didn't succeed.

My question is can we run a url where it is fetching data from directories not child of abcd.com

Thanks

Edit:

Let say I have this directory structure under /www/:

    /xzy

    /blah/abcd.com/

And I want to access data in /xyz

答:
No.

Relative URIs are resolved into absolute URIs by the client. ../ just causes the previous directory to be dropped. If there isn't one, then the ../ is ignored.

It would be a pretty major security problem if a web server could be instructed to fetch arbitrary content from above the web root.


问:
What is the purpose of this clear_mem function?
I've been trying to work out exactly what this function's purpose is I've come across..
The code intentionally has bad code practices, so I am trying to figure out if this is one of them.

Here is the function:

```<code>void clear_mem(char *memblock, int siz) {
  register int i;

  for (i=0; i<=siz;i++)
      *(memblock+i) = 0;

}
</code>```

The function is called within the following function:

```<code>char *get_argument(char line[], int argno){
    char *argument = malloc(512);
    char clone[512];
    strncpy(clone, line, strlen(line)+1);

    int current_arg = 0;
    char *splitted = strtok(clone, " ");
    while (splitted != NULL){
        if (splitted[0] != ':'){
            current_arg++;
        }
        if (current_arg == argno+1){
            clear_mem(argument, 512); //Here
            strncpy(argument, splitted, strlen(splitted)+1);
            return argument;
            free(argument);
        }
        splitted = strtok(NULL, " ");
    }

    if (current_arg != argno){
        argument[0] = '\0';
    }
    free(argument);
    return argument;
}
</code>```

Thanks in advance!

答:
In this code:

```<code>for (i=0; i<=siz;i++)
      *(memblock+i) = 0;
</code>```

memblock+i adds the integer i to the pointer memblock. The result points i elements beyond where memblock points. Since memblock is a pointer to char, the result points i characters beyond where memblock points.

Then *(memblock+i) refers to the character at that address. *(memblock+i) is equivalent to memblock[i]. *(memblock+i) = 0 sets the character to zero.

So the effect of this code is to set all characters indexed by i during the loop to zero. It clears a block of memory.

The for (i=0; i<=siz;i++) causes the loop to iterate with i taking all values from zero up to and including siz. Thus, siz+1 characters will be set to zero.

We can see this is an error because get_argument allocates 512 bytes for argument and then later calls clear_mem(argument, 512), which clears 513 bytes. The resulting behavior is not defined by the C code.

Body:
I've been trying to work out exactly what this function's purpose is I've come across..
The code intentionally has bad code practices, so I am trying to figure out if this is one of them.

Here is the function:

void clear_mem(char *memblock, int siz) {
  register int i;

  for (i=0; i<=siz;i++)
      *(memblock+i) = 0;

}

The function is called within the following function:

char *get_argument(char line[], int argno){
    char *argument = malloc(512);
    char clone[512];
    strncpy(clone, line, strlen(line)+1);

    int current_arg = 0;
    char *splitted = strtok(clone, " ");
    while (splitted != NULL){
        if (splitted[0] != ':'){
            current_arg++;
        }
        if (current_arg == argno+1){
            clear_mem(argument, 512); //Here
            strncpy(argument, splitted, strlen(splitted)+1);
            return argument;
            free(argument);
        }
        splitted = strtok(NULL, " ");
    }

    if (current_arg != argno){
        argument[0] = '\0';
    }
    free(argument);
    return argument;
}

Thanks in advance!

Body:
In this code:

for (i=0; i<=siz;i++)
      *(memblock+i) = 0;

memblock+i adds the integer i to the pointer memblock. The result points i elements beyond where memblock points. Since memblock is a pointer to char, the result points i characters beyond where memblock points.

Then *(memblock+i) refers to the character at that address. *(memblock+i) is equivalent to memblock[i]. *(memblock+i) = 0 sets the character to zero.

So the effect of this code is to set all characters indexed by i during the loop to zero. It clears a block of memory.

The for (i=0; i<=siz;i++) causes the loop to iterate with i taking all values from zero up to and including siz. Thus, siz+1 characters will be set to zero.

We can see this is an error because get_argument allocates 512 bytes for argument and then later calls clear_mem(argument, 512), which clears 513 bytes. The resulting behavior is not defined by the C code.


问:
How to align item in middle of navbar?
There is 6 items in navbar:

first 3 items should be aligned as flex-start - on beginning of navbar.

Then Logo should be in center of navbar

And on the end -> flex-end should come 2 icons

Here is screenshot of navbar current condition:

Problem: is position of Logo - am using margin-left: '27%'. And on different screen size logo is not aligned well.

I would like to align some how that logo trough flex, is there a way to do that with flex?

Check the code:

HTML/jsx:

```<code> <div className="container">
  <header className="header">
    <nav className="user-nav">
      <div className="user-nav-item">
        <Link href="/">
          <a className="user-nav-item-link">Overview</a>
        </Link>
      </div>
      <div className="user-nav-item">
        <Link href="/search">
          <a className="user-nav-item-link">Search</a>
        </Link>
      </div>
      <div className="user-nav-item">
        <Link href="/feed">
          <a className="user-nav-item-link">Feed</a>
        </Link>
      </div>
      <h3 className="logo">Logo</h3>
    </nav>

    <div className="user-nav-icon">
      <div className="user-nav-icon-box">
        <img src={bellIcon} alt="notify icon" />
      </div>
      <div className="user-nav-icon-box">
        <img src={settingsIcon} alt="settings icon" />
      </div>
    </div>
  </header>
</div>
</code>```

CSS:

```<code>.container {
  max-width: 100vw;
  display: flex;
  flex-direction: column;

.header {
  display: flex;
  align-items: center;
  height: 5rem;
  color: #fff;
  background-color: black;

  .user-nav {
    width: 100%;
    display: flex;
    align-items: center;

    &-item {
      width: 5.5rem;
      padding: 1.5rem;
      cursor: pointer;
    }

    &-item-link {
      text-decoration: none;
      color: white;
    }

    .logo {
      margin-left: 27%;
    }

    &-icon {
      display: flex;
      align-items: center;
      background-color: white;
      color: red;
      margin-right: 3rem;

      & > * {
        padding: 0 0.8rem;
        cursor: pointer;
      }

      &-icon-notification {
        color: red;
      }
    }
  }
}

}
</code>```

答:
Using Flex Box. It will be harder to achieve that, I have an alternative. Please test this code on codepen:

* {
  box-sizing: border-box;
}

.parent{
  width: 100%;
  min-height: 80px;
  background-color: yellow;
  display: relative;
}
.nav-menu,
.icons{
  display: inline-block;
}
.icons{
  float: right;
  margin-left: 75px; /*This will help your icons to never go below the logo element*/
}
.nav-menu{
  margin-right: 75px; /*This will help your nav-menu items to never go below the logo element*/
}
.logo{
  width: 150px;
  height: 40px;
  position: absolute;
  left: 50%;
   background-color: green;
  transform: translateX(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="nav-menu"> Your Menu</div>
  <div class="logo"></div>
  <div class="icons">Your Icons</div>
</div></code>```

Title: How to align item in middle of navbar?

Body:
There is 6 items in navbar:

first 3 items should be aligned as flex-start - on beginning of navbar.

Then Logo should be in center of navbar

And on the end -> flex-end should come 2 icons

Here is screenshot of navbar current condition:

Problem: is position of Logo - am using margin-left: '27%'. And on different screen size logo is not aligned well.

I would like to align some how that logo trough flex, is there a way to do that with flex?

Check the code:

HTML/jsx:

        <Link href="/">
          Overview
        </Link>

        <Link href="/search">
          Search
        </Link>

        <Link href="/feed">
          Feed
        </Link>

Logo

CSS:

.container {
  max-width: 100vw;
  display: flex;
  flex-direction: column;

.header {
  display: flex;
  align-items: center;
  height: 5rem;
  color: #fff;
  background-color: black;

  .user-nav {
    width: 100%;
    display: flex;
    align-items: center;

    &-item {
      width: 5.5rem;
      padding: 1.5rem;
      cursor: pointer;
    }

    &-item-link {
      text-decoration: none;
      color: white;
    }

    .logo {
      margin-left: 27%;
    }

    &-icon {
      display: flex;
      align-items: center;
      background-color: white;
      color: red;
      margin-right: 3rem;

      & > * {
        padding: 0 0.8rem;
        cursor: pointer;
      }

      &-icon-notification {
        color: red;
      }
    }
  }
}

}

Body:
Using Flex Box. It will be harder to achieve that, I have an alternative. Please test this code on codepen:

* {
  box-sizing: border-box;
}

.parent{
  width: 100%;
  min-height: 80px;
  background-color: yellow;
  display: relative;
}
.nav-menu,
.icons{
  display: inline-block;
}
.icons{
  float: right;
  margin-left: 75px; /*This will help your icons to never go below the logo element*/
}
.nav-menu{
  margin-right: 75px; /*This will help your nav-menu items to never go below the logo element*/
}
.logo{
  width: 150px;
  height: 40px;
  position: absolute;
  left: 50%;
   background-color: green;
  transform: translateX(-50%);
}

<div class="parent">
  <div class="nav-menu"> Your Menu</div>
  <div class="logo"></div>
  <div class="icons">Your Icons</div>
</div>


问:
Combine the result of 2 SELECT in one
I have 2 selects:

```<code>SELECT *
FROM driverdetails
WHERE driverdetails.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'

SELECT *
FROM location
WHERE location.utc = (  SELECT MAX(location.utc)
                        FROM location
                        WHERE location.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'
                    );
</code>```

And I am trying to have a single result like:
Columns from select1 + columns from select 2

How do I achieve the columns one after another by keeping all conditions from example?

答:
You should try to use subselect then:

```<code>SELECT
     (SELECT *
     FROM driverdetails
     WHERE driverdetails.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'
     ),
     (SELECT *
     FROM location
     WHERE location.utc = (  SELECT MAX(location.utc)
                        FROM location
                        WHERE location.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'
     );
</code>```

UPD: after you edited tables to match by some column, i recommend you to use the answer above

Title: Combine the result of 2 SELECT in one

Body:
I have 2 selects:

SELECT *
FROM driverdetails
WHERE driverdetails.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'

SELECT *
FROM location
WHERE location.utc = (  SELECT MAX(location.utc)
                        FROM location
                        WHERE location.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'
                    );

And I am trying to have a single result like:
Columns from select1 + columns from select 2

How do I achieve the columns one after another by keeping all conditions from example?

Body:
You should try to use subselect then:

SELECT
     (SELECT *
     FROM driverdetails
     WHERE driverdetails.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'
     ),
     (SELECT *
     FROM location
     WHERE location.utc = (  SELECT MAX(location.utc)
                        FROM location
                        WHERE location.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'
     );

UPD: after you edited tables to match by some column, i recommend you to use the answer above


问:
how does the Entrypoint command works here
How does the ENTRYPOINT command works given in the below docker compose file. I have found the docker compose file in replica Set mongo docker-compose. "usr/bin/mongod" is the first command given in the ENTRYPOINT, my Question is whether the usr/bin/mongod will start the local mongo and run it has docker container or it will pull the mongo image from repository and run it as container if so why we are using "usr/bin/mongod".

```<code>version: "3"
services:
  mongo-1:
    hostname: mongo-1
    container_name: mongo-1
    image: mongo:4.0
    ports:
      - "127.0.0.1:28000:28000"
    volumes:
      - ./mongo-1/data:/data/db
    restart: always
    entrypoint: [ "/usr/bin/mongod", "--port", "28000", "--bind_ip_all", "--replSet", "rs1" ]
</code>```

using this compose file i am able to connect mongoDB running in the port 28000 from host machine but when i replace the ENTRYPOINT with CMD in the compose file i am not able to connect the mongoDB from host machine.

答:
You are using the image "mongo:4.0" which has its own ENTRYPOINT and CMD defined. When you redeclare any of them in your docker-compose.yml then you are overwriting the original ones.

ENTRYPOINT is the main command and CMD are only parameters sent to the main command. For this reason it works for you when you define ENTRYPOINT with a valid command. If you change it to CMD then when is run is the original ENTRYPOINT ("docker-entrypoint.sh") and the new command.

Your entrypoint uses the binary from inside your container that is based on the specified image.

For reference you can see the Dockerfile of the official image: https://github.com/docker-library/mongo/blob/40056ae591c1caca88ffbec2a426e4da07e02d57/4.0/Dockerfile

The ENTRYPOINT and CMD are defined at the end.

Body:
How does the ENTRYPOINT command works given in the below docker compose file. I have found the docker compose file in replica Set mongo docker-compose. "usr/bin/mongod" is the first command given in the ENTRYPOINT, my Question is whether the usr/bin/mongod will start the local mongo and run it has docker container or it will pull the mongo image from repository and run it as container if so why we are using "usr/bin/mongod".

version: "3"
services:
  mongo-1:
    hostname: mongo-1
    container_name: mongo-1
    image: mongo:4.0
    ports:
      - "127.0.0.1:28000:28000"
    volumes:
      - ./mongo-1/data:/data/db
    restart: always
    entrypoint: [ "/usr/bin/mongod", "--port", "28000", "--bind_ip_all", "--replSet", "rs1" ]

using this compose file i am able to connect mongoDB running in the port 28000 from host machine but when i replace the ENTRYPOINT with CMD in the compose file i am not able to connect the mongoDB from host machine.


问:
changing a key name in NSDictionary
I have a method which returns me a nsdictionary with certain keys and values. i need to change the key names from the dictionary to a new key name but the values need to be same for that key,but i am stuck here.need help</p>

答:
This method will only work with a mutable dictionary. It doesn't check what should be done if the new key already exists.

You can get a mutable dictionary of a immutable by calling mutableCopy on it.

```<code>- (void)exchangeKey:(NSString *)aKey withKey:(NSString *)aNewKey inMutableDictionary:(NSMutableDictionary *)aDict
{
    if (![aKey isEqualToString:aNewKey]) {
        id objectToPreserve = [aDict objectForKey:aKey];
        [aDict setObject:objectToPreserve forKey:aNewKey];
        [aDict removeObjectForKey:aKey];
    }
}
</code>```

Title: changing a key name in NSDictionary

Body:
This method will only work with a mutable dictionary. It doesn't check what should be done if the new key already exists.

You can get a mutable dictionary of a immutable by calling mutableCopy on it.

- (void)exchangeKey:(NSString *)aKey withKey:(NSString *)aNewKey inMutableDictionary:(NSMutableDictionary *)aDict
{
    if (![aKey isEqualToString:aNewKey]) {
        id objectToPreserve = [aDict objectForKey:aKey];
        [aDict setObject:objectToPreserve forKey:aNewKey];
        [aDict removeObjectForKey:aKey];
    }
}


问:
How to choose batch_size, steps_per_epoch and epoch with Keras generator
I'm training 2 different CNN (custom and transfer learning) for an image classification problem.
I use the same generator for both models.
The dataset contains 5000 samples for 5 classes, but is imbalanced.

Here's the custom model I'm using.

```<code>def __init__(self, transfer_learning = False, lambda_reg = 0.001, drop_out_rate = 0.1):
    if(transfer_learning == False):
        self.model = Sequential();
        self.model.add(Conv2D(32, (3,3), input_shape = (224,224,3), activation = "relu"))
        self.model.add(MaxPooling2D(pool_size = (2,2)))

        self.model.add(Conv2D(64, (1,1), activation = "relu"))
        self.model.add(MaxPooling2D(pool_size = (2,2)))

        self.model.add(Conv2D(128, (3,3), activation = "relu"))
        self.model.add(MaxPooling2D(pool_size = (2,2)))

        self.model.add(Conv2D(128, (1,1), activation = "relu"))
        self.model.add(MaxPooling2D(pool_size = (2,2)))

        self.model.add(Flatten())

        self.model.add(Dense(512))
        self.model.add(Dropout(drop_out_rate))
        self.model.add(Dense(256))
        self.model.add(Dropout(drop_out_rate))

        self.model.add(Dense(5, activation = "softmax"))
</code>```

So I can't understand the relation between steps_per_epoch and batch_size.
batch_size is the number of samples the generator sends.
But is steps_per_epoch the number of batch_size to complete one training epoch?
If so, then it should be: steps_per_epoch = total_samples/batch_size ?

Whatever value I try, I always get the same problem (on both models), the val_acc seems to reach a local optima.

答:
First of all, steps_per_epoch = total_samples/batch_size is correct in general terms.

It's an example code written by tensowflow as following:

```<code>for epoch in range(training_epochs):
    avg_cost = 0
    total_batch = int(mnist.train.num_examples / batch_size)

    for i in range(total_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        feed_dict = {X: batch_xs, Y: batch_ys}
        c, _ = sess.run([cost, optimizer], feed_dict=feed_dict)
        avg_cost += c / total_batch

    print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost))

print('Learning Finished!')
</code>```

By the way, Although It is not exactly related with your question. There are some various optimizer such as Stochastic Gradient Descent and Adam because that a learning takes too long time with heavy data set.

It does not learn all data every time. There are many articles about that. Here I just leave one of them.

And, For your val_acc, It seems that Your model has so many Convolution layer.

You reduced filters and maxpooling of convolution layers, But, I think it is too much. How is going on? Is it better than before?

Body:
I'm training 2 different CNN (custom and transfer learning) for an image classification problem.
I use the same generator for both models.
The dataset contains 5000 samples for 5 classes, but is imbalanced.

Here's the custom model I'm using.

def __init__(self, transfer_learning = False, lambda_reg = 0.001, drop_out_rate = 0.1):
    if(transfer_learning == False):
        self.model = Sequential();
        self.model.add(Conv2D(32, (3,3), input_shape = (224,224,3), activation = "relu"))
        self.model.add(MaxPooling2D(pool_size = (2,2)))

        self.model.add(Conv2D(64, (1,1), activation = "relu"))
        self.model.add(MaxPooling2D(pool_size = (2,2)))

        self.model.add(Conv2D(128, (3,3), activation = "relu"))
        self.model.add(MaxPooling2D(pool_size = (2,2)))

        self.model.add(Conv2D(128, (1,1), activation = "relu"))
        self.model.add(MaxPooling2D(pool_size = (2,2)))

        self.model.add(Flatten())

        self.model.add(Dense(512))
        self.model.add(Dropout(drop_out_rate))
        self.model.add(Dense(256))
        self.model.add(Dropout(drop_out_rate))

        self.model.add(Dense(5, activation = "softmax"))

So I can't understand the relation between steps_per_epoch and batch_size.
batch_size is the number of samples the generator sends.
But is steps_per_epoch the number of batch_size to complete one training epoch?
If so, then it should be: steps_per_epoch = total_samples/batch_size ?

Whatever value I try, I always get the same problem (on both models), the val_acc seems to reach a local optima.

Body:
First of all, steps_per_epoch = total_samples/batch_size is correct in general terms.

It's an example code written by tensowflow as following:

for epoch in range(training_epochs):
    avg_cost = 0
    total_batch = int(mnist.train.num_examples / batch_size)

    for i in range(total_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        feed_dict = {X: batch_xs, Y: batch_ys}
        c, _ = sess.run([cost, optimizer], feed_dict=feed_dict)
        avg_cost += c / total_batch

    print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost))

print('Learning Finished!')

By the way, Although It is not exactly related with your question. There are some various optimizer such as Stochastic Gradient Descent and Adam because that a learning takes too long time with heavy data set.

It does not learn all data every time. There are many articles about that. Here I just leave one of them.

And, For your val_acc, It seems that Your model has so many Convolution layer.

You reduced filters and maxpooling of convolution layers, But, I think it is too much. How is going on? Is it better than before?


问:
Failing the whole Test Suite if one Test Case fails while running dependent test through VSTS
I have dependent test cases in my suite. If my first test fails it marks all other test as fail as well. So at the end it show that all all the test cases has failed which is not true.

Is there a way though which I can mark the test as 'failed due to dependent test failure' or something else so that it shows that it failed because the dependent test failed.
Is there a way to add a new state in test instead of only have pass, fail, not executed states.

I have added a common flag in our tests which marks the tests as failed when any dependent test fails.
As you can see in the code below.
It marks the test as Assert.Fail inside else part if the previous test has failed.
Is there a way to mark it in some other state and not failed for example : 'Failed due to dependent test failure'.

```<code>bool hasPreviousTestCasePassed = false
[TestMethod]
    public void DemoTest1()
    {
     try
        {
          ////perform all the test steps
          hasPreviousTestCasePassed = true;
        }
        catch (Exception ex)
        {
            hasPreviousTestCasePassed = false;
        }
    }

 [TestMethod]
    public void DemoTest2()
    {
        try
        {
            if (hasPreviousTestCasePassed)
            {
              ///perform all the test steps and mark flag as true after all steps
             hasPreviousTestCasePassed = true;
            }
            else
            {
               Assert.Fail("Execution for " + TestContext.TestName + " is aborted as the previous test case failed.");
            }
        }
        catch (Exception ex)
        {
            hasPreviousTestCasePassed = false;
        }
    }
</code>```

Expected result would be to have a way to mark a test as Failed due to dependent test failure and not just mark it as failed.

The Idea behind doing this is that when my first test fails then it marks all the test as failed and the outcome says that all the test has been fail which is not actually true because they got executed.

So I want a way to show case the dependent failure in a separate state so that the results are more clear.

答:
Would Assert.Inconclusive help? MSDN docs

It will make the distinction between a failing test and a 'suspicious test' due to previous failure obvious.

Body:
I have dependent test cases in my suite. If my first test fails it marks all other test as fail as well. So at the end it show that all all the test cases has failed which is not true.

Is there a way though which I can mark the test as 'failed due to dependent test failure' or something else so that it shows that it failed because the dependent test failed.
Is there a way to add a new state in test instead of only have pass, fail, not executed states.

I have added a common flag in our tests which marks the tests as failed when any dependent test fails.
As you can see in the code below.
It marks the test as Assert.Fail inside else part if the previous test has failed.
Is there a way to mark it in some other state and not failed for example : 'Failed due to dependent test failure'.

bool hasPreviousTestCasePassed = false
[TestMethod]
    public void DemoTest1()
    {
     try
        {
          ////perform all the test steps
          hasPreviousTestCasePassed = true;
        }
        catch (Exception ex)
        {
            hasPreviousTestCasePassed = false;
        }
    }

 [TestMethod]
    public void DemoTest2()
    {
        try
        {
            if (hasPreviousTestCasePassed)
            {
              ///perform all the test steps and mark flag as true after all steps
             hasPreviousTestCasePassed = true;
            }
            else
            {
               Assert.Fail("Execution for " + TestContext.TestName + " is aborted as the previous test case failed.");
            }
        }
        catch (Exception ex)
        {
            hasPreviousTestCasePassed = false;
        }
    }

Expected result would be to have a way to mark a test as Failed due to dependent test failure and not just mark it as failed.

The Idea behind doing this is that when my first test fails then it marks all the test as failed and the outcome says that all the test has been fail which is not actually true because they got executed.

So I want a way to show case the dependent failure in a separate state so that the results are more clear.


问:
How to get columns that are repeating in different tables in a database inside SQL Server
I've a database with huge number of tables. From these tables I want to list out all the column names that are appearing in more than one table along with the their table names.

I tried google search to find any suitable article that can explain how to achieve the results that I've described in the problem section.

No code snippets

No error messages.

答:
There are a lot of results and snippets that show how to get all column names in a database. It's a single query to sys.columns, eg :

```<code>select Name
from sys.columns
</code>```

The same SQL queries that return multiple occurences in any table can be used here too, eg :

```<code>select Name,count(*)
from sys.columns
group by Name
having count(*)>1
</code>```

Will return column names that occur more than once.

You can get the column and table names without joining by using COUNT() with OVER :

```<code>with t as (
    select name,
           object_name(object_id) as TableName,
           count(*) over (partition by name) cnt
    from sys.columns
)
select *
from t
where cnt >1
</code>```

Body:
There are a lot of results and snippets that show how to get all column names in a database. It's a single query to sys.columns, eg :

select Name
from sys.columns

The same SQL queries that return multiple occurences in any table can be used here too, eg :

select Name,count(*)
from sys.columns
group by Name
having count(*)>1

Will return column names that occur more than once.

You can get the column and table names without joining by using COUNT() with OVER :

with t as (
    select name,
           object_name(object_id) as TableName,
           count(*) over (partition by name) cnt
    from sys.columns
)
select *
from t
where cnt >1


问:
LibGDX Button does not recognize clicks (Stage + ChangeListener)
EDIT: First Cemmentator "Second" was right. I forgot to set Gdx.input.setInputProcessor(stage); - Now everything is working as it should. Thanks!

My Libgdx Buttons "Back", "Menu" and "TryAgain" (which bring you back to another Screen) are not working.

I worked through every solution that I could find but they still not work properly. I also use Buttons and stages in my other Screens and they all work like a charm.

Do you guys see any mistakes in the code? CreateStage() creates the stage and they get displayed through the render Method.

Any Help is greatly appreciated!

```<code>public class HighscoreScreen extends ScreenAdapter {

private final GameClass game;
private int score;
private String name;
private boolean menuView;

private SpriteBatch batch;
private BitmapFont scoreFont;

private String[] players;
private int[] scores;
private int counter = 0;
private OrthographicCamera camera;
private Stage stage;
private ScreenViewport v;

public HighscoreScreen (GameClass game, OrthographicCamera camera, int score, String name) {
    this.camera = camera;
    this.game = game;
    this.score = score;
    this.name = name;
    this.batch = new SpriteBatch();
    menuView = false;
    batch = new SpriteBatch();

    scoreFont = new BitmapFont(Gdx.files.internal("Fonts/score.fnt"),
            Gdx.files.internal("Fonts/score.png"),false);
    createStage();
}

public HighscoreScreen (GameClass game, OrthographicCamera camera){
    this.game = game;
    this.camera = camera;
    this.batch = new SpriteBatch();
    menuView = true;

    scoreFont = new BitmapFont(Gdx.files.internal("Fonts/score.fnt"),
            Gdx.files.internal("Fonts/score.png"),false);

}

public void createStage(){

    v = new ScreenViewport();
    v.setCamera(camera);
    stage = new Stage(v, batch);

    if (menuView) {

        Buttons back = new Buttons("Back");
        stage.addActor(back.createButton(GameInfo.WIDTH / 2 - 100,
                GameInfo.HEIGHT / 2 - 200));

        back.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                game.setScreen(new MenuScreen(game));
            }
        });

    } else {

        Buttons tryAgain = new Buttons("Try Again");
        stage.addActor(tryAgain.createButton(GameInfo.WIDTH / 2 - 200,
                GameInfo.HEIGHT / 2 - 200));

        tryAgain.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                game.setScreen(new SurvivalScreen(game, name));
            }
        });

        Buttons menu = new Buttons("Menu");
        stage.addActor(menu.createButton(GameInfo.WIDTH / 2,
                GameInfo.HEIGHT / 2 - 200));

        menu.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                game.setScreen(new MenuScreen(game));
            }
        });
    }
}

@Override
public void render(float delta) {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    if (menuView) {

        if (counter == 0) {

            createStage();
            writeScoresToFile();
            readHighscore();
            counter++;

        }

        batch.begin();
        highscoreToFont();
        batch.end();
        stage.act();
        stage.draw();

    } else {

        if (counter == 0) {

            createStage();
            writeScoresToFile();
            readHighscore();
            compareHighscore();
            writeHighscore();
            counter++;

        }

        batch.begin();
        highscoreToFont();
        batch.end();
        stage.act();
        stage.draw();

    }

}

public void dispose(){
    batch.dispose();
    stage.dispose();
}
</code>```

答:
You are probably missing the settings of the input processor to your stage (at least it's not in the code you have posted).

```<code>Gdx.input.setInputProcessor(stage);
</code>```

Note:

Assuming the the Buttons class returns a proper actor.

(see my comment above)

Body:
EDIT: First Cemmentator "Second" was right. I forgot to set Gdx.input.setInputProcessor(stage); - Now everything is working as it should. Thanks!

My Libgdx Buttons "Back", "Menu" and "TryAgain" (which bring you back to another Screen) are not working.

I worked through every solution that I could find but they still not work properly. I also use Buttons and stages in my other Screens and they all work like a charm.

Do you guys see any mistakes in the code? CreateStage() creates the stage and they get displayed through the render Method.

Any Help is greatly appreciated!

public class HighscoreScreen extends ScreenAdapter {

private final GameClass game;
private int score;
private String name;
private boolean menuView;

private SpriteBatch batch;
private BitmapFont scoreFont;

private String[] players;
private int[] scores;
private int counter = 0;
private OrthographicCamera camera;
private Stage stage;
private ScreenViewport v;

public HighscoreScreen (GameClass game, OrthographicCamera camera, int score, String name) {
    this.camera = camera;
    this.game = game;
    this.score = score;
    this.name = name;
    this.batch = new SpriteBatch();
    menuView = false;
    batch = new SpriteBatch();

    scoreFont = new BitmapFont(Gdx.files.internal("Fonts/score.fnt"),
            Gdx.files.internal("Fonts/score.png"),false);
    createStage();
}

public HighscoreScreen (GameClass game, OrthographicCamera camera){
    this.game = game;
    this.camera = camera;
    this.batch = new SpriteBatch();
    menuView = true;

    scoreFont = new BitmapFont(Gdx.files.internal("Fonts/score.fnt"),
            Gdx.files.internal("Fonts/score.png"),false);

}

public void createStage(){

    v = new ScreenViewport();
    v.setCamera(camera);
    stage = new Stage(v, batch);

    if (menuView) {

        Buttons back = new Buttons("Back");
        stage.addActor(back.createButton(GameInfo.WIDTH / 2 - 100,
                GameInfo.HEIGHT / 2 - 200));

        back.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                game.setScreen(new MenuScreen(game));
            }
        });

    } else {

        Buttons tryAgain = new Buttons("Try Again");
        stage.addActor(tryAgain.createButton(GameInfo.WIDTH / 2 - 200,
                GameInfo.HEIGHT / 2 - 200));

        tryAgain.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                game.setScreen(new SurvivalScreen(game, name));
            }
        });

        Buttons menu = new Buttons("Menu");
        stage.addActor(menu.createButton(GameInfo.WIDTH / 2,
                GameInfo.HEIGHT / 2 - 200));

        menu.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                game.setScreen(new MenuScreen(game));
            }
        });
    }
}

@Override
public void render(float delta) {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    if (menuView) {

        if (counter == 0) {

            createStage();
            writeScoresToFile();
            readHighscore();
            counter++;

        }

        batch.begin();
        highscoreToFont();
        batch.end();
        stage.act();
        stage.draw();

    } else {

        if (counter == 0) {

            createStage();
            writeScoresToFile();
            readHighscore();
            compareHighscore();
            writeHighscore();
            counter++;

        }

        batch.begin();
        highscoreToFont();
        batch.end();
        stage.act();
        stage.draw();

    }

}

public void dispose(){
    batch.dispose();
    stage.dispose();
}

Body:
You are probably missing the settings of the input processor to your stage (at least it's not in the code you have posted).

Gdx.input.setInputProcessor(stage);

Note:

Assuming the the Buttons class returns a proper actor.

(see my comment above)


问:
read csv with escape characters
I have a csv file with some text, among others. I want to tokenize (split into a list of words) this text and am having problems with how pd.read_csv interprets escape characters.

My csv file looks like this:

```<code>text, number
one line\nother line, 12
</code>```

and the code is like follows:

```<code>df = pd.read_csv('test.csv')
word_tokenize(df.iloc[0,0])
</code>```

output is:

```<code>['one', 'line\\nother', 'line']
</code>```

while what I want is:

```<code>['one', 'line', 'other', 'line']
</code>```

The problem is pd.read_csv() is not interpreting the \n as a newline character but as two characters (\ and n).

I've tried setting the escapechar argument to '\' and to '\\' but both just remove the slash from the string without doing any interpretation of a newline character, i.e. the string becomes on one linenon other line.

If I explicitly set df.iloc[0,0] = 'one line\nother line', word_tokenize works just fine, because \n is actually interpreted as a newline character this time.

Ideally I would do this simply changing the way pd.read_csv() interprets the file, but other solutions are also ok.

答:
You can simply try this</p>

```<code>import pandas as pd

df = pd.read_csv("test.csv", header=None)
df = df.apply(lambda x: x.str.replace('\\', " "))
print(df.iloc[1, 0])

# output: one line other line
</code>```

Title: read csv with escape characters

Body:
I have a csv file with some text, among others. I want to tokenize (split into a list of words) this text and am having problems with how pd.read_csv interprets escape characters.

My csv file looks like this:

text, number
one line\nother line, 12

and the code is like follows:

df = pd.read_csv('test.csv')
word_tokenize(df.iloc[0,0])

output is:

['one', 'line\\nother', 'line']

while what I want is:

['one', 'line', 'other', 'line']

The problem is pd.read_csv() is not interpreting the \n as a newline character but as two characters (\ and n).

I've tried setting the escapechar argument to '\' and to '\\' but both just remove the slash from the string without doing any interpretation of a newline character, i.e. the string becomes on one linenon other line.

If I explicitly set df.iloc[0,0] = 'one line\nother line', word_tokenize works just fine, because \n is actually interpreted as a newline character this time.

Ideally I would do this simply changing the way pd.read_csv() interprets the file, but other solutions are also ok.

Body:
You can simply try this

import pandas as pd

df = pd.read_csv("test.csv", header=None)
df = df.apply(lambda x: x.str.replace('\\', " "))
print(df.iloc[1, 0])

# output: one line other line


问:
AKS exposing application using HTTP application routing
I'm trying to expose application using HTTP application routing. I enabled http_application_routing addons which is result in this config :

```<code>  "addonProfiles": {
    "httpapplicationrouting": {
      "config": {
        "HTTPApplicationRoutingZoneName": "****.northeurope.aksapp.io",
        "httpapplicationroutingzonename": "****.northeurope.aksapp.io"
      },
      "enabled": true
    }
  }
</code>```

I created ingress resource :

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: addon-http-application-routing
  labels:
    name: axon-azure
  name: axon-ing-azure
spec:
  rules:
  - host: axon.****.northeurope.aksapp.io
    http:
      paths:
      - backend:
          serviceName: axon-svc
          servicePort: 8024
        path: /
</code>```

But it doesn't work when I test it :

```<code>curl axon.****.northeurope.aksapp.io
curl: (6) Could not resolve host: axon.****.northeurope.aksapp.io
</code>```

Following the AKS documentation, I'm thinking about a DNS problem because the DNS zone name doesn't appear using this command (but I don't know why) :

```<code>az aks show --resource-group myResourceGroup --name myAKSCluster --query addonProfiles.httpApplicationRouting.config.HTTPApplicationRoutingZoneName -o table
</code>```

Any idea of what's going wrong in this case ?

答:
For the HTTP application routing in AKS, when you enable the routing feature using the CLI command:

```<code>az aks enable-addons --resource-group your_resource_group --name your_akscluster --addons http_application_routing
</code>```

If there is no error, then you can get the DNS zone that Azure creates for you through the CLI command:

```<code>az aks show --resource-group your_resource_group --name your_akscluster --query addonProfiles.httpApplicationRouting.config.HTTPApplicationRoutingZoneName -o table
</code>```

In the above two CLI commands, you need to change the your_resource_group and your_akscluster with your own group and AKS.

And after you create the ingress with the yaml file, you should wait a bit long time which Azure create the record for you in the DNS zone. Maybe 5 minutes are needed. You can take a look if the record is already in the DNS zone.

If you need the HTTP route, I will suggest you create it yourself following the steps in Create an ingress controller in Azure Kubernetes Service (AKS) or Use a static IP. In this way, you will know exactly which step you have done or mistake.

Body:
I'm trying to expose application using HTTP application routing. I enabled http_application_routing addons which is result in this config :

  "addonProfiles": {
    "httpapplicationrouting": {
      "config": {
        "HTTPApplicationRoutingZoneName": "****.northeurope.aksapp.io",
        "httpapplicationroutingzonename": "****.northeurope.aksapp.io"
      },
      "enabled": true
    }
  }

I created ingress resource :

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: addon-http-application-routing
  labels:
    name: axon-azure
  name: axon-ing-azure
spec:
  rules:
  - host: axon.****.northeurope.aksapp.io
    http:
      paths:
      - backend:
          serviceName: axon-svc
          servicePort: 8024
        path: /

But it doesn't work when I test it :

curl axon.****.northeurope.aksapp.io
curl: (6) Could not resolve host: axon.****.northeurope.aksapp.io

Following the AKS documentation, I'm thinking about a DNS problem because the DNS zone name doesn't appear using this command (but I don't know why) :

az aks show --resource-group myResourceGroup --name myAKSCluster --query addonProfiles.httpApplicationRouting.config.HTTPApplicationRoutingZoneName -o table

Any idea of what's going wrong in this case ?

Body:
For the HTTP application routing in AKS, when you enable the routing feature using the CLI command:

az aks enable-addons --resource-group your_resource_group --name your_akscluster --addons http_application_routing

If there is no error, then you can get the DNS zone that Azure creates for you through the CLI command:

az aks show --resource-group your_resource_group --name your_akscluster --query addonProfiles.httpApplicationRouting.config.HTTPApplicationRoutingZoneName -o table

In the above two CLI commands, you need to change the your_resource_group and your_akscluster with your own group and AKS.

And after you create the ingress with the yaml file, you should wait a bit long time which Azure create the record for you in the DNS zone. Maybe 5 minutes are needed. You can take a look if the record is already in the DNS zone.

If you need the HTTP route, I will suggest you create it yourself following the steps in Create an ingress controller in Azure Kubernetes Service (AKS) or Use a static IP. In this way, you will know exactly which step you have done or mistake.


问:
What other get method characters can be used? aside from question mark?
the normal get:
http://localhost/get.php?id=2&get=row

can it be done like this?

http://localhost/get.php&id=2&get=row

or in other way.

When a user make a parameter to my site like

http://test.com/?url=http://localhost/sample/

or what if it contains a "?id=234"

so the new url is http://test.com/?url=http://localhost/smaple?id=1234

it creates now a 2 question mark.

答:
When a user make a parameter to your site, he has to urlencode such data, so, it's going to be

```<code>http://test.com/?url=http%3A%2F%2Flocalhost%2Fsmaple%3Fid%3D1234
</code>```

Body:
When a user make a parameter to your site, he has to urlencode such data, so, it's going to be

http://test.com/?url=http%3A%2F%2Flocalhost%2Fsmaple%3Fid%3D1234


问:
How to send variable with the guzzle post method
I have an API and I need to send some data to it and I am using guzzle for handling it so here is my code:

```<code>$amount = $request->get('amount');
    $client = new \GuzzleHttp\Client();
    $requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => '{
        "Amount":"i want to send $amount here",
        "something":"1",
        "Description":"desc",
        }'
    ]);
</code>```

so every thing is fine and static data is being send but I want to know how can I send a variable.

答:
Amount can pass in an array and after you can encode with json using ```json_encode``</p>

<p>Hope this works for you.</p>

```<code>$amount = $request->get('amount');
$client = new \GuzzleHttp\Client();
$url   = "http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber";
$data   = [
            "amount"      => $amount,
            "something"   => "1",
            "description" => "desc",
          ];

$requestAPI = $client->post( $url, [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode($data);
    ]);
</code>```

Body:
I have an API and I need to send some data to it and I am using guzzle for handling it so here is my code:

$amount = $request->get('amount');
    $client = new \GuzzleHttp\Client();
    $requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => '{
        "Amount":"i want to send $amount here",
        "something":"1",
        "Description":"desc",
        }'
    ]);

so every thing is fine and static data is being send but I want to know how can I send a variable.

Body:
Amount can pass in an array and after you can encode with json using ```json_encode``

Hope this works for you.

$amount = $request->get('amount');
$client = new \GuzzleHttp\Client();
$url   = "http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber";
$data   = [
            "amount"      => $amount,
            "something"   => "1",
            "description" => "desc",
          ];

$requestAPI = $client->post( $url, [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode($data);
    ]);


问:
Spring Unit Test - NestedServletException instead of custom exception
I am trying to write integration tests for REST API built using Spring MVC. Following is my controller class.

```<code>@RestController
@RequestMapping("/api")
public class ZoningToolRestController {

    @Autowired
    ImageProcessingService service;

    @RequestMapping(value = "/page/{index}", produces = "image/png", method = RequestMethod.GET)
    public byte[] getPage(@PathVariable("index") int index) throws InvalidIndexException, IOException {

        return service.getPage(index);
    }

    @ExceptionHandler
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("error", e.getMessage());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<Map<String, Object>>(map, headers, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
</code>```

Following is my test class

```<code>    @RunWith(SpringRunner.class)
@SpringBootTest
public class ZoningToolRestControllerTests {

    private MockMvc mvc;

    @Autowired
    private ZoningToolRestController zoningToolRestController;

    @Before
    public void setup() {
        this.mvc = MockMvcBuilders.standaloneSetup(zoningToolRestController)
                .setHandlerExceptionResolvers(getExceptionResolver())
                .build();
    }

    private HandlerExceptionResolver getExceptionResolver() {

        ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver();
        exceptionResolver.setMappedHandlerClasses(InvalidIndexException.class, ExceptionHandler.class);

        return exceptionResolver;
    }

    /**
     * Test to check if image is returned in case of valid call
     *
     * @throws Exception
     */
    @Test
    public void givenDocument_whenGetValidPage_thenSuccess() throws Exception {

        mvc.perform(get("/api/page/1").accept(MediaType.IMAGE_PNG)).andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.IMAGE_PNG));
    }

    /**
     * Test to check if server throws an error when wrong page is passed
     *
     * @throws Exception
     */
    @Test
    public void givenDocument_whenGetWrongPage_thenError() throws Exception {
        mvc.perform(get("/api/page/11").accept(MediaType.IMAGE_PNG)).andExpect(status().isInternalServerError())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
    }

}

</code>```

Now when I am trying to run this unit test, the second unit test is failing saying it is encountering a NestedSerlvletException when it is expecting a InvalidIndexException

What am I doing wrong?

Update
Stack Trace

```<code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is in.co.dhdigital.zoningtool.processors.InvalidIndexException: Invalid index passed.
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
    at in.co.dhdigital.zoningtool.test.controllers.ZoningToolRestControllerTests.givenDocument_whenGetWrongPage_thenError(ZoningToolRestControllerTests.java:73)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: in.co.dhdigital.zoningtool.processors.InvalidIndexException: Invalid index passed.
    at in.co.dhdigital.zoningtool.processors.impl.TiffImageProcessor.getPage(TiffImageProcessor.java:53)
    at in.co.dhdigital.zoningtool.services.ImageProcessingService.getPage(ImageProcessingService.java:32)
    at in.co.dhdigital.zoningtool.controllers.ZoningToolRestController.getPage(ZoningToolRestController.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    ... 41 more
</code>```

答:
Here is the test method throw an input validation (Bad input)
  exception or not.

```<code>  @Test(expected = ConstraintViolationException.class)
    public void addBadInput() throws Exception {
        try {
            mockMvc.perform(post(URL).content(object_mapper.writeValueAsString(bad_input_val)).
                    accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isBadRequest());
        } catch (NestedServletException e) {
            throw (Exception) e.getCause();

        }
    }
</code>```

Body:
I am trying to write integration tests for REST API built using Spring MVC. Following is my controller class.

@RestController
@RequestMapping("/api")
public class ZoningToolRestController {

    @Autowired
    ImageProcessingService service;

    @RequestMapping(value = "/page/{index}", produces = "image/png", method = RequestMethod.GET)
    public byte[] getPage(@PathVariable("index") int index) throws InvalidIndexException, IOException {

        return service.getPage(index);
    }

    @ExceptionHandler
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("error", e.getMessage());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<Map<String, Object>>(map, headers, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Following is my test class

    @RunWith(SpringRunner.class)
@SpringBootTest
public class ZoningToolRestControllerTests {

    private MockMvc mvc;

    @Autowired
    private ZoningToolRestController zoningToolRestController;

    @Before
    public void setup() {
        this.mvc = MockMvcBuilders.standaloneSetup(zoningToolRestController)
                .setHandlerExceptionResolvers(getExceptionResolver())
                .build();
    }

    private HandlerExceptionResolver getExceptionResolver() {

        ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver();
        exceptionResolver.setMappedHandlerClasses(InvalidIndexException.class, ExceptionHandler.class);

        return exceptionResolver;
    }

    /**
     * Test to check if image is returned in case of valid call
     *
     * @throws Exception
     */
    @Test
    public void givenDocument_whenGetValidPage_thenSuccess() throws Exception {

        mvc.perform(get("/api/page/1").accept(MediaType.IMAGE_PNG)).andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.IMAGE_PNG));
    }

    /**
     * Test to check if server throws an error when wrong page is passed
     *
     * @throws Exception
     */
    @Test
    public void givenDocument_whenGetWrongPage_thenError() throws Exception {
        mvc.perform(get("/api/page/11").accept(MediaType.IMAGE_PNG)).andExpect(status().isInternalServerError())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
    }

}

Now when I am trying to run this unit test, the second unit test is failing saying it is encountering a NestedSerlvletException when it is expecting a InvalidIndexException

What am I doing wrong?

Update
Stack Trace

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is in.co.dhdigital.zoningtool.processors.InvalidIndexException: Invalid index passed.
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
    at in.co.dhdigital.zoningtool.test.controllers.ZoningToolRestControllerTests.givenDocument_whenGetWrongPage_thenError(ZoningToolRestControllerTests.java:73)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: in.co.dhdigital.zoningtool.processors.InvalidIndexException: Invalid index passed.
    at in.co.dhdigital.zoningtool.processors.impl.TiffImageProcessor.getPage(TiffImageProcessor.java:53)
    at in.co.dhdigital.zoningtool.services.ImageProcessingService.getPage(ImageProcessingService.java:32)
    at in.co.dhdigital.zoningtool.controllers.ZoningToolRestController.getPage(ZoningToolRestController.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    ... 41 more

Body:
Here is the test method throw an input validation (Bad input)
  exception or not.

  @Test(expected = ConstraintViolationException.class)
    public void addBadInput() throws Exception {
        try {
            mockMvc.perform(post(URL).content(object_mapper.writeValueAsString(bad_input_val)).
                    accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isBadRequest());
        } catch (NestedServletException e) {
            throw (Exception) e.getCause();

        }
    }


问:
python converting a List of Tuples into a Dict with external keys
I have a list of tuples like this

```<code>[
(1,'a'),
(2,'b'),
(3,'c'),
(4,'d'),
(5,'e')
]
</code>```

The result should be a list of dictionaries

```<code>[
{'id': 1, 'label': 'a'},
{'id': 2, 'label': 'b'},
{'id': 3, 'label': 'c'},
{'id': 4, 'label': 'd'},
{'id': 5, 'label': 'e'}
]
</code>```

I'm using python 3.6

The first value in every tuple is named as 'id' and the second value
in every tuple is named as 'label'.

I want to get the above result without using loop since the data will be huge.
Is there any built-in method to achieve my result?

答:
Using map

Ex:

```<code>data = [
(1,'a'),
(2,'b'),
(3,'c'),
(4,'d'),
(5,'e')
]

keys = ["id", 'label']
print(list(map(lambda x: dict(zip(keys, x)), data)))

#List comprehension
#print([dict(zip(keys, i)) for i in data])
</code>```

Output:

```<code>[{'id': 1, 'label': 'a'},
 {'id': 2, 'label': 'b'},
 {'id': 3, 'label': 'c'},
 {'id': 4, 'label': 'd'},
 {'id': 5, 'label': 'e'}]
</code>```

Body:
I have a list of tuples like this

[
(1,'a'),
(2,'b'),
(3,'c'),
(4,'d'),
(5,'e')
]

The result should be a list of dictionaries

[
{'id': 1, 'label': 'a'},
{'id': 2, 'label': 'b'},
{'id': 3, 'label': 'c'},
{'id': 4, 'label': 'd'},
{'id': 5, 'label': 'e'}
]

I'm using python 3.6

The first value in every tuple is named as 'id' and the second value
in every tuple is named as 'label'.

I want to get the above result without using loop since the data will be huge.
Is there any built-in method to achieve my result?

Body:
Using map

Ex:

data = [
(1,'a'),
(2,'b'),
(3,'c'),
(4,'d'),
(5,'e')
]

keys = ["id", 'label']
print(list(map(lambda x: dict(zip(keys, x)), data)))

#List comprehension
#print([dict(zip(keys, i)) for i in data])

Output:

[{'id': 1, 'label': 'a'},
 {'id': 2, 'label': 'b'},
 {'id': 3, 'label': 'c'},
 {'id': 4, 'label': 'd'},
 {'id': 5, 'label': 'e'}]


问:
How to change content mode on AVPlayer video?
My problem is that when I'm displaying video it's bigger than my screen size. Maybe the problem is not content mode but wrong frame bounds or something.

```<code>let theURL = Bundle.main.url(forResource:"videkas", withExtension: "mp4")

    avPlayer = AVPlayer(url: theURL!)
    avPlayerLayer = AVPlayerLayer(player: avPlayer)
    avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
    avPlayer.volume = 0
    avPlayer.actionAtItemEnd = .none

    avPlayerLayer.frame = (featureView13?.bounds)!
    featureView13?.backgroundColor = .clear
    featureView13?.layer.insertSublayer(avPlayerLayer, at: 0)

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(playerItemDidReachEnd(notification:)),
                                           name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                           object: avPlayer.currentItem)
</code>```

I also tried avPlayerLayer.frame = (featureView13?.layer.bounds)! but no luck.

答:
Try using,</p>

```<code>avPlayerLayer.frame = (featureView13?.bounds)!
avPlayerLayer.videoGravity = .resizeAspect
avPlayerLayer.contentsGravity = .resizeAspect
</code>```

Body:
My problem is that when I'm displaying video it's bigger than my screen size. Maybe the problem is not content mode but wrong frame bounds or something.

let theURL = Bundle.main.url(forResource:"videkas", withExtension: "mp4")

    avPlayer = AVPlayer(url: theURL!)
    avPlayerLayer = AVPlayerLayer(player: avPlayer)
    avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
    avPlayer.volume = 0
    avPlayer.actionAtItemEnd = .none

    avPlayerLayer.frame = (featureView13?.bounds)!
    featureView13?.backgroundColor = .clear
    featureView13?.layer.insertSublayer(avPlayerLayer, at: 0)

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(playerItemDidReachEnd(notification:)),
                                           name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                           object: avPlayer.currentItem)

I also tried avPlayerLayer.frame = (featureView13?.layer.bounds)! but no luck.

Body:
Try using,

avPlayerLayer.frame = (featureView13?.bounds)!
avPlayerLayer.videoGravity = .resizeAspect
avPlayerLayer.contentsGravity = .resizeAspect


问:
during pull request build how does the build definition know to build feature branch
In Azure DevOps I created a branch policy for dev branch and selected a build definition.

in the build definition "Default branch for manual and scheduled builds" is set to Master
and under trigger continuous integration is disabled.

When we do a pull request from feature to dev branch. It seems to take the right branch to build but how does the build definition know which branch to build?

答:
When you set the build policy in dev branch, the pr you initiated triggers the branch which you set the policy.

The branch you choose in "Default branch for manual and scheduled builds" is the branch that triggers when you build manually.