问:
Skipping the New Method in Controller (Go Right to the Create Method)
In Rails, I'd like to skip the "new" method in a controller entirely and go directly to the create method. (I don't need any form data to be submitted, and just want to go directly to creating the object based on data from the currently logged in user.)

In rake routes, I don't see a prefix that allows me to link directly to the controller's create method, so I think I should link to the new method and have that redirect to the create action without accepting any input.

I tried doing this with the following:

```<code> def new
    create
 end

 def create
    @request = Request.new
    @request.requestor_id = current_user.id
    @request.status = "S1"
    @request.save

    respond_with(@request, :location => "/products/findexchanges")
 end
</code>```

When browsing the DB, I can see that this is calling the create action and is adding the record to the db, but after it is done it is redirecting me to new.html.erb rather than the location defined at the end of the create method.

答: Use button_to instead of link_to. I tried using link_to and even after specifying method: :post, action: :create, it still takes me to index using GET. After using button_to and passing params in ####_path, it directly went to the create method and added data to database. Although I am not sure its correct way or safe way to do this.

Body:
In Rails, I'd like to skip the "new" method in a controller entirely and go directly to the create method. (I don't need any form data to be submitted, and just want to go directly to creating the object based on data from the currently logged in user.)

In rake routes, I don't see a prefix that allows me to link directly to the controller's create method, so I think I should link to the new method and have that redirect to the create action without accepting any input.

I tried doing this with the following:

 def new
    create
 end

 def create
    @request = Request.new
    @request.requestor_id = current_user.id
    @request.status = "S1"
    @request.save

    respond_with(@request, :location => "/products/findexchanges")
 end

When browsing the DB, I can see that this is calling the create action and is adding the record to the db, but after it is done it is redirecting me to new.html.erb rather than the location defined at the end of the create method.


来源: stackexchange

问:
Why are MySQL queries slow on one device but not on another?
I'm creating a Text-Based RPG using mostly only PHP and MySQL. I experience some slow queries on my laptop, but these same queries are massively faster on my PC, my laptop is a bit older tho. Here are the specs of both, and example of a query, following with what I use.

PC:

->Graphics: NVidia GeForce 1060 3GB

->Processor: Ryzen 3 1300x 3.5GhZ 10MB Cache

->RAM: 8GB DDR4 2400MHz

->SSD: 256GB

//Not sure if those are important

->Database server version: 10.1.26-MariaDB

->Apache: 2.4.27

->Database client version: libmysql - mysqlnd 5.0.12-dev - 20150407

Laptop:

->Graphics: Intel HD 3000

->Processor: Intel Pentium 2020M 2.4GHz 2MB Cache

->RAM: 4GB DDR3

->HDD: 512GB

Here's an query example:

```<code>UPDATE data SET posx = $posX, posy = $posY, last_action = '.time().', current_stamina = $newStamina WHERE id = $id
</code>```

Average time for query like this on my PC is: 0.004 seconds, yet this same query on my laptop takes between 0.4 seconds and 0.1 second. On average it executes somewhere in 0.2 seconds. I consider this very slow for a single simple query. I thought it could've been because of missing indexes, so I've added index for ID, still the same results.

I am not very concerned about my laptops performance, but, what I'm concerned about is if I'm experiencing such slower queries on my laptop, should I expect the same slower queries when I put game on online server? (I do not have one yet)

Problem is that other queries on my laptop are fast (e.g. reading from database or joins).

I know this is very specific kind of thing, so I'm grateful on any info.

Thank you,

Hector

答:
There can be so many factors to this. First you have less memory on your laptop, which may be important if mariadb is configured the same on pc and laptop, to use more than 4GB of memory for example. This can cause problems. Then, as mentioned, you may have SSD on your PC, but hard disk on you laptop. Then there may be a lot of resident applications running on your laptop, which slows down mysql. Try to compare the configuration of mysql on both devices, check how many processes are running on both, check the IO times on the laptop.

You most probably don't have to worry for putting you app online and have slow queries - those servers are configured well and definitely simple update shouldn't be a problem.

ContentLicense: CC BY-SA 3.0

Body:
I'm creating a Text-Based RPG using mostly only PHP and MySQL. I experience some slow queries on my laptop, but these same queries are massively faster on my PC, my laptop is a bit older tho. Here are the specs of both, and example of a query, following with what I use.

PC:

->Graphics: NVidia GeForce 1060 3GB

->Processor: Ryzen 3 1300x 3.5GhZ 10MB Cache

->RAM: 8GB DDR4 2400MHz

->SSD: 256GB

//Not sure if those are important

->Database server version: 10.1.26-MariaDB

->Apache: 2.4.27

->Database client version: libmysql - mysqlnd 5.0.12-dev - 20150407

Laptop:

->Graphics: Intel HD 3000

->Processor: Intel Pentium 2020M 2.4GHz 2MB Cache

->RAM: 4GB DDR3

->HDD: 512GB

Here's an query example:

UPDATE data SET posx = $posX, posy = $posY, last_action = '.time().', current_stamina = $newStamina WHERE id = $id

Average time for query like this on my PC is: 0.004 seconds, yet this same query on my laptop takes between 0.4 seconds and 0.1 second. On average it executes somewhere in 0.2 seconds. I consider this very slow for a single simple query. I thought it could've been because of missing indexes, so I've added index for ID, still the same results.

I am not very concerned about my laptops performance, but, what I'm concerned about is if I'm experiencing such slower queries on my laptop, should I expect the same slower queries when I put game on online server? (I do not have one yet)

Problem is that other queries on my laptop are fast (e.g. reading from database or joins).

I know this is very specific kind of thing, so I'm grateful on any info.

Thank you,

Hector


问:
How to mock http header in MockRestServiceServer?
I'm using MockRestServiceServer to mock an external webservice xml response.
That already works fine, but how can I also mock the http header inside the response, not only the response body?

```<code>    @MockBean
    private RestTemplate restTemplate;

    private MockRestServiceServer mockServer;

    @Before
    public void createServer() throws Exception {
        mockServer = MockRestServiceServer.createServer(restTemplate);
    }

    @Test
    public void test() {
        String xml = loadFromFile("productsResponse.xml");
        mockServer.expect(MockRestRequestMatchers.anything()).andRespond(MockRestResponseCreators.withSuccess(xml, MediaType.APPLICATION_XML));
    }
</code>```

答:
Just follow your withSuccess method with headers method.

```<code>mockServer
       .expect(...)
       .andRespond(withSuccess().headers(...));
</code>```

Body:
I'm using MockRestServiceServer to mock an external webservice xml response.
That already works fine, but how can I also mock the http header inside the response, not only the response body?

    @MockBean
    private RestTemplate restTemplate;

    private MockRestServiceServer mockServer;

    @Before
    public void createServer() throws Exception {
        mockServer = MockRestServiceServer.createServer(restTemplate);
    }

    @Test
    public void test() {
        String xml = loadFromFile("productsResponse.xml");
        mockServer.expect(MockRestRequestMatchers.anything()).andRespond(MockRestResponseCreators.withSuccess(xml, MediaType.APPLICATION_XML));
    }

Body:
Just follow your withSuccess method with headers method.

mockServer
       .expect(...)
       .andRespond(withSuccess().headers(...));


问:
SpringBoot: how to pass argument (request id) from controller through all program?
I use SpringBoot app. Every request has ID. And I has to use this ID when log errors in some services and more lowlevel places of the program. How can I  implement it? Thank you!</p>

答:
For adding a context id to you log you can use the MDC :

in your code :

```<code> MDC.put("first", "Dorothy");
</code>```

in your logback.xml

```<code><appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
  <layout>
    <Pattern>%X{first} %X{last} - %m%n</Pattern>
  </layout>
</appender>
</code>```

See https://logback.qos.ch/manual/mdc.html

Body:
For adding a context id to you log you can use the MDC :

in your code :

 MDC.put("first", "Dorothy");

in your logback.xml

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
  <layout>
    <Pattern>%X{first} %X{last} - %m%n</Pattern>
  </layout>
</appender>

See https://logback.qos.ch/manual/mdc.html


问:
django raw query percent sign problem
I trying to Django raw sql query in like function, but results is empty. I try mysql client tool this query and get many records. how to solution this problem?

my query:

```<code>  SELECT s.* , s.id as pk
    FROM d_status as s,
         (select post_id
            from p_useractions
           where from_user_id in
                 (select to_user_id
                    from p_fallowers
                   where from_user_id = 1)
         ) as a
   WHERE s.from_user_id = 1 OR
         s.text like '%@Mustafa Yontar2123%' OR
         s.id = a.post_id
GROUP BY s.id
ORDER BY s.last_update
   LIMIT 25
</code>```

答:
Quoting from the documentation for MySQL:

```
With LIKE you can use the following two wildcard characters in the pattern.

    Character  Description
    %          Matches any number of characters, even zero characters
    _          Matches exactly one character

To test for literal instances of a wildcard character, precede it by the
escape character. If you do not specify the ESCAPE character, \ is assumed.
```

So your pattern needs to be '\%@Mustafa Yontar2123\%'. The Python code for the query will look like this:

```<code>query = r"""SELECT s.* , s.id as pk FROM d_status as s,
                   (SELECT post_id FROM p_useractions WHERE from_user_id in
                     (SELECT to_user_id FROM p_fallowers WHERE from_user_id = 1)) as a
            WHERE s.from_user_id = 1 or
                  s.text like '\%@Mustafa Yontar2123\%' or
                  s.id = a.post_id
            GROUP BY s.id
            ORDER BY s.last_update
            LIMIT 25"""
</code>```

The documentation for PostgreSQL and SQLite mention the same thing.

ContentLicense: CC BY-SA 2.5

Title: django raw query percent sign problem

Body:
I trying to Django raw sql query in like function, but results is empty. I try mysql client tool this query and get many records. how to solution this problem?

my query:

  SELECT s.* , s.id as pk
    FROM d_status as s,
         (select post_id
            from p_useractions
           where from_user_id in
                 (select to_user_id
                    from p_fallowers
                   where from_user_id = 1)
         ) as a
   WHERE s.from_user_id = 1 OR
         s.text like '%@Mustafa Yontar2123%' OR
         s.id = a.post_id
GROUP BY s.id
ORDER BY s.last_update
   LIMIT 25

Body:
Quoting from the documentation for MySQL:

With LIKE you can use the following two wildcard characters in the pattern.

    Character  Description
    %          Matches any number of characters, even zero characters
    _          Matches exactly one character

To test for literal instances of a wildcard character, precede it by the
escape character. If you do not specify the ESCAPE character, \ is assumed.

So your pattern needs to be '\%@Mustafa Yontar2123\%'. The Python code for the query will look like this:

query = r"""SELECT s.* , s.id as pk FROM d_status as s,
                   (SELECT post_id FROM p_useractions WHERE from_user_id in
                     (SELECT to_user_id FROM p_fallowers WHERE from_user_id = 1)) as a
            WHERE s.from_user_id = 1 or
                  s.text like '\%@Mustafa Yontar2123\%' or
                  s.id = a.post_id
            GROUP BY s.id
            ORDER BY s.last_update
            LIMIT 25"""

The documentation for PostgreSQL and SQLite mention the same thing.


问:
Realtime-notifications with ajax
Hello i'm a new developer and  in my laravel project i have implemented a real time chat function with ajax but i also want to add a real time notification system with ajax so when a message is written all users are notified for that message it would be very helpful if you could help me

here's my index page :

```<code>@extends('admin.app')
@section('content')
    <div class="container">
        <div class="row" style ="padding-top:40px;">
            <h3 class="text-center">Welcome {{Auth::user()->FullName}}</h3>
            <br/><br/>
            <div class="col-md-2">
                    <p>Users online</p>
                    @foreach($users as $user)
                        @if($user->isOnline())
                            <li>{{$user->FullName}}</li>
                        @endif
                    @endforeach

            </div>

            <div class="col-md-8">
                <div class="panel panel-info">
                    <div class="panel-heading">
                        Recent Chat
                    </div>
                    <div class="panel-body">
                        <ul class="media-list" id="message">

                            @foreach($messages as $message )
                                <li class="media">
                                    <div class="media-body">
                                        <div class="media">

                                            <div class="media-body" >
                                                {{$message->message}}
                                                <br/>
                                               <bold> <small class="text-muted">{{$message->from_name}} |{{$message->created_at}}
                                                   </small></bold>
                                                <hr>
                                            </div>
                                        </div>
                                    </div>
                                </li>

                            @endforeach
                        </ul>
                        <div>
                            <div class="panel-footer">
                                <div class="input-group">
                                    <input type="text" name="message" class="form-control" placeholder="Enter Message"/>
                                    {{csrf_field()}}
                                    <input type="hidden" name="from_name" value="{{Auth::user()->FullName}}">
                                    <span class="input-group-btn">
                                    <button type="submit" id="send" class="btn btn-info">Send</button>
                                </span>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript" src="/assets/admin/plugins/jquery/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            setTimeout(realTime, 2000);
        });
        function realTime() {
            $.ajax({
                type:'post',
                url:'/chat/get',
                data:{
                    '_token':$('input[name=_token]').val(),
                },
                success: function (data) {
                    $('#message').replaceWith(' <ul class="media-list" id="message"></ul>');
                    for (var i=0; i < data.length; i++){
                        $('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data[i].message+'<br/><small class="text-muted">'+data[i].from_name+'|'+ data[i].created_at+'</small><hr/></div></div></div></li>')
                    }
                },
            });
            setTimeout(realTime, 2000);
        }
        $(document).on('click','#send', function (){
            $.ajax({
                type:'post',
                url:'/chat/send',
                data:{
                    '_token':$('input[name=_token]').val(),
                    'from_name':$('input[name=from_name]').val(),
                    'message':$('input[name=message]').val(),
                },
                success: function (data) {
                  $('#message').append('  <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data.message+'<br/><small class="text-muted">'+data.from_name+'|'+ data.created_at+'</small><hr/></div></div></div></li>');
                }
            })

            $('input[name=message]').val('');
        });

    </script>

@stop
</code>```

here's my routes :

```<code>Route::get('/chat', 'Chat\ChatController@index')->name('chat.index');
Route::post('/chat/send', 'Chat\ChatController@sendMessage' )->name('admin.chat.sendMessage');
Route::post('/chat/get', 'Chat\ChatController@getMessage' );
</code>```

here's my controllers:

```<code> public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $users=user::all();
        $messages=message::all();
        return view('admin.chat.index',['messages'=> $messages],compact('users'));
    }

    public function sendMessage(Request $request){

        $send = new Message();
        $send ->from_name = $request->from_name;
        $send ->message = $request->message;
        $send->save();
        return response()->json($send);

    }

    public function  getMessage(){
        $message = Message::all();
        return response()->json($message);

    }
</code>```

Sorry in advanced for the bad english but i am a foreigner

答:
well you have to read this tutorial and implement like this....

https://laracasts.com/discuss/channels/general-discussion/step-by-step-guide-to-installing-socketio-and-broadcasting-events-with-laravel-51

Title: Realtime-notifications with ajax

Body:
Hello i'm a new developer and  in my laravel project i have implemented a real time chat function with ajax but i also want to add a real time notification system with ajax so when a message is written all users are notified for that message it would be very helpful if you could help me

here's my index page :

@extends('admin.app')
@section('content')

Welcome {{Auth::user()->FullName}}

Users online

                    @foreach($users as $user)
                        @if($user->isOnline())

{{$user->FullName}}

                        @endif
                    @endforeach

                        Recent Chat

                            @foreach($messages as $message )

                                                {{$message->message}}

                                               <bold> {{$message->from_name}} |{{$message->created_at}}
                                                   </bold>

                            @endforeach

                                    <input type="text" name="message" class="form-control" placeholder="Enter Message"/>
                                    {{csrf_field()}}
                                    <input type="hidden" name="from_name" value="{{Auth::user()->FullName}}">

                                    <button type="submit" id="send" class="btn btn-info">Send</button>

@stop

here's my routes :

Route::get('/chat', 'Chat\ChatController@index')->name('chat.index');
Route::post('/chat/send', 'Chat\ChatController@sendMessage' )->name('admin.chat.sendMessage');
Route::post('/chat/get', 'Chat\ChatController@getMessage' );

here's my controllers:

 public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $users=user::all();
        $messages=message::all();
        return view('admin.chat.index',['messages'=> $messages],compact('users'));
    }

    public function sendMessage(Request $request){

        $send = new Message();
        $send ->from_name = $request->from_name;
        $send ->message = $request->message;
        $send->save();
        return response()->json($send);

    }

    public function  getMessage(){
        $message = Message::all();
        return response()->json($message);

    }

Sorry in advanced for the bad english but i am a foreigner


问:
the link between fcntl and sockets
I have read about socket, connecting, fcntl, buffers, etc.
But I don't know what the link between the sockets and the fcntl function is.
I only know that sockets are used to make a connection, and fcntl is used to control open files. I don't know how fcntl is used to control files and how it is different from the fopen, fwrite, fclose functions.
So could anyone help with this, because I am stuck.</p>

答:
fcntl() is used to control a file descriptor (not specifically a file).

open() may be used to obtain a file descriptor associated with a file. Also for example socket() and pipe() calls return a file descriptor. Those file descriptors may be later used with fcntl().

So the connection is: the file descriptor obtained from a socket() call may be used as the argument to fcntl() function.

File descriptors and associated functions are part of the POSIX standard.

You mentioned fopen().

fopen() returns a FILE pointer. In simple words, FILE pointer is something build above file descriptor (on most *unix systems, but this is not necessary and may not be true). For example, FILE pointer may have some buffering options: written bytes are stored in a buffer and then flushed on a newline (this behavior may be modified using setvbuf()) or manually by a fflush() call.

You may use fileno() to get the file descriptor associated with the FILE* pointer. And then use this file descriptor with the fcntl() call. ( FILE* pointer is not necessary associated with a file either, for example it may be associated with a memory buffer, see fmemopen() function. )
fopen(), fwrite(), fclose() are part of the C standard.

Title: the link between fcntl and sockets


问:
how to choose which dependency resources will be used in spring boot application
I have fat-jar spring boot application in jar A.jar
in this fat-jar I have folder lib with two jar files (dependencies)
let's say B.jar and D.jar in each of these jar file (B and D) we have application.properties (resource) which is loaded automatically during initialization of application.

Unfortunately application.propertiesfrom D.jar is loaded before application.properties from B.jar

How to load application.properties from B.jar instead of application.properties from D.jar ?

答:
Depends on location on classpath always first application.properties will be loaded. Order of jar files on classpath in my case (maven pom.xml) depends on order of registering dependencies in pom.xml

If I use

```<code><dependencies>
    <dependency>
        //B.jar
    </dependency>
    <dependency>
        //D.jar
    </dependency>
</dependencies>
</code>```

then application.properties from B.jar will be loaded.

Body:
Depends on location on classpath always first application.properties will be loaded. Order of jar files on classpath in my case (maven pom.xml) depends on order of registering dependencies in pom.xml

If I use

<dependencies>
    <dependency>
        //B.jar
    </dependency>
    <dependency>
        //D.jar
    </dependency>
</dependencies>

then application.properties from B.jar will be loaded.


问:
Optimal project organization and querysets
I have 2 models Company and Product with FK on Product:

```<code>class Product(Meta):
    company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE)
</code>```

In case of a View that will gather company products what is the optimal approach(use infor form both models):

1) add the View in companies app and as queryset use:

Company.objects.prefetch_related('products').get(pk=company_pk)

2) add the View in products app and as queryset use:

Product.objects.select_related('company').filter(company=company_pk)

What about ordering can be chained with prefetch or select ?

答:
The Django docs illustrate the difference quite well:

prefetch_related(*lookups)

Returns a QuerySet that will
  automatically retrieve, in a single batch, related objects for each of
  the specified lookups.

This has a similar purpose to select_related, in that both are
  designed to stop the deluge of database queries that is caused by
  accessing related objects, but the strategy is quite different.

select_related works by creating an SQL join and including the fields
  of the related object in the SELECT statement. For this reason,
  select_related gets the related objects in the same database query.
  However, to avoid the much larger result set that would result from
  joining across a ‘many’ relationship, select_related is limited to
  single-valued relationships - foreign key and one-to-one.

select_related(*fields)

Returns a QuerySet that will “follow” foreign-key relationships,
  selecting additional related-object data when it executes its query.
  This is a performance booster which results in a single more complex
  query but means later use of foreign-key relationships won’t require
  database queries.

Body:
I have 2 models Company and Product with FK on Product:

class Product(Meta):
    company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE)

In case of a View that will gather company products what is the optimal approach(use infor form both models):

1) add the View in companies app and as queryset use:

Company.objects.prefetch_related('products').get(pk=company_pk)

2) add the View in products app and as queryset use:

Product.objects.select_related('company').filter(company=company_pk)

What about ordering can be chained with prefetch or select ?


问:
Tensorflow: Variable rnn/basic_lstm_cell/kernel already exists, disallowed
Here is a part of my tensorflow RNN network code written in jupyter. The whole code runs perfect for the first time, however, running it furthermore produces an error. The code:

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)

def recurrent_nn_model(x):
   x = tf.transpose(x, [1,0,2])
   x = tf.reshape(x, [-1, chunk_size])
   x = tf.split(x, n_chunks, 0)

   lstm_layer = {'hidden_state': tf.zeros([n_batches, lstm_size]),
              'current_state': tf.zeros([n_batches, lstm_size])}
   layer = {'weights': tf.Variable(tf.random_normal([lstm_size, n_classes])),
         'biases': tf.Variable(tf.random_normal([n_classes]))}
   lstm = rnn_cell.BasicLSTMCell(lstm_size)
   rnn_outputs, rnn_states = rnn.static_rnn(lstm, x, dtype=tf.float32)
   output = tf.add(tf.matmul(rnn_outputs[-1], layer['weights']),
            layer['biases'])

   return output
```

The error is:

Variable rnn/basic_lstm_cell/kernel already exists, disallowed. Did
  you mean to set reuse=True in VarScope? Originally defined at:

答:
If recurrent_nn_model is the whole network, just add this line to reset previously defined graph:

tf.reset_default_graph()
```

<p>If you're intentionally calling <code>recurrent_nn_model</code> several times and combine these RNNs into one graph, you should use different variable scopes for each one:</p>

<pre class="lang-py prettyprint-override"><code> with tf.variable_scope('lstm1'):
   recurrent_nn_model(x1)
 with tf.variable_scope('lstm2'):
   recurrent_nn_model(x2)
</code>```

Body:
Here is a part of my tensorflow RNN network code written in jupyter. The whole code runs perfect for the first time, however, running it furthermore produces an error. The code:

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)

def recurrent_nn_model(x):
   x = tf.transpose(x, [1,0,2])
   x = tf.reshape(x, [-1, chunk_size])
   x = tf.split(x, n_chunks, 0)

   lstm_layer = {'hidden_state': tf.zeros([n_batches, lstm_size]),
              'current_state': tf.zeros([n_batches, lstm_size])}
   layer = {'weights': tf.Variable(tf.random_normal([lstm_size, n_classes])),
         'biases': tf.Variable(tf.random_normal([n_classes]))}
   lstm = rnn_cell.BasicLSTMCell(lstm_size)
   rnn_outputs, rnn_states = rnn.static_rnn(lstm, x, dtype=tf.float32)
   output = tf.add(tf.matmul(rnn_outputs[-1], layer['weights']),
            layer['biases'])

   return output

The error is:

Variable rnn/basic_lstm_cell/kernel already exists, disallowed. Did
  you mean to set reuse=True in VarScope? Originally defined at:

Body:
If recurrent_nn_model is the whole network, just add this line to reset previously defined graph:

tf.reset_default_graph()

If you're intentionally calling recurrent_nn_model several times and combine these RNNs into one graph, you should use different variable scopes for each one:

 with tf.variable_scope('lstm1'):
   recurrent_nn_model(x1)
 with tf.variable_scope('lstm2'):
   recurrent_nn_model(x2)


问:
URISyntaxException: Invalid % sequence
I am new to IPv6, When I am trying create a URI using IPv6, I encountered this exception. The full exception is

```<code>java.net.URISyntaxException: Invalid % sequence: %wl in authority at index 32: tcp://[fe80::ceb8:a8ff:fe23:5b84%wlan0]:1883
at libcore.net.UriCodec.validate(UriCodec.java:58)
at java.net.URI.parseURI(URI.java:394)
at java.net.URI.<init>(URI.java:204)
</code>```

I code I use looks like this

```<code>String ipv6 = "tcp://[fe80::ceb8:a8ff:fe23:5b84%wlan0]:1883";
URI uri = new URI(ipv6);

SocketAddress sockaddr = new InetSocketAddress(InetAddress.getByName(uri.getHost()), 1883);
Socket socket = new Socket();
socket.connect(sockaddr);
</code>```

The above code works without any exception in Samsung Galaxy S5 running Android 7.1.1, but not Asus Zenfone GoTV and Android emulator running Android 5 and 6.

Does anybody know why?

Thanks.

答:
The % character is a special character in URLs and needs to be escaped. Actually, % is the escape character. You can escape it as %25:

```<code>String ipv6 = "tcp://[fe80::ceb8:a8ff:fe23:5b84%25wlan0]:1883";
</code>```

Title: URISyntaxException: Invalid % sequence

Body:
I am new to IPv6, When I am trying create a URI using IPv6, I encountered this exception. The full exception is

java.net.URISyntaxException: Invalid % sequence: %wl in authority at index 32: tcp://[fe80::ceb8:a8ff:fe23:5b84%wlan0]:1883
at libcore.net.UriCodec.validate(UriCodec.java:58)
at java.net.URI.parseURI(URI.java:394)
at java.net.URI.<init>(URI.java:204)

I code I use looks like this

String ipv6 = "tcp://[fe80::ceb8:a8ff:fe23:5b84%wlan0]:1883";
URI uri = new URI(ipv6);

SocketAddress sockaddr = new InetSocketAddress(InetAddress.getByName(uri.getHost()), 1883);
Socket socket = new Socket();
socket.connect(sockaddr);

The above code works without any exception in Samsung Galaxy S5 running Android 7.1.1, but not Asus Zenfone GoTV and Android emulator running Android 5 and 6.

Does anybody know why?

Thanks.

Body:
The % character is a special character in URLs and needs to be escaped. Actually, % is the escape character. You can escape it as %25:

String ipv6 = "tcp://[fe80::ceb8:a8ff:fe23:5b84%25wlan0]:1883";


问:
Visual studio can't find a controller even though I have added a reference to it and made sure it is public
I have a Unit Test solution that references the main solution for the controller.

Reference: using Solution.Controllers;

Unit Test class:

```<code>namespace solution.UnitTests.SolutionTests.ControllersTests
{
    [TestClass]
    public class BrandCategoryControllerTests
    {
        private BrandCategoryController _brandCategoryController;
        [TestInitialize]
        public void Init()
        {
            _brandCategoryController = new BrandCategoryController();
        }
    }
}
</code>```

The controller it is referencing is in Solution/Controllers folder.

The file begins with:

```<code>namespace Solution.Controllers
{
    public class BrandCategoryController : Controller
</code>```

So I don't see why it can't find it. I've tried the intellisense and it doesn't recognize it. I've tried Cleaning and rebuilding the solution and closing and reopening visual studio. The annoying part is I have another controller and another controller test class both of which share the same folder structures and they work fine.

The error I am getting is "The type or namespace "BrandCategoryController" could not be found (are you missing a using directive or an assembly reference?)" I have added a using Directive and have tried using the full reference on the private variable.

答: Rebuild the Solution.Controllers project separately and fix build errors.

Body:
I have a Unit Test solution that references the main solution for the controller.

Reference: using Solution.Controllers;

Unit Test class:

namespace solution.UnitTests.SolutionTests.ControllersTests
{
    [TestClass]
    public class BrandCategoryControllerTests
    {
        private BrandCategoryController _brandCategoryController;
        [TestInitialize]
        public void Init()
        {
            _brandCategoryController = new BrandCategoryController();
        }
    }
}

The controller it is referencing is in Solution/Controllers folder.

The file begins with:

namespace Solution.Controllers
{
    public class BrandCategoryController : Controller

So I don't see why it can't find it. I've tried the intellisense and it doesn't recognize it. I've tried Cleaning and rebuilding the solution and closing and reopening visual studio. The annoying part is I have another controller and another controller test class both of which share the same folder structures and they work fine.

The error I am getting is "The type or namespace "BrandCategoryController" could not be found (are you missing a using directive or an assembly reference?)" I have added a using Directive and have tried using the full reference on the private variable.


问:
Querying specific object from a jpa datamodel
I have a question about querying with an orm mapper like hibernate. Suppose you have a database model like this

```<code>class A {
    int i;
    B b;
}

class B {
    int j;
}
</code>```

If I want to save an object the hibernate engine can add all class instances at once by cascading queries. This will also work if I fetch an object from the database by value from class A.

But what if i want to have all entries of Class A with holds the objects of B with value j = 10?

In SQL i would have something like this:

```<code>SELECT * FROM A a, B b WHERE a.ref = b.ref AND b.j = 10;
</code>```

But with an ORM the ref is modeled with the object references. How am i supposed to create a query like this? First of all: Do I have to write a query? And secondly: How will hibernate resolve these references a.ref = b.ref

答:
Define one EntityManager:

```<code>  EntityManager em;
</code>```

Then:

```<code>  CriteriaBuilder builder = em.getCriteriaBuilder();
  CriteriaQuery<A> query = builder.createQuery(A.class);
  Root<A> from = query.from(A.class);
  from.fetch("b");
  Predicate predicate = builder.and(predicate, builder.equal(from.get("b").get("j"), 10);
  TypedQuery<A> typedQuery = em.createQuery(query.select(from).where(predicate));
  List<A> results = typedQuery.getResultList();
</code>```

Body:
I have a question about querying with an orm mapper like hibernate. Suppose you have a database model like this

class A {
    int i;
    B b;
}

class B {
    int j;
}

If I want to save an object the hibernate engine can add all class instances at once by cascading queries. This will also work if I fetch an object from the database by value from class A.

But what if i want to have all entries of Class A with holds the objects of B with value j = 10?

In SQL i would have something like this:

SELECT * FROM A a, B b WHERE a.ref = b.ref AND b.j = 10;

But with an ORM the ref is modeled with the object references. How am i supposed to create a query like this? First of all: Do I have to write a query? And secondly: How will hibernate resolve these references a.ref = b.ref

Body:
Define one EntityManager:

  EntityManager em;

Then:

  CriteriaBuilder builder = em.getCriteriaBuilder();
  CriteriaQuery<A> query = builder.createQuery(A.class);
  Root<A> from = query.from(A.class);
  from.fetch("b");
  Predicate predicate = builder.and(predicate, builder.equal(from.get("b").get("j"), 10);
  TypedQuery<A> typedQuery = em.createQuery(query.select(from).where(predicate));
  List<A> results = typedQuery.getResultList();


问:
How to retrieve data of nested class instance from parent class instance in ASP.NET Core?
I am trying to modeling a class at school, and I end up with something like this:

```<code>public class Class
{
    public int ID { get; set; }
    public int Grade { get; set; }
    public Teacher ClassTeacher { get; set; }
}
</code>```

This is the Teacher class:

```<code>public class Teacher
{
    public int ID { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [DataType(DataType.Date)]
    public DateTime Birthday { get; set; }
}
</code>```

When I use scaffolding, migrate and update the database, this is the structure Entity Framework built for me:

```<code>dbo.Class:
ID: int
ClassTeacherID: int
Grade: int

dbo.Teacher:
ID: int
Birthday: datetime2(7)
FirstName: nvarchar(MAX)
LastName: nvarchar(MAX)
</code>```

I want to display the Teacher's FirstName in Views\Classes\Details.cshtml, but the Model.ClassTeacher is null, even after I created a Teacher instance in the database and set ClassTeacherID to the newly created Teacher's ID.

Looking for your helps.

EDIT

ClassesController.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;

namespace WebApplication1.Models
{
    public class ClassesController : Controller
    {
        private readonly WebApplication1Context _context;

        public ClassesController(WebApplication1Context context)
        {
            _context = context;
        }

        // GET: Classes
        public async Task<IActionResult> Index()
        {
            return View(await _context.Class.ToListAsync());
        }

        // GET: Classes/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var @class = await _context.Class
                .SingleOrDefaultAsync(m => m.ID == id);
            if (@class == null)
            {
                return NotFound();
            }

            return View(@class);
        }

        // GET: Classes/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Classes/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ID,Grade")] Class @class)
        {
            if (ModelState.IsValid)
            {
                _context.Add(@class);
                await _context.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(@class);
        }

        // GET: Classes/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var @class = await _context.Class.SingleOrDefaultAsync(m => m.ID == id);
            if (@class == null)
            {
                return NotFound();
            }
            return View(@class);
        }

        // POST: Classes/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,Grade")] Class @class)
        {
            if (id != @class.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(@class);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ClassExists(@class.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction("Index");
            }
            return View(@class);
        }

        // GET: Classes/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var @class = await _context.Class
                .SingleOrDefaultAsync(m => m.ID == id);
            if (@class == null)
            {
                return NotFound();
            }

            return View(@class);
        }

        // POST: Classes/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var @class = await _context.Class.SingleOrDefaultAsync(m => m.ID == id);
            _context.Class.Remove(@class);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        private bool ClassExists(int id)
        {
            return _context.Class.Any(e => e.ID == id);
        }
    }
}
</code>```

TeachersController.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;

namespace WebApplication1.Models
{
    public class TeachersController : Controller
    {
        private readonly WebApplication1Context _context;

        public TeachersController(WebApplication1Context context)
        {
            _context = context;
        }

        // GET: Teachers
        public async Task<IActionResult> Index()
        {
            return View(await _context.Teacher.ToListAsync());
        }

        // GET: Teachers/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var teacher = await _context.Teacher
                .SingleOrDefaultAsync(m => m.ID == id);
            if (teacher == null)
            {
                return NotFound();
            }

            return View(teacher);
        }

        // GET: Teachers/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Teachers/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ID,FirstName,LastName,Birthday")] Teacher teacher)
        {
            if (ModelState.IsValid)
            {
                _context.Add(teacher);
                await _context.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(teacher);
        }

        // GET: Teachers/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var teacher = await _context.Teacher.SingleOrDefaultAsync(m => m.ID == id);
            if (teacher == null)
            {
                return NotFound();
            }
            return View(teacher);
        }

        // POST: Teachers/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,FirstName,LastName,Birthday")] Teacher teacher)
        {
            if (id != teacher.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(teacher);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TeacherExists(teacher.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction("Index");
            }
            return View(teacher);
        }

        // GET: Teachers/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var teacher = await _context.Teacher
                .SingleOrDefaultAsync(m => m.ID == id);
            if (teacher == null)
            {
                return NotFound();
            }

            return View(teacher);
        }

        // POST: Teachers/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var teacher = await _context.Teacher.SingleOrDefaultAsync(m => m.ID == id);
            _context.Teacher.Remove(teacher);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        private bool TeacherExists(int id)
        {
            return _context.Teacher.Any(e => e.ID == id);
        }
    }
}
</code>```

答:
I know it's been a while since the question has been written, but you should try to Include the object reference you want.

```<code>var @class = await _context.Class.Include("Teacher")
            .SingleOrDefaultAsync(m => m.ID == id);
</code>```

Include will get the dependent object and put it back in your Class model.
You can chain the Include directives if you have different referenced objects.

Note : You will have to add :

```<code>using Microsoft.EntityFrameworkCore;
</code>```

on top of your code to allow Include to work.

Body:
I am trying to modeling a class at school, and I end up with something like this:

public class Class
{
    public int ID { get; set; }
    public int Grade { get; set; }
    public Teacher ClassTeacher { get; set; }
}

This is the Teacher class:

public class Teacher
{
    public int ID { get; set; }

    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [DataType(DataType.Date)]
    public DateTime Birthday { get; set; }
}

When I use scaffolding, migrate and update the database, this is the structure Entity Framework built for me:

dbo.Class:
ID: int
ClassTeacherID: int
Grade: int

dbo.Teacher:
ID: int
Birthday: datetime2(7)
FirstName: nvarchar(MAX)
LastName: nvarchar(MAX)

I want to display the Teacher's FirstName in Views\Classes\Details.cshtml, but the Model.ClassTeacher is null, even after I created a Teacher instance in the database and set ClassTeacherID to the newly created Teacher's ID.

Looking for your helps.

EDIT

ClassesController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;

namespace WebApplication1.Models
{
    public class ClassesController : Controller
    {
        private readonly WebApplication1Context _context;

        public ClassesController(WebApplication1Context context)
        {
            _context = context;
        }

        // GET: Classes
        public async Task<IActionResult> Index()
        {
            return View(await _context.Class.ToListAsync());
        }

        // GET: Classes/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var @class = await _context.Class
                .SingleOrDefaultAsync(m => m.ID == id);
            if (@class == null)
            {
                return NotFound();
            }

            return View(@class);
        }

        // GET: Classes/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Classes/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ID,Grade")] Class @class)
        {
            if (ModelState.IsValid)
            {
                _context.Add(@class);
                await _context.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(@class);
        }

        // GET: Classes/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var @class = await _context.Class.SingleOrDefaultAsync(m => m.ID == id);
            if (@class == null)
            {
                return NotFound();
            }
            return View(@class);
        }

        // POST: Classes/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,Grade")] Class @class)
        {
            if (id != @class.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(@class);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ClassExists(@class.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction("Index");
            }
            return View(@class);
        }

        // GET: Classes/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var @class = await _context.Class
                .SingleOrDefaultAsync(m => m.ID == id);
            if (@class == null)
            {
                return NotFound();
            }

            return View(@class);
        }

        // POST: Classes/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var @class = await _context.Class.SingleOrDefaultAsync(m => m.ID == id);
            _context.Class.Remove(@class);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        private bool ClassExists(int id)
        {
            return _context.Class.Any(e => e.ID == id);
        }
    }
}

TeachersController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;

namespace WebApplication1.Models
{
    public class TeachersController : Controller
    {
        private readonly WebApplication1Context _context;

        public TeachersController(WebApplication1Context context)
        {
            _context = context;
        }

        // GET: Teachers
        public async Task<IActionResult> Index()
        {
            return View(await _context.Teacher.ToListAsync());
        }

        // GET: Teachers/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var teacher = await _context.Teacher
                .SingleOrDefaultAsync(m => m.ID == id);
            if (teacher == null)
            {
                return NotFound();
            }

            return View(teacher);
        }

        // GET: Teachers/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Teachers/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ID,FirstName,LastName,Birthday")] Teacher teacher)
        {
            if (ModelState.IsValid)
            {
                _context.Add(teacher);
                await _context.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(teacher);
        }

        // GET: Teachers/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var teacher = await _context.Teacher.SingleOrDefaultAsync(m => m.ID == id);
            if (teacher == null)
            {
                return NotFound();
            }
            return View(teacher);
        }

        // POST: Teachers/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,FirstName,LastName,Birthday")] Teacher teacher)
        {
            if (id != teacher.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(teacher);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TeacherExists(teacher.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction("Index");
            }
            return View(teacher);
        }

        // GET: Teachers/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var teacher = await _context.Teacher
                .SingleOrDefaultAsync(m => m.ID == id);
            if (teacher == null)
            {
                return NotFound();
            }

            return View(teacher);
        }

        // POST: Teachers/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var teacher = await _context.Teacher.SingleOrDefaultAsync(m => m.ID == id);
            _context.Teacher.Remove(teacher);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        private bool TeacherExists(int id)
        {
            return _context.Teacher.Any(e => e.ID == id);
        }
    }
}

Body:
I know it's been a while since the question has been written, but you should try to Include the object reference you want.

var @class = await _context.Class.Include("Teacher")
            .SingleOrDefaultAsync(m => m.ID == id);

Include will get the dependent object and put it back in your Class model.
You can chain the Include directives if you have different referenced objects.

Note : You will have to add :

using Microsoft.EntityFrameworkCore;

on top of your code to allow Include to work.


问:
How can I find dependancies in my data in R? (A + B + C -> D)
I want to reduce my data by sorting out dependent variables. E.g. A + B + C -> D so I can leave out D without loosing any information.

```<code>d <- data.frame(A = c( 1, 2, 3, 4, 5),
                B = c( 2, 4, 6, 4, 2),
                C = c( 3, 4, 2, 1, 0),
                D = c( 6, 10, 11, 9, 9))
</code>```

The last value of D is wrong, that is because the data can be inaccurate.

How can I identify these dependencies with R and how can I influence the accuracy of the correlation? (e.g., use a cutoff of 80 or 90 percent)

Example findCorrelation only considers pair-wise correlations. Is there a function for multiple correlations?

答:
You want to find dependencies in your data, you contrast findCorrelation with what you want asking 'is there a function for multiple correlations'.  To answer that we need to clarify the technique that is appropriate for you...

Do you want partial correlation:

Partial correlation is the correlation of two variables while controlling for a third or more other variables

or semi-partial correlation?

Semi-partial correlation is the correlation of two variables with variation from a third or more other variables removed only from the second variable.

Definitions from {ppcor}. Decent YouTube video although the speaker might have some of the relationship to regression details slightly confused/confusing.

To Fer Arce's suggestion... it is about right.  Regression is quite related to these methods, however when predictors are correlated (called multicollinearity) it can cause issues (see the answer by gung).  You could force your predictors to be orthogonal (uncorrelated) via PCA, but then you'd make interpreting the coefficients quite hard.

Implementation:

```<code>library(ppcor)
d <- data.frame(A = c( 1, 2, 3, 4, 5),
                B = c( 2, 4, 6, 4, 2),
                C = c( 3, 4, 2, 1, 0),
                D = c( 6, 10, 11, 9, 9))
# partial correlations
pcor(d, method = "pearson")
# semi-partial correlations
spcor(d, method = "pearson")
</code>```

Body:
I want to reduce my data by sorting out dependent variables. E.g. A + B + C -> D so I can leave out D without loosing any information.

d <- data.frame(A = c( 1, 2, 3, 4, 5),
                B = c( 2, 4, 6, 4, 2),
                C = c( 3, 4, 2, 1, 0),
                D = c( 6, 10, 11, 9, 9))

The last value of D is wrong, that is because the data can be inaccurate.

How can I identify these dependencies with R and how can I influence the accuracy of the correlation? (e.g., use a cutoff of 80 or 90 percent)

Example findCorrelation only considers pair-wise correlations. Is there a function for multiple correlations?

Body:
You want to find dependencies in your data, you contrast findCorrelation with what you want asking 'is there a function for multiple correlations'.  To answer that we need to clarify the technique that is appropriate for you...

Do you want partial correlation:

Partial correlation is the correlation of two variables while controlling for a third or more other variables

or semi-partial correlation?

Semi-partial correlation is the correlation of two variables with variation from a third or more other variables removed only from the second variable.

Definitions from {ppcor}. Decent YouTube video although the speaker might have some of the relationship to regression details slightly confused/confusing.

To Fer Arce's suggestion... it is about right.  Regression is quite related to these methods, however when predictors are correlated (called multicollinearity) it can cause issues (see the answer by gung).  You could force your predictors to be orthogonal (uncorrelated) via PCA, but then you'd make interpreting the coefficients quite hard.

Implementation:

library(ppcor)
d <- data.frame(A = c( 1, 2, 3, 4, 5),
                B = c( 2, 4, 6, 4, 2),
                C = c( 3, 4, 2, 1, 0),
                D = c( 6, 10, 11, 9, 9))
# partial correlations
pcor(d, method = "pearson")
# semi-partial correlations
spcor(d, method = "pearson")


问:
Free Monte carlo simulator for financial quotes?
I am experimenting with an application I am writing in prolog , and I need to use monte carlo simulator that would output prices for different randomly generated scenarios. Does anyone know where to look for something that would do this for free ? (I am not look for a library to use such as QuantLib)

Thanx

答:
Without knowing exactly what you are trying to do it is difficult to recommend something specific. However http://cran.r-project.org/web/packages/ has many monte carlo packages for R.

Personally I use http://hackage.haskell.org/package/monte-carlo/ which is a toolkit for haskell. I have not found the off the shelf simulators to be very useful.


问:
What is the difference between Unit.type and Unit
I have the method below:

```<code>override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] = {
  val f = Future.sequence(notifications.map(insert)).map(_ => Unit)
  f.onFailure { case ex => sys.error(s"Got exception whilst saving PushNotification: $ex") }
  f
}
</code>```

It gives the following compiler error:

```<code>  type mismatch;
  found   : scala.concurrent.Future[Unit.type]
  required: scala.concurrent.Future[Unit]
     f
     ^
</code>```

I thought Unit was a type with a single element, thus there shouldn't be any confusion when it comes to Unit. I tried googling this but I couldn't find any more information about what "Unit.type" is.

If I simplify the method like this, then it works fine:

```<code>override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] =
  Future.sequence(notifications.map(insert)).map(_ => Unit)
</code>```

What is going on here?

答:
Unit's sole instance is ().  Unit used as a value is the companion object for Unit (which mainly manages boxing and unboxing)

```<code>val f = Future.sequence(notifications.map(insert)).map(_ => ())
</code>```

Body:
I have the method below:

override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] = {
  val f = Future.sequence(notifications.map(insert)).map(_ => Unit)
  f.onFailure { case ex => sys.error(s"Got exception whilst saving PushNotification: $ex") }
  f
}

It gives the following compiler error:

  type mismatch;
  found   : scala.concurrent.Future[Unit.type]
  required: scala.concurrent.Future[Unit]
     f
     ^

I thought Unit was a type with a single element, thus there shouldn't be any confusion when it comes to Unit. I tried googling this but I couldn't find any more information about what "Unit.type" is.

If I simplify the method like this, then it works fine:

override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] =
  Future.sequence(notifications.map(insert)).map(_ => Unit)

What is going on here?

Body:
Unit's sole instance is ().  Unit used as a value is the companion object for Unit (which mainly manages boxing and unboxing)

val f = Future.sequence(notifications.map(insert)).map(_ => ())


问:
Formatting multiple lines of PYsnmp 4.4 print output to rows and columns Python 2.7
I'm new to python and looking for some assistance on formatting print output to rows and columns. This data will eventually be sent to csv file.

The script will grab data from multiple hosts. The number of lines is variable as well as the length of the interface name and description.

Currently the output looks like this:

```<code>hostname IF-MIB::ifDescr.1 = GigabitEthernet0/0/0<br/>
hostname IF-MIB::ifAlias.1 = --> InterfaceDesc<br/>
hostname IF-MIB::ifOperStatus.1 = 'up'<br/>
hostname IF-MIB::ifDescr.2 = GigabitEthernet0/0/1<br/>
hostname IF-MIB::ifAlias.2 = --> InterfaceDesc<br/>
hostname IF-MIB::ifOperStatus.2 = 'up'<br/>
hostname IF-MIB::ifDescr.3 = GigabitEthernet0/0/2<br/>
hostname IF-MIB::ifAlias.3 = --> InterfaceDesc<br/>
hostname IF-MIB::ifOperStatus.3 = 'up'<br/>
</code>```

I'm trying to format it to the following rows and columns with headers of each row(hostname, interface, interface desc, and status).

```<code>hostname        interface              interface desc       status
hostname        GigabitEthernet0/0/0   InterfaceDesc        up
hostname        GigabitEthernet0/0/1   InterfaceDesc        up
hostname        GigabitEthernet0/0/2   InterfaceDesc        up
</code>```

The print code I currently have is here. I want to keep the print statements for errors.

```<code>for errorIndication, errorStatus, errorIndex, varBinds in snmp_iter:
            # Check for errors and print out results
            if errorIndication:
                print(errorIndication)
            elif errorStatus:
                print('%s at %s' % (errorStatus.prettyPrint(),
                                errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
            else:
                for varBind in varBinds:
                    print(hostip),
                    print(' = '.join([x.prettyPrint() for x in varBind]))
</code>```

Full script:

```<code>from pysnmp.hlapi import *

routers = ["router1"]

#adds routers to bulkCmd
def snmpquery (hostip):
    snmp_iter = bulkCmd(SnmpEngine(),
                        CommunityData('Community'),
                        UdpTransportTarget((hostip, 161)),
                        ContextData(),
                        0, 50,  # fetch up to 50 OIDs
                        ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')),
                        ObjectType(ObjectIdentity('IF-MIB', 'ifAlias')),
                        ObjectType(ObjectIdentity('IF-MIB', 'ifOperStatus')),
                        lexicographicMode=False) # End bulk request once outside of OID child objects
    for errorIndication, errorStatus, errorIndex, varBinds in snmp_iter:
        # Check for errors and print out results
        if errorIndication:
            print(errorIndication)
        elif errorStatus:
            print('%s at %s' % (errorStatus.prettyPrint(),
                            errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
        else:
            for rowId, varBind in enumerate(varBindTable):
                oid, value = varBind
                print('%20.20s' % value)
                if not rowId and rowId % 3 == 0:
                    print('\n')

# calls snmpquery for all routers in list
for router in routers:
    snmpquery(router)
</code>```

Any help you can provide is much appreciated.
Thanks!

答:
Assuming the snmp_iter is initialized with three SNMP table columns:

```<code>snmp_iter = bulkCmd(SnmpEngine(),
                    UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
                    Udp6TransportTarget(('demo.snmplabs.com', 161)),
                    ContextData(),
                    0, 25,
                    ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')),
                    ObjectType(ObjectIdentity('IF-MIB', 'ifAlias')),
                    ObjectType(ObjectIdentity('IF-MIB', 'ifOperStatus')))
</code>```

you can be sure that (for the GETNEXT and GETBULK commands) pysnmp always returns rectangular table in a row by row fashion.

Knowing the number of the columns you have requested (3) you should be able to print the output row by row:

```<code>for rowId, varBind in enumerate(varBindTable):
    oid, value = varBind
    print('%20.20s' % value)
    if not rowId and rowId % 3 == 0:
        print('\n')
</code>```

Body:
I'm new to python and looking for some assistance on formatting print output to rows and columns. This data will eventually be sent to csv file.

The script will grab data from multiple hosts. The number of lines is variable as well as the length of the interface name and description.

Currently the output looks like this:

hostname IF-MIB::ifDescr.1 = GigabitEthernet0/0/0

hostname IF-MIB::ifAlias.1 = --> InterfaceDesc

hostname IF-MIB::ifOperStatus.1 = 'up'

hostname IF-MIB::ifDescr.2 = GigabitEthernet0/0/1

hostname IF-MIB::ifAlias.2 = --> InterfaceDesc

hostname IF-MIB::ifOperStatus.2 = 'up'

hostname IF-MIB::ifDescr.3 = GigabitEthernet0/0/2

hostname IF-MIB::ifAlias.3 = --> InterfaceDesc

hostname IF-MIB::ifOperStatus.3 = 'up'

I'm trying to format it to the following rows and columns with headers of each row(hostname, interface, interface desc, and status).

hostname        interface              interface desc       status
hostname        GigabitEthernet0/0/0   InterfaceDesc        up
hostname        GigabitEthernet0/0/1   InterfaceDesc        up
hostname        GigabitEthernet0/0/2   InterfaceDesc        up

The print code I currently have is here. I want to keep the print statements for errors.

for errorIndication, errorStatus, errorIndex, varBinds in snmp_iter:
            # Check for errors and print out results
            if errorIndication:
                print(errorIndication)
            elif errorStatus:
                print('%s at %s' % (errorStatus.prettyPrint(),
                                errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
            else:
                for varBind in varBinds:
                    print(hostip),
                    print(' = '.join([x.prettyPrint() for x in varBind]))

Full script:

from pysnmp.hlapi import *

routers = ["router1"]

#adds routers to bulkCmd
def snmpquery (hostip):
    snmp_iter = bulkCmd(SnmpEngine(),
                        CommunityData('Community'),
                        UdpTransportTarget((hostip, 161)),
                        ContextData(),
                        0, 50,  # fetch up to 50 OIDs
                        ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')),
                        ObjectType(ObjectIdentity('IF-MIB', 'ifAlias')),
                        ObjectType(ObjectIdentity('IF-MIB', 'ifOperStatus')),
                        lexicographicMode=False) # End bulk request once outside of OID child objects
    for errorIndication, errorStatus, errorIndex, varBinds in snmp_iter:
        # Check for errors and print out results
        if errorIndication:
            print(errorIndication)
        elif errorStatus:
            print('%s at %s' % (errorStatus.prettyPrint(),
                            errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
        else:
            for rowId, varBind in enumerate(varBindTable):
                oid, value = varBind
                print('%20.20s' % value)
                if not rowId and rowId % 3 == 0:
                    print('\n')

# calls snmpquery for all routers in list
for router in routers:
    snmpquery(router)

Any help you can provide is much appreciated.
Thanks!

Body:
Assuming the snmp_iter is initialized with three SNMP table columns:

snmp_iter = bulkCmd(SnmpEngine(),
                    UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
                    Udp6TransportTarget(('demo.snmplabs.com', 161)),
                    ContextData(),
                    0, 25,
                    ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')),
                    ObjectType(ObjectIdentity('IF-MIB', 'ifAlias')),
                    ObjectType(ObjectIdentity('IF-MIB', 'ifOperStatus')))

you can be sure that (for the GETNEXT and GETBULK commands) pysnmp always returns rectangular table in a row by row fashion.

Knowing the number of the columns you have requested (3) you should be able to print the output row by row:

for rowId, varBind in enumerate(varBindTable):
    oid, value = varBind
    print('%20.20s' % value)
    if not rowId and rowId % 3 == 0:
        print('\n')


问:
poedit workaround for dynamic gettext
I have started using gettext for translating text and messages i send to user.
I am using poedit as an editor, but i am struggling with dynamic messages.

For example i have things like the login where i have a variable that tells the type of error.

```<code>$this->translate('page-error-' . $error);
</code>```

When i auto update from poedit this gets read like "page-error-".
What i do is have a file where i place dummy calls to the translate method with all the possible keys to have them added in my poedit when auto updating.

I don't particularly like this situation.
How do you guys do it.

Thanks for your ideas

答:
If you have a finite number of errors, you can add some dummy code inside a if (false) condition, whose sole purpose is to have PoEdit pick up the translations.

For example:

```<code>if (false) {
  _('role_visitor');
  _('role_hiker_reader');
  _('role_hiker');
  _('role_translator');
  _('role_proofreader');
  _('role_moderator');
  _('role_moderator_2');
  _('role_moderator_3');
  _('role_admin');
}
</code>```

You can then translate with:

```<code>$translated_role = _('role_' . $role);
</code>```

Credits to: http://eng.marksw.com/2012/12/05/how-to-expose-dynamic-translatable-text-to-translation-tools-like-poedit/

Title: poedit workaround for dynamic gettext

Body:
I have started using gettext for translating text and messages i send to user.
I am using poedit as an editor, but i am struggling with dynamic messages.

For example i have things like the login where i have a variable that tells the type of error.

$this->translate('page-error-' . $error);

When i auto update from poedit this gets read like "page-error-".
What i do is have a file where i place dummy calls to the translate method with all the possible keys to have them added in my poedit when auto updating.

I don't particularly like this situation.
How do you guys do it.

Thanks for your ideas

Body:
If you have a finite number of errors, you can add some dummy code inside a if (false) condition, whose sole purpose is to have PoEdit pick up the translations.

For example:

if (false) {
  _('role_visitor');
  _('role_hiker_reader');
  _('role_hiker');
  _('role_translator');
  _('role_proofreader');
  _('role_moderator');
  _('role_moderator_2');
  _('role_moderator_3');
  _('role_admin');
}

You can then translate with:

$translated_role = _('role_' . $role);

Credits to: http://eng.marksw.com/2012/12/05/how-to-expose-dynamic-translatable-text-to-translation-tools-like-poedit/


问:
Access docker container from host using containers name
I am developing a service and using there docker compose to spin services like postgres, redis, elasticsearch. I have a web application that is based on RubyOnRails and writes and reads from all those services.

Here is my docker-compose.yml

```<code>version: '2'

services:
  redis:
    image: redis:2.8
    networks:
      - frontapp

  elasticsearch:
    image: elasticsearch:2.2
    networks:
      - frontapp

  postgres:
    image: postgres:9.5
    environment:
      POSTGRES_USER: elephant
      POSTGRES_PASSWORD: smarty_pants
      POSTGRES_DB: elephant
    volumes:
      - /var/lib/postgresql/data
    networks:
      - frontapp

networks:
  frontapp:
    driver: bridge
</code>```

And i can ping containers within this network

```<code>$ docker-compose run redis /bin/bash
root@777501e06c03:/data# ping postgres
PING postgres (172.20.0.2): 56 data bytes
64 bytes from 172.20.0.2: icmp_seq=0 ttl=64 time=0.346 ms
64 bytes from 172.20.0.2: icmp_seq=1 ttl=64 time=0.047 ms
...
</code>```

So far so good. Now I want to run ruby on rails application on my host machine but be able to access postgres instance with url like postgresql://username:password@postgres/database currently that is not possible

```<code>$ ping postgres
ping: unknown host postgres
</code>```

I can see my network in docker

```<code>$ docker network ls
NETWORK ID          NAME                DRIVER
ac394b85ce09        bridge              bridge
0189d7e86b33        elephant_default    bridge
7e00c70bde3b        elephant_frontapp   bridge
a648554a72fa        host                host
4ad9f0f41b36        none                null
</code>```

And I can see an interface to it

```<code>$ ifconfig
br-0189d7e86b33 Link encap:Ethernet  HWaddr 02:42:76:72:bb:c2
          inet addr:172.18.0.1  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::42:76ff:fe72:bbc2/64 Scope:Link
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:36 errors:0 dropped:0 overruns:0 frame:0
          TX packets:60 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:2000 (2.0 KB)  TX bytes:8792 (8.7 KB)

br-7e00c70bde3b Link encap:Ethernet  HWaddr 02:42:e7:d1:fe:29
          inet addr:172.20.0.1  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::42:e7ff:fed1:fe29/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1584 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1597 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:407137 (407.1 KB)  TX bytes:292299 (292.2 KB)
...
</code>```

But i am not sure what should I do next. I tried to play a bit with /etc/resolv.conf, mainly with nameserver directive, but that had no effect.

I would appreciate any help of suggestions how to configure this setup correctly.

UPDATE

After browsing through Internet resources I managed to assign static IP addresses to boxes. For now it is enough for me to continue development. Here is my current docker-compose.yml

```<code>version: '2'

services:
  redis:
    image: redis:2.8
    networks:
      frontapp:
        ipv4_address: 172.25.0.11

  elasticsearch:
    image: elasticsearch:2.2
    networks:
      frontapp:
        ipv4_address: 172.25.0.12

  postgres:
    image: postgres:9.5
    environment:
      POSTGRES_USER: elephant
      POSTGRES_PASSWORD: smarty_pants
      POSTGRES_DB: elephant
    volumes:
      - /var/lib/postgresql/data
    networks:
      frontapp:
        ipv4_address: 172.25.0.10

networks:
  frontapp:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.25.0.0/16
          gateway: 172.25.0.1
</code>```

答:
There are two solutions (except /etc/hosts) described here and here

I wrote my own solution in Python and implemented it as service to provide mapping from container hostname to its IP. Here it is: https://github.com/nicolai-budico/dockerhosts

It launches dnsmasq with parameter --hostsdir=/var/run/docker-hosts and updates file /var/run/docker-hosts/hosts each time a list of running containers was changed.
Once file /var/run/docker-hosts/hosts is changed, dnsmasq automatically updates its mapping and container become available by hostname in a second.

```<code>$ docker run -d --hostname=myapp.local.com --rm -it ubuntu:17.10
9af0b6a89feee747151007214b4e24b8ec7c9b2858badff6d584110bed45b740

$ nslookup myapp.local.com
Server:         127.0.0.53
Address:        127.0.0.53#53

Non-authoritative answer:
Name:   myapp.local.com
Address: 172.17.0.2
</code>```

There are install and uninstall scripts. Only you need is to allow your system to interact with this dnsmasq instance. I registered in in systemd-resolved:

```<code>$ cat /etc/systemd/resolved.conf

[Resolve]
DNS=127.0.0.54
#FallbackDNS=
#Domains=
#LLMNR=yes
#MulticastDNS=yes
#DNSSEC=no
#Cache=yes
#DNSStubListener=udp
</code>```

Body:
I am developing a service and using there docker compose to spin services like postgres, redis, elasticsearch. I have a web application that is based on RubyOnRails and writes and reads from all those services.

Here is my docker-compose.yml

version: '2'

services:
  redis:
    image: redis:2.8
    networks:
      - frontapp

  elasticsearch:
    image: elasticsearch:2.2
    networks:
      - frontapp

  postgres:
    image: postgres:9.5
    environment:
      POSTGRES_USER: elephant
      POSTGRES_PASSWORD: smarty_pants
      POSTGRES_DB: elephant
    volumes:
      - /var/lib/postgresql/data
    networks:
      - frontapp

networks:
  frontapp:
    driver: bridge

And i can ping containers within this network

$ docker-compose run redis /bin/bash
root@777501e06c03:/data# ping postgres
PING postgres (172.20.0.2): 56 data bytes
64 bytes from 172.20.0.2: icmp_seq=0 ttl=64 time=0.346 ms
64 bytes from 172.20.0.2: icmp_seq=1 ttl=64 time=0.047 ms
...

So far so good. Now I want to run ruby on rails application on my host machine but be able to access postgres instance with url like postgresql://username:password@postgres/database currently that is not possible

$ ping postgres
ping: unknown host postgres

I can see my network in docker

$ docker network ls
NETWORK ID          NAME                DRIVER
ac394b85ce09        bridge              bridge
0189d7e86b33        elephant_default    bridge
7e00c70bde3b        elephant_frontapp   bridge
a648554a72fa        host                host
4ad9f0f41b36        none                null

And I can see an interface to it

$ ifconfig
br-0189d7e86b33 Link encap:Ethernet  HWaddr 02:42:76:72:bb:c2
          inet addr:172.18.0.1  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::42:76ff:fe72:bbc2/64 Scope:Link
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:36 errors:0 dropped:0 overruns:0 frame:0
          TX packets:60 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:2000 (2.0 KB)  TX bytes:8792 (8.7 KB)

br-7e00c70bde3b Link encap:Ethernet  HWaddr 02:42:e7:d1:fe:29
          inet addr:172.20.0.1  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::42:e7ff:fed1:fe29/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1584 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1597 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:407137 (407.1 KB)  TX bytes:292299 (292.2 KB)
...

But i am not sure what should I do next. I tried to play a bit with /etc/resolv.conf, mainly with nameserver directive, but that had no effect.

I would appreciate any help of suggestions how to configure this setup correctly.

UPDATE

After browsing through Internet resources I managed to assign static IP addresses to boxes. For now it is enough for me to continue development. Here is my current docker-compose.yml

version: '2'

services:
  redis:
    image: redis:2.8
    networks:
      frontapp:
        ipv4_address: 172.25.0.11

  elasticsearch:
    image: elasticsearch:2.2
    networks:
      frontapp:
        ipv4_address: 172.25.0.12

  postgres:
    image: postgres:9.5
    environment:
      POSTGRES_USER: elephant
      POSTGRES_PASSWORD: smarty_pants
      POSTGRES_DB: elephant
    volumes:
      - /var/lib/postgresql/data
    networks:
      frontapp:
        ipv4_address: 172.25.0.10

networks:
  frontapp:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.25.0.0/16
          gateway: 172.25.0.1

Body:
There are two solutions (except /etc/hosts) described here and here

I wrote my own solution in Python and implemented it as service to provide mapping from container hostname to its IP. Here it is: https://github.com/nicolai-budico/dockerhosts

It launches dnsmasq with parameter --hostsdir=/var/run/docker-hosts and updates file /var/run/docker-hosts/hosts each time a list of running containers was changed.
Once file /var/run/docker-hosts/hosts is changed, dnsmasq automatically updates its mapping and container become available by hostname in a second.

$ docker run -d --hostname=myapp.local.com --rm -it ubuntu:17.10
9af0b6a89feee747151007214b4e24b8ec7c9b2858badff6d584110bed45b740

$ nslookup myapp.local.com
Server:         127.0.0.53
Address:        127.0.0.53#53

Non-authoritative answer:
Name:   myapp.local.com
Address: 172.17.0.2

There are install and uninstall scripts. Only you need is to allow your system to interact with this dnsmasq instance. I registered in in systemd-resolved:

$ cat /etc/systemd/resolved.conf

[Resolve]
DNS=127.0.0.54
#FallbackDNS=
#Domains=
#LLMNR=yes
#MulticastDNS=yes
#DNSSEC=no
#Cache=yes
#DNSStubListener=udp


问:
Running Jmeter gives 'findstr' is not recognized as an internal or external command
I am trying to open Jmeter by the batch file but it gives me a error like this:

```<code>'findstr' is not recognized as an internal or external command,
operable program or batch file.
Not able to find Java executable or version. Please check your Java installation.
errorlevel=2
Press any key to continue . . .
</code>```

How can I fix this?

答:
1.Browse to C:\Windows\System32 and search "findstr" file.

2. Copy and paste the "findstr" file in the bin folder of Jmeter
(i.e) the path C:.....\apache-jmeter-3.3\apache-jmeter-3.3\bin

3. Then try to run the "jmeterw" or the "jmeter" bat file , it should work fine.

Body:
I am trying to open Jmeter by the batch file but it gives me a error like this:

'findstr' is not recognized as an internal or external command,
operable program or batch file.
Not able to find Java executable or version. Please check your Java installation.
errorlevel=2
Press any key to continue . . .

How can I fix this?


问:
Precedence Function
I'm trying to write a function, that goes within my main program, that will compare the precedence of operators being input by the user. The function would look for the following operators:

+, -, * , / with *, / having the highest precedence and +, - having the lowest precedence.

The operators with the lowest precedence go on the bottom of a stack while those with the highest precedence go on the top of the stack. So if a user types in +-*/, */+- should be displayed in the terminal.

Any ideas on how I should go about this?

答:
Read all of the operators into a std::string.  Write a function with the following type:

```<code>bool is_higher_precedence(char lhs, char rhs);
</code>```

This function should return whether lhs has higher precedence than rhs.

You can then use this function as the functor parameter of std::sort to sort the operators by precedence.

Title: Precedence Function

Body:
Read all of the operators into a std::string.  Write a function with the following type:

bool is_higher_precedence(char lhs, char rhs);

This function should return whether lhs has higher precedence than rhs.

You can then use this function as the functor parameter of std::sort to sort the operators by precedence.


问:
how to pass variables to an include file from every parent file laravel
i am an absolute beginner in laravel so far i have created a basic structure of my website in laravel, there are some views in resources/views now there is a folder inside view named as includes and inside that folder there is a file named as banner.blade.php now this banner is included in almost every file which is in resources/views what i want to do is pass a variable containing the name of the banner and echo that variable inside the banner file. here's my code

this is the parent blade from where i need to send a variable e.g $banner_name="contact us"

```<code>@extends("app")

@section("content")

    @include("includes.banner-others")
</code>```

and this is my banner-others file

```<code><div class="banner-others">
    <div class="container">
        <div class="row">
            <h1>{{"uneeb"}}</h1>// i need to echo the $banner_name here.
        </div>
    </div>
</div>
</code>```

答: you don't need to pass variable. when you include a blade inside a parent blade, you can access parent's variables inside included one.</p>

Body:
i am an absolute beginner in laravel so far i have created a basic structure of my website in laravel, there are some views in resources/views now there is a folder inside view named as includes and inside that folder there is a file named as banner.blade.php now this banner is included in almost every file which is in resources/views what i want to do is pass a variable containing the name of the banner and echo that variable inside the banner file. here's my code

this is the parent blade from where i need to send a variable e.g $banner_name="contact us"

@extends("app")

@section("content")

    @include("includes.banner-others")

and this is my banner-others file

{{"uneeb"}}
// i need to echo the $banner_name here.


问:
Connect to Active MQ with golang
Amazon MQ (Active MQ) says it works with amqp, and there's a go package here https://github.com/streadway/amqp but when I try to Dial() I get this error

```<code>Exception (501) Reason: "Exception (501) Reason: \"frame could not be parsed\""
</code>```

I suspect it is because although this is an amqp package, and Amazon MQ accepts amqp, this is specifically a RabbitMQ amqp package... does this make sense?

Another option is STOMP, which I've tried using the example here https://github.com/go-stomp/stomp/blob/master/examples/client_test/main.go
But Dial() is giving me this super not helpful error: "invalid command"

It's embarrassing asking how to connect, but it's where I'm stuck. Thanks in advance

答:
AMQP 0.x (RabbitMQ) is a very different protocol from AMQP 1.0 (ActiveMQ, etc). AMQP 1.0 is not backwards compatible.

You need a client library that supports AMQP 1.0.

I have not tested it, but this lib claims to work.
https://github.com/vcabbage/amqp

Title: Connect to Active MQ with golang

Body:
Amazon MQ (Active MQ) says it works with amqp, and there's a go package here https://github.com/streadway/amqp but when I try to Dial() I get this error

Exception (501) Reason: "Exception (501) Reason: \"frame could not be parsed\""

I suspect it is because although this is an amqp package, and Amazon MQ accepts amqp, this is specifically a RabbitMQ amqp package... does this make sense?

Another option is STOMP, which I've tried using the example here https://github.com/go-stomp/stomp/blob/master/examples/client_test/main.go
But Dial() is giving me this super not helpful error: "invalid command"

It's embarrassing asking how to connect, but it's where I'm stuck. Thanks in advance


问:
npm module for ActiveMQ calls
What is the best npm library to make ActiveMQ calls from nodejs? I've tried 'stomp' but sometimes it acts wired.
Whenever I use stomp port (61613) it worked
but when I use tcp port (61616) it throws an exception in ActiveMQ logs saying packet size is max out.</p>

答: The behavior you describe as "weird" is the behavior I would expect.  The listener on port 61616 in ActiveMQ 5.x is for OpenWire clients and therefore not suitable for STOMP clients.  If you use a STOMP transportConnector then you shouldn't have any problem.</p>

Title: npm module for ActiveMQ calls


问:
blueimp jQuery-File-Upload can't find uploaded files
after installing blueimp jQuery-File-Upload on centos the upload seems working properly as i can see upload traffic on machine interface, the problem is that  i can't find the uploaded files in /php/files directory.

link on github : https://github.com/blueimp/jQuery-File-Upload

what is the right directory of uploaded file?

if it is /php/files , why cant i see any files inside this directory?

how to change the default upload directory?

[root@localhost /]#  cd /var/www/html/upload/server/php/files/

[root@localhost files]# ls

[root@localhost files]#

enter image description here

upload progress

答:
in fileupload options there is a url tag which you can use to post to your server method. (this is a .net example)

```<code>    $('#fileupload').fileupload({
        url: '@(Url.Content("~/"))controller_name/your_method_name'
    });
</code>```

and in your method you can get uploaded files like:

```<code>var file = Request.Files[i]; // use in for loop
///// do some other thing ///
var filePath = your_path;
file.SaveAs(filePath);
</code>```

Body:
in fileupload options there is a url tag which you can use to post to your server method. (this is a .net example)

    $('#fileupload').fileupload({
        url: '@(Url.Content("~/"))controller_name/your_method_name'
    });

and in your method you can get uploaded files like:

var file = Request.Files[i]; // use in for loop
///// do some other thing ///
var filePath = your_path;
file.SaveAs(filePath);


问:
Add custom headers and retrieve custom header using Microsoft Graph API
I am currently using Microsoft Graph API to retrieve my email, send new email and answer to an email.

I use Code Grant authorization to identify my user and access its information.

PROBLEM

This application let the user send email to our customers that have unpaid invoice. But the application uses GET https://graph.microsoft.com/v1.0/me/messages (with $search set to the customer email) to retrieve every mail that involves the customer, so the user can trace every conversation made by other employees.

The problem is to be able to differentiate emails (sent from our app) from others mails (sent from Outlook app). We would like to use email headers, which are accepted by a large amount of mail servers, and with which we could filter the search result to inform the user which email comes from our app.

The desired outcome would be that for example, I could be able to call Microsoft Graph API like so :

GET https://graph.microsoft.com/v1.0/me/messages with OData Parameters : $search="john.doe@gmail.com" and $select=subject,bodyPreviewreceivedDateTime,headers

Then asuming the request has send back a 200 code the JSON output would be :

Notice the X-MY-COMPANY-INVOICE, which would be the ultimate goal for us to let the app be aware this was sent from our app and not from Outlook app.

QUESTION

Is there any way to perform this using Microsoft Graph API? If not, does Microsoft plan to release this feature any soon?

QUESTION 2

I am opened to suggestion, is this the best way to do this or am I going right on the wall with this technique? If yes, what would be the best way to overcome this issue?

答:
This is a good use case for Extensions. You can use these mechanisms to attach custom data to an element (messages, events, users, groups, etc.). </p>

<p>There are several types of extensions available with Microsoft Graph: Extended Properties, Open Extensions or Schema Extension. Each has it's own set of constraints so it is worth reviewing each to determine which works best for your scenario and architecture. That said, based on your description, I suspect Schema Extensions may be the best fit here. </p>

ContentLicense: CC BY-SA 4.0

Body:
This is a good use case for Extensions. You can use these mechanisms to attach custom data to an element (messages, events, users, groups, etc.).

There are several types of extensions available with Microsoft Graph: Extended Properties, Open Extensions or Schema Extension. Each has it's own set of constraints so it is worth reviewing each to determine which works best for your scenario and architecture. That said, based on your description, I suspect Schema Extensions may be the best fit here.


问:
Cannot compile Release build of UWP - Visual Studio 2017
I have finished a small Windows 10 app in C# and XAML and now I want to do a "Release" build of the app so that I can create app package.

The problem is: VS 2017 cannot create a release build of the app.

Please see the error message which VS give out after trying to release-build for around 20 mins.

I'm using Syncfusion PDF Viewer control in the app & hence have added reference to "Syncfusion Controls for UWP XAML".

I have tried un-checking the "Compile with .NET Native tool chain" in properties page. It works and I can do a release-build, BUT the Windows App Cert Kit "fails" my app.

Another information which I would like to add is: even if I do a File -> New UWP Project and try to do a release build of that - it still does not work.

I've also read the issue here, but it's does not seem relevant to my project. e.g., I am not referencing a winmd type.

What could be wrong?

答:
The reason for this is "Syncfusion controls". Details about this here
You need to remove the extension ""Syncfusion Controls for UWP Xaml" and add path to syncfusion libraries(which you use) .</p>


问:
How to send local variables via post
Via a hidden input field I want to send a value from Site 1 to Site 2.
But at Site 2 it says the value is null.

I guess this is because it is local value. But it has to be local and I'm not sure.

Here is my code where I declare the value (page 1):

```<code>string stringproductid = Request.QueryString["id"].tostring();
int productid = stringproductid.AsInt();
</code>```

Here I send it via a hidden field inside a form (page 1):

```<code><input type="hidden" id="@productid" value="@productid" name="@productid">
</code>```

Here I try to receive it (at page 2):

```<code>string idstring = Request.Form["productid"].ToString(); //error
</code>```

答:
It should be name="productid" . The @ you're using there is making Razor put the value of productID into that attribute. So if you look at your raw generated HTML it is going to be something like name="346".

That belongs in the "value" attribute, which you did correctly, but what you need to be putting in the "name" is the name of the field, so that the browser posts it back correctly with that field name. :-)

Title: How to send local variables via post

Body:
Via a hidden input field I want to send a value from Site 1 to Site 2.
But at Site 2 it says the value is null.

I guess this is because it is local value. But it has to be local and I'm not sure.

Here is my code where I declare the value (page 1):

string stringproductid = Request.QueryString["id"].tostring();
int productid = stringproductid.AsInt();

Here I send it via a hidden field inside a form (page 1):

<input type="hidden" id="@productid" value="@productid" name="@productid">

Here I try to receive it (at page 2):

string idstring = Request.Form["productid"].ToString(); //error


问:
What's the equivalent of Alt-left/right arrow key like Eclipse in IntelilJ?
In Eclipse you can use alt+<- or -> to move between places you were. What is the equivalent in Intellij?

答: I would suggest just go and select eclipse shortcuts option instead of default provided by IntelliJ idea ide</p>