问:
Cannot set output layer to classification
I am currently trying to implement a CNN which purpose is to perform classification, but for some reason am I not able to define my output dimension to 1.

Here is an example code:

```<code>import keras
from keras.layers.merge import Concatenate
from keras.models import Model
from keras.layers import Input, Dense
from keras.layers import Dropout
from keras.layers.core import Dense, Activation, Lambda, Reshape,Flatten
from keras.layers import Conv2D, MaxPooling2D, Reshape, ZeroPadding2D
import numpy as np

train_data_1 = np.random.randint(100,size=(100,3,6,3))
train_data_2 = np.random.randint(100,size=(100,3,6,3))
test_data_1 = np.random.randint(100,size=(10,3,6,3))
test_data_2 = np.random.randint(100,size=(10,3,6,3))
labels_train_data =np.random.randint(145,size=100)
labels_test_data =np.random.randint(145,size=10)

input_img_1 = Input(shape=(3, 6, 3))
input_img_2 = Input(shape=(3, 6, 3))

conv2d_1_1 = Conv2D(filters = 32, kernel_size = (3,3) , padding = "same" , activation = 'relu' , name = "conv2d_1_1" )(input_img_1)
conv2d_2_1 = Conv2D(filters = 64, kernel_size = (3,3) , padding = "same" , activation = 'relu' )(conv2d_1_1)
conv2d_3_1 = Conv2D(filters = 64, kernel_size = (3,3) , padding = "same" , activation = 'relu' )(conv2d_2_1)
conv2d_4_1 = Conv2D(filters = 32, kernel_size = (1,1) , padding = "same" , activation = 'relu' )(conv2d_3_1)
conv2d_4_1_flatten = Flatten()(conv2d_4_1)

conv2d_1_2 = Conv2D(filters = 32, kernel_size = (3,3) , padding = "same" , activation = 'relu' , name = "conv2d_1_2")(input_img_2)
conv2d_2_2 = Conv2D(filters = 64, kernel_size = (3,3) , padding = "same" , activation = 'relu' )(conv2d_1_2)
conv2d_3_2 = Conv2D(filters = 64, kernel_size = (3,3) , padding = "same" , activation = 'relu' )(conv2d_2_2)
conv2d_4_2 = Conv2D(filters = 32, kernel_size = (1,1) , padding = "same" , activation = 'relu' )(conv2d_3_2)
conv2d_4_2_flatten = Flatten()(conv2d_4_2)

merge = keras.layers.concatenate([conv2d_4_1_flatten, conv2d_4_2_flatten])

dense1 = Dense(100, activation = 'relu')(merge)
dense2 = Dense(50,activation = 'relu')(dense1)
dense3 = Dense(1 ,activation = 'softmax')(dense2)

model = Model(inputs = [input_img_1, input_img_2] , outputs = dense3)
model.compile(loss="sparse_categorical_crossentropy", optimizer="adam")

print model.summary()

labels_train = keras.utils.to_categorical(labels_train_data, num_classes=145)
labels_test = keras.utils.to_categorical(labels_test_data, num_classes=145)

hist_current = model.fit(x = [train_data_1, train_data_2],
                    y = labels_train,
                    shuffle=False,
                    validation_data=([test_data_1 ,test_data_2], labels_test),
                    validation_split=0.1,
                    epochs=150000,
                    batch_size = 15,
                    verbose=1)
</code>```

And the error message being:

```<code>Traceback (most recent call last):
  File "test_model.py", line 57, in <module>
    verbose=1)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1405, in fit
    batch_size=batch_size)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1299, in _standardize_user_data
    exception_prefix='model target')
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 133, in _standardize_input_data
    str(array.shape))
ValueError: Error when checking model target: expected dense_3 to have shape (None, 1) but got array with shape (100, 145)
</code>```

答:
several inconsistencies in your model :

dense3 = Dense(1 ,activation = 'softmax')(dense2) : you cannot use a softmax on one neuron alone. The softmax normalizese the output of the layer so that it sums up to 1... In this case if you normalize one value alone, it will always output 1. However this is not why you get the error

just how many classes do you have? From your network, you output one value (last layer is Dense(1)) so I would expect that you want to predict 2 classes (output 1 or 0). But here We see that your output is a categorical with 145 possibilities... Your label_train array is 100 one hot vectors of length 145, so I assume that you want to classify the 100 samples into 145 different categories... This is why keras is complaining, your networks outputs (100,1) and your targets (labels) are (100,145). What do you really want to do ?

Edit :

Following the comment, since you want to predictif the image belongs to one of 145 classes, you will have to output 145 values. So you will have to change the top layers of your network so that your last layer is a Dense(145, activation='softmax'). So I propose that you replace

```<code>dense1 = Dense(100, activation = 'relu')(merge)
dense2 = Dense(50,activation = 'relu')(dense1)
dense3 = Dense(1 ,activation = 'softmax')(dense2)
</code>```

with

```<code>dense1 = Dense(200, activation = 'relu')(merge)
dense2 = Dense(150, activation = 'relu')(dense1)
dense3 = Dense(145, activation = 'softmax')(dense2)
</code>```

If you really want to have 3 dense layers, otherwise you can just remove the middle one... This will depend on your usecase, so the architecture of the hidden layers is up to you. I'm just insisting that your last layer should be a Dense(145, activation='softmax').

Makes sense?

Edit 2 :

On top of that, you shouldn't encode your targets (labels) as categoricals, when you use sparse_categorical_crossentropy, it is done automatically under the hood.

So either you use keras.utils.to_categorical on your targets with loss=categorical_crossentropy

or you don't transform the targets with keras.utils.to_categorical and use loss=sparse_categorical_crossentropy.

It's running on my machine.

Body:
I am currently trying to implement a CNN which purpose is to perform classification, but for some reason am I not able to define my output dimension to 1.

Here is an example code:

import keras
from keras.layers.merge import Concatenate
from keras.models import Model
from keras.layers import Input, Dense
from keras.layers import Dropout
from keras.layers.core import Dense, Activation, Lambda, Reshape,Flatten
from keras.layers import Conv2D, MaxPooling2D, Reshape, ZeroPadding2D
import numpy as np

train_data_1 = np.random.randint(100,size=(100,3,6,3))
train_data_2 = np.random.randint(100,size=(100,3,6,3))
test_data_1 = np.random.randint(100,size=(10,3,6,3))
test_data_2 = np.random.randint(100,size=(10,3,6,3))
labels_train_data =np.random.randint(145,size=100)
labels_test_data =np.random.randint(145,size=10)

input_img_1 = Input(shape=(3, 6, 3))
input_img_2 = Input(shape=(3, 6, 3))

conv2d_1_1 = Conv2D(filters = 32, kernel_size = (3,3) , padding = "same" , activation = 'relu' , name = "conv2d_1_1" )(input_img_1)
conv2d_2_1 = Conv2D(filters = 64, kernel_size = (3,3) , padding = "same" , activation = 'relu' )(conv2d_1_1)
conv2d_3_1 = Conv2D(filters = 64, kernel_size = (3,3) , padding = "same" , activation = 'relu' )(conv2d_2_1)
conv2d_4_1 = Conv2D(filters = 32, kernel_size = (1,1) , padding = "same" , activation = 'relu' )(conv2d_3_1)
conv2d_4_1_flatten = Flatten()(conv2d_4_1)

conv2d_1_2 = Conv2D(filters = 32, kernel_size = (3,3) , padding = "same" , activation = 'relu' , name = "conv2d_1_2")(input_img_2)
conv2d_2_2 = Conv2D(filters = 64, kernel_size = (3,3) , padding = "same" , activation = 'relu' )(conv2d_1_2)
conv2d_3_2 = Conv2D(filters = 64, kernel_size = (3,3) , padding = "same" , activation = 'relu' )(conv2d_2_2)
conv2d_4_2 = Conv2D(filters = 32, kernel_size = (1,1) , padding = "same" , activation = 'relu' )(conv2d_3_2)
conv2d_4_2_flatten = Flatten()(conv2d_4_2)

merge = keras.layers.concatenate([conv2d_4_1_flatten, conv2d_4_2_flatten])

dense1 = Dense(100, activation = 'relu')(merge)
dense2 = Dense(50,activation = 'relu')(dense1)
dense3 = Dense(1 ,activation = 'softmax')(dense2)

model = Model(inputs = [input_img_1, input_img_2] , outputs = dense3)
model.compile(loss="sparse_categorical_crossentropy", optimizer="adam")

print model.summary()

labels_train = keras.utils.to_categorical(labels_train_data, num_classes=145)
labels_test = keras.utils.to_categorical(labels_test_data, num_classes=145)

hist_current = model.fit(x = [train_data_1, train_data_2],
                    y = labels_train,
                    shuffle=False,
                    validation_data=([test_data_1 ,test_data_2], labels_test),
                    validation_split=0.1,
                    epochs=150000,
                    batch_size = 15,
                    verbose=1)

And the error message being:

Traceback (most recent call last):
  File "test_model.py", line 57, in <module>
    verbose=1)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1405, in fit
    batch_size=batch_size)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1299, in _standardize_user_data
    exception_prefix='model target')
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 133, in _standardize_input_data
    str(array.shape))
ValueError: Error when checking model target: expected dense_3 to have shape (None, 1) but got array with shape (100, 145)

Body:
several inconsistencies in your model :

dense3 = Dense(1 ,activation = 'softmax')(dense2) : you cannot use a softmax on one neuron alone. The softmax normalizese the output of the layer so that it sums up to 1... In this case if you normalize one value alone, it will always output 1. However this is not why you get the error

just how many classes do you have? From your network, you output one value (last layer is Dense(1)) so I would expect that you want to predict 2 classes (output 1 or 0). But here We see that your output is a categorical with 145 possibilities... Your label_train array is 100 one hot vectors of length 145, so I assume that you want to classify the 100 samples into 145 different categories... This is why keras is complaining, your networks outputs (100,1) and your targets (labels) are (100,145). What do you really want to do ?

Edit :

Following the comment, since you want to predictif the image belongs to one of 145 classes, you will have to output 145 values. So you will have to change the top layers of your network so that your last layer is a Dense(145, activation='softmax'). So I propose that you replace

dense1 = Dense(100, activation = 'relu')(merge)
dense2 = Dense(50,activation = 'relu')(dense1)
dense3 = Dense(1 ,activation = 'softmax')(dense2)

with

dense1 = Dense(200, activation = 'relu')(merge)
dense2 = Dense(150, activation = 'relu')(dense1)
dense3 = Dense(145, activation = 'softmax')(dense2)

If you really want to have 3 dense layers, otherwise you can just remove the middle one... This will depend on your usecase, so the architecture of the hidden layers is up to you. I'm just insisting that your last layer should be a Dense(145, activation='softmax').

Makes sense?

Edit 2 :

On top of that, you shouldn't encode your targets (labels) as categoricals, when you use sparse_categorical_crossentropy, it is done automatically under the hood.

So either you use keras.utils.to_categorical on your targets with loss=categorical_crossentropy

or you don't transform the targets with keras.utils.to_categorical and use loss=sparse_categorical_crossentropy.

It's running on my machine.


来源: stackexchange

问:
Autofac injection of an object's property rather than the object
I'm using Autofac and EF Core, in an ASP.NET Core environment.

My EF context:

```<code>public interface IMyContext { /* ... */ }
public class MyContext : DbContext, IMyContext { /* ... */ }
</code>```

Which is registered per-request:

```<code>builder.RegisterType<MyContext>().As<IMyContext>().InstancePerLifetimeScope();
</code>```

Problem: in some class, I need DbContext.ChangeTracker. However what I have is IMyContext.

I don't want to add it as a property to the interface (that gives too much power to consumers), and I don't want to cast ((DbContext)_context).ChangeTracker (that destroys encapsulation).

So I must inject a ChangeTracker into the constructor:

```<code>public Foo(IMyContext context, ChangeTracker changeTracker)
{
  _context = context;
  _changeTracker = changeTracker;
}
</code>```

I've read the docs, but don't understand how to register it.

The injected ChangeTracker MUST be the same one from the current lifetime scope's MyContext:

```<code>_context.ChangeTracker.Equals(_changeTracker)
</code>```

答:
Because your context is registered as InstancePerLifetimeScope you can us an overload of the register that take a lambda to resolve the context and then access the changeTracker property.

```<code>builder.Register(c => ((DbContext)c.Resolve<IMyContext>()).ChangeTracker)
       .As<ChangeTracker>()
       .InstancePerLifetimeScope();
</code>```

The c.Resolve<IMyContext>() of the lambda will use the current lifetimescope

ContentLicense: CC BY-SA 3.0

Body:
I'm using Autofac and EF Core, in an ASP.NET Core environment.

My EF context:

public interface IMyContext { /* ... */ }
public class MyContext : DbContext, IMyContext { /* ... */ }

Which is registered per-request:

builder.RegisterType<MyContext>().As<IMyContext>().InstancePerLifetimeScope();

Problem: in some class, I need DbContext.ChangeTracker. However what I have is IMyContext.

I don't want to add it as a property to the interface (that gives too much power to consumers), and I don't want to cast ((DbContext)_context).ChangeTracker (that destroys encapsulation).

So I must inject a ChangeTracker into the constructor:

public Foo(IMyContext context, ChangeTracker changeTracker)
{
  _context = context;
  _changeTracker = changeTracker;
}

I've read the docs, but don't understand how to register it.

The injected ChangeTracker MUST be the same one from the current lifetime scope's MyContext:

_context.ChangeTracker.Equals(_changeTracker)

Body:
Because your context is registered as InstancePerLifetimeScope you can us an overload of the register that take a lambda to resolve the context and then access the changeTracker property.

builder.Register(c => ((DbContext)c.Resolve<IMyContext>()).ChangeTracker)
       .As<ChangeTracker>()
       .InstancePerLifetimeScope();

The c.Resolve<IMyContext>() of the lambda will use the current lifetimescope


问:
Jekyll sass file not compiling
I've set up a new Jekyll site to test the Neat 2.0 grid. However, as I run Jekyll Serve I've noticed that nothing from my main.scss file doesn't compile into my main.css file:(

Folder set up

Config.yml

```<code>sass:
  sass_dir: _scss
</code>```

What's happening here and how can I get my main.scss file to compile?

答:
I am playing with this as well, but I'm a beginner, so take my advice with a pinch of salt.

However, my setup is working and compiling all scss changes when I'm running "jekyll serve --watch" with my _sass folder specified in config.yml as:

```<code>sass:
    sass_dir: _sass
</code>```

My _sass folder itself contains a couple of _scss files, which I use for styling, but the important thing, I think, is that my jekyll CSS folder contains only imports in only one file named main.scss, like this:

```<code> ---
 # Front matter comment to ensure Jekyll properly reads the file
 ---
 @import
 "layout",
 "grids",
 "etc"
</code>```

Hopefully this not-very-techinical explaination is of use either to you, or to someone googling how to make jekyll compile/process and watch for changes in .sccs files.

Title: Jekyll sass file not compiling

Body:
I've set up a new Jekyll site to test the Neat 2.0 grid. However, as I run Jekyll Serve I've noticed that nothing from my main.scss file doesn't compile into my main.css file:(

Folder set up

Config.yml

sass:
  sass_dir: _scss

What's happening here and how can I get my main.scss file to compile?

Body:
I am playing with this as well, but I'm a beginner, so take my advice with a pinch of salt.

However, my setup is working and compiling all scss changes when I'm running "jekyll serve --watch" with my _sass folder specified in config.yml as:

sass:
    sass_dir: _sass

My _sass folder itself contains a couple of _scss files, which I use for styling, but the important thing, I think, is that my jekyll CSS folder contains only imports in only one file named main.scss, like this:

 ---
 # Front matter comment to ensure Jekyll properly reads the file
 ---
 @import
 "layout",
 "grids",
 "etc"

Hopefully this not-very-techinical explaination is of use either to you, or to someone googling how to make jekyll compile/process and watch for changes in .sccs files.


问:
Div with fixed width and inline element
I wrote some simple html document. I have two element inside: div with FIXED width, and image after it. As far I know, image is inline element, so it suppose to be positioned next to div, on the right side, since div has fixed width and there is a plenty room for image. Instead, image goes below div element. So it seems, that div element takes 100% of width no matter of what size it is. Why this happens?
Code: </p>

```<code>    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title></title>
            <meta charset="UTF-8" />

        </head>
    <body>
        <div style="width:500px;"><p>Some text</p></div>
        <img src="someImage.jpeg " />
    </body>
    </html>
</code>```

答:
So, You want to know the reason behind divs chooosing next line instead setting in-line automatically.

Some elements in CSS are block level elements, which means they automatically start a new line. For instance, if you create two single word paragraph elements, they won’t flow into each other but will appear on separate lines. Other elements are inline elements. This means that they appear “in line” with the previous content. One example is an anchor tag, which can appear within another element such as a paragraph without causing any extra whitespace or new lines to occur.

One way to cheat this model of layout is to use floats, which allow a given element to shift to one side of its line and have other content flow down its side. A right-floated element will be pushed all the way to the right of its container and have content flow down its left side and a left-floated element will be pushed all the way to the left side with content flowing down its right side.

The classic example is when you toss an image in with a paragraph and want the two to appear side by side rather than stacked. First we create both elements with some HTML:

```<code>  <img src="http://domain/200/200/" />
  <p>Hello World...</p>
</code>```

Alone, this code does not produce the effect that we want. The paragraph element is a block level element that appears on its own line and so the paragraph and the image are shown stacked in the normal document flow.

We can change this behavior by floating our image to the right. The CSS for this is very basic:

```<code> img {
      float: right;
      margin: 20px;
      }
</code>```

How Exactly the Box Thing Works

The question you should be asking yourself is, “why?” Why wouldn’t increasing the paragraph margin increase the space between the image and the paragraph? The reason is that we’re failing to grasp the box model as it pertains to that paragraph.

If you’re ever doubtful about how your layout is working on a basic level, try applying a border or two to see what’s going on. If we use this technique on the paragraph, the result may surprise you.

```<code>   p {
       border: solid 1px black;
     }
</code>```

As you can see, the image is actually inside of the paragraph’s box! This solves our margin riddle. Any margin that we add to the paragraph is being applied way off to the right of the image, this is why it doesn’t increase the space between the image and the paragraph.

If we wanted the change this behavior so that the paragraph doesn’t wrap around the image, we could float the paragraph to the left and give it a specified width (without expressing the width, the paragraph is 100% wide and won’t fit next to the image).

```<code>   img {
     float: right;
     margin: 20px;
     }

  p {
     float: left;
     width: 220px;
     margin: 20px;
     }
</code>```

Hope You got it...

That's the crazy box thing. :)

Title: Div with fixed width and inline element

Body:
I wrote some simple html document. I have two element inside: div with FIXED width, and image after it. As far I know, image is inline element, so it suppose to be positioned next to div, on the right side, since div has fixed width and there is a plenty room for image. Instead, image goes below div element. So it seems, that div element takes 100% of width no matter of what size it is. Why this happens?
Code:

    <!DOCTYPE html>

            <title></title>
            <meta charset="UTF-8" />

Some text

Body:
So, You want to know the reason behind divs chooosing next line instead setting in-line automatically.

Some elements in CSS are block level elements, which means they automatically start a new line. For instance, if you create two single word paragraph elements, they won’t flow into each other but will appear on separate lines. Other elements are inline elements. This means that they appear “in line” with the previous content. One example is an anchor tag, which can appear within another element such as a paragraph without causing any extra whitespace or new lines to occur.

One way to cheat this model of layout is to use floats, which allow a given element to shift to one side of its line and have other content flow down its side. A right-floated element will be pushed all the way to the right of its container and have content flow down its left side and a left-floated element will be pushed all the way to the left side with content flowing down its right side.

The classic example is when you toss an image in with a paragraph and want the two to appear side by side rather than stacked. First we create both elements with some HTML:

  <img src="http://domain/200/200/" />
  <p>Hello World...</p>

Alone, this code does not produce the effect that we want. The paragraph element is a block level element that appears on its own line and so the paragraph and the image are shown stacked in the normal document flow.

We can change this behavior by floating our image to the right. The CSS for this is very basic:

 img {
      float: right;
      margin: 20px;
      }

How Exactly the Box Thing Works

The question you should be asking yourself is, “why?” Why wouldn’t increasing the paragraph margin increase the space between the image and the paragraph? The reason is that we’re failing to grasp the box model as it pertains to that paragraph.

If you’re ever doubtful about how your layout is working on a basic level, try applying a border or two to see what’s going on. If we use this technique on the paragraph, the result may surprise you.

   p {
       border: solid 1px black;
     }

As you can see, the image is actually inside of the paragraph’s box! This solves our margin riddle. Any margin that we add to the paragraph is being applied way off to the right of the image, this is why it doesn’t increase the space between the image and the paragraph.

If we wanted the change this behavior so that the paragraph doesn’t wrap around the image, we could float the paragraph to the left and give it a specified width (without expressing the width, the paragraph is 100% wide and won’t fit next to the image).

   img {
     float: right;
     margin: 20px;
     }

  p {
     float: left;
     width: 220px;
     margin: 20px;
     }

Hope You got it...

That's the crazy box thing. :)


问:
Scanner + System.in stop condition
I'm reading a file with Scanner + System.in. My command in Linux looks like:

```<code>cat -A test.txt | java -jar test.jar
</code>```

I'm reading input like:

```<code>Scanner input = new Scanner(System.in);

    while (input.hasNextLine())
    {
        String log_line = input.nextLine();
    }
</code>```

The question is.. How I can stop reading when the end of file is reached?

答:
The problem is that System.in never "ends", i.e. EOF is never sent to the stream, so hasNextLine() after the last line is blocking waiting for more data.

The solution is to pass the file name to your app, than you open FileInputStream(filePath) and use it in Scanner constructor.

Title: Scanner + System.in stop condition

Body:
I'm reading a file with Scanner + System.in. My command in Linux looks like:

cat -A test.txt | java -jar test.jar

I'm reading input like:

Scanner input = new Scanner(System.in);

    while (input.hasNextLine())
    {
        String log_line = input.nextLine();
    }

The question is.. How I can stop reading when the end of file is reached?

ContentLicense: CC BY-SA 2.5


问:
Django Rest Framework remove csrf
I know that there are answers regarding Django Rest Framework, but I couldn't find a solution to my problem.

I have an application which has authentication and some functionality.
I added a new app to it, which uses Django Rest Framework. I want to use the library only in this app. Also I want to make POST request, and I always receive this response:

```<code>{
    "detail": "CSRF Failed: CSRF token missing or incorrect."
}
</code>```

I have the following code:

```<code># urls.py
from django.conf.urls import patterns, url

urlpatterns = patterns(
    'api.views',
    url(r'^object/$', views.Object.as_view()),
)

# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt

class Object(APIView):

    @csrf_exempt
    def post(self, request, format=None):
        return Response({'received data': request.data})
</code>```

I want add the API without affecting the current application.
So my questions is how can I disable CSRF only for this app ?

答:
For all who did not find a helpful answer. Yes DRF automatically removes CSRF protection if you do not use SessionAuthentication AUTHENTICATION CLASS, for example, many developers use only JWT:

```<code>'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
</code>```

But issue CSRF not set may be occurred from some another reason, for exmple you not correctly added path to you view:

```<code>url(r'^api/signup/', CreateUserView),  # <= error! DRF cant remove CSRF because it is not as_view that does it!
</code>```

instead of

```<code>url(r'^api/signup/', CreateUserView.as_view()),
</code>```

Title: Django Rest Framework remove csrf

Body:
I know that there are answers regarding Django Rest Framework, but I couldn't find a solution to my problem.

I have an application which has authentication and some functionality.
I added a new app to it, which uses Django Rest Framework. I want to use the library only in this app. Also I want to make POST request, and I always receive this response:

{
    "detail": "CSRF Failed: CSRF token missing or incorrect."
}

I have the following code:

# urls.py
from django.conf.urls import patterns, url

urlpatterns = patterns(
    'api.views',
    url(r'^object/$', views.Object.as_view()),
)

# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt

class Object(APIView):

    @csrf_exempt
    def post(self, request, format=None):
        return Response({'received data': request.data})

I want add the API without affecting the current application.
So my questions is how can I disable CSRF only for this app ?

Body:
For all who did not find a helpful answer. Yes DRF automatically removes CSRF protection if you do not use SessionAuthentication AUTHENTICATION CLASS, for example, many developers use only JWT:

'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),

But issue CSRF not set may be occurred from some another reason, for exmple you not correctly added path to you view:

url(r'^api/signup/', CreateUserView),  # <= error! DRF cant remove CSRF because it is not as_view that does it!

instead of

url(r'^api/signup/', CreateUserView.as_view()),


问:
Android database creation sql code check
I'm working with my first android SQL database and I have a strong feeling that something is wrong with my database creation sql statement.
What am I missing guys?

```<code>private static final String CREATE_MOVES_TABLE =
    "CREATE TABLE " + TABLE_MOVES + "(" +
         KEY_ID + " INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," +
         DATE + " TEXT,"  +
         TRANSPORT + " TEXT," +
         MARSH + " INTEGER," +
         TIMEHOPON + " TEXT," +
         TIMEHOPOFF + " TEXT" +
    ");";
</code>```

I don't have a field for key_id in my constructor (I feel that it might be the weak part).

答:
There is no need to have KEY_ID passed into your constructor, it should be a constant value.

Also, you are doing a lot of extra work to get an autoincrement on your primary key. You can remove all that generated.. stuff and replace with autoincrement

```<code>class DB {

    private static final String KEY_ID = "id";
    private static final String DATE = "date";
    private static final String TRANSPORT = "transport";
    private static final String MARSH = "marsh";
    private static final String TIMEHOPON = "timehopon";
    private static final String TIMEHOPOFF = "timehopoff";

    private static final String CREATE_MOVES_TABLE =
    "CREATE TABLE " + TABLE_MOVES + "("
        + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        + DATE + " TEXT,"
        + TRANSPORT + " TEXT,"
        + MARSH + " INTEGER,"
        + TIMEHOPON + " TEXT,"
        + TIMEHOPOFF + " TEXT" + ");";

    // the rest of the class...

}
</code>```

Body:
I'm working with my first android SQL database and I have a strong feeling that something is wrong with my database creation sql statement.
What am I missing guys?

private static final String CREATE_MOVES_TABLE =
    "CREATE TABLE " + TABLE_MOVES + "(" +
         KEY_ID + " INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," +
         DATE + " TEXT,"  +
         TRANSPORT + " TEXT," +
         MARSH + " INTEGER," +
         TIMEHOPON + " TEXT," +
         TIMEHOPOFF + " TEXT" +
    ");";

I don't have a field for key_id in my constructor (I feel that it might be the weak part).

Body:
There is no need to have KEY_ID passed into your constructor, it should be a constant value.

Also, you are doing a lot of extra work to get an autoincrement on your primary key. You can remove all that generated.. stuff and replace with autoincrement

class DB {

    private static final String KEY_ID = "id";
    private static final String DATE = "date";
    private static final String TRANSPORT = "transport";
    private static final String MARSH = "marsh";
    private static final String TIMEHOPON = "timehopon";
    private static final String TIMEHOPOFF = "timehopoff";

    private static final String CREATE_MOVES_TABLE =
    "CREATE TABLE " + TABLE_MOVES + "("
        + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        + DATE + " TEXT,"
        + TRANSPORT + " TEXT,"
        + MARSH + " INTEGER,"
        + TIMEHOPON + " TEXT,"
        + TIMEHOPOFF + " TEXT" + ");";

    // the rest of the class...

}


问:
Create dummy variable
I am trying to write a default function which will work for any variable in the dataset and in turns create dummy variable for the same after removing the original variable.

```<code>dummy= function(x){
    xs = union(x,NULL)
    xm = matrix(0, length(x), length(xs))
    for(i in 1:length(x)){
        xm[i,which(xs==x[i])] = 1
    }
    return(xm[,1:length(xs)-1])
}
</code>```

For example, from a dataset, I have a categorical variable called "Married". Now I want to create dummy variables like this
Married Unmarried
1         0
1         0
0         1
0         1
0         1
 Also it should remove the original variable "Married" and add dummy variable to the dataset.

答:
Look into the documentation for the dummy.data.frame function from the dummies package. It allows for flexible use of the model.matrix function.

```<code>library(dummies)
set.seed(20170402)
n <- 5
df <- data.frame(x = rnorm(n),
                 y = rnorm(n, 1),
                 red_herring = as.logical(round(runif(n, 0, 1))))

# Character column
df$red_herring <- dplyr::if_else(df$red_herring == T, 'Yes', 'No', NA_character_)

# Factor column
df$married <- factor(df$red_herring, levels = c('No', 'Yes'))
</code>```

Dummy variables are created for character and factor classes by default:

```<code>dummies::dummy.data.frame(df)
#             x         y red_herringNo red_herringYes marriedNo marriedYes
# 1 -2.49355296 1.6209886             0              1         0          1
# 2  0.06896791 2.6101371             1              0         1          0
# 3 -0.01188042 0.4857511             0              1         0          1
# 4  0.47565318 1.1194925             0              1         0          1
# 5  0.34437239 3.0801658             1              0         1          0
</code>```

You can pass a vector of variables that you want transformed to the names argument:

```<code>dummies::dummy.data.frame(df, names = 'married')
#             x         y red_herring marriedNo marriedYes
# 1 -2.49355296 1.6209886         Yes         0          1
# 2  0.06896791 2.6101371          No         1          0
# 3 -0.01188042 0.4857511         Yes         0          1
# 4  0.47565318 1.1194925         Yes         0          1
# 5  0.34437239 3.0801658          No         1          0
</code>```

Or you can specify what classes of variables you want transformed into dummy variables via dummy.classes:

```<code>dummies::dummy.data.frame(df, dummy.classes = 'factor')
#             x         y red_herring marriedNo marriedYes
# 1 -2.49355296 1.6209886         Yes         0          1
# 2  0.06896791 2.6101371          No         1          0
# 3 -0.01188042 0.4857511         Yes         0          1
# 4  0.47565318 1.1194925         Yes         0          1
# 5  0.34437239 3.0801658          No         1          0
</code>```

Title: Create dummy variable

Body:
I am trying to write a default function which will work for any variable in the dataset and in turns create dummy variable for the same after removing the original variable.

dummy= function(x){
    xs = union(x,NULL)
    xm = matrix(0, length(x), length(xs))
    for(i in 1:length(x)){
        xm[i,which(xs==x[i])] = 1
    }
    return(xm[,1:length(xs)-1])
}

For example, from a dataset, I have a categorical variable called "Married". Now I want to create dummy variables like this
Married Unmarried
1         0
1         0
0         1
0         1
0         1
 Also it should remove the original variable "Married" and add dummy variable to the dataset.

Body:
Look into the documentation for the dummy.data.frame function from the dummies package. It allows for flexible use of the model.matrix function.

library(dummies)
set.seed(20170402)
n <- 5
df <- data.frame(x = rnorm(n),
                 y = rnorm(n, 1),
                 red_herring = as.logical(round(runif(n, 0, 1))))

# Character column
df$red_herring <- dplyr::if_else(df$red_herring == T, 'Yes', 'No', NA_character_)

# Factor column
df$married <- factor(df$red_herring, levels = c('No', 'Yes'))

Dummy variables are created for character and factor classes by default:

dummies::dummy.data.frame(df)
#             x         y red_herringNo red_herringYes marriedNo marriedYes
# 1 -2.49355296 1.6209886             0              1         0          1
# 2  0.06896791 2.6101371             1              0         1          0
# 3 -0.01188042 0.4857511             0              1         0          1
# 4  0.47565318 1.1194925             0              1         0          1
# 5  0.34437239 3.0801658             1              0         1          0

You can pass a vector of variables that you want transformed to the names argument:

dummies::dummy.data.frame(df, names = 'married')
#             x         y red_herring marriedNo marriedYes
# 1 -2.49355296 1.6209886         Yes         0          1
# 2  0.06896791 2.6101371          No         1          0
# 3 -0.01188042 0.4857511         Yes         0          1
# 4  0.47565318 1.1194925         Yes         0          1
# 5  0.34437239 3.0801658          No         1          0

Or you can specify what classes of variables you want transformed into dummy variables via dummy.classes:

dummies::dummy.data.frame(df, dummy.classes = 'factor')
#             x         y red_herring marriedNo marriedYes
# 1 -2.49355296 1.6209886         Yes         0          1
# 2  0.06896791 2.6101371          No         1          0
# 3 -0.01188042 0.4857511         Yes         0          1
# 4  0.47565318 1.1194925         Yes         0          1
# 5  0.34437239 3.0801658          No         1          0


问:
How to use fscanf to reads any character into a string until a tab is reached?
How to use fscanf to reads any character into a string until a tab is reached?

My data file have only 1 row:

```<code>123'\t'(Tab)345'\t'Le Duc Huy'\t'567
</code>```

and i use fscanf like this:

```<code>fscanf(fin,"%d %d %d %[^\t]%s %d",&m,&n,&k,s,&q);
</code>```

it return q with wrong value. Anybody can tell me what made it failed?

答:
Using fscanf(), you will need a negated character class and a length:

```<code>char string[32];

if (fscanf(fp, "%31[^\t]", string) != 1)
    ...error or EOF...
</code>```

The modified version of the question has a data string with a single quote after the final tab, and the single quote cannot be converted to an integer, so the value in q is undefined.  Note that you must check the return value of fscanf() to ensure that all the fields you expected to match actually did match,  In the context, if probably returned the value 4 instead of 5, telling you there was an error.

Body:
How to use fscanf to reads any character into a string until a tab is reached?

My data file have only 1 row:

123'\t'(Tab)345'\t'Le Duc Huy'\t'567

and i use fscanf like this:

fscanf(fin,"%d %d %d %[^\t]%s %d",&m,&n,&k,s,&q);

it return q with wrong value. Anybody can tell me what made it failed?

Body:
Using fscanf(), you will need a negated character class and a length:

char string[32];

if (fscanf(fp, "%31[^\t]", string) != 1)
    ...error or EOF...

The modified version of the question has a data string with a single quote after the final tab, and the single quote cannot be converted to an integer, so the value in q is undefined.  Note that you must check the return value of fscanf() to ensure that all the fields you expected to match actually did match,  In the context, if probably returned the value 4 instead of 5, telling you there was an error.


问:
Javascript / JQuery Sorting out div by text value
I have a list which looks like this:

```<code><div class="list-group">
    <div class="list-group-item">
        <div class="media">
            <span class="label label-success pull-right">10</span>
            <div class="pull-left">
                <img class="media-object img-circle" src="img.jpg" alt="Image">
            </div>
            <div class="media-body">
                <h4 class="media-heading">name here</h4>
            </div>
        </div>
    </div>
    <div class="list-group-item">
        <div class="media">
            <span class="label label-success pull-right">7</span>
            <div class="pull-left">
                <img class="media-object img-circle" src="img.jpg" alt="Image">
            </div>
            <div class="media-body">
                <h4 class="media-heading">name here too</h4>
            </div>
        </div>
    </div>
    <div class="list-group-item">
        <div class="media">
            <span class="label label-success pull-right">3</span>
            <div class="pull-left">
                <img class="media-object img-circle" src="img.jpg" alt="Image">
            </div>
            <div class="media-body">
                <h4 class="media-heading">name here </h4>
            </div>
        </div>
    </div>
</div>
</code>```

There are 3 items in this list as you can see.
There is a  with class label that contain a number, the three of them do.

I need to have a toggle the ordering by these numbers Asc and Desc ...

How can I do this? Would it be easier if I wrapped the list-group-item div's in
 ?

答:
Select the elements in question, .sort() them in the appropriate direction, then append them to their container (where the append operation will move existing elements).

So a little something like this:

$("button").click(function(e) {

  var direction = $(this).data("dir")
  $(this).data("dir", direction * -1)
    .text("Sort (" + (direction == 1 ? "desc" : "asc") + ")")

  $("div.list-group-item").sort(function(a,b) {
    return ($(a).find("span.label").text() - $(b).find("span.label").text()) * direction
  }).appendTo(".list-group")

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.list-group-item div { display: inline-block; }</code>```

<button data-dir="1">Sort (asc)</button>

            10

name here for 10

            7

name here too (7)

            3

name here for 3

```

Note that the - and * operators both coerce their operands to numbers.

Body:
I have a list which looks like this:

            10

name here

            7

name here too

            3

name here

There are 3 items in this list as you can see.
There is a  with class label that contain a number, the three of them do.

I need to have a toggle the ordering by these numbers Asc and Desc ...

How can I do this? Would it be easier if I wrapped the list-group-item div's in
 ?

Body:
Select the elements in question, .sort() them in the appropriate direction, then append them to their container (where the append operation will move existing elements).

So a little something like this:

$("button").click(function(e) {

  var direction = $(this).data("dir")
  $(this).data("dir", direction * -1)
    .text("Sort (" + (direction == 1 ? "desc" : "asc") + ")")

  $("div.list-group-item").sort(function(a,b) {
    return ($(a).find("span.label").text() - $(b).find("span.label").text()) * direction
  }).appendTo(".list-group")

})

div.list-group-item div { display: inline-block; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button data-dir="1">Sort (asc)</button>
<div class="list-group">
    <div class="list-group-item">
        <div class="media">
            <span class="label label-success pull-right">10</span>
            <div class="pull-left">
                <img class="media-object img-circle" src="img.jpg" alt="Image">
            </div>
            <div class="media-body">
                <h4 class="media-heading">name here for 10</h4>
            </div>
        </div>
    </div>
    <div class="list-group-item">
        <div class="media">
            <span class="label label-success pull-right">7</span>
            <div class="pull-left">
                <img class="media-object img-circle" src="img.jpg" alt="Image">
            </div>
            <div class="media-body">
                <h4 class="media-heading">name here too (7)</h4>
            </div>
        </div>
    </div>
    <div class="list-group-item">
        <div class="media">
            <span class="label label-success pull-right">3</span>
            <div class="pull-left">
                <img class="media-object img-circle" src="img.jpg" alt="Image">
            </div>
            <div class="media-body">
                <h4 class="media-heading">name here for 3</h4>
            </div>
        </div>
    </div>
</div>

Note that the - and * operators both coerce their operands to numbers.


问:
import mysql DB from .sql setting default table to MyISAM
I need to convert a MyISAM latin 1 DB into a MyISAM utf8 db

following another question I exported my DB without any encoding specification

```<code>mysqldump -uroot -p --skip-opt --set-charset --skip-set-charset mydb > mydb_utf8.sql
</code>```

changed my DB to default charset utf8

now I need to specify on import that i want MyISAM tables ( default setting is InnoDB )

```<code>mysql -uroot -p --default-character-set=utf8 --default-storage-engine=MyISAM mydb < mydb_utf8.sql
</code>```

--default-storage-engine=MyISAM give me this error "mysql: unknown variable 'default-storage-engine=MyISAM'"

答:
--default-storage-engine looks like its a mysqld startup option not a mysql start option..

Open your SQL file with a text editor and on the top

```<code>SET default_storage_engine=MyISAM;
</code>```

Body:
I need to convert a MyISAM latin 1 DB into a MyISAM utf8 db

following another question I exported my DB without any encoding specification

mysqldump -uroot -p --skip-opt --set-charset --skip-set-charset mydb > mydb_utf8.sql

changed my DB to default charset utf8

now I need to specify on import that i want MyISAM tables ( default setting is InnoDB )

mysql -uroot -p --default-character-set=utf8 --default-storage-engine=MyISAM mydb < mydb_utf8.sql

--default-storage-engine=MyISAM give me this error "mysql: unknown variable 'default-storage-engine=MyISAM'"

Body:
--default-storage-engine looks like its a mysqld startup option not a mysql start option..

Open your SQL file with a text editor and on the top

SET default_storage_engine=MyISAM;


问:
How to get MAC address of connected Access point?
I am using Scapy to sniff access point(AP) beacon packets and also getting all AP beacon packets and it's MAC address nearby AP but I need exact MAC address of connected AP then How to sniff only connected AP beacon frame or How to filter connected AP beacon frame using scapy or any alternate idea.

*I am doing it in python 2.7

答:
I choose alternate method i.e using command in python program

Code snippet

```<code>def Check_connected_ap():
    cmd =["nmcli -f BSSID,ACTIVE dev wifi list | awk '$2 ~ /yes/ {print $1}'"]
    address = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    (out, err) = address.communicate()
    print out
</code>```

Body:
I choose alternate method i.e using command in python program

Code snippet

def Check_connected_ap():
    cmd =["nmcli -f BSSID,ACTIVE dev wifi list | awk '$2 ~ /yes/ {print $1}'"]
    address = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    (out, err) = address.communicate()
    print out


问:
Multiple database connection with same table manes laravel
I have two database having tables with same name.
I am using laravel to connect through this.

Note : I am able to make multiple connections but I am unable to access tables having same name.

Example

Database 1 :

Table: ads

Database 2

Table: ads

How can I make database connection / model for these two different tables having same name , which are in two different databases.

答: refer your tables with db names... for example db1.ads & db2.ads ... hope it helps</p>


问:
Replace empty element in a list using sapply
I have two lists. The first one has an empty element. I'd like to replace that empty element with the first vector of the third list element of another list.

```<code>l1 <- list(a=1:3,b=4:9,c="")
l2 <- list(aa=11:13,bb=14:19,cc=data.frame(matrix(100:103,ncol=2)))

l1[sapply(l1, `[[`, 1)==""] <- l2[[3]][[1]]
</code>```

Using sapply, I can identify which elements are empty. However, when I try to assign a vector to this empty element: I get this error message:

Warning message: In l1[sapply(l1, [[, 1) == ""] <- l2[[3]][[1]] :

  number of items to replace is not a multiple of replacement length

This is only a warning, but the result I get is not the one I want. This is the l1 I get:

```<code>> l1
$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100
</code>```

This is what I need (two elements in $c):

```<code>> l1
$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100 101
</code>```

答:
The right-hand side should be a list, since you're replacing a list element. So you want that to be

```<code>... <- list(l2[[3]][[1]])
</code>```

In addition, you might consider using !nzchar(l1) in place of sapply(...) == "".  It might be more efficient.  The final expression would be:

```<code>l1[!nzchar(l1)] <- list(l2[[3]][[1]])
</code>```

giving the updated l1:

```<code>$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100 101
</code>```

Body:
I have two lists. The first one has an empty element. I'd like to replace that empty element with the first vector of the third list element of another list.

l1 <- list(a=1:3,b=4:9,c="")
l2 <- list(aa=11:13,bb=14:19,cc=data.frame(matrix(100:103,ncol=2)))

l1[sapply(l1, `[[`, 1)==""] <- l2[[3]][[1]]

Using sapply, I can identify which elements are empty. However, when I try to assign a vector to this empty element: I get this error message:

Warning message: In l1[sapply(l1, [[, 1) == ""] <- l2[[3]][[1]] :

  number of items to replace is not a multiple of replacement length

This is only a warning, but the result I get is not the one I want. This is the l1 I get:

> l1
$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100

This is what I need (two elements in $c):

> l1
$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100 101

Body:
The right-hand side should be a list, since you're replacing a list element. So you want that to be

... <- list(l2[[3]][[1]])

In addition, you might consider using !nzchar(l1) in place of sapply(...) == "".  It might be more efficient.  The final expression would be:

l1[!nzchar(l1)] <- list(l2[[3]][[1]])

giving the updated l1:

$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100 101


问:
Distinct in Spring Data MongoDB
Has anyone tried incorporating distinct in their query using Spring Data for Mongo. If you have an example can you please post it. Where and how should I include the distinct flag?

Link to the Spring Data Mongo example -- Example 4.4. Query creation from method names

```<code>// Enables the distinct flag for the query
List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);
</code>```

答:
You can see the differences of the usage of distinct between Spring Data JPA and Spring Data MongoDB here:

```<code>@Before
public void setUp() {

    this.dave = customers.save(new Customer("Dave", "Matthews"));
    this.carter2 = customers.save(new Customer("Carter", "Z"));
    this.carter = customers.save(new Customer("Carter", "Beauford"));
}

@Test
public void distinctProjectsEntityIntoInterface() {

    Collection<CustomerProjection> result = customers.findAllProjectedDistinctBy();

    assertThat(result, hasSize(2));
}
</code>```

distinct in spring data jpa

```<code>@Before
public void setUp() {

    customers.deleteAll();

    this.dave = customers.save(new Customer("Dave", "Matthews"));
    this.carter2 = customers.save(new Customer("Carter", "Z"));
    this.carter = customers.save(new Customer("Carter", "Beauford"));
}

@Test
public void distinctProjectsEntityIntoInterface() {

    Collection<CustomerProjection> result = customers.findAllProjectedDistinctBy();

    assertThat(result, hasSize(3));
}
</code>```

distinct in spring data mongodb

where

```<code>interface CustomerProjection {

    String getFirstname();
}
</code>```

Title: Distinct in Spring Data MongoDB

Body:
Has anyone tried incorporating distinct in their query using Spring Data for Mongo. If you have an example can you please post it. Where and how should I include the distinct flag?

Link to the Spring Data Mongo example -- Example 4.4. Query creation from method names

// Enables the distinct flag for the query
List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);

Body:
You can see the differences of the usage of distinct between Spring Data JPA and Spring Data MongoDB here:

@Before
public void setUp() {

    this.dave = customers.save(new Customer("Dave", "Matthews"));
    this.carter2 = customers.save(new Customer("Carter", "Z"));
    this.carter = customers.save(new Customer("Carter", "Beauford"));
}

@Test
public void distinctProjectsEntityIntoInterface() {

    Collection<CustomerProjection> result = customers.findAllProjectedDistinctBy();

    assertThat(result, hasSize(2));
}

distinct in spring data jpa

@Before
public void setUp() {

    customers.deleteAll();

    this.dave = customers.save(new Customer("Dave", "Matthews"));
    this.carter2 = customers.save(new Customer("Carter", "Z"));
    this.carter = customers.save(new Customer("Carter", "Beauford"));
}

@Test
public void distinctProjectsEntityIntoInterface() {

    Collection<CustomerProjection> result = customers.findAllProjectedDistinctBy();

    assertThat(result, hasSize(3));
}

distinct in spring data mongodb

where

interface CustomerProjection {

    String getFirstname();
}


问:
How to add libcurl in clion
After install
sudo apt-get install libcurl4-openssl-dev

i trying to add curl in cmake of clion,but i can't understand how make this.
this my standart cmake file

```<code>cmake_minimum_required(VERSION 3.6)
project(untitled3)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

add_executable(untitled3 ${SOURCE_FILES})
</code>```

答:
This should be able to help you.</p>
```<code>cmake_minimum_required(VERSION 3.3)
project(untitled3)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -lcurl")

set(SOURCE_FILES main.cpp)
add_executable(untitled3 ${SOURCE_FILES})
target_link_libraries(untitled3 curl)
</code>```

Title: How to add libcurl in clion

Body:
After install
sudo apt-get install libcurl4-openssl-dev

i trying to add curl in cmake of clion,but i can't understand how make this.
this my standart cmake file

cmake_minimum_required(VERSION 3.6)
project(untitled3)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

add_executable(untitled3 ${SOURCE_FILES})

Body:
This should be able to help you.

cmake_minimum_required(VERSION 3.3)
project(untitled3)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -lcurl")

set(SOURCE_FILES main.cpp)
add_executable(untitled3 ${SOURCE_FILES})
target_link_libraries(untitled3 curl)

ContentLicense: CC BY-SA 4.0


问:
OpenCV in Python: "ImportError: DLL load failed"
So many questions already about this topic, but I didn't find any satisfying answer about the "DLL not found" traditional issue.

I'm using Python 3.5 installed via Anaconda 3;

I have installed with pip the 'official' opencv_python-3.2.0.6-cp34-cp34m-win_amd64.whl (right from here https://pypi.python.org/pypi/opencv-python);

Windows version is 7 - 64 bits;

I have uninstalled all the redistributable VC++ that were present on my machine and reinstalled its 2015 version - so the famous as well as mandatory DLL msvcp140.dll is present on my laptop;

the cv2 module is present in the Lib/site-packages directory;

it contains, among others, file 'cv2.cp35-win_amd64.pyd'.

Meanwhile, I still can't get access to cv2:

```<code>>>> import cv2
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import cv2
  File "C:\Program Files\Anaconda3\lib\site-packages\cv2\__init__.py", line 7, in <module>
    from . import cv2
ImportError: DLL load failed: The specified module could not be found.
</code>```

Modifying the name of the .pyd --> cv2.pyd does not solve the problem, nor does the installing via pip of the unofficial but great wheel version from Gohlke (http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv)

Any idea about what is going on?

答:
As mentioned in the comment which I didn't notice at first, you can resolve this by installing from the unofficial site (Gohlke)
(http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv)

I uninstalled the official one by calling:

```<code>pip uninstall opencv-python
</code>```

And then downloaded the .whl package from the mentioned site (you need to carefully choose the correct python version and the correct processor architecture x86 or x64).

And then, go to the path where the .whl file is downloaded and call:

```<code>pip install opencv_python-x.x.x-cpxx-cpxxm-win_xx.whl
</code>```

Body:
So many questions already about this topic, but I didn't find any satisfying answer about the "DLL not found" traditional issue.

I'm using Python 3.5 installed via Anaconda 3;

I have installed with pip the 'official' opencv_python-3.2.0.6-cp34-cp34m-win_amd64.whl (right from here https://pypi.python.org/pypi/opencv-python);

Windows version is 7 - 64 bits;

I have uninstalled all the redistributable VC++ that were present on my machine and reinstalled its 2015 version - so the famous as well as mandatory DLL msvcp140.dll is present on my laptop;

the cv2 module is present in the Lib/site-packages directory;

it contains, among others, file 'cv2.cp35-win_amd64.pyd'.

Meanwhile, I still can't get access to cv2:

>>> import cv2
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import cv2
  File "C:\Program Files\Anaconda3\lib\site-packages\cv2\__init__.py", line 7, in <module>
    from . import cv2
ImportError: DLL load failed: The specified module could not be found.

Modifying the name of the .pyd --> cv2.pyd does not solve the problem, nor does the installing via pip of the unofficial but great wheel version from Gohlke (http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv)

Any idea about what is going on?

Body:
As mentioned in the comment which I didn't notice at first, you can resolve this by installing from the unofficial site (Gohlke)
(http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv)

I uninstalled the official one by calling:

pip uninstall opencv-python

And then downloaded the .whl package from the mentioned site (you need to carefully choose the correct python version and the correct processor architecture x86 or x64).

And then, go to the path where the .whl file is downloaded and call:

pip install opencv_python-x.x.x-cpxx-cpxxm-win_xx.whl


问:
How to attach ngrx/store with an angular router guard
I'm a beginner with ngrx/store and this is my first project using it.

I have successfully set up my angular project with ngrx/store and I'm able to dispatch a load action after initializing my main component like this:

ngOnInit() { this.store.dispatch({type: LOAD_STATISTICS}); }

I have set up an effect to load the data when this action is dispatched:

```<code>@Effect()
loadStatistic = this.actions.ofType(LOAD_STATISTICS).switchMap(() => {
    return this.myService.loadStatistics().map(response => {
        return {type: NEW_STATISTICS, payload: response};
    });
});
</code>```

My reducer looks like this:

```<code>reduce(oldstate: Statistics = initialStatistics, action: Action): Statistic {
    switch (action.type) {
        case LOAD_STATISTICS:
            return oldstate;
        case NEW_STATISTICS:
            const newstate = new Statistics(action.payload);

            return newstate;
    ....
</code>```

Although this works, I can't get my head around how to use this with a router guard as I currently need to dispatch the LOAD_ACTION only once.

Also, that a component has to dispatch a LOAD action, to load initial data doesn't sound right to me. I'd expect that the store itself knows that it needs to load data and I don't have to dispatch an action first. If this were the case, I could delete the ngOnInit() method in my component.

I already have looked into the ngrx-example-app but I haven't understood really how this works.

EDIT:

After adding a resolve guard that returns the ngrx-store observable the route does not get activated. Here is the resolve:

```<code>   @Injectable()
  export class StatisticsResolver implements Resolve<Statistic> {
    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Statistic> {
        // return Observable.of(new Statistic());
        return this.store.select("statistic").map(statistic => {
        console.log("stats", statistic);

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

This is the route:

```<code>const routes: Routes = [
    {path: '', component: TelefonanlageComponent, resolve: {statistic:  TelefonieStatisticResolver}},
];
</code>```

答:
I don't quite understand why you would send the resolved data to your component through the resolver. The whole point of setting up a ngrx store is to have a single source of data. So, what you simply want to do here, is make sure that the data is true. Rest, the component can get the data from the store using a selector.

I can see that you are calling LOAD_ACTION from the ngOnInit method of your component. You cannot call an action to resolve data, which then leads to the component, on Init of which you call the action! This is why your router isn't loading the route.

Not sure if you understood that, but it makes sense!

In simple terms, what you are doing is this. You are locking a room and then pushing the key through the gap beneath the door, and then wondering why the door isn't opening.

Keep the key with you!

The guard's resolve method should call the LOAD_ACTION. Then the resolve should wait for the data to load, and then the router should proceed to the component.

How do you do that?

The other answers are setting up subscriptions, but the thing is you don't want to do that in your guards. It's not good practice to subscribe in guards, as they will then need to be unsubscribed, but if the data isn't resolved, or the guards return false, then the router never gets to unsubscribe and we have a mess.

So, use take(n). This operator will take n values from the subscription, and then automatically kill the subscription.

Also, in your actions, you will need LOAD_STATISTICS_SUCCESS and a LOAD_STATISTICS_FAIL. As your service method can fail!

In the reducer State, you would need a loaded property, which turns to true when the service call is successful and LOAD_STATISTICS_SUCCESS action is called.

Add a selector in the main reducer, getStatisticsLoaded and then in your gaurd, your setup would look like this:

```<code>resolve(): Observable<boolean> {

this.store.dispatch({type: LOAD_STATISTICS});

return this.store.select(getStatisticsLoaded)
    .filter(loaded => loaded)
    .take(1);
</code>```

}

So, only when the loaded property changes to true, filter will allow the stream to continue. take will take the first value and pass along. At which point the resolve completes, and the router can proceed.

Again, take will kill the subscription.

Body:
I'm a beginner with ngrx/store and this is my first project using it.

I have successfully set up my angular project with ngrx/store and I'm able to dispatch a load action after initializing my main component like this:

ngOnInit() { this.store.dispatch({type: LOAD_STATISTICS}); }

I have set up an effect to load the data when this action is dispatched:

@Effect()
loadStatistic = this.actions.ofType(LOAD_STATISTICS).switchMap(() => {
    return this.myService.loadStatistics().map(response => {
        return {type: NEW_STATISTICS, payload: response};
    });
});

My reducer looks like this:

reduce(oldstate: Statistics = initialStatistics, action: Action): Statistic {
    switch (action.type) {
        case LOAD_STATISTICS:
            return oldstate;
        case NEW_STATISTICS:
            const newstate = new Statistics(action.payload);

            return newstate;
    ....

Although this works, I can't get my head around how to use this with a router guard as I currently need to dispatch the LOAD_ACTION only once.

Also, that a component has to dispatch a LOAD action, to load initial data doesn't sound right to me. I'd expect that the store itself knows that it needs to load data and I don't have to dispatch an action first. If this were the case, I could delete the ngOnInit() method in my component.

I already have looked into the ngrx-example-app but I haven't understood really how this works.

EDIT:

After adding a resolve guard that returns the ngrx-store observable the route does not get activated. Here is the resolve:

   @Injectable()
  export class StatisticsResolver implements Resolve<Statistic> {
    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Statistic> {
        // return Observable.of(new Statistic());
        return this.store.select("statistic").map(statistic => {
        console.log("stats", statistic);

        return statistic;
    });
}

This is the route:

const routes: Routes = [
    {path: '', component: TelefonanlageComponent, resolve: {statistic:  TelefonieStatisticResolver}},
];

Body:
I don't quite understand why you would send the resolved data to your component through the resolver. The whole point of setting up a ngrx store is to have a single source of data. So, what you simply want to do here, is make sure that the data is true. Rest, the component can get the data from the store using a selector.

I can see that you are calling LOAD_ACTION from the ngOnInit method of your component. You cannot call an action to resolve data, which then leads to the component, on Init of which you call the action! This is why your router isn't loading the route.

Not sure if you understood that, but it makes sense!

In simple terms, what you are doing is this. You are locking a room and then pushing the key through the gap beneath the door, and then wondering why the door isn't opening.

Keep the key with you!

The guard's resolve method should call the LOAD_ACTION. Then the resolve should wait for the data to load, and then the router should proceed to the component.

How do you do that?

The other answers are setting up subscriptions, but the thing is you don't want to do that in your guards. It's not good practice to subscribe in guards, as they will then need to be unsubscribed, but if the data isn't resolved, or the guards return false, then the router never gets to unsubscribe and we have a mess.

So, use take(n). This operator will take n values from the subscription, and then automatically kill the subscription.

Also, in your actions, you will need LOAD_STATISTICS_SUCCESS and a LOAD_STATISTICS_FAIL. As your service method can fail!

In the reducer State, you would need a loaded property, which turns to true when the service call is successful and LOAD_STATISTICS_SUCCESS action is called.

Add a selector in the main reducer, getStatisticsLoaded and then in your gaurd, your setup would look like this:

resolve(): Observable<boolean> {

this.store.dispatch({type: LOAD_STATISTICS});

return this.store.select(getStatisticsLoaded)
    .filter(loaded => loaded)
    .take(1);

}

So, only when the loaded property changes to true, filter will allow the stream to continue. take will take the first value and pass along. At which point the resolve completes, and the router can proceed.

Again, take will kill the subscription.


问:
Javascript import function syntax
I am trying to import a function from another module but on running am getting an error:

```<code>TypeError: _this.getData is not a function.
</code>```

data.js

```<code>function getData() {
  return [
    { id: 1,
      name: 'Pluto',
      type: 'Dwarf Planet'
    },
    { id: 2,
      name: 'Neptune',
      type: 'Planet'
    }
  ]
}
export { getData }
</code>```

worker.js

```<code>import getData from data.js

this.data = this.getData()
</code>```

Then on run I get the browser error as mentioned above. Any ideas as to what I am doing incorrectly?

答:
That should be

```<code>import { getData } from data.js
</code>```

Without the brackets, you're importing the default export which doesn't exist.

Title: Javascript import function syntax

Body:
I am trying to import a function from another module but on running am getting an error:

TypeError: _this.getData is not a function.

data.js

function getData() {
  return [
    { id: 1,
      name: 'Pluto',
      type: 'Dwarf Planet'
    },
    { id: 2,
      name: 'Neptune',
      type: 'Planet'
    }
  ]
}
export { getData }

worker.js

import getData from data.js

this.data = this.getData()

Then on run I get the browser error as mentioned above. Any ideas as to what I am doing incorrectly?

Body:
That should be

import { getData } from data.js

Without the brackets, you're importing the default export which doesn't exist.


答:
Change your import as a named import like this:

```<code>import { getData } from data.js
</code>```

Or export getData function as a default export like this:

```<code>export default { getData }
</code>```

Title: Javascript import function syntax

Body:
Change your import as a named import like this:

import { getData } from data.js

Or export getData function as a default export like this:

export default { getData }


问:
What would be the best way in scala to convert between case classes?
I have a model class im getting back from an api inside my servcie, and when I return it to some client I want to use my own model to keep it simpler and cleaner for the client.

example :

```<code>case class ReturnedModel(succeed: Option[String], reason: Reason, transactionId: List[Int], opId: Option[Int])

case class MyReturnedModel(reason: String)
</code>```

I might need to do more of those in the future so I thought maybe there is a best practice to do it that I dont know of, thanks!

答:
You can use a companion object with a custom "apply" method:

```<code>case class MyReturnedModel(reason: String)

object MyReturnedModel {
  def apply(mod: ReturnedModel) = MyReturnedModel(mod.reason.toString)
}

val data: ReturnedModel = ... // Some instance of ReturnedModel
val mr = MyReturnModel(data)
</code>```

Just note that the case class and its companion object need to be in the same file for this to work.

Body:
I have a model class im getting back from an api inside my servcie, and when I return it to some client I want to use my own model to keep it simpler and cleaner for the client.

example :

case class ReturnedModel(succeed: Option[String], reason: Reason, transactionId: List[Int], opId: Option[Int])

case class MyReturnedModel(reason: String)

I might need to do more of those in the future so I thought maybe there is a best practice to do it that I dont know of, thanks!

Body:
You can use a companion object with a custom "apply" method:

case class MyReturnedModel(reason: String)

object MyReturnedModel {
  def apply(mod: ReturnedModel) = MyReturnedModel(mod.reason.toString)
}

val data: ReturnedModel = ... // Some instance of ReturnedModel
val mr = MyReturnModel(data)

Just note that the case class and its companion object need to be in the same file for this to work.


问:
Why an object is invisible?
I have a class. In this class I declare a a private variable private Agent agent;. In my class I have

```<code>private Thread controller = new Thread() {
...
}
</code>```

Within the above private thread I call getParameter which is a private method of the considered class. Within the getParameter I call one of the methods of the agent. As a result I get a NullPointerException. So, I conclude that agent is not visible from the getParameter.

Why is that? Can it be that the reason of that is that the getParameter is within the private Thread? And, if it is the case, how the described problem can be resolved?

ADDED

I realized that I need to be more specific. My code is organized like that:

```<code>public class GameWindow {
   ...
   private Agent agent;
   ...
   private Thread controller = new Thread() {
        public void run() {
           ...
           Agent agent = new Agent();
           ...
           parameter = getParameter();
        }
  }
  ...
  private String getParameter() {
     ...
     agent.someMethod();
     ...
  }
}
</code>```

ADDED 2
In the GameWindow I have:

```<code>public void startWindow() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            controller.start();
        }
    });
}
</code>```

答:
You appear to be creating this new thread in an instance initializer. Which means that the containing instance may not be fully initialized when the thread starts running (you don't show where you call start()).

And some unasked-for advice: (1) don't subclass thread, create a Runnable, and (2) don't create your own threads, use an ExecutorService

Title: Why an object is invisible?

Body:
I have a class. In this class I declare a a private variable private Agent agent;. In my class I have

private Thread controller = new Thread() {
...
}

Within the above private thread I call getParameter which is a private method of the considered class. Within the getParameter I call one of the methods of the agent. As a result I get a NullPointerException. So, I conclude that agent is not visible from the getParameter.

Why is that? Can it be that the reason of that is that the getParameter is within the private Thread? And, if it is the case, how the described problem can be resolved?

ADDED

I realized that I need to be more specific. My code is organized like that:

public class GameWindow {
   ...
   private Agent agent;
   ...
   private Thread controller = new Thread() {
        public void run() {
           ...
           Agent agent = new Agent();
           ...
           parameter = getParameter();
        }
  }
  ...
  private String getParameter() {
     ...
     agent.someMethod();
     ...
  }
}

ADDED 2
In the GameWindow I have:

public void startWindow() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            controller.start();
        }
    });
}


问:
Sum of primes below 2 million
What am i doing wrong here?

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

    int main(){
        int i,count;
        long long int sum = 0, num;

        for(num = 1; num <= 1000; num++){
            count = 0;
            for(i = 2; i <= num / 2; i++){
                if(num % i == 0){
                    count++;
                    break;
                }
            }
            if(count == 0 && num != 1)
                sum = sum + num;
        }
        printf("Sum of prime numbers is: %d ", sum);
        return 0;
    }
</code>```

I tried to make a program that outputs the sum of all primes below nth number, n being 2 million however when i try to run it, there is a slight delay and it outputs nothing... it works well enough  for small numbers like 1000 or 100 but big numbers it just does not output anything.There are no error or bugs that i know of either. (please help, i know nothing, so guide this young one)

答:
The above program is fine, but it is possible to further reduce the time complexity and make it faster.
 The better approach is to use sieve of eratosthenes algorithm.
You can read about it here http://www.geeksforgeeks.org/sieve-of-eratosthenes/

The program for your problem is

```<code>#include <bits/stdc++.h>
using namespace std;

void SieveOfEratosthenes(long long int n)
{

    bool prime[n+1];
    memset(prime, true, sizeof(prime));

    for (long long int p=2; p*p<=n; p++)
    {
        if (prime[p] == true)
        {
                 for (int i=p*2; i<=n; i += p)
                prime[i] = false;
        }
    }

 long long sum=0;
        for (int p=2; p<=n; p++)
       if (prime[p])
          sum+=p;
          cout << sum << " ";
}

int main()
{
    int n = 2000000;
    cout << "sum of prime numbers less then 2000000 is :" << endl;
    SieveOfEratosthenes(n);
    return 0;
}
</code>```

Please let me know if you face difficulty in understanding the program.

Note: You can also use Segmented seive to further reduce the time complexity

Title: Sum of primes below 2 million

Body:
What am i doing wrong here?

  #include<stdio.h>

    int main(){
        int i,count;
        long long int sum = 0, num;

        for(num = 1; num <= 1000; num++){
            count = 0;
            for(i = 2; i <= num / 2; i++){
                if(num % i == 0){
                    count++;
                    break;
                }
            }
            if(count == 0 && num != 1)
                sum = sum + num;
        }
        printf("Sum of prime numbers is: %d ", sum);
        return 0;
    }

I tried to make a program that outputs the sum of all primes below nth number, n being 2 million however when i try to run it, there is a slight delay and it outputs nothing... it works well enough  for small numbers like 1000 or 100 but big numbers it just does not output anything.There are no error or bugs that i know of either. (please help, i know nothing, so guide this young one)

Body:
The above program is fine, but it is possible to further reduce the time complexity and make it faster.
 The better approach is to use sieve of eratosthenes algorithm.
You can read about it here http://www.geeksforgeeks.org/sieve-of-eratosthenes/

The program for your problem is

#include <bits/stdc++.h>
using namespace std;

void SieveOfEratosthenes(long long int n)
{

    bool prime[n+1];
    memset(prime, true, sizeof(prime));

    for (long long int p=2; p*p<=n; p++)
    {
        if (prime[p] == true)
        {
                 for (int i=p*2; i<=n; i += p)
                prime[i] = false;
        }
    }

 long long sum=0;
        for (int p=2; p<=n; p++)
       if (prime[p])
          sum+=p;
          cout << sum << " ";
}

int main()
{
    int n = 2000000;
    cout << "sum of prime numbers less then 2000000 is :" << endl;
    SieveOfEratosthenes(n);
    return 0;
}

Please let me know if you face difficulty in understanding the program.

Note: You can also use Segmented seive to further reduce the time complexity


问:
How to view php logs information with php docker container?
I have a php-fpm docker container .  Php-fpm is run inside container, can i get php-fpm's log on host machine?  If i can,  how to do?</p>

答:
The common approach is that applications inside a container don't log to a file, but output logs on stdout / stderr. Anything that's printed to stdout / stderr by the container's main process is collected by the built-in logging facilities of docker, and can be viewed using docker logs <container-name>.

By default, the logs are stored per-container using the json-file logging driver, and will be deleted when the container itself is deleted, but there are other logging drivers available (see Configure logging drivers) that allow you to send those logs to (e.g.) syslog, journald, gelf.

Also see

View a container's logs

docker logs


问:
Adding Markers in Maps during app is running unsuccessful
I have been trying to implement markers in my google maps activity while the application runs. There are some pre-defined "Location" objects, and there is a marker at the "current location" of the user.

Using a SeekBar, I'm trying to change the range of the current location in which the markers of the location objects should be displayed, but on changing the SeekBar, nothing happens (no markers get added, there's just one at the current location). Apologies for the unwanted extra code, I believe the most important parts to look at are onConnected(), onSeekBarChangedListener() and onMapReady()

This is my MapsActivity.java:

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.
OnConnectionFailedListener, OnSeekBarChangeListener {

    private GoogleApiClient googleApiClient;
    private SeekBar rangeSeekBar;
    private GoogleMap mMap;
    private Intent intent;
    private Location currentLocation;
    private Location[] locations;
    private double range;

    Location locationOne;
    Location locationTwo;
    Location locationThree;
    Location locationFour;
    Location locationFive;
    Location locationSix;
    Location locationSeven;

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

        locationOne = new Location("");
        locationTwo = new Location("");
        locationThree = new Location("");
        locationFour = new Location("");
        locationFive = new Location("");
        locationSix = new Location("");
        locationSeven = new Location("");

        locationOne.setLatitude(10.1399);
        locationOne.setLongitude(76.1784);

        locationTwo.setLatitude(10.2244);
        locationTwo.setLongitude(76.1978);

        locationThree.setLatitude(9.6175);
        locationThree.setLongitude(76.4301);

        locationFour.setLatitude(9.5987);
        locationFour.setLongitude(76.3116);

        locationFive.setLatitude(9.6175);
        locationFive.setLongitude(76.4301);

        locationSix.setLatitude(9.6737);
        locationSix.setLongitude(76.5610);

        locationSeven.setLatitude(15.5152);
        locationSeven.setLongitude(73.8565);

        locations = new Location[]{
            locationOne,
            locationTwo,
            locationThree,
            locationFour,
            locationFive,
            locationSix,
            locationSeven
        };

        rangeSeekBar = (SeekBar)findViewById(R.id.rangeSeekBar);
        rangeSeekBar.setProgress(0);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        googleApiClient.disconnect();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng india = new LatLng(20.5937, 78.9629);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(india, 5));

        if(googleApiClient==null){
            googleApiClient  = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        }

        googleApiClient.connect();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        if(ContextCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MapsActivity.this,new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},1);
        } else {
            currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

            LatLng currentLoc = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
            mMap.addMarker(new MarkerOptions().position(currentLoc).title("Your current location"));
        }

        addingMarkersInRange(0);
    }

    public void addingMarkersInRange(double range){
        for(int i=0;i<locations.length;i++){
            if(currentLocation.distanceTo(locations[i])<range) {
                LatLng tempLatLng = new LatLng(locations[i].getLatitude(), locations[i].getLongitude());
                mMap.addMarker(new MarkerOptions().position(tempLatLng));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(tempLatLng));
            }
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        addingMarkersInRange(rangeSeekBar.getProgress()*700000);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
}
</code>```

答:
Your addinMarkersInRange() method is only adding markers for LatLngs in locations array. So, you need to add to locations array before invoking addingMarkersInRange. But, since you cannot add to an array, please change locations to a List and you should be good to go.

You are not setting listener on SeekBar object. Please set OnSeekBarChangeListener like so in your onCreate():

```<code>// code you already have
rangeSeekBar = (SeekBar)findViewById(R.id.rangeSeekBar);
rangeSeekBar.setProgress(0);

// register event listener here
rangeSeekBar.setOnSeekBarChangeListener(this);
</code>```

Body:
I have been trying to implement markers in my google maps activity while the application runs. There are some pre-defined "Location" objects, and there is a marker at the "current location" of the user.

Using a SeekBar, I'm trying to change the range of the current location in which the markers of the location objects should be displayed, but on changing the SeekBar, nothing happens (no markers get added, there's just one at the current location). Apologies for the unwanted extra code, I believe the most important parts to look at are onConnected(), onSeekBarChangedListener() and onMapReady()

This is my MapsActivity.java:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.
OnConnectionFailedListener, OnSeekBarChangeListener {

    private GoogleApiClient googleApiClient;
    private SeekBar rangeSeekBar;
    private GoogleMap mMap;
    private Intent intent;
    private Location currentLocation;
    private Location[] locations;
    private double range;

    Location locationOne;
    Location locationTwo;
    Location locationThree;
    Location locationFour;
    Location locationFive;
    Location locationSix;
    Location locationSeven;

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

        locationOne = new Location("");
        locationTwo = new Location("");
        locationThree = new Location("");
        locationFour = new Location("");
        locationFive = new Location("");
        locationSix = new Location("");
        locationSeven = new Location("");

        locationOne.setLatitude(10.1399);
        locationOne.setLongitude(76.1784);

        locationTwo.setLatitude(10.2244);
        locationTwo.setLongitude(76.1978);

        locationThree.setLatitude(9.6175);
        locationThree.setLongitude(76.4301);

        locationFour.setLatitude(9.5987);
        locationFour.setLongitude(76.3116);

        locationFive.setLatitude(9.6175);
        locationFive.setLongitude(76.4301);

        locationSix.setLatitude(9.6737);
        locationSix.setLongitude(76.5610);

        locationSeven.setLatitude(15.5152);
        locationSeven.setLongitude(73.8565);

        locations = new Location[]{
            locationOne,
            locationTwo,
            locationThree,
            locationFour,
            locationFive,
            locationSix,
            locationSeven
        };

        rangeSeekBar = (SeekBar)findViewById(R.id.rangeSeekBar);
        rangeSeekBar.setProgress(0);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        googleApiClient.disconnect();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng india = new LatLng(20.5937, 78.9629);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(india, 5));

        if(googleApiClient==null){
            googleApiClient  = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        }

        googleApiClient.connect();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        if(ContextCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MapsActivity.this,new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},1);
        } else {
            currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

            LatLng currentLoc = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
            mMap.addMarker(new MarkerOptions().position(currentLoc).title("Your current location"));
        }

        addingMarkersInRange(0);
    }

    public void addingMarkersInRange(double range){
        for(int i=0;i<locations.length;i++){
            if(currentLocation.distanceTo(locations[i])<range) {
                LatLng tempLatLng = new LatLng(locations[i].getLatitude(), locations[i].getLongitude());
                mMap.addMarker(new MarkerOptions().position(tempLatLng));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(tempLatLng));
            }
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        addingMarkersInRange(rangeSeekBar.getProgress()*700000);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
}

Body:
Your addinMarkersInRange() method is only adding markers for LatLngs in locations array. So, you need to add to locations array before invoking addingMarkersInRange. But, since you cannot add to an array, please change locations to a List and you should be good to go.

You are not setting listener on SeekBar object. Please set OnSeekBarChangeListener like so in your onCreate():

// code you already have
rangeSeekBar = (SeekBar)findViewById(R.id.rangeSeekBar);
rangeSeekBar.setProgress(0);

// register event listener here
rangeSeekBar.setOnSeekBarChangeListener(this);


问:
Unable to set location on PowerShell Script which runs from Automata (Ayehu eyeShare tool)

Script i am trying to run from Ayehu eyeShare:

Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"

Set-Location "LB2:"

Dir

and out put i am getting is local system C drive files listed not from "LB2:"

LB2: is our site location for SCCM
nor i am execute any command of configuration manager because the command do not run from LB2 drive , its by default takes C

Note: if i run direct from windows PowerShell its works fine but not from Automate tool.

答:
The Account which uses to run the script should have read access to the site

try running it from an account which has access to the site.

Regards,

Kvprasoon


问:
Xamarin Forms in Visual Studio 2017 XAML validation
I am really new to Xamarin.Forms and trying to learn using this nice tutorial.

I have managed to set up everything in Visual Studio 2017 Community Edition and successfully deploy to both emulated and physical devices (Android only).

During various trials, I have noticed that some XAML errors are not highlighted and build is successfully performed, but XAML failed at runtime, crashing the app. E.g. misspell a style name or any an attribute value.

Running in debug mode will just hang the app. Breaking it indicates the following line:

```<code>public partial class MainPage : global::Xamarin.Forms.ContentPage {  [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
    private void InitializeComponent() {
        // this is the last line from my code that hands when XAML is invalid
        this.LoadFromXaml(typeof(MainPage));
    }
}
</code>```

Resuming the execution shows a hint of what is wrong (no fancy details as provided by the new VS2017 exception interface):

Unhandled Exception:

Xamarin.Forms.Xaml.XamlParseException:  occurred

Question: Is there a way to catch invalid XAML errors earlier? Or at least obtain more relevant information? Or is this a known limitation of Xamarin.Forms?

To make things worse, autocomplete for attribute values does not seem to work in VS2017 (it works in VS2015), but this is another issue for another question.

Further details about installed software:

```<code>Microsoft Visual Studio Community 2017
Version 15.0.26228.9 D15RTWSVC
Microsoft .NET Framework
Version 4.6.01586

Installed Version: Community

Xamarin   4.3.0.795 (aece090)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin.Android SDK   7.1.0.41 (9578cdc)
Xamarin.Android Reference Assemblies and MSBuild support.

Xamarin.iOS and Xamarin.Mac SDK   10.4.0.123 (35d1ccd)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.
</code>```

答:
To catch XAML errors at compilation time you have to add one line to AssemblyInfo.cs :

```<code>[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
</code>```

More information on this can be found here.

Unfortunately Xamarin.Forms XAML intellisense support in VS is not like for WPF or SilverLight, it's very limited currently. One suggestion can be to write your ui in code, this way you will get a feedback faster and if you are very new to Xamarin.Forms XAML you can  get familiar with it much easier because of intellisense in code behind.

Another option is to use IDE extensions, in your case as I understand it is VS 2017 for Windows so it will not help you, but for Xamarin Studio for MC you have tools like mfractor, that build to solve the issues you addressed.

Body:
I am really new to Xamarin.Forms and trying to learn using this nice tutorial.

I have managed to set up everything in Visual Studio 2017 Community Edition and successfully deploy to both emulated and physical devices (Android only).

During various trials, I have noticed that some XAML errors are not highlighted and build is successfully performed, but XAML failed at runtime, crashing the app. E.g. misspell a style name or any an attribute value.

Running in debug mode will just hang the app. Breaking it indicates the following line:

public partial class MainPage : global::Xamarin.Forms.ContentPage {  [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
    private void InitializeComponent() {
        // this is the last line from my code that hands when XAML is invalid
        this.LoadFromXaml(typeof(MainPage));
    }
}

Resuming the execution shows a hint of what is wrong (no fancy details as provided by the new VS2017 exception interface):

Unhandled Exception:

Xamarin.Forms.Xaml.XamlParseException:  occurred

Question: Is there a way to catch invalid XAML errors earlier? Or at least obtain more relevant information? Or is this a known limitation of Xamarin.Forms?

To make things worse, autocomplete for attribute values does not seem to work in VS2017 (it works in VS2015), but this is another issue for another question.

Further details about installed software:

Microsoft Visual Studio Community 2017
Version 15.0.26228.9 D15RTWSVC
Microsoft .NET Framework
Version 4.6.01586

Installed Version: Community

Xamarin   4.3.0.795 (aece090)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin.Android SDK   7.1.0.41 (9578cdc)
Xamarin.Android Reference Assemblies and MSBuild support.

Xamarin.iOS and Xamarin.Mac SDK   10.4.0.123 (35d1ccd)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

Body:
To catch XAML errors at compilation time you have to add one line to AssemblyInfo.cs :

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]

More information on this can be found here.

Unfortunately Xamarin.Forms XAML intellisense support in VS is not like for WPF or SilverLight, it's very limited currently. One suggestion can be to write your ui in code, this way you will get a feedback faster and if you are very new to Xamarin.Forms XAML you can  get familiar with it much easier because of intellisense in code behind.

Another option is to use IDE extensions, in your case as I understand it is VS 2017 for Windows so it will not help you, but for Xamarin Studio for MC you have tools like mfractor, that build to solve the issues you addressed.


问:
How to positioning divs float left but also to top

How to make Divs inside div float left with no spaces; As you can see on the image have spaces, i am using these codes;

```<code>main {position:relative;left:339.5px;top:40px;width:1018px;height:1000px;-webkit-box-shadow:inset 0px 0px 40px;}

main div {float:left;margin:1px;-webkit-box-shadow:inset 0px 0px 20px;}
#div_size1 {width:336px;height:200px;}
#div_size2 {width:336px;height:300px;}
#div_size3 {width:336px;height:100px;}

<main>
<div id="div_size1">
</div>
<div id="div_size2">
</div>
<div id="div_size3">
</div>
<div id="div_size3">
</div>
<div id="div_size3">
</div>
<div id="div_size2">
</div>
<div id="div_size2">
</div>
<div id="div_size1">
</div>
<div id="div_size2">
</div>
<div id="div_size3">
</div>
<div id="div_size3">
</div>
</main>
</code>```

答:
If you post the HTML as well I can help more. But it looks like you don't have any floats on the divs you want to float. </p>

```<code>#div_size1 {float:left;width:336px;height:200px;}
#div_size2 {float:left;width:336px;height:300px;}
#div_size3 {float:left;width:336px;height:100px;}
</code>```

Body:
How to make Divs inside div float left with no spaces; As you can see on the image have spaces, i am using these codes;

main {position:relative;left:339.5px;top:40px;width:1018px;height:1000px;-webkit-box-shadow:inset 0px 0px 40px;}

main div {float:left;margin:1px;-webkit-box-shadow:inset 0px 0px 20px;}
#div_size1 {width:336px;height:200px;}
#div_size2 {width:336px;height:300px;}
#div_size3 {width:336px;height:100px;}

Body:
If you post the HTML as well I can help more. But it looks like you don't have any floats on the divs you want to float.

#div_size1 {float:left;width:336px;height:200px;}
#div_size2 {float:left;width:336px;height:300px;}
#div_size3 {float:left;width:336px;height:100px;}