问:
Center my navigation buttons
I tried a lot of solutions to center my navigation buttons but non worked and I don't find the right solution. I tried space-between but I want it responsive.

Here is my HTML:

```<code><ul>

    <li class="btn"><a href="">The performances</a></li>

    <li class="btn"><a href="">About Us</a></li>

    <li class="btn"><a href="">Book Now !</a></li>

</ul>
</code>```

Here is my CSS code:

```<code>nav li{
    display: inline-block;
    padding: 10px;}

nav a{
    color:#fff;
    text-decoration:none;
}

nav .btn{
  -webkit-border-radius: 17;
  -moz-border-radius: 17;
  border-radius: 17px;
  font-family: Georgia;
  color: #fff;
  font-size: 20px;
  background: #8B0000;
  padding: 5px 10px 5px 10px;
  margin:0 auto;
  text-decoration: none;
 text-align: center;}

.btn:hover{
  background: #A26161;
  text-decoration: none;
}
</code>```

Thank you for your advices !

答:
Assuming there is a nav element surrounding the ul, add the following CSS style for nav:

```<code>nav {
  text-align: center;
}
</code>```

It leaves you with the following:

nav {
  text-align: center;
}

nav li{
    display: inline-block;
    padding: 10px;
}

nav a {
    color:#fff;
    text-decoration:none;
}

nav .btn {
  -webkit-border-radius: 17;
  -moz-border-radius: 17;
  border-radius: 17px;
  font-family: Georgia;
  color: #fff;
  font-size: 20px;
  background: #8B0000;
  padding: 5px 10px 5px 10px;
  margin:0 auto;
  text-decoration: none;
 text-align: center;
}

.btn:hover {
  background: #A26161;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>

    <li class="btn">The performances</li>

    <li class="btn">About Us</li>

    <li class="btn">Book Now !</li>

    </ul>
</nav></code>```

Title: Center my navigation buttons

Body:
I tried a lot of solutions to center my navigation buttons but non worked and I don't find the right solution. I tried space-between but I want it responsive.

Here is my HTML:

The performances

About Us

Book Now !

Here is my CSS code:

nav li{
    display: inline-block;
    padding: 10px;}

nav a{
    color:#fff;
    text-decoration:none;
}

nav .btn{
  -webkit-border-radius: 17;
  -moz-border-radius: 17;
  border-radius: 17px;
  font-family: Georgia;
  color: #fff;
  font-size: 20px;
  background: #8B0000;
  padding: 5px 10px 5px 10px;
  margin:0 auto;
  text-decoration: none;
 text-align: center;}

.btn:hover{
  background: #A26161;
  text-decoration: none;
}

Thank you for your advices !

Body:
Assuming there is a nav element surrounding the ul, add the following CSS style for nav:

nav {
  text-align: center;
}

It leaves you with the following:

nav {
  text-align: center;
}

nav li{
    display: inline-block;
    padding: 10px;
}

nav a {
    color:#fff;
    text-decoration:none;
}

nav .btn {
  -webkit-border-radius: 17;
  -moz-border-radius: 17;
  border-radius: 17px;
  font-family: Georgia;
  color: #fff;
  font-size: 20px;
  background: #8B0000;
  padding: 5px 10px 5px 10px;
  margin:0 auto;
  text-decoration: none;
 text-align: center;
}

.btn:hover {
  background: #A26161;
  text-decoration: none;
}

<nav>
  <ul>

    <li class="btn"><a href="">The performances</a></li>

    <li class="btn"><a href="">About Us</a></li>

    <li class="btn"><a href="">Book Now !</a></li>

    </ul>
</nav>


来源: stackexchange

问:
Ripple effect on Android Lollipop CardView
I'm trying to get a CardView to display the ripple effect when touched by setting the android:backgound attribute in the activity XML file as described here on the Android Developers page, but it isn't working. No animation at all, but the method in onClick is called. I've also tried creating a ripple.xml file as suggested here, but same result.

The CardView as it appears in the activity's XML file:

```<code><android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="155dp"
    android:layout_height="230dp"
    android:elevation="4dp"
    android:translationZ="5dp"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:onClick="showNotices"
    android:background="?android:attr/selectableItemBackground"
    android:id="@+id/notices_card"
    card_view:cardCornerRadius="2dp">

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

I'm relatively new to android development, so I might have made a few obvious mistakes.

答:
For those searching for a solution to the issue of the ripple effect not working on a programmatically created CardView (or in my case custom view which extends CardView) being shown in a RecyclerView, the following worked for me. Basically declaring the XML attributes mentioned in the other answers declaratively in the XML layout file doesn't seem to work for a programmatically created CardView, or one created from a custom layout (even if root view is CardView or merge element is used), so they have to be set programmatically like so:

```<code>private class MadeUpCardViewHolder extends RecyclerView.ViewHolder {
    private MadeUpCardView cardView;

    public MadeUpCardViewHolder(View v){
        super(v);

        this.cardView = (MadeUpCardView)v;

        // Declaring in XML Layout doesn't seem to work in RecyclerViews
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int[] attrs = new int[]{R.attr.selectableItemBackground};
            TypedArray typedArray = context.obtainStyledAttributes(attrs);
            int selectableItemBackground = typedArray.getResourceId(0, 0);
            typedArray.recycle();

            this.cardView.setForeground(context.getDrawable(selectableItemBackground));
            this.cardView.setClickable(true);
        }
    }
}
</code>```

Where MadeupCardView extends CardView Kudos to this answer for the TypedArray part.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get a CardView to display the ripple effect when touched by setting the android:backgound attribute in the activity XML file as described here on the Android Developers page, but it isn't working. No animation at all, but the method in onClick is called. I've also tried creating a ripple.xml file as suggested here, but same result.

The CardView as it appears in the activity's XML file:

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="155dp"
    android:layout_height="230dp"
    android:elevation="4dp"
    android:translationZ="5dp"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:onClick="showNotices"
    android:background="?android:attr/selectableItemBackground"
    android:id="@+id/notices_card"
    card_view:cardCornerRadius="2dp">

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

I'm relatively new to android development, so I might have made a few obvious mistakes.

Body:
For those searching for a solution to the issue of the ripple effect not working on a programmatically created CardView (or in my case custom view which extends CardView) being shown in a RecyclerView, the following worked for me. Basically declaring the XML attributes mentioned in the other answers declaratively in the XML layout file doesn't seem to work for a programmatically created CardView, or one created from a custom layout (even if root view is CardView or merge element is used), so they have to be set programmatically like so:

private class MadeUpCardViewHolder extends RecyclerView.ViewHolder {
    private MadeUpCardView cardView;

    public MadeUpCardViewHolder(View v){
        super(v);

        this.cardView = (MadeUpCardView)v;

        // Declaring in XML Layout doesn't seem to work in RecyclerViews
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int[] attrs = new int[]{R.attr.selectableItemBackground};
            TypedArray typedArray = context.obtainStyledAttributes(attrs);
            int selectableItemBackground = typedArray.getResourceId(0, 0);
            typedArray.recycle();

            this.cardView.setForeground(context.getDrawable(selectableItemBackground));
            this.cardView.setClickable(true);
        }
    }
}

Where MadeupCardView extends CardView Kudos to this answer for the TypedArray part.

ContentLicense: CC BY-SA 3.0


问:
How to do jprofiling in local machine without installing or downloading jprofiler in remote machine
I want to do jprofiling of our remote tomcat server from local machine.
In our linux box we dont have Jprofiler installed or downloaded.
Please suggest if we can do remote profiling without installing Jprofiler in the remote machine.
Thanks in advance.</p>

答:
In JProfiler, invoke

Session->Integration Wizards->New Server Integration

choose the remote option and select the Tomcat server, then follow the steps in the integration wizard.


问:
TypeError: list indices must be integers or slices, not str 'convert the chararter'
```<code>Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
for n in range(0, 20):
      print(Number[n]+1\n)
InputNum3 = input()
Number[InputNum3] = ''.join(str('-'))
</code>```

want:

```<code>1       2
     3
     4
     .... 20
</code>```

input 2

want:

```<code>1
      -
      3
      4...20
</code>```

but the result is:

TypeError: list indices must be integers or slices, not str

答:
```<code>Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
for n in range(0, 20):
      print(Number[n]+1\n)
>>InputNum3 = int(input())
Number[InputNum3] = ''.join(str('-'))
</code>```

input function accept values as string.

Body:
Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
for n in range(0, 20):
      print(Number[n]+1\n)
InputNum3 = input()
Number[InputNum3] = ''.join(str('-'))

want:

1       2
     3
     4
     .... 20

input 2

want:

1
      -
      3
      4...20

but the result is:

TypeError: list indices must be integers or slices, not str

Body:
Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
for n in range(0, 20):
      print(Number[n]+1\n)
>>InputNum3 = int(input())
Number[InputNum3] = ''.join(str('-'))

input function accept values as string.


问:
Tools used for programming in Linux
I would like to start programming using the Linux operating system and all the free stuff out there.

What is the most common and the best language to use with Linux, C or C++ or C#?

What tools are similar to Turbo C, or Visual Studio in Windows?

答: You may also consider portability, that is you can deploy and run your application to different OS, like Mac-OS. And one candidate that offers that is C# Mono.</p>

ContentLicense: CC BY-SA 2.5

Title: Tools used for programming in Linux


问:
Resize a matrix in matlab and keep the same values
I have a 2 dimentional matrix [n,m] containing indices of segmented regions. I need to reshape or resize the matrix in matlab to any size [n',m'] without losing the original values. In other words, I need to extend the segmented regions. I tried to use reshpae, but it did not work since the scale must be similar for both the height and the width. imresize did not work as well because it changes the orignal values.

答:
Here's something quick that I came up with. Concatenating matrices is one way to extend the size of a matrix without messing with existing data:

```<code>s = zeros(3,3);
for x = 1:3 % just adds numbers so it can be studied
    s(:,x) = x;
end
t = [s, zeros(3,3)]; % adds a 3 by 3 matrix to the right
u = [s; zeros(3,3)]; % adds a 3 by 3 matrix below
v = [t; zeros(3,6)]; % adds a 3 by 6 matrix below t matrix
</code>```

Let me know if another solution is needed. It's simple, but I don't understand what you want.

Body:
Here's something quick that I came up with. Concatenating matrices is one way to extend the size of a matrix without messing with existing data:

s = zeros(3,3);
for x = 1:3 % just adds numbers so it can be studied
    s(:,x) = x;
end
t = [s, zeros(3,3)]; % adds a 3 by 3 matrix to the right
u = [s; zeros(3,3)]; % adds a 3 by 3 matrix below
v = [t; zeros(3,6)]; % adds a 3 by 6 matrix below t matrix

Let me know if another solution is needed. It's simple, but I don't understand what you want.


问:
htaccess 301 redirect rules issue
I am trying to do a simple redirection, but I encounter this error, when I do the 301 redirect using the htaccess, it returns the redirect but with the value

.htaccess

```<code>RewriteRule ^clientes/(\w+)/?$ clientes.php?id=$1 [L]

Redirect 301 /clientes/juan http://google.es
</code>```

result:

```<code>https://www.google.es/?id=juan&gws_rd=ssl
</code>```

答:
It's because you are mixing mod-alias (Redirect) with mod-rewrite (RewriteRule) . These are two diffrent modules with diffrent runtime behaviour .

Try using this :

```<code>RewriteRule ^clientes/juan http://google.com [L,R=301]
RewriteRule ^clientes/(\w+)/?$ clientes.php?id=$1 [L]
</code>```

Clear your browser cache before testing these rules.

Title: htaccess 301 redirect rules issue

Body:
I am trying to do a simple redirection, but I encounter this error, when I do the 301 redirect using the htaccess, it returns the redirect but with the value

.htaccess

RewriteRule ^clientes/(\w+)/?$ clientes.php?id=$1 [L]

Redirect 301 /clientes/juan http://google.es

result:

https://www.google.es/?id=juan&gws_rd=ssl

Body:
It's because you are mixing mod-alias (Redirect) with mod-rewrite (RewriteRule) . These are two diffrent modules with diffrent runtime behaviour .

Try using this :

RewriteRule ^clientes/juan http://google.com [L,R=301]
RewriteRule ^clientes/(\w+)/?$ clientes.php?id=$1 [L]

Clear your browser cache before testing these rules.


问:
Running Tensorflow Classifier Model in C++/Obj-C++ results in different result than Python
Ive retrained an InceptionV3 model via the Tensorflow for Poets tutorials and can successfully run label_image.py on my trained data and on new data and get correct labels with good accuracy. Awesome!

If I run my model through my Mac Obj-C++ app my resulting labels are wildly different.

For example - my training is to classify which 'shot type' a frame of video is, (extreme close up, close up, medium, long, extreme long) for classifying video editing content.

label_image.py classifies a frame from a video as 85% likely close up.
My C++ / Obj-C App run with the same frame classifies it as Extreme Long with 60%

Both are running the same version of Tensorflow (1.1) on Mac OS X CPU compiled with AVX/SIMD/FMA optimizations.

My Apps pipeline :

I have a BGR ordered OpenCV Mat image which I can use successfully elsewhere and get sane results from. I create this CV Mat from an OS X CVPixelBufferRef mapped to a BGRA CV MAT like so:

```<code>cv::cvtColor(BGRAImage, frameMat, cv::COLOR_BGRA2BGR);
</code>```

I feed that BGR CV Mat (named frameMat) into a Tensor via code borrowed from the iOS contrib example, like so :

```<code> void* baseAddress = (void*)frameMat.datastart;
 size_t width = (size_t) frameMat.cols;
 size_t height = (size_t) frameMat.rows;
 size_t bytesPerRow =  (size_t) frameMat.cols * 3; // (BGR)

 const int wanted_input_width = 299;
 const int wanted_input_height = 299;
 const int wanted_input_channels = 3;
 const float input_mean = 128.0f;
 const float input_std = 128.0f;

 resized_tensor = tensorflow::Tensor( tensorflow::DT_FLOAT, tensorflow::TensorShape({1, wanted_input_height, wanted_input_width, wanted_input_channels}));

auto image_tensor_mapped = resized_tensor.tensor<float, 4>();
tensorflow::uint8 *in = sourceStartAddr;
float *out = image_tensor_mapped.data();
for (int y = 0; y < wanted_input_height; ++y)
{
    float *out_row = out + (y * wanted_input_width * wanted_input_channels);
    for (int x = 0; x < wanted_input_width; ++x)
    {
        const int in_x = (y * (int)width) / wanted_input_width;
        const int in_y = (x * image_height) / wanted_input_height;

        tensorflow::uint8 *in_pixel = in + (in_y * width * (image_channels)) + (in_x * (image_channels));
        float *out_pixel = out_row + (x * wanted_input_channels);

        // Interestingly the iOS example uses BGRA and DOES NOT re-order tensor channels to RGB <-> BGR
        // Matching that.
        out_pixel[0] = ((float)in_pixel[0] - (float)input_mean) / (float)input_std;
        out_pixel[1] = ((float)in_pixel[1] - (float)input_mean) / (float)input_std;
        out_pixel[2] = ((float)in_pixel[2] - (float)input_mean) / (float)input_std;
    }
}
</code>```

My session creation code:

```<code> tensorflow::Status load_graph_status = ReadBinaryProto(tensorflow::Env::Default(), [inception2015GraphPath cStringUsingEncoding:NSUTF8StringEncoding], &inceptionGraphDef);

 if (load_graph_status.ok())
 {
      tensorflow::SessionOptions options;
      inceptionSession = std::unique_ptr<tensorflow::Session>(tensorflow::NewSession(options));
      tensorflow::Status session_create_status = inceptionSession->Create(inceptionGraphDef);
 }
</code>```

Running the graph:

```<code>    tensorflow::Status run_status = inceptionSession->Run({ {input_layer, resized_tensor} }, {feature_layer, final_layer}, {}, &outputs);
</code>```

And pulling out the labels / feature vector (penultimate layer)

```<code>    NSMutableArray* outputLabels = [NSMutableArray arrayWithCapacity:self.labelsArray.count];
NSMutableArray* outputScores = [NSMutableArray arrayWithCapacity:self.labelsArray.count];

// 1 = labels and scores
auto predictions = outputs[1].flat<float>();

for (int index = 0; index < predictions.size(); index += 1)
{
    const float predictionValue = predictions(index);

    NSString* labelKey  = self.labelsArray[index % predictions.size()];

    NSNumber* currentLabelScore = self.averageLabelScores[labelKey];

    NSNumber* incrementedScore = @([currentLabelScore floatValue] + predictionValue );
    self.averageLabelScores[labelKey] = incrementedScore;

    [outputLabels addObject:labelKey];
    [outputScores addObject:@(predictionValue)];
}

// 0 is feature vector
tensorflow::Tensor feature = outputs[0];
int64_t numElements = feature.NumElements();
tensorflow::TTypes<float>::Flat featureVec = feature.flat<float>();

NSMutableArray* featureElements = [NSMutableArray arrayWithCapacity:numElements];

for(int i = 0; i < numElements; i++)
{
    [featureElements addObject:@( featureVec(i) ) ];
}

if(self.averageFeatureVec == nil)
{
    self.averageFeatureVec = featureElements;
}
else
{
    // average each vector element with the prior
    for(int i = 0; i < featureElements.count; i++)
    {
        float  a = [featureElements[i] floatValue];
        float  b = [self.averageFeatureVec[i] floatValue];

        self.averageFeatureVec[i] = @( MAX(a,b)) ;
    }
}

return @{ kSynopsisStandardMetadataFeatureVectorDictKey : featureElements ,
          @"Labels" : outputLabels,
          @"Scores" : outputScores,
          };
</code>```

I've attempted to look into the tensor ordering (NHWC), and have checked the tensor creation code but I might be missing something obvious to others. Ive also tried changing channel order, to no avail.

Any insight would be greatly helpful. Thank you!

答:
My usual method for debugging issues like this is:

First save out a raw C array of values from an example input that I know works. For example, make sure that label_image works with your newly-trained model, and then write out the float* array you get from input_layer->flat<float>().data(), using pseudo-code like this:

    float* input_data = input_layer->flat<float>().data();
    int input_data_count = input_layer->flat<float>().size();
    printf("float g_test_input[]={\n");
    for (int i = 0; i < input_data_count; ++i) {
      printf("  %f,\n", input_data[i]);
    }
    printf("};\n");

You should end up with a big array that you can copy into your new code. Overwrite whatever input you have in the code you want to test. Now run it, and you should see the same output that you saw from label_image. If you don't, you know there's something different about the model you're loading. If the output is identical, then you know that the input preprocessing is different.

Assuming that it's the preprocessing that's wrong, my next step is to try loading an image from disk. The iOS example code does that in the simple example. Save out some of your expected input into an image file, and then make sure that both label_image and your code produce the same result.

Body:
Ive retrained an InceptionV3 model via the Tensorflow for Poets tutorials and can successfully run label_image.py on my trained data and on new data and get correct labels with good accuracy. Awesome!

If I run my model through my Mac Obj-C++ app my resulting labels are wildly different.

For example - my training is to classify which 'shot type' a frame of video is, (extreme close up, close up, medium, long, extreme long) for classifying video editing content.

label_image.py classifies a frame from a video as 85% likely close up.
My C++ / Obj-C App run with the same frame classifies it as Extreme Long with 60%

Both are running the same version of Tensorflow (1.1) on Mac OS X CPU compiled with AVX/SIMD/FMA optimizations.

My Apps pipeline :

I have a BGR ordered OpenCV Mat image which I can use successfully elsewhere and get sane results from. I create this CV Mat from an OS X CVPixelBufferRef mapped to a BGRA CV MAT like so:

cv::cvtColor(BGRAImage, frameMat, cv::COLOR_BGRA2BGR);

I feed that BGR CV Mat (named frameMat) into a Tensor via code borrowed from the iOS contrib example, like so :

 void* baseAddress = (void*)frameMat.datastart;
 size_t width = (size_t) frameMat.cols;
 size_t height = (size_t) frameMat.rows;
 size_t bytesPerRow =  (size_t) frameMat.cols * 3; // (BGR)

 const int wanted_input_width = 299;
 const int wanted_input_height = 299;
 const int wanted_input_channels = 3;
 const float input_mean = 128.0f;
 const float input_std = 128.0f;

 resized_tensor = tensorflow::Tensor( tensorflow::DT_FLOAT, tensorflow::TensorShape({1, wanted_input_height, wanted_input_width, wanted_input_channels}));

auto image_tensor_mapped = resized_tensor.tensor<float, 4>();
tensorflow::uint8 *in = sourceStartAddr;
float *out = image_tensor_mapped.data();
for (int y = 0; y < wanted_input_height; ++y)
{
    float *out_row = out + (y * wanted_input_width * wanted_input_channels);
    for (int x = 0; x < wanted_input_width; ++x)
    {
        const int in_x = (y * (int)width) / wanted_input_width;
        const int in_y = (x * image_height) / wanted_input_height;

        tensorflow::uint8 *in_pixel = in + (in_y * width * (image_channels)) + (in_x * (image_channels));
        float *out_pixel = out_row + (x * wanted_input_channels);

        // Interestingly the iOS example uses BGRA and DOES NOT re-order tensor channels to RGB <-> BGR
        // Matching that.
        out_pixel[0] = ((float)in_pixel[0] - (float)input_mean) / (float)input_std;
        out_pixel[1] = ((float)in_pixel[1] - (float)input_mean) / (float)input_std;
        out_pixel[2] = ((float)in_pixel[2] - (float)input_mean) / (float)input_std;
    }
}

My session creation code:

 tensorflow::Status load_graph_status = ReadBinaryProto(tensorflow::Env::Default(), [inception2015GraphPath cStringUsingEncoding:NSUTF8StringEncoding], &inceptionGraphDef);

 if (load_graph_status.ok())
 {
      tensorflow::SessionOptions options;
      inceptionSession = std::unique_ptr<tensorflow::Session>(tensorflow::NewSession(options));
      tensorflow::Status session_create_status = inceptionSession->Create(inceptionGraphDef);
 }

Running the graph:

    tensorflow::Status run_status = inceptionSession->Run({ {input_layer, resized_tensor} }, {feature_layer, final_layer}, {}, &outputs);

And pulling out the labels / feature vector (penultimate layer)

    NSMutableArray* outputLabels = [NSMutableArray arrayWithCapacity:self.labelsArray.count];
NSMutableArray* outputScores = [NSMutableArray arrayWithCapacity:self.labelsArray.count];

// 1 = labels and scores
auto predictions = outputs[1].flat<float>();

for (int index = 0; index < predictions.size(); index += 1)
{
    const float predictionValue = predictions(index);

    NSString* labelKey  = self.labelsArray[index % predictions.size()];

    NSNumber* currentLabelScore = self.averageLabelScores[labelKey];

    NSNumber* incrementedScore = @([currentLabelScore floatValue] + predictionValue );
    self.averageLabelScores[labelKey] = incrementedScore;

    [outputLabels addObject:labelKey];
    [outputScores addObject:@(predictionValue)];
}

// 0 is feature vector
tensorflow::Tensor feature = outputs[0];
int64_t numElements = feature.NumElements();
tensorflow::TTypes<float>::Flat featureVec = feature.flat<float>();

NSMutableArray* featureElements = [NSMutableArray arrayWithCapacity:numElements];

for(int i = 0; i < numElements; i++)
{
    [featureElements addObject:@( featureVec(i) ) ];
}

if(self.averageFeatureVec == nil)
{
    self.averageFeatureVec = featureElements;
}
else
{
    // average each vector element with the prior
    for(int i = 0; i < featureElements.count; i++)
    {
        float  a = [featureElements[i] floatValue];
        float  b = [self.averageFeatureVec[i] floatValue];

        self.averageFeatureVec[i] = @( MAX(a,b)) ;
    }
}

return @{ kSynopsisStandardMetadataFeatureVectorDictKey : featureElements ,
          @"Labels" : outputLabels,
          @"Scores" : outputScores,
          };

I've attempted to look into the tensor ordering (NHWC), and have checked the tensor creation code but I might be missing something obvious to others. Ive also tried changing channel order, to no avail.

Any insight would be greatly helpful. Thank you!


问:
How to obtain a list of numbers that are divided by a certain number using the filter function in Python?
I want to write a function that recieves a list and a number and returns another list with all numbers that are divided by the number passed by argument. For example:

```<code>filter_list_by_factor([1, 2, 3, 4, 5], 2)
>>> [2, 4]
</code>```

So I thought about creating a function called is_factor:

```<code>def is_factor(a, b):
    return a % b == 0
</code>```

Then, I wanted to call the function this way:

```<code>def filter_list_by_factor(numbers_list, number):
    return list(filter(is_factor, numbers_list))
</code>```

But it result in this error: TypeError: is_factor() missing 1 required positional argument: 'b'

Can you guys help me?

答:
You can wrap it in a lambda or use functools.partial:

```<code>def is_factor(a, b):
    return a % b == 0

def filter_list_by_factor(numbers_list, number):
    return list(filter(lambda x: is_factor(x, number), numbers_list))

from functools import partial

def filter_list_by_factor(numbers_list, number):
    return list(filter(partial(is_factor, b=number), numbers_list))
</code>```

Body:
I want to write a function that recieves a list and a number and returns another list with all numbers that are divided by the number passed by argument. For example:

filter_list_by_factor([1, 2, 3, 4, 5], 2)
>>> [2, 4]

So I thought about creating a function called is_factor:

def is_factor(a, b):
    return a % b == 0

Then, I wanted to call the function this way:

def filter_list_by_factor(numbers_list, number):
    return list(filter(is_factor, numbers_list))

But it result in this error: TypeError: is_factor() missing 1 required positional argument: 'b'

Can you guys help me?

Body:
You can wrap it in a lambda or use functools.partial:

def is_factor(a, b):
    return a % b == 0

def filter_list_by_factor(numbers_list, number):
    return list(filter(lambda x: is_factor(x, number), numbers_list))

from functools import partial

def filter_list_by_factor(numbers_list, number):
    return list(filter(partial(is_factor, b=number), numbers_list))


问:
Java Scanners: How to keep the same line after an input
I have a small code segment that I do not know how to fix.  This is it:

```<code>System.out.print("y=");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("x+");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();
</code>```

The output is: y=3 on one line, and x+4 on the next.  I would like them to be on the same line.  How do I do this?

答:
It is bit confusing to understand your question why you want it ?

But here is a snippet you can try and see if it can be useful to you!

```<code> import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;

 public class so1 {
     public static void main(String[] args) throws IOException {
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         String arrayStr = br.readLine();
         String[] auxStr = arrayStr.split(" ");
         int[] arr = new int[2];

        for(int i=0;i<auxStr.length;i++){
           arr[i]= Integer.parseInt(auxStr[i]);
        }

        System.out.println("y="+arr[0] + " x+"+arr[1]);
  }

}
</code>```

Here is what you can get -

```<code>3 4
y=3 x+4
</code>```

Update your question if you not find it useful . I will update accordingly.

Body:
I have a small code segment that I do not know how to fix.  This is it:

System.out.print("y=");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("x+");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();

The output is: y=3 on one line, and x+4 on the next.  I would like them to be on the same line.  How do I do this?

Body:
It is bit confusing to understand your question why you want it ?

But here is a snippet you can try and see if it can be useful to you!

 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;

 public class so1 {
     public static void main(String[] args) throws IOException {
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         String arrayStr = br.readLine();
         String[] auxStr = arrayStr.split(" ");
         int[] arr = new int[2];

        for(int i=0;i<auxStr.length;i++){
           arr[i]= Integer.parseInt(auxStr[i]);
        }

        System.out.println("y="+arr[0] + " x+"+arr[1]);
  }

}

Here is what you can get -

3 4
y=3 x+4

Update your question if you not find it useful . I will update accordingly.


问:
TextView + variable
I've added to my TextView, after it has been modified with set.Text, a variable of type int (CONT1)
How do I change only the color of the variable cont1?
part of my code:

```<code>TextView cpu=(TextView) findViewById(R.id.cpu);
cpu.setText("CPU: " + cont1);
</code>```

I tried to put the value of cont1 in a new TextView and then add it to the first TextView in this way:

```<code>TextView cpu=(TextView) findViewById(R.id.cpu);
TextView color=new TextView(this);
color.setText(cont1);
color.setTextColor(220);
cpu.setText("CPU: " + color);
</code>```

but the output gives me strange values,how can I do to change only the color of the variable CONT1?

the problem is that I'm not merge two TextView

cpu.setText("CPU: " + color);
this code no work ,Why can not I merge two TextView?

答:
When you need to use variable and format as HTML, you can use:

strings.xml:

Important part is use <![CDATA[ and variable $s.

<string name="html_cdata_variable"><![CDATA[CPU:%1$s]]></string>

example.java

```<code>    TextView color = findViewById(R.id.text_view_color);
    String variable = "some text in variable";
    color.setText(Html.fromHtml(getString(R.string.html_cdata_variable, variable);
</code>```

When string contains CDATA it will return HTML entities back to string by getString and variable too.
So after retrive data by getString variable will be inflated, but HTML entities will not be trimmed.

Title: TextView + variable

Body:
I've added to my TextView, after it has been modified with set.Text, a variable of type int (CONT1)
How do I change only the color of the variable cont1?
part of my code:

TextView cpu=(TextView) findViewById(R.id.cpu);
cpu.setText("CPU: " + cont1);

I tried to put the value of cont1 in a new TextView and then add it to the first TextView in this way:

TextView cpu=(TextView) findViewById(R.id.cpu);
TextView color=new TextView(this);
color.setText(cont1);
color.setTextColor(220);
cpu.setText("CPU: " + color);

but the output gives me strange values,how can I do to change only the color of the variable CONT1?

the problem is that I'm not merge two TextView

cpu.setText("CPU: " + color);
this code no work ,Why can not I merge two TextView?

Body:
When you need to use variable and format as HTML, you can use:

strings.xml:

Important part is use <![CDATA[ and variable $s.

<string name="html_cdata_variable"><![CDATA[<b>CPU:</b>%1$s]]></string>

example.java

    TextView color = findViewById(R.id.text_view_color);
    String variable = "some text in variable";
    color.setText(Html.fromHtml(getString(R.string.html_cdata_variable, variable);

When string contains CDATA it will return HTML entities back to string by getString and variable too.
So after retrive data by getString variable will be inflated, but HTML entities will not be trimmed.


问:
How to make an html table responsive
I have an html table that is created using constant contact and and I would like to make it responsive and fit the container div holding it.

Here is the demo

I tried the following but this doesn't work as well

```<code><table border="0" width="100%" cellspacing="0" cellpadding="0">
</code>```

答:
You can use bootstrap to make table responsive.
 Define class as table-responsive to make table as responsive.</p>

```<code>  <div class="table-responsive">
<table class="table">
        ...
      </table>
    </div>
</code>```

Title: How to make an html table responsive

Body:
You can use bootstrap to make table responsive.
 Define class as table-responsive to make table as responsive.

  <div class="table-responsive">
<table class="table">
        ...
      </table>
    </div>


问:
Table not updated when user logout
What is the proper way to indicate in your db when a user is logout of an application.

```<code>session::start();
$username = session::check()["username"];
$link->query("UPDATE admin SET isOnline = 0 WHERE username = '".$username."'");
session::destroy();
exit;
</code>```

This is my current implementation.

答:
edit: </p>

```<code>$link->query("UPDATE admin SET isOnline = 0 WHERE username ='".$username."'");
</code>```

Title: Table not updated when user logout

Body:
What is the proper way to indicate in your db when a user is logout of an application.

session::start();
$username = session::check()["username"];
$link->query("UPDATE admin SET isOnline = 0 WHERE username = '".$username."'");
session::destroy();
exit;

This is my current implementation.

Body:
edit:

$link->query("UPDATE admin SET isOnline = 0 WHERE username ='".$username."'");


问:
Python 3.6 in Visual Studio 2017 How to Run Program in the Interactive Shell
I downloaded and installed Visual Studio along with Anaconda to get access to all of the packages that come pre installed with Anaconda. I am trying to figure out how to run code such that it runs in the interactive shell. Right now when I hit F5 an Anaconda 3 cmd line window comes up with the prompt "Press any key to continue..." comes up.  My question is: how can I make it so that when I hit F5 my code is executed in the interactive Python shell much like it does on the basic IDLE that comes with Python.

This seems like a question that a simple Google Search could fix, but for some reason I cannot find the answer. I've done some google searching, and I watched the Visual Studio python official Microsoft series about it. One of the videos touched on using the interactive shell, but even in the video, when he clicked the Start (Run) button, the code ran in what looked like the command line.

I have used IDLE in the past, and now I think it is time to make the change to a bigger IDE. I love the code completion and templates of visual studio, and I can't wait to solve this (noob) question.

Thanks

答:
I'm not sure if it's the best way to do that, but here is what I do to quickly run Python script in Interactive Shell in Visual Studio 2017:

Add #%% sequence at the beginning of *.py file

Press Ctrl+Enter having cursor active in text editor

Code from #%% to end of file (or another #%%) will appear on Interactive Window

#%% is basically beginning of the cell. Cell is a part of code you would want to run at once in Interactive Shell. Cell begins with #%% and ends with another #%% which initializes another cell.

For example: you have following code in Visual Studio:

```<code>#%% Cell 1
print("Hello world1")
print("Hello world2")
#%% Cell 2
print("Hello world3")
</code>```

When you click/focus on third line and press Ctrl+Enter you will run second and third line in Interactive Window.

Body:
I'm not sure if it's the best way to do that, but here is what I do to quickly run Python script in Interactive Shell in Visual Studio 2017:

Add #%% sequence at the beginning of *.py file

Press Ctrl+Enter having cursor active in text editor

Code from #%% to end of file (or another #%%) will appear on Interactive Window

#%% is basically beginning of the cell. Cell is a part of code you would want to run at once in Interactive Shell. Cell begins with #%% and ends with another #%% which initializes another cell.

For example: you have following code in Visual Studio:

#%% Cell 1
print("Hello world1")
print("Hello world2")
#%% Cell 2
print("Hello world3")

When you click/focus on third line and press Ctrl+Enter you will run second and third line in Interactive Window.


问:
Generated Code from Gradle Plugin not visible to Dagger compiler using android-apt
I'm trying to write a custom plugin that will generate some code (specifically, a Dagger module) off of some of the xml files in my android project.  I've been able to get the code to generate, but when I try and use the generated module in a Dagger Component, the Dagger compiler fails:

I've put together a small demo project that demonstrates the failure.  There are two modules: the plugin and the android app (FYI: I had to comment out the plugin-related code in the apps' build.gradle until I had installed the plugin locally).

When I rebuild the app, the generated module shows up right where I expect it, and the dagger component sees it in IJ.  But it is apparently not available at the time when the android-apt plugin invokes the dagger compiler (or that location is not included in code the compiler is looking at).

I've made sure to have all the compile tasks depend on my "generate" task, and the failing task is compileDebugJavaWithJavac which should therefore know about my generated code.

For trying to include the source, I have:

```<code>AndroidSourceSet mainSourceSet = p.android.sourceSets.getByName('main')
LOG.info("Adding directory ${outputDir} to android source set ${mainSourceSet}")
mainSourceSet.java.srcDir(outputDir)
</code>```

Despite this, I get:

```<code>Compiling with JDK Java compiler API.
C:\projects\java\android\android_plugin_demo\plugindemoapplication\src\main\java\com\bdl\plugindemoapplication\DaggerComponent.java:12: error: cannot find symbol
@Component(modules = PluginDaggerModule.class)
                     ^
  symbol: class PluginDaggerModule
C:\projects\java\android\android_plugin_demo\plugindemoapplication\src\main\java\com\bdl\plugindemoapplication\DaggerComponent.java:13: error: dagger.internal.codegen.ComponentProcessor was unable to process this interface because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
public interface DaggerComponent {
       ^
2 errors
</code>```

So, what magic am I missing to allow for the dagger compiler to see my generated code?

答:
After some more experimentation, I believe I have found the answer.  I don't yet know why this works, but if I move the addition of the output directory to the AndroidSourceSet's srcDir to before the p.afterEvaluate closure, it appears to find it.

This seems odd to me as the task dependency is only added in the afterEvaluate block, and it looks like the new task was being executed prior to the compile, so even without this change, I'd have expected the srcDir add to also be executed prior to the compile attempt.

But at least I have it working now.

Body:
I'm trying to write a custom plugin that will generate some code (specifically, a Dagger module) off of some of the xml files in my android project.  I've been able to get the code to generate, but when I try and use the generated module in a Dagger Component, the Dagger compiler fails:

I've put together a small demo project that demonstrates the failure.  There are two modules: the plugin and the android app (FYI: I had to comment out the plugin-related code in the apps' build.gradle until I had installed the plugin locally).

When I rebuild the app, the generated module shows up right where I expect it, and the dagger component sees it in IJ.  But it is apparently not available at the time when the android-apt plugin invokes the dagger compiler (or that location is not included in code the compiler is looking at).

I've made sure to have all the compile tasks depend on my "generate" task, and the failing task is compileDebugJavaWithJavac which should therefore know about my generated code.

For trying to include the source, I have:

AndroidSourceSet mainSourceSet = p.android.sourceSets.getByName('main')
LOG.info("Adding directory ${outputDir} to android source set ${mainSourceSet}")
mainSourceSet.java.srcDir(outputDir)

Despite this, I get:

Compiling with JDK Java compiler API.
C:\projects\java\android\android_plugin_demo\plugindemoapplication\src\main\java\com\bdl\plugindemoapplication\DaggerComponent.java:12: error: cannot find symbol
@Component(modules = PluginDaggerModule.class)
                     ^
  symbol: class PluginDaggerModule
C:\projects\java\android\android_plugin_demo\plugindemoapplication\src\main\java\com\bdl\plugindemoapplication\DaggerComponent.java:13: error: dagger.internal.codegen.ComponentProcessor was unable to process this interface because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
public interface DaggerComponent {
       ^
2 errors

So, what magic am I missing to allow for the dagger compiler to see my generated code?


问:
How should i solve this error:bad operand types for binary operator '&&'
I don't know what's wrong but this code is giving me this  error: bad operand types for binary operator '&&'

```<code>  if((n%2==0) && (n>>6) && (n<<20))
{

          ans = "Not Weird";
      }
</code>```

答:
>> and << are bitwise operators. They evaluate to integral types and Java does not convert integral types implicitly to boolean types, which are required for && arguments and the if condition.

So you ought to rewrite to

```<code>if (n > 6 && n < 20 && n % 2 == 0)
</code>```

I've taken the liberty of removing the superfluous parentheses and re-ordered the statements so the computationally cheaper > and < are evaluated first, and the more expensive % only if necessary. It's a micro-optimisation but demonstrates to readers of your code that you know what you're doing.

Body:
I don't know what's wrong but this code is giving me this  error: bad operand types for binary operator '&&'

  if((n%2==0) && (n>>6) && (n<<20))
{

          ans = "Not Weird";
      }

Body:
>> and << are bitwise operators. They evaluate to integral types and Java does not convert integral types implicitly to boolean types, which are required for && arguments and the if condition.

So you ought to rewrite to

if (n > 6 && n < 20 && n % 2 == 0)

I've taken the liberty of removing the superfluous parentheses and re-ordered the statements so the computationally cheaper > and < are evaluated first, and the more expensive % only if necessary. It's a micro-optimisation but demonstrates to readers of your code that you know what you're doing.


问:
Weird compile error involving type parameters with a wildcard
I am sorry, I can't formulate the title (or the question for that matter) to be any more informative than this, because I have no idea what is going on here. Why doesn't this code compile:

```<code> class Foo
 class Bar[+R <: Foo] { def bar = "bar" }
 class Bak(val b: Bar[_])
 val bak = new Bak(new Bar[Foo])
 bak.b.bar // fine
 println(bak.b) // fine
 bak.b  // oops!
 ^^^ type arguments [Any] do not conform to class Bar's type parameter bounds [+R <: Foo]
</code>```

What is this? Why can I use the variable, but not assign it it a val???
Does it make sense to anyone?

答:
Covariant with Wildcard type, the compiler will set the res's container type to Any, like:

```<code>scala> val l: List[_] = List(123)
l: List[_] = List(123)
scala> l
res1: List[Any] = List(123)
scala> :type l
List[Any]
</code>```

As the above code,  List container type is _, and since List is covariant, so the compiler will set l's res type to List[Any].

And as your code snippet R is upperbound to Foo, so there will be a conflict between Foo with Any:

```<code>val res: Bar[Any] = bak.b //+R <: Foo
</code>```

so this compile error is throwed, in repl it will auto assign bak.b to a temp res variable.

Body:
I am sorry, I can't formulate the title (or the question for that matter) to be any more informative than this, because I have no idea what is going on here. Why doesn't this code compile:

 class Foo
 class Bar[+R <: Foo] { def bar = "bar" }
 class Bak(val b: Bar[_])
 val bak = new Bak(new Bar[Foo])
 bak.b.bar // fine
 println(bak.b) // fine
 bak.b  // oops!
 ^^^ type arguments [Any] do not conform to class Bar's type parameter bounds [+R <: Foo]

What is this? Why can I use the variable, but not assign it it a val???
Does it make sense to anyone?

Body:
Covariant with Wildcard type, the compiler will set the res's container type to Any, like:

scala> val l: List[_] = List(123)
l: List[_] = List(123)
scala> l
res1: List[Any] = List(123)
scala> :type l
List[Any]

As the above code,  List container type is _, and since List is covariant, so the compiler will set l's res type to List[Any].

And as your code snippet R is upperbound to Foo, so there will be a conflict between Foo with Any:

val res: Bar[Any] = bak.b //+R <: Foo

so this compile error is throwed, in repl it will auto assign bak.b to a temp res variable.


问:
What is the best way to cast from ArrayList to List in .Net 2.0
I have a ArrayList of type BookingData to List<BookingData> ?

I am using .net 2.0 so i cannot use arrayList.Cast<int>().ToList() , and I dont want to make here foreach loop , do you have better ideas ?

Thanks.

答:
ToList() method is nothing but the Synthetic sugar for creating a List representation but internally it is also using loop to generate the list item.

so it is much cleaner and simpler to use a foreach iterator block.


问:
Averaging data over a week, with a week having between 0 and 2 values
I have a "weekly" xts object. The data is referring to futures (fronth month futures). The weeks were calculated as follows:

week 1 ends on the last business day of the previous calendar month

week 2 ends on the 5th business day of the current calendar month

week 3 ends on the 10th business day of the current calendar month

week 4 ends on the day when the near contract expires

The data looks as follows (part of the data as example):

```<code>2005-09-30  0.0019094400
2005-10-07  0.0020219110
2005-10-14  0.0067063990
2005-10-20  0.0074893360
2005-10-31  0.0028761630
2005-11-07  0.0011331470
2005-11-14  0.0031749880
2005-11-18  0.0007342980
2005-11-30  0.0025730810
2005-12-07 -0.0003133450
2005-12-14 -0.0008288860
2005-12-20  0.0013468400
2005-12-30  0.0012742930
2006-01-09 -0.0007873670
2006-01-17 -0.0004193150
2006-01-20 -0.0005391370
2006-01-31 -0.0022229660
</code>```

If I call "string" on my dataset, I get the following (you can ignore X here, the important data is Date and Risk.Premium):

```<code>   'data.frame':    484 obs. of  3 variables:
 $ Date        : num  NA NA NA NA NA NA NA NA NA NA ...
 $ Risk.Premium: num  0.00191 0.00202 0.00671 0.00749 0.00288 ...
 $ X           : logi  NA NA NA NA NA NA ...
</code>```

As you can see, there is between 0 and 2 values for one week in the data. I want to transform the data into "proper" weekly data, so I can compare it with other weekly data (i.e. if a week has 2 values, take the average, if a week has zero values, drop this week). Does anyone have an idea how to do this?

答:
Creating sample data:

```<code>mydf <- data.frame(
  date  = c("2005-09-30", "2005-10-07", "2005-10-08", "2005-11-12"),
  value = c(1, 2, 3, 4))
</code>```

Then create a function that, given a week, finds the average. It will return NaN if given a week that doesn't have any values.

```<code>weekAverage <- function(week) {
  vals <- mydf[which(format(as.Date(mydf$date), "%W") == week), 2]
  mean(vals)
}
</code>```

Then apply the function to each unique week in the data frame.

```<code>weeks <- unique(format(as.Date(mydf$date), "%W"))
weeklyAverages <- data.frame(
  Week = weeks,
  Average = sapply(weeks, weekAverage))

weeklyAverages
##   Week Average
##39   39     1.0
##40   40     2.5
##45   45     4.0
</code>```

This works if all your weeks are within the same year, because it only factors in the week of the year, not the year. If you want to include year, you can change the format string to "%W %Y" or similar.

Body:
I have a "weekly" xts object. The data is referring to futures (fronth month futures). The weeks were calculated as follows:

week 1 ends on the last business day of the previous calendar month

week 2 ends on the 5th business day of the current calendar month

week 3 ends on the 10th business day of the current calendar month

week 4 ends on the day when the near contract expires

The data looks as follows (part of the data as example):

2005-09-30  0.0019094400
2005-10-07  0.0020219110
2005-10-14  0.0067063990
2005-10-20  0.0074893360
2005-10-31  0.0028761630
2005-11-07  0.0011331470
2005-11-14  0.0031749880
2005-11-18  0.0007342980
2005-11-30  0.0025730810
2005-12-07 -0.0003133450
2005-12-14 -0.0008288860
2005-12-20  0.0013468400
2005-12-30  0.0012742930
2006-01-09 -0.0007873670
2006-01-17 -0.0004193150
2006-01-20 -0.0005391370
2006-01-31 -0.0022229660

If I call "string" on my dataset, I get the following (you can ignore X here, the important data is Date and Risk.Premium):

   'data.frame':    484 obs. of  3 variables:
 $ Date        : num  NA NA NA NA NA NA NA NA NA NA ...
 $ Risk.Premium: num  0.00191 0.00202 0.00671 0.00749 0.00288 ...
 $ X           : logi  NA NA NA NA NA NA ...

As you can see, there is between 0 and 2 values for one week in the data. I want to transform the data into "proper" weekly data, so I can compare it with other weekly data (i.e. if a week has 2 values, take the average, if a week has zero values, drop this week). Does anyone have an idea how to do this?

Body:
Creating sample data:

mydf <- data.frame(
  date  = c("2005-09-30", "2005-10-07", "2005-10-08", "2005-11-12"),
  value = c(1, 2, 3, 4))

Then create a function that, given a week, finds the average. It will return NaN if given a week that doesn't have any values.

weekAverage <- function(week) {
  vals <- mydf[which(format(as.Date(mydf$date), "%W") == week), 2]
  mean(vals)
}

Then apply the function to each unique week in the data frame.

weeks <- unique(format(as.Date(mydf$date), "%W"))
weeklyAverages <- data.frame(
  Week = weeks,
  Average = sapply(weeks, weekAverage))

weeklyAverages
##   Week Average
##39   39     1.0
##40   40     2.5
##45   45     4.0

This works if all your weeks are within the same year, because it only factors in the week of the year, not the year. If you want to include year, you can change the format string to "%W %Y" or similar.


问:
Can't get Novell.Directory.Ldap.NETStandard library to query
I need to let the user query an Active Directory for names in .Net Core.
So I am building an Active Directory Search Web API Service.

I am able to connect with the bind statement.
But I am not able to get any results back with my query although there is no error.

Another programmer sent me some code he uses in other applications.  But it uses the DirectoryEntry object which is not available in .Net Core.

So I am trying to use the Novell.Directory.Ldap.NetStandard library.

Here is the code the other developer sent me:

```<code>public static List<UserProfileModel> GetADUsers(string alias)
    {
        List<UserProfileModel> users = new List<UserProfileModel>();

        if (alias == null || alias.Trim().Equals(""))
        {
            return users;
        }

        try
        {
            // Ad path LDAP://ourOrg.gov/CN=Users,DC=ourOrg,DC=gov
            DirectoryEntry de2 = new DirectoryEntry(ConfigurationManager.AppSettings["AD_Path"], ConfigurationManager.AppSettings["AD_User"], ConfigurationManager.AppSettings["AD_Password"]);
            de2.Path = ConfigurationManager.AppSettings["AD_Path"];

            de2.AuthenticationType = AuthenticationTypes.Secure;

            DirectorySearcher deSearch = new DirectorySearcher();

            deSearch.SearchRoot = de2;
            deSearch.Filter = "(samaccountname=*" + alias + "*)";

            LOGGER.Debug(String.Format("Active Directory Search Filter {0}", deSearch.Filter));

            SearchResultCollection results = deSearch.FindAll();
            String raw = "";

            LOGGER.Debug(String.Format("Active Directory Search Result Counts {0}", results.Count));

            if (results.Count > 0)
            {
                foreach (SearchResult item in results)
                {
                    UserProfileModel userProfileModel = new UserProfileModel();

                    userProfileModel.Name = GetADProperty("name", item);
                    userProfileModel.email = GetADProperty("mail", item);
                    userProfileModel.identity = GetADProperty("userPrincipalName", item);
                    userProfileModel.first_name = GetADProperty("givenName", item);
                    userProfileModel.last_name = GetADProperty("sn", item);
                    users.Add(userProfileModel);
                    raw = String.Format("{0}/n{1}", raw, userProfileModel.ToString());
                }
                LOGGER.Debug(String.Format("Active Directory Search Resuts ToString: {0}", raw));
            }
        }
        catch (Exception e)
        {
            LOGGER.Error("Unable to Query Active Directory", e);
        }

        return users;
    }
</code>```

I need to translate this into Novell's LDAP library.

Here is my attempt:

```<code>    [HttpGet]
    public async Task<List<UserProfileModel>> GetByName(string alias)
    {

        int ldapPort = LdapConnection.DEFAULT_PORT;
        string ldapHost = "ourOrg.gov";
        string loginDn = @"ourOrg\myName";
        string password = "myPass";

        List<UserProfileModel> users = new List<UserProfileModel>();

        if (alias == null || alias.Trim().Equals(""))
        {
            return users;
        }

        try
        {
            using (var con = new LdapConnection())
            {
                con.Connect(ldapHost, ldapPort);
                con.Bind(loginDn, password);

                LdapSearchResults results = con.Search(
                    "cn=users,dc=ourOrg,dc=gov",
                    LdapConnection.SCOPE_ONE,
                    "samaccountname=*",
                    null,
                    false);

                // NO RESULTS:(
            }

            return users;
        }
        catch(Exception ex)
        {
            throw ex;
        }

    }
</code>```

I don't get an error.
But there are 0 results.

I originally had this part:

"samaccountname=*",

like:

"samaccountname={alias}",

but I'm just trying to get back results at this point.

答:
I got this working:</p>

```<code>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Hrsa.Core.Web.App.Models.ViewModels;
using Novell.Directory.Ldap;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace Hrsa.Core.Web.App.Controllers.Api
{
    [Route("api/[controller]")]
    public class ActiveDirectoryController : Controller
    {
        private readonly AppSettings _appSettings;

        public ActiveDirectoryController(IOptions<AppSettings> appSettings)
        {
            _appSettings = appSettings.Value;
        }

        [HttpGet]
        public async Task<List<UserProfileModel>> GetByName(string alias)
        {
            int ldapPort = LdapConnection.DEFAULT_PORT;
            string ldapHost = _appSettings.HrsaLdapHost;    // ourOrgName.gov
            string loginDn = _appSettings.AdUser;
            string password = _appSettings.AdPassword;

            string searchBase = _appSettings.HrsaAdSearchBase;
            string searchFilter = $"(samaccountname=*{alias}*)";
            string[] attributes = new string[] { "cn", "userPrincipalName", "st", "givenname", "samaccountname",
                "description", "telephonenumber", "department", "displayname", "name", "mail", "givenName", "sn" };

            List<UserProfileModel> users = new List<UserProfileModel>();

            if (alias == null || alias.Trim().Equals(""))
            {
                return users;
            }

            try
            {
                using (var con = new LdapConnection())
                {
                    con.Connect(ldapHost, ldapPort);
                    con.Bind(loginDn, password);

                    LdapSearchQueue queue = con.Search(
                        searchBase,
                        LdapConnection.SCOPE_SUB,
                        searchFilter,
                        attributes,
                        false,
                        (LdapSearchQueue)null,
                        (LdapSearchConstraints)null);

                    LdapMessage message;

                    while ((message = queue.getResponse()) != null)
                    {
                        if (message is LdapSearchResult)
                        {
                            LdapEntry entry = ((LdapSearchResult)message).Entry;

                            LdapAttributeSet attributeSet = entry.getAttributeSet();

                            users.Add(new UserProfileModel
                            {

                                Cn = attributeSet.getAttribute("cn")?.StringValue,
                                UserPrincipalName = attributeSet.getAttribute("userPrincipalName")?.StringValue,
                                St = attributeSet.getAttribute("st")?.StringValue,
                                Givenname = attributeSet.getAttribute("givenname")?.StringValue,
                                Samaccountname = attributeSet.getAttribute("samaccountname")?.StringValue,
                                Description = attributeSet.getAttribute("description")?.StringValue,
                                Telephonenumber = attributeSet.getAttribute("telephonenumber")?.StringValue,
                                Department = attributeSet.getAttribute("department")?.StringValue,
                                Displayname = attributeSet.getAttribute("displayname")?.StringValue,
                                Name = attributeSet.getAttribute("name")?.StringValue,
                                Mail = attributeSet.getAttribute("mail")?.StringValue,
                                GivenName = attributeSet.getAttribute("givenName")?.StringValue,
                                Sn = attributeSet.getAttribute("sn")?.StringValue
                            });
                        }
                    }
                }

                return users;
            }
            catch(Exception ex)
            {
                throw ex;
            }

        }
    }
}
</code>```

Body:
I need to let the user query an Active Directory for names in .Net Core.
So I am building an Active Directory Search Web API Service.

I am able to connect with the bind statement.
But I am not able to get any results back with my query although there is no error.

Another programmer sent me some code he uses in other applications.  But it uses the DirectoryEntry object which is not available in .Net Core.

So I am trying to use the Novell.Directory.Ldap.NetStandard library.

Here is the code the other developer sent me:

public static List<UserProfileModel> GetADUsers(string alias)
    {
        List<UserProfileModel> users = new List<UserProfileModel>();

        if (alias == null || alias.Trim().Equals(""))
        {
            return users;
        }

        try
        {
            // Ad path LDAP://ourOrg.gov/CN=Users,DC=ourOrg,DC=gov
            DirectoryEntry de2 = new DirectoryEntry(ConfigurationManager.AppSettings["AD_Path"], ConfigurationManager.AppSettings["AD_User"], ConfigurationManager.AppSettings["AD_Password"]);
            de2.Path = ConfigurationManager.AppSettings["AD_Path"];

            de2.AuthenticationType = AuthenticationTypes.Secure;

            DirectorySearcher deSearch = new DirectorySearcher();

            deSearch.SearchRoot = de2;
            deSearch.Filter = "(samaccountname=*" + alias + "*)";

            LOGGER.Debug(String.Format("Active Directory Search Filter {0}", deSearch.Filter));

            SearchResultCollection results = deSearch.FindAll();
            String raw = "";

            LOGGER.Debug(String.Format("Active Directory Search Result Counts {0}", results.Count));

            if (results.Count > 0)
            {
                foreach (SearchResult item in results)
                {
                    UserProfileModel userProfileModel = new UserProfileModel();

                    userProfileModel.Name = GetADProperty("name", item);
                    userProfileModel.email = GetADProperty("mail", item);
                    userProfileModel.identity = GetADProperty("userPrincipalName", item);
                    userProfileModel.first_name = GetADProperty("givenName", item);
                    userProfileModel.last_name = GetADProperty("sn", item);
                    users.Add(userProfileModel);
                    raw = String.Format("{0}/n{1}", raw, userProfileModel.ToString());
                }
                LOGGER.Debug(String.Format("Active Directory Search Resuts ToString: {0}", raw));
            }
        }
        catch (Exception e)
        {
            LOGGER.Error("Unable to Query Active Directory", e);
        }

        return users;
    }

I need to translate this into Novell's LDAP library.

Here is my attempt:

    [HttpGet]
    public async Task<List<UserProfileModel>> GetByName(string alias)
    {

        int ldapPort = LdapConnection.DEFAULT_PORT;
        string ldapHost = "ourOrg.gov";
        string loginDn = @"ourOrg\myName";
        string password = "myPass";

        List<UserProfileModel> users = new List<UserProfileModel>();

        if (alias == null || alias.Trim().Equals(""))
        {
            return users;
        }

        try
        {
            using (var con = new LdapConnection())
            {
                con.Connect(ldapHost, ldapPort);
                con.Bind(loginDn, password);

                LdapSearchResults results = con.Search(
                    "cn=users,dc=ourOrg,dc=gov",
                    LdapConnection.SCOPE_ONE,
                    "samaccountname=*",
                    null,
                    false);

                // NO RESULTS:(
            }

            return users;
        }
        catch(Exception ex)
        {
            throw ex;
        }

    }

I don't get an error.
But there are 0 results.

I originally had this part:

"samaccountname=*",

like:

"samaccountname={alias}",

but I'm just trying to get back results at this point.

Body:
I got this working:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Hrsa.Core.Web.App.Models.ViewModels;
using Novell.Directory.Ldap;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace Hrsa.Core.Web.App.Controllers.Api
{
    [Route("api/[controller]")]
    public class ActiveDirectoryController : Controller
    {
        private readonly AppSettings _appSettings;

        public ActiveDirectoryController(IOptions<AppSettings> appSettings)
        {
            _appSettings = appSettings.Value;
        }

        [HttpGet]
        public async Task<List<UserProfileModel>> GetByName(string alias)
        {
            int ldapPort = LdapConnection.DEFAULT_PORT;
            string ldapHost = _appSettings.HrsaLdapHost;    // ourOrgName.gov
            string loginDn = _appSettings.AdUser;
            string password = _appSettings.AdPassword;

            string searchBase = _appSettings.HrsaAdSearchBase;
            string searchFilter = $"(samaccountname=*{alias}*)";
            string[] attributes = new string[] { "cn", "userPrincipalName", "st", "givenname", "samaccountname",
                "description", "telephonenumber", "department", "displayname", "name", "mail", "givenName", "sn" };

            List<UserProfileModel> users = new List<UserProfileModel>();

            if (alias == null || alias.Trim().Equals(""))
            {
                return users;
            }

            try
            {
                using (var con = new LdapConnection())
                {
                    con.Connect(ldapHost, ldapPort);
                    con.Bind(loginDn, password);

                    LdapSearchQueue queue = con.Search(
                        searchBase,
                        LdapConnection.SCOPE_SUB,
                        searchFilter,
                        attributes,
                        false,
                        (LdapSearchQueue)null,
                        (LdapSearchConstraints)null);

                    LdapMessage message;

                    while ((message = queue.getResponse()) != null)
                    {
                        if (message is LdapSearchResult)
                        {
                            LdapEntry entry = ((LdapSearchResult)message).Entry;

                            LdapAttributeSet attributeSet = entry.getAttributeSet();

                            users.Add(new UserProfileModel
                            {

                                Cn = attributeSet.getAttribute("cn")?.StringValue,
                                UserPrincipalName = attributeSet.getAttribute("userPrincipalName")?.StringValue,
                                St = attributeSet.getAttribute("st")?.StringValue,
                                Givenname = attributeSet.getAttribute("givenname")?.StringValue,
                                Samaccountname = attributeSet.getAttribute("samaccountname")?.StringValue,
                                Description = attributeSet.getAttribute("description")?.StringValue,
                                Telephonenumber = attributeSet.getAttribute("telephonenumber")?.StringValue,
                                Department = attributeSet.getAttribute("department")?.StringValue,
                                Displayname = attributeSet.getAttribute("displayname")?.StringValue,
                                Name = attributeSet.getAttribute("name")?.StringValue,
                                Mail = attributeSet.getAttribute("mail")?.StringValue,
                                GivenName = attributeSet.getAttribute("givenName")?.StringValue,
                                Sn = attributeSet.getAttribute("sn")?.StringValue
                            });
                        }
                    }
                }

                return users;
            }
            catch(Exception ex)
            {
                throw ex;
            }

        }
    }
}


问:
js Date changes on october 10th (BST)
Why does JS Date object change toUTCString on October 10th?

```<code>new Date('2017-10-9').toUTCString()
"Sun, 08 Oct 2017 23:00:00 GMT"

new Date('2017-10-10').toUTCString()
"Tue, 10 Oct 2017 00:00:00 GMT"
</code>```

I am writing these in the UK. BST ends on October 29th. What is going on?!

答:
In the first example the date is parsed as local date, and in the second as UTC date. To parse the first date as UTC too, add a 0 before 9.

console.log(new Date('2017-10-09').toUTCString()); // Mon, 09 Oct 2017 00:00:00 GMT```

Inconsistencies in date parsing like that are why you should always pass a date in ISO-8601 format to the Date constructor. You can also use a library like Moment.js.

Title: js Date changes on october 10th (BST)

Body:
Why does JS Date object change toUTCString on October 10th?

new Date('2017-10-9').toUTCString()
"Sun, 08 Oct 2017 23:00:00 GMT"

new Date('2017-10-10').toUTCString()
"Tue, 10 Oct 2017 00:00:00 GMT"

I am writing these in the UK. BST ends on October 29th. What is going on?!

Body:
In the first example the date is parsed as local date, and in the second as UTC date. To parse the first date as UTC too, add a 0 before 9.

console.log(new Date('2017-10-09').toUTCString()); // Mon, 09 Oct 2017 00:00:00 GMT

Inconsistencies in date parsing like that are why you should always pass a date in ISO-8601 format to the Date constructor. You can also use a library like Moment.js.


问:
A SimpleStackDemo, and using loops to return values from an array, LIFO
This is a programming assignment from a class I am in.  I do not want you to solve it for me, just help me understand.  I will say as well, the professor is very rigid about how the program should look, so please don't give me a solution which changes any of the names(unless they should be reserved.)  Also, we have not covered stacks, pop() or push(), so I looked ahead 4 chapters to even get an inkling of what he is looking for.

This is the code he has given us.

```<code>    public class SimpleStack {

        char[] data;//this array holds that stack
        int tos;    //index of top of stack

        //Construct an empty stack given it's size.
        public SimpleStack(int size){
            data = new char[size];

            tos = 0;
        }

        public void push(char ch){
            if(isFull()){
                System.out.println("--Stack is full.");
                return;
            }
            data[tos] = ch;
            tos++;
        }

        public char pop(){
            if(isEmpty()){
                System.out.println("--Stack is empty.");
                return (char)0;
            }
            tos--;
            return data[tos];
        }

        public isEmpty(){
            boolean empty(tos = 0);
        }

        public isFull(){

        }
}
</code>```

I am supposed to finish the two boolean statements at the bottom, which I have an idea of how I do that.  Also I am supposed to create the main method to call the SimpleStack, and input A-J as a ten character test, then have it give me the reverse.  I am not told how I should construct the main, but the prof also does not say I need to get user input.  So I could just create an array already filled from A-J.

I tested my main using this code.  I could ask for the user to give me the starting letter "A" and then create a loop to end it before "K", and I was also testing how I might send to SimpleStack the size the array is supposed to be.

```<code>import javax.swing.*;

public class SimpleStackDemo {

    public static void main(String[] args) {

        char c[] = "ABCDEFGHIJ".toCharArray();
        int aryL = c.length;

        SimpleStack sS1 = new SimpleStack(aryL);

        //System.out.println("The Array is, " + aryL);

        //SimpleStack sS1 = new SimpleStack(//something);

    }

}
</code>```

What I think I want to do is ask the user for how big the array should be, use that to call on SimpleStack, then ask what letter they want to start at, which will then be put to tos?

答:
So, isFull is easy to do. Why? When instantiating your SimpleStack, the user must specify the size of the stack, and that size is used to create data. You know what index you're on, tos. All you have to do is check if the tos is the last index:

```<code> return (tos == data.length - 1);
</code>```

isEmpty follows the same idea. tos is your current index. All you have to do is check if your current index is 0:

```<code> return (tos == 0);
</code>```

Things to note:

When you push() or pop(), your tos increases or decreases, keeping track of your index. Because you know where you are in the stack, you can always tell relative to the absolutes whether you're at the either end of the Stack.

In your main class:

```<code>public static void main(String[] args) {

    char c[] = "ABCDEFGHIJ".toCharArray();
    int aryL = c.length;

    SimpleStack sS1 = new SimpleStack(aryL); // You have a stack with size 10;
    System.out.println(sS1.isEmpty()); // on index 0, will return true.
    sS1.push('A'); // Adds A to top of empty stack, tos = 1 after this line
    sS1.push('B'); // Adds B to top of empty stack, tos = 2 after this line
    sS1.push('C'); // Adds C to top of empty stack, tos = 3 after this line
    sS1.pop();     // Removes top of empty stack, tos = 2 after this line
    sS1.push('C'); // Adds C to top of empty stack, tos = 3 after this line

    // Stack now looks like:
    //  C
    //  B
    //  A -> bottom of stack

}
</code>```

Body:
This is a programming assignment from a class I am in.  I do not want you to solve it for me, just help me understand.  I will say as well, the professor is very rigid about how the program should look, so please don't give me a solution which changes any of the names(unless they should be reserved.)  Also, we have not covered stacks, pop() or push(), so I looked ahead 4 chapters to even get an inkling of what he is looking for.

This is the code he has given us.

    public class SimpleStack {

        char[] data;//this array holds that stack
        int tos;    //index of top of stack

        //Construct an empty stack given it's size.
        public SimpleStack(int size){
            data = new char[size];

            tos = 0;
        }

        public void push(char ch){
            if(isFull()){
                System.out.println("--Stack is full.");
                return;
            }
            data[tos] = ch;
            tos++;
        }

        public char pop(){
            if(isEmpty()){
                System.out.println("--Stack is empty.");
                return (char)0;
            }
            tos--;
            return data[tos];
        }

        public isEmpty(){
            boolean empty(tos = 0);
        }

        public isFull(){

        }
}

I am supposed to finish the two boolean statements at the bottom, which I have an idea of how I do that.  Also I am supposed to create the main method to call the SimpleStack, and input A-J as a ten character test, then have it give me the reverse.  I am not told how I should construct the main, but the prof also does not say I need to get user input.  So I could just create an array already filled from A-J.

I tested my main using this code.  I could ask for the user to give me the starting letter "A" and then create a loop to end it before "K", and I was also testing how I might send to SimpleStack the size the array is supposed to be.

import javax.swing.*;

public class SimpleStackDemo {

    public static void main(String[] args) {

        char c[] = "ABCDEFGHIJ".toCharArray();
        int aryL = c.length;

        SimpleStack sS1 = new SimpleStack(aryL);

        //System.out.println("The Array is, " + aryL);

        //SimpleStack sS1 = new SimpleStack(//something);

    }

}

What I think I want to do is ask the user for how big the array should be, use that to call on SimpleStack, then ask what letter they want to start at, which will then be put to tos?

Body:
So, isFull is easy to do. Why? When instantiating your SimpleStack, the user must specify the size of the stack, and that size is used to create data. You know what index you're on, tos. All you have to do is check if the tos is the last index:

 return (tos == data.length - 1);

isEmpty follows the same idea. tos is your current index. All you have to do is check if your current index is 0:

 return (tos == 0);

Things to note:

When you push() or pop(), your tos increases or decreases, keeping track of your index. Because you know where you are in the stack, you can always tell relative to the absolutes whether you're at the either end of the Stack.

In your main class:

public static void main(String[] args) {

    char c[] = "ABCDEFGHIJ".toCharArray();
    int aryL = c.length;

    SimpleStack sS1 = new SimpleStack(aryL); // You have a stack with size 10;
    System.out.println(sS1.isEmpty()); // on index 0, will return true.
    sS1.push('A'); // Adds A to top of empty stack, tos = 1 after this line
    sS1.push('B'); // Adds B to top of empty stack, tos = 2 after this line
    sS1.push('C'); // Adds C to top of empty stack, tos = 3 after this line
    sS1.pop();     // Removes top of empty stack, tos = 2 after this line
    sS1.push('C'); // Adds C to top of empty stack, tos = 3 after this line

    // Stack now looks like:
    //  C
    //  B
    //  A -> bottom of stack

}


问:
Accessing TempData variables
I'm using ajax to make a post request to my server side, I am creating a file, once that file has been created, I need to display it in my browser, I've read that using ajax is not possible to display that file, but I can use my success event in my ajax function to call another method in my server side, I've been trying to store that file as an array of bytes in memory using TempData or even Session variables, and then read them on the other method I'm calling on ajax success(called DisplayFile) , but the TempData variables are always null when the DisplayFile method is called... If you have different suggestions to do this are welcome,  I've been thinking in send the array of bytes to JQuery and then make another request passing it as a parameter but it is a very long array of bytes.., I'm not sure why the TempData value is null when DisplayFile method is called from client side...

```<code>$.ajax({ url: "/FileManagement/Files",
         type: 'post',
         data: formData,
         success: function(result){
           window.location = "/FileManagement/DisplayFile"
}
})

public JsonResult Files(//parameters...)
{
//...some code
 TempData["BytesArray"] = fileBytes; //fileBytes is an array of bytes
 TempData["FileName"] = fileName;
}

public ActionResult DisplayFile()
{
var file = TempData["BytesArray"];  //null
var fileName = TempData["FileName"];
}
</code>```

UPDATE
It's working now with Session variables instead of TempData, maybe it's because this controller is inside the Areas folder? This controller is not inside the Controllers folder, maybe it has to do with that, in order for Session to work I had to use the complete path to it like: System.Web.HttpContext.Current.Session["test"] = "asasa"; I'm still trying to figure out why with TempData the value is null when the second method is called...

答:
the way you did was correct , you should be able to access the tempdata in the further get request ,even though it is from ajax.

See this accepted answer , which almost related to what you want

:https://forums.asp.net/t/1911620.aspx?How+to+pass+tempdata+to+controller+from+view+

casting may be a problem for you. try that.

Hope it will be helpful

Thanks
Karthik

Title: Accessing TempData variables

Body:
I'm using ajax to make a post request to my server side, I am creating a file, once that file has been created, I need to display it in my browser, I've read that using ajax is not possible to display that file, but I can use my success event in my ajax function to call another method in my server side, I've been trying to store that file as an array of bytes in memory using TempData or even Session variables, and then read them on the other method I'm calling on ajax success(called DisplayFile) , but the TempData variables are always null when the DisplayFile method is called... If you have different suggestions to do this are welcome,  I've been thinking in send the array of bytes to JQuery and then make another request passing it as a parameter but it is a very long array of bytes.., I'm not sure why the TempData value is null when DisplayFile method is called from client side...

$.ajax({ url: "/FileManagement/Files",
         type: 'post',
         data: formData,
         success: function(result){
           window.location = "/FileManagement/DisplayFile"
}
})

public JsonResult Files(//parameters...)
{
//...some code
 TempData["BytesArray"] = fileBytes; //fileBytes is an array of bytes
 TempData["FileName"] = fileName;
}

public ActionResult DisplayFile()
{
var file = TempData["BytesArray"];  //null
var fileName = TempData["FileName"];
}

UPDATE
It's working now with Session variables instead of TempData, maybe it's because this controller is inside the Areas folder? This controller is not inside the Controllers folder, maybe it has to do with that, in order for Session to work I had to use the complete path to it like: System.Web.HttpContext.Current.Session["test"] = "asasa"; I'm still trying to figure out why with TempData the value is null when the second method is called...


问:
Does JRE Installation automatically defines PATH and JAVA_HOME on Windows?
I am installing JRE on windows server 2012 (which is a production server). I want to know if the installation will automatically update/create PATH and JAVA_HOME environment variable. I have no place to test it and hence asking this question.

Also want to know, does Java update automatically updates JAVA_HOME as well?

Thanks!

答: Non you have to add that variable manually through windows properties, and also you have to add the path to bin directory to the path variable</p>


问:
UWP MapControl: How to prevent zoom on MapDoubleTapped?
I need to catch a double click/tap event on a map polygon in order to show an "edit properties" dialog. How can I prevent the map zoom on double tap (on a polygon)? There is no e.Handled property available. The map must still be zoomable by double tapping on free space (no polygon).</p>

答:
Here is an example of how you can disable the zooming when double clicking:

```<code>MyMapControl.MapDoubleTapped += MyMapControl_MapDoubleTapped;

private void MyMapControl_MapDoubleTapped(MapControl sender, MapInputEventArgs args)
{
    var currentCamera = sender.ActualCamera;
    sender.TrySetSceneAsync(MapScene.CreateFromCamera(currentCamera));
}
</code>```

If you only want to disable this when a polygon is double tapped. Try using setting the scene in your polygon double tap event handler.

Body:
Here is an example of how you can disable the zooming when double clicking:

MyMapControl.MapDoubleTapped += MyMapControl_MapDoubleTapped;

private void MyMapControl_MapDoubleTapped(MapControl sender, MapInputEventArgs args)
{
    var currentCamera = sender.ActualCamera;
    sender.TrySetSceneAsync(MapScene.CreateFromCamera(currentCamera));
}

If you only want to disable this when a polygon is double tapped. Try using setting the scene in your polygon double tap event handler.


问:
Appending the datetime to the end of every line in a 600 million row file
I have a 680 million rows (19gig) file that I need the datetime appended onto every line. I get this file every night and I have to add the time that I processed it to the end of each line. I have tried many ways to do this including sed/awk and loading it into a SQL database with the last column being defaulted to the current timestamp.

I was wondering if there is a fast way to do this? My fastest way so far takes two hours and that is just not fast enough given the urgency of the information in this file.  It is a flat CSV file.

edit1:

Here's what I've done so far:

```<code>awk -v date="$(date +"%Y-%m-%d %r")" '{ print $0","date}' lrn.ae.txt > testoutput.txt
</code>```

Time = 117 minutes

```<code>perl -ne 'chomp; printf "%s.pdf\n", $_' EXPORT.txt > testoutput.txt
</code>```

Time = 135 minutes

```<code>mysql load data local infile '/tmp/input.txt' into table testoutput
</code>```

Time = 211 minutes

答:
If you want to add the same (current) datetime to each row in the file, you might as well leave the file as it is, and put the datetime in the filename instead. Depending on the use later, the software that processes the file could then first get the datetime from the filename.

To put the same datetime at the end of each row, some simple code could be written:

Make a string containing a separator and the datetime.

Read the lines from the file, append the above string and write back to a new file.

This way a conversion from datetime to string is only done once, and converting the file should not take much longer than copying the file on disk.

Body:
I have a 680 million rows (19gig) file that I need the datetime appended onto every line. I get this file every night and I have to add the time that I processed it to the end of each line. I have tried many ways to do this including sed/awk and loading it into a SQL database with the last column being defaulted to the current timestamp.

I was wondering if there is a fast way to do this? My fastest way so far takes two hours and that is just not fast enough given the urgency of the information in this file.  It is a flat CSV file.

edit1:

Here's what I've done so far:

awk -v date="$(date +"%Y-%m-%d %r")" '{ print $0","date}' lrn.ae.txt > testoutput.txt

Time = 117 minutes

perl -ne 'chomp; printf "%s.pdf\n", $_' EXPORT.txt > testoutput.txt

Time = 135 minutes

mysql load data local infile '/tmp/input.txt' into table testoutput

Time = 211 minutes


问:
Is this PHP opendir() very taxing on the server?
```<code>if (is_dir($dir)) {
  if($handle = opendir($dir)) {
        while($file = readdir($handle)) {
        // Break the filename by period; if there's more than one piece, grab the last piece.
        $parts = explode(".", $file);
        if (is_array($parts) && count($parts) > 1) {
            $ext = end($parts);
            // If it's an image that we want, echo the code.
          if ($ext == "png" OR $ext == "PNG" OR $ext == "jpg" OR $ext == "JPG" OR $ext == "jpeg" OR $ext == "JPEG" OR $ext == "gif" OR $ext == "GIF")
            echo "<img src=\"$path/$file\" />";
      }
    }
    closedir($handle);
  }
...
</code>```

I'm using it in Wordpress, and the page loads pretty slowly, but it could also be from having a lot of images on it. I just wanted to make sure I wasn't doing something that was frowned upon for performance reasons.

答:
We cant exactly say that opendir is slow as they is many configuration values that can effect performance.

what you should do is benchmark the segement of code in your app like so:

```<code>$start = microtime(true);
//Your Code
$end = (microtime(true) - $start);
</code>```

and see exactly how long it had taken to process.

Some other tips:

$ext == "png" OR $ext == "PNG" is redundant, you should use $ext = strtolower(end($parts)); and then just use:

```<code>$ext == "png" OR $ext == "jpg" OR $ext == "jpeg" OR $ext == "gif"
</code>```

better yet you can just use

```<code>if(in_array($ext,array("png","jpg","jpeg","gif"))){}
</code>```

also instead of using OR just use the double piped operator for the or condition: ||.

Body:
if (is_dir($dir)) {
  if($handle = opendir($dir)) {
        while($file = readdir($handle)) {
        // Break the filename by period; if there's more than one piece, grab the last piece.
        $parts = explode(".", $file);
        if (is_array($parts) && count($parts) > 1) {
            $ext = end($parts);
            // If it's an image that we want, echo the code.
          if ($ext == "png" OR $ext == "PNG" OR $ext == "jpg" OR $ext == "JPG" OR $ext == "jpeg" OR $ext == "JPEG" OR $ext == "gif" OR $ext == "GIF")
            echo "";
      }
    }
    closedir($handle);
  }
...

I'm using it in Wordpress, and the page loads pretty slowly, but it could also be from having a lot of images on it. I just wanted to make sure I wasn't doing something that was frowned upon for performance reasons.

Body:
We cant exactly say that opendir is slow as they is many configuration values that can effect performance.

what you should do is benchmark the segement of code in your app like so:

$start = microtime(true);
//Your Code
$end = (microtime(true) - $start);

and see exactly how long it had taken to process.

Some other tips:

$ext == "png" OR $ext == "PNG" is redundant, you should use $ext = strtolower(end($parts)); and then just use:

$ext == "png" OR $ext == "jpg" OR $ext == "jpeg" OR $ext == "gif"

better yet you can just use

if(in_array($ext,array("png","jpg","jpeg","gif"))){}

also instead of using OR just use the double piped operator for the or condition: ||.


问:
HTML tags  lost during receiving data from another Activity (ANDROID) putExtra getStringExtra
Hello I share some strings from strings.xml between 2 activities. In first one I have code like :

```<code> public void onClick(View v)
    {
        Intent intent;
        switch (v.getId())
        {
            case R.id.shops_id:
                intent = new Intent(this, TitleContent.class);
                intent.putExtra("content", getString(R.string.shop_content));
                startActivity(intent);
                break;
        }
    }
</code>```

In second one I'm receiving data like :

```<code>        Intent intent = getIntent();
        String content1 = intent.getStringExtra("content");
TextView content  =  (TextView)findViewById(R.id.contentID);

        if(content1!=null){

            content.setText(content1);
        }
</code>```

XML looks like :

```<code><resources>

    <string name="shop_content"><b>bold content</b></string>

</resources>
</code>```

Problem is that during sharing data html tags are lost. I try to use getText instead of getString but it doesn't work. In receiving activity I try to use to .setText(Html.fromHtml(somestring)); but it doesn;t work either.

答:
Problem is that during sharing data html tags are lost

When reading in a string resource, if you have basic HTML tags, those will be interpreted and applied to the result. However, that only works if you use getResources().getText(R.string.shop_content) instead of getString(), and if you use getCharSequenceExtra() instead of getStringExtra().

Or, pass R.string.shop_content as an int extra, so the second activity can use setText(getIntent().getIntExtra("content")).

(BTW, it is a good idea to define extra keys as constants, such as static final String EXTRA_CONTENT="content", so that both activities are using the same key)

Title: HTML tags <b></b> lost during receiving data from another Activity (ANDROID) putExtra getStringExtra

Body:
Hello I share some strings from strings.xml between 2 activities. In first one I have code like :

 public void onClick(View v)
    {
        Intent intent;
        switch (v.getId())
        {
            case R.id.shops_id:
                intent = new Intent(this, TitleContent.class);
                intent.putExtra("content", getString(R.string.shop_content));
                startActivity(intent);
                break;
        }
    }

In second one I'm receiving data like :

        Intent intent = getIntent();
        String content1 = intent.getStringExtra("content");
TextView content  =  (TextView)findViewById(R.id.contentID);

        if(content1!=null){

            content.setText(content1);
        }

XML looks like :

<resources>

    <string name="shop_content">bold content</string>

</resources>

Problem is that during sharing data html tags are lost. I try to use getText instead of getString but it doesn't work. In receiving activity I try to use to .setText(Html.fromHtml(somestring)); but it doesn;t work either.


问:
Unable to get Libre Office to load on redhat 6. Get stuck at the splash screen
This recently starting happening. I had been happily using libre office previously. I have tried rebooting and re-installing libre office with no effect. Using version 5.3.3.2-2.x86_64 of libre office. Using Redhat 6 version 2.6.32-642.15.1.el6.x86_64.
Process status shows </p>

```<code> jgaer@ljgaer1_/tmp/RPMS: ps -eafl | grep libre
 0 S jgaer     5860     1  0  80   0 - 75116 futex_ 04:33 ?          00:00:00 /opt/libreoffice5.3/program/oosplash --calc
 0 S jgaer     5878  5860  0  80   0 - 202475 futex_ 04:33 ?       00:00:00 /opt/libreoffice5.3/program/soffice.bin --calc --splash-pipe=5
 0 S jgaer     6078  5056  0  80   0 - 25830 pipe_w 04:46 pts/0    00:00:00 grep libre
</code>```

答: removing the directory $HOME/.config/libreoffice corrected the problem. </p>

Body:
This recently starting happening. I had been happily using libre office previously. I have tried rebooting and re-installing libre office with no effect. Using version 5.3.3.2-2.x86_64 of libre office. Using Redhat 6 version 2.6.32-642.15.1.el6.x86_64.
Process status shows

 jgaer@ljgaer1_/tmp/RPMS: ps -eafl | grep libre
 0 S jgaer     5860     1  0  80   0 - 75116 futex_ 04:33 ?          00:00:00 /opt/libreoffice5.3/program/oosplash --calc
 0 S jgaer     5878  5860  0  80   0 - 202475 futex_ 04:33 ?       00:00:00 /opt/libreoffice5.3/program/soffice.bin --calc --splash-pipe=5
 0 S jgaer     6078  5056  0  80   0 - 25830 pipe_w 04:46 pts/0    00:00:00 grep libre


问:
Extract RDD[(Array[String]) from RDD[(String, Array[String]) [Spark/scala]
I have this prbolem, I have one of this kind  RDD[(String, Array[String]), and I would like extract from it a RDD[Array[String]] that contains the values grouped by key:

e.g:

```<code>val x :RDD[(String, Array[String]) =
RDD[(a, Array[ "ra", "re", "ri"]),
(a, Array[ "ta", "te", "ti"]),
(b, Array[ "pa", "pe", "pi"])]
</code>```

I would like get:

```<code>val result: RDD[(String, RDD[Array[String]]) =
RDD[(a, RDD[Array[("ra", "re", "ri"),( "ta", "te", "ti")]]),
(b,  RDD[Array[("pa", "pe", "pi"),...]])
,...]
</code>```

答:
A simple reduceByKey should solve your issue

```<code>x.reduceByKey((prev, next)=> (prev ++ next))
</code>```

Body:
I have this prbolem, I have one of this kind  RDD[(String, Array[String]), and I would like extract from it a RDD[Array[String]] that contains the values grouped by key:

e.g:

val x :RDD[(String, Array[String]) =
RDD[(a, Array[ "ra", "re", "ri"]),
(a, Array[ "ta", "te", "ti"]),
(b, Array[ "pa", "pe", "pi"])]

I would like get:

val result: RDD[(String, RDD[Array[String]]) =
RDD[(a, RDD[Array[("ra", "re", "ri"),( "ta", "te", "ti")]]),
(b,  RDD[Array[("pa", "pe", "pi"),...]])
,...]

Body:
A simple reduceByKey should solve your issue

x.reduceByKey((prev, next)=> (prev ++ next))


问:
Rotating part of an image in 3D space
Here's the setup: This is for an ecommerce art site where some paintings are canvas transfers. The painting wraps around the sides and top and bottom of the canvas. We have high-res images of the entire painting, but what we want to display is a quasi-3D representation of the image in which you can see how the sides of the painting wrap around the canvas. Here's a rough sketch of what I'm talking about:

My question is, how can I rotate an image in 3D space? The approach I think I'd like to take, is to cut off a portion of the top and side of the image, and rotate then in 3D and then stich it back on to the top and side to give it the 3D look. How do I go about about doing that? It can be done using any .Net technology (GDI+, WPF etc.).

答:
In WPF using the ViewPort3D class you can create a cuboid which is 8x5x1 units. Create the image as a texture and then apply the texture to the front face (8x5) and the side faces (5x1) and the top and bottom faces (8x1) using texture coordinates. The front face coordinates should be: (1/9, 1/6), (8/9, 1/6), (1/9, 5/6) and (8/9, 5/6) for the front face, and from the nearest edge to those coordinates for the sides, e.g. for the left side: (0, 1/6), (1/9, 1/6), (0, 5/6) and (1/9, 5/6) for the left side.

Edit:
If you then want to be able to perform rotations on the 3D canvas model you can follow the advice here:
How can I do 3D transformation in WPF?

Title: Rotating part of an image in 3D space


问:
Center/Right-justify two labels in GTK sharp
I have two labels I want to horizontally align within a window, but need one to be centered and the other to be right justified.  How do I accomplish this with boxes and/or tables?</p>

答:
I ended up creating an HBox and added it to a VBox.  To the HBox I added three widgets:

```<code>var hBox = new HBox(true, 0);
hBox.PackStart(new Label(), true, true, 0);
hBox.PackStart(new Alignment(0.5f, 0, 0, 0) { new Label() }, true, true, 0);
hBox.PackStart(new Alignment(1, 0, 0, 0) { new Label() }, true, true, 0);
</code>```

The key seemed to be homogeneous sizing (the true in the HBox constructor) and the center and right alignment widgets.

Body:
I ended up creating an HBox and added it to a VBox.  To the HBox I added three widgets:

var hBox = new HBox(true, 0);
hBox.PackStart(new Label(), true, true, 0);
hBox.PackStart(new Alignment(0.5f, 0, 0, 0) { new Label() }, true, true, 0);
hBox.PackStart(new Alignment(1, 0, 0, 0) { new Label() }, true, true, 0);

The key seemed to be homogeneous sizing (the true in the HBox constructor) and the center and right alignment widgets.