问:
Field-level validation in Django REST - checking that field value is actually valid
I have a Django 1.10 project and a model like this:

```<code>class Student(models.Model):
    #...
    university = models.ForeignKey(University, ...)
</code>```

...and a serializer in which I want to perform a check like this (I provide a pseudo-code because I've got no idea how to write native Django code):

```<code>class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = '__all__'

    def validate_student(self, value):
        if invalid_value_is_provided_for_student:
            value = 666
        return value
</code>```

And most importantly, I want to re-assign a specific value to the field in case invalid value has been provided (in the example above, I assign 666 to it).
One way to do this that occurred to me is:

```<code>   def validate_student(self, value):
        if value not in University.objects.values('id'):
            value = 666
        return value
</code>```

...which seems to be a bit dirty. I have a feeling that Django has a native more elegant way to implement this using exception handling. Any ideas?

答:
You don't have to write any extra codes for that because you are creating the serializer by extending ModelSerializer. So that your serializer contains the default validation for university field provided by restframework. remove the validators and try to add some students with existing and non existing university id fields.

models.py

```<code>class Student(models.Model):
    #...
    university = models.ForeignKey(University, ...)
</code>```

serializers.py

```<code>class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = '__all__'
</code>```

leave the validation part to serializers.ModelSerializer. What happens here is ModelSerializer creates university attributes inside your serializer  like

university = PrimaryKeyRelatedField(queryset=University.objects.all())
Which is sufficient for the validation

UPDATE #2 based on the comment

For that requirement, you have to override the university field in the StudentSerializer class. Then you have to implement the model linking on create method.

models.py

```<code>class Student(models.Model):
    #...
    university = models.ForeignKey(University, ...)
</code>```

serializers.py

```<code>class StudentSerializer(serializers.ModelSerializer):

    university = serializers.IntegerField()

    class Meta:
        model = Student
        fields = '__all__'

    def create(self, validated_data):
        university_id = validated_data.pop('university')
        try:
            university = University.objects.get(id=university)
        except University.DoesNotExist:
            # default
            university = University.objects.get(id=666)
        return Student.objects.create(university=university, **validated_data)
</code>```

hope this will solve your issue

Body:
I have a Django 1.10 project and a model like this:

class Student(models.Model):
    #...
    university = models.ForeignKey(University, ...)

...and a serializer in which I want to perform a check like this (I provide a pseudo-code because I've got no idea how to write native Django code):

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = '__all__'

    def validate_student(self, value):
        if invalid_value_is_provided_for_student:
            value = 666
        return value

And most importantly, I want to re-assign a specific value to the field in case invalid value has been provided (in the example above, I assign 666 to it).
One way to do this that occurred to me is:

   def validate_student(self, value):
        if value not in University.objects.values('id'):
            value = 666
        return value

...which seems to be a bit dirty. I have a feeling that Django has a native more elegant way to implement this using exception handling. Any ideas?

Body:
You don't have to write any extra codes for that because you are creating the serializer by extending ModelSerializer. So that your serializer contains the default validation for university field provided by restframework. remove the validators and try to add some students with existing and non existing university id fields.

models.py

class Student(models.Model):
    #...
    university = models.ForeignKey(University, ...)

serializers.py

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = '__all__'

leave the validation part to serializers.ModelSerializer. What happens here is ModelSerializer creates university attributes inside your serializer  like

university = PrimaryKeyRelatedField(queryset=University.objects.all())
Which is sufficient for the validation

UPDATE #2 based on the comment

For that requirement, you have to override the university field in the StudentSerializer class. Then you have to implement the model linking on create method.

models.py

class Student(models.Model):
    #...
    university = models.ForeignKey(University, ...)

serializers.py

class StudentSerializer(serializers.ModelSerializer):

    university = serializers.IntegerField()

    class Meta:
        model = Student
        fields = '__all__'

    def create(self, validated_data):
        university_id = validated_data.pop('university')
        try:
            university = University.objects.get(id=university)
        except University.DoesNotExist:
            # default
            university = University.objects.get(id=666)
        return Student.objects.create(university=university, **validated_data)

hope this will solve your issue


来源: stackexchange

问:
Not able to read InputStream from RS232 Bluetooth module
I am trying to read values from a weighing machine connected to bluetooth module(M143 RS232 Bluetooth Serial Adapter purchased from eBay).I am able to connect the device and i am getting Socket object.But the InputStream is blocking and not able to read data from the stream(inputstream.available() is always returns zero).There is no issue when i write something to the OutputStream.I tried using BufferedReader but no change.Following is the code i tried.

```<code>InputStream inputStream = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
   total.append(line).append('\n');
}
//code is not reaching here it is blocking in the while loop
if(outputStream!=null){
  outputStream.flush();
  outputStream.close();
}
</code>```

答:
It is important to note that .read() or .readline() only halts reading when there is a newline or EOF, end of file.

However, socket connection does not have EOF unless the socket transfer is done.

so you could do the two following cases:

1) Change the other side(weighing machine in your case) to add \n or \r after each data transfer to let the Android side know one full set of data was sent.
This keeps the benefit of socket connection.
and you could do

```<code>while ((line = r.readLine()) != null) {
    //do what you want to do with line
    //... you dont need string builder in this case
}
</code>```

2) Halt each connection from the other side after each data transfer. This is not recommended because it is not anymore a socket transfer when you cut after every data transfer. Also it might cause TIME_WAIT and hinder further connections.

I was able to do the first case to solve my problem when I was in your shoes.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to read values from a weighing machine connected to bluetooth module(M143 RS232 Bluetooth Serial Adapter purchased from eBay).I am able to connect the device and i am getting Socket object.But the InputStream is blocking and not able to read data from the stream(inputstream.available() is always returns zero).There is no issue when i write something to the OutputStream.I tried using BufferedReader but no change.Following is the code i tried.

InputStream inputStream = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
   total.append(line).append('\n');
}
//code is not reaching here it is blocking in the while loop
if(outputStream!=null){
  outputStream.flush();
  outputStream.close();
}

Body:
It is important to note that .read() or .readline() only halts reading when there is a newline or EOF, end of file.

However, socket connection does not have EOF unless the socket transfer is done.

so you could do the two following cases:

1) Change the other side(weighing machine in your case) to add \n or \r after each data transfer to let the Android side know one full set of data was sent.
This keeps the benefit of socket connection.
and you could do

while ((line = r.readLine()) != null) {
    //do what you want to do with line
    //... you dont need string builder in this case
}

2) Halt each connection from the other side after each data transfer. This is not recommended because it is not anymore a socket transfer when you cut after every data transfer. Also it might cause TIME_WAIT and hinder further connections.

I was able to do the first case to solve my problem when I was in your shoes.


问:
Laravel version: 5.4.28 api routes not working on localhost
I downloaded Laravel 5.4.28 and created one api route. Nothing works on localhost. I am using XAMPP on Windows 8.1 as local development.

But everything is working fine on server. I also notice one strange thing. It will work on localhost if I create virtual host on localhost. like below.

```<code>php artisan serve
</code>```

Is that true? or Am I missing anything?

My api routes are like this...

http://localhost:1234/adminapi/public/api/v1/authenticateuser

答:
If your XAMPP works normally with normal PHP pages, did you check which version of php XAMPP uses ? the minimum required version is

```<code>PHP >= 5.6.4
</code>```

Laravel Official Website

The default version of XAMPP's PHP framework is 5.6.30

Body:
I downloaded Laravel 5.4.28 and created one api route. Nothing works on localhost. I am using XAMPP on Windows 8.1 as local development.

But everything is working fine on server. I also notice one strange thing. It will work on localhost if I create virtual host on localhost. like below.

php artisan serve

Is that true? or Am I missing anything?

My api routes are like this...

http://localhost:1234/adminapi/public/api/v1/authenticateuser

Body:
If your XAMPP works normally with normal PHP pages, did you check which version of php XAMPP uses ? the minimum required version is

PHP >= 5.6.4

Laravel Official Website

The default version of XAMPP's PHP framework is 5.6.30


问:
full-text search condition in sql
```<code> select * from quotestable where contains(RelatedKeyword, 'Benjamin Franklin Quotes')
</code>```

returns an error

```<code> Msg 7630, Level 15, State 3, Line 1
 Syntax error near 'Franklin' in the full-text search condition 'Benjamin Franklin'.
</code>```

I am surprised as to why. It should ideally search for the word but it has returned error message.

答:
I believe you are searching for the complete string Benjamin Franklin Quotes in RelatedKeyword column

You need to use double quotes to escape the space between your words.

```<code>select *
from quotestable
where contains(RelatedKeyword, '"Benjamin Franklin Quotes"')
</code>```

Title: full-text search condition in sql

Body:
 select * from quotestable where contains(RelatedKeyword, 'Benjamin Franklin Quotes')

returns an error

 Msg 7630, Level 15, State 3, Line 1
 Syntax error near 'Franklin' in the full-text search condition 'Benjamin Franklin'.

I am surprised as to why. It should ideally search for the word but it has returned error message.

Body:
I believe you are searching for the complete string Benjamin Franklin Quotes in RelatedKeyword column

You need to use double quotes to escape the space between your words.

select *
from quotestable
where contains(RelatedKeyword, '"Benjamin Franklin Quotes"')


问:
What is the difference between app.component.ts & app.component.html
I am not understanding the difference between app.component.ts & app.component.html in angular 2.

I am able to create the page using both. Then what to use in developing a web page.

Please guide me, I am new to angularjs2.
Thanks!

答:
app.component.ts - This file is main class file for any component
app.component.html - This file is component's html which can be bind with app component

app.component.ts has one @component decorator in which you can also define your html part as template

if you want to give any html file external link then you will use templateUrl and pass html file into it


问:
Time complexity of a de-duping algorithm
Here is a function for removing duplicates from an array.

function dedupe(arr) {
    var seen = {};
    arr.forEach((e,i)=>{
        if (seen[e]) {
            arr.splice(i, 1);
        }
        seen[e] = true;
    });
    return arr;
}

console.log(dedupe([1, 2, 1, 3, 4]));```
</div>
</div>
</p>

<p>I am interested in the time complexity of this function.</p>

<p>If we assume that <code>Array</code> is backed by a real array, does that the time complexity can be analysed as follows?</p>

<ul>
<li>allocation of <code>seen</code>: O(1)</li>
<li>enumerate all elements: O(n)</li>
<li>removal of a duplicate: O(n) (because re-allocation required item by item?)</li>
<li>return O(1)</li>
</ul>

<p>So is this an O(n^2) algorithm?</p>

<p><strong>Edit:</strong></p>

<p>Corrected for indexing issue.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function dedupe(arr) {
    var seen = {};
    for(let i = 0; i < arr.length; i++) {
        const e = arr[i];
        if (seen[e]) {
            arr.splice(i, 1);
            i--; // we have modified the array and need to continue from the current index
        }
        seen[e] = true;
    }
    return arr;
}

console.log(dedupe([1, 2, 1, 3, 1, 4, 4, 7, 6, 7, 7, 7, 1, 5]));</code>```

For those upset by the performance of the above, this is O(N) I think.

I wanted to de-dupe in-place. Use of Set maintains the order across host environments.

function dedupe(arr) {
    var seen = new Set();
    for(let i = 0; i < arr.length; i++) {
        seen.add(arr[i]);
    }
    arr.length = 0; // empty the array
    return arr.concat(...seen.keys());
}

console.log(dedupe([1, 2, 1, 3, 1, 4, 4, 7, 6, 7, 7, 7, 1, 5]));```

答:
You could save seen by filtering by index:

var t1 = [1, 2, 1, 1, 3, 1, 1, 4];
function uniqueList(list) {
    return list.filter(function (value, index, arr) {
        return list.indexOf(value) == index;
    });
}
console.log(t1);
console.log(uniqueList(t1));```

Body:
Here is a function for removing duplicates from an array.

function dedupe(arr) {
    var seen = {};
    arr.forEach((e,i)=>{
        if (seen[e]) {
            arr.splice(i, 1);
        }
        seen[e] = true;
    });
    return arr;
}

console.log(dedupe([1, 2, 1, 3, 4]));

I am interested in the time complexity of this function.

If we assume that Array is backed by a real array, does that the time complexity can be analysed as follows?

allocation of seen: O(1)

enumerate all elements: O(n)

removal of a duplicate: O(n) (because re-allocation required item by item?)

return O(1)

So is this an O(n^2) algorithm?

Edit:

Corrected for indexing issue.

function dedupe(arr) {
    var seen = {};
    for(let i = 0; i < arr.length; i++) {
        const e = arr[i];
        if (seen[e]) {
            arr.splice(i, 1);
            i--; // we have modified the array and need to continue from the current index
        }
        seen[e] = true;
    }
    return arr;
}

console.log(dedupe([1, 2, 1, 3, 1, 4, 4, 7, 6, 7, 7, 7, 1, 5]));

For those upset by the performance of the above, this is O(N) I think.

I wanted to de-dupe in-place. Use of Set maintains the order across host environments.

function dedupe(arr) {
    var seen = new Set();
    for(let i = 0; i < arr.length; i++) {
        seen.add(arr[i]);
    }
    arr.length = 0; // empty the array
    return arr.concat(...seen.keys());
}

console.log(dedupe([1, 2, 1, 3, 1, 4, 4, 7, 6, 7, 7, 7, 1, 5]));


问:
WPF : How to create separate Resources for each item in a bound ItemsControl
I want to achieve the following:

My ViewModel exposes a property named 'Categories' which is a collection of CategoryViewModel objects

Each CategoryViewModel object exposes a property called 'Items' which is a collection of strings*.

On my View, I want a TabControl with a TabItem for each object in the 'Categories' collection.

The Content of each TabItem should be a xceed DataGrid control displaying the contents of the selected tab's Items collection.

```<code><TabControl ItemsSource="{Binding Categories}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding CategoryName}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <xcdg:DataGridControl
                    ItemsSource="{Binding Items}"
                    AutoCreateColumns="True">
            </xcdg:DataGridControl>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>
</code>```

This works ok when I bind directly to the ItemsSource property of the DataGridControl. However, in order to utilize all of the functionality of the DataGridControl, I need to bind the ItemsSource property of the DataGridControl to a DataGridCollectionViewSource object that is bound to my Items collection. I do this when the grid ISN'T nested in another control by creating a DataGridCollectionViewSource object in the Resources section of the UserControl and binding to that.

```<code><UserControl>
    <UserControl.Resources>
        <xcdg:DataGridCollectionViewSource x:Key="GridData"
            Source="{Binding Items}" />
    </UserControl.Resources>
    <Grid>
        <xcdg:DataGridControl
                ItemsSource="{Binding Source={StaticResource GridData}}"
                AutoCreateColumns="True">
        </xcdg:DataGridControl>
    </Grid>
</UserControl>
</code>```

How do I need to structure the XAML so that when the TabControl is being bound, a DataGridCollectionViewSource object is created for each TabItem so that the DataGridControl that is generated within the content of the TabItem can be bound to it?

Clear as mud, right? :)

Thanks!

Notes:

*In the real solution the collection contains objects of a class that is more complex than a simple string, but a string was used to make the example more simple.

答:
OK, this is a bit of a long-shot, but could you use the DataGrid.Tag ...

```<code><TabControl.ContentTemplate>
    <DataTemplate>
        <xcdg:DataGridControl
                ItemsSource="{Binding RelativeSource={RelativeSource Self}, Path=Tag}"
                AutoCreateColumns="True">
            <xcdg:DataGridControl.Tag>
                 <xcdg:DataGridCollectionViewSource x:Key="GridData"
                      Source="{Binding Items}" />
            </xcdg:DataGridControl.Tag>
        </xcdg:DataGridControl>
    </DataTemplate>
</TabControl.ContentTemplate>
</code>```

Or ... resources can be defined on any FrameworkElement, so you could try:

```<code><TabControl.ContentTemplate>
    <DataTemplate>
        <xcdg:DataGridControl
                ItemsSource="{Binding Source={StaticResource GridData}}"
                AutoCreateColumns="True">
            <xcdg:DataGridControl.Resources>
                 <xcdg:DataGridCollectionViewSource x:Key="GridData"
                      Source="{Binding Items}" />
            </xcdg:DataGridControl.Resources>
        </xcdg:DataGridControl>
    </DataTemplate>
</TabControl.ContentTemplate>
</code>```

I don't use the eXceed Grid so cannot test whether these work - just a couple of ideas to try!

Colin E.

ContentLicense: CC BY-SA 2.5

Body:
I want to achieve the following:

My ViewModel exposes a property named 'Categories' which is a collection of CategoryViewModel objects

Each CategoryViewModel object exposes a property called 'Items' which is a collection of strings*.

On my View, I want a TabControl with a TabItem for each object in the 'Categories' collection.

The Content of each TabItem should be a xceed DataGrid control displaying the contents of the selected tab's Items collection.

<TabControl ItemsSource="{Binding Categories}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding CategoryName}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <xcdg:DataGridControl
                    ItemsSource="{Binding Items}"
                    AutoCreateColumns="True">
            </xcdg:DataGridControl>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

This works ok when I bind directly to the ItemsSource property of the DataGridControl. However, in order to utilize all of the functionality of the DataGridControl, I need to bind the ItemsSource property of the DataGridControl to a DataGridCollectionViewSource object that is bound to my Items collection. I do this when the grid ISN'T nested in another control by creating a DataGridCollectionViewSource object in the Resources section of the UserControl and binding to that.

<UserControl>
    <UserControl.Resources>
        <xcdg:DataGridCollectionViewSource x:Key="GridData"
            Source="{Binding Items}" />
    </UserControl.Resources>
    <Grid>
        <xcdg:DataGridControl
                ItemsSource="{Binding Source={StaticResource GridData}}"
                AutoCreateColumns="True">
        </xcdg:DataGridControl>
    </Grid>
</UserControl>

How do I need to structure the XAML so that when the TabControl is being bound, a DataGridCollectionViewSource object is created for each TabItem so that the DataGridControl that is generated within the content of the TabItem can be bound to it?

Clear as mud, right? :)

Thanks!

Notes:

*In the real solution the collection contains objects of a class that is more complex than a simple string, but a string was used to make the example more simple.

Body:
OK, this is a bit of a long-shot, but could you use the DataGrid.Tag ...

<TabControl.ContentTemplate>
    <DataTemplate>
        <xcdg:DataGridControl
                ItemsSource="{Binding RelativeSource={RelativeSource Self}, Path=Tag}"
                AutoCreateColumns="True">
            <xcdg:DataGridControl.Tag>
                 <xcdg:DataGridCollectionViewSource x:Key="GridData"
                      Source="{Binding Items}" />
            </xcdg:DataGridControl.Tag>
        </xcdg:DataGridControl>
    </DataTemplate>
</TabControl.ContentTemplate>

Or ... resources can be defined on any FrameworkElement, so you could try:

<TabControl.ContentTemplate>
    <DataTemplate>
        <xcdg:DataGridControl
                ItemsSource="{Binding Source={StaticResource GridData}}"
                AutoCreateColumns="True">
            <xcdg:DataGridControl.Resources>
                 <xcdg:DataGridCollectionViewSource x:Key="GridData"
                      Source="{Binding Items}" />
            </xcdg:DataGridControl.Resources>
        </xcdg:DataGridControl>
    </DataTemplate>
</TabControl.ContentTemplate>

I don't use the eXceed Grid so cannot test whether these work - just a couple of ideas to try!

Colin E.


问:
how to stop user after inserting 5 rows into table while userid is same in all 5 rows in codeigniter?
code:

```<code><?php
        if($this->input->post('insert'))
        {
            $data = array(
                'college_name' => $college_name,
                'name' => $_POST['name'],
                'student_id' => $student_id,
                'email' => $_POST['email'],
                'mobile' => $_POST['phone'],
                'city' => $_POST['city'],
                'course' => $_POST['course'],
                'inquiry' => $_POST['inquiry'],
                'query' => $_POST['query'],
                'date' => date('Y-m-d')
                );

            $query = $this->db->insert('college_contact',$data);
            if($query == true)
            {
                echo "<script>alert('your enquiry submitted successfully');</script>";
            }

            $this->db->select('name');
            $this->db->from('college_contact');
            $where = "student_id = '$student_id'";
            $this->db->where($where);
            $query = $this->db->get();
            $result = $query->num_rows();
            if($result > 0)
            {
                echo "you are not allow";
            }
        }
    ?>
</code>```

I am new in codeigniter. In this code I have created form and inserting its value into the database and now I want that if a particular student inserting 5 time data into table then he would be not allowed to insert more data into database. So, How can I do this ? Please help me.

Thank You

答:
While student insert when you have to check in your model:
Try this way, might it helps. </p>

```<code>$student_id = your student id which you get while inserting.

$query =$this->db->select('your_student_id')
                    ->from('college_contact')
                    ->where('your_student_id',$student_id)
                    ->get();

   //Now Find Number of rows
   $number_of_rows = $query->num_rows();
   if($number_of_rows < 5){
          //Put your insert query here

   } else {
         // Redirector gives the message that you have already inserted 5    times..or whatever you want in the message.
   }
</code>```

Body:
code:

<?php
        if($this->input->post('insert'))
        {
            $data = array(
                'college_name' => $college_name,
                'name' => $_POST['name'],
                'student_id' => $student_id,
                'email' => $_POST['email'],
                'mobile' => $_POST['phone'],
                'city' => $_POST['city'],
                'course' => $_POST['course'],
                'inquiry' => $_POST['inquiry'],
                'query' => $_POST['query'],
                'date' => date('Y-m-d')
                );

            $query = $this->db->insert('college_contact',$data);
            if($query == true)
            {
                echo "";
            }

            $this->db->select('name');
            $this->db->from('college_contact');
            $where = "student_id = '$student_id'";
            $this->db->where($where);
            $query = $this->db->get();
            $result = $query->num_rows();
            if($result > 0)
            {
                echo "you are not allow";
            }
        }
    ?>

I am new in codeigniter. In this code I have created form and inserting its value into the database and now I want that if a particular student inserting 5 time data into table then he would be not allowed to insert more data into database. So, How can I do this ? Please help me.

Thank You

Body:
While student insert when you have to check in your model:
Try this way, might it helps.

$student_id = your student id which you get while inserting.

$query =$this->db->select('your_student_id')
                    ->from('college_contact')
                    ->where('your_student_id',$student_id)
                    ->get();

   //Now Find Number of rows
   $number_of_rows = $query->num_rows();
   if($number_of_rows < 5){
          //Put your insert query here

   } else {
         // Redirector gives the message that you have already inserted 5    times..or whatever you want in the message.
   }


问:
Airflow python client
We have some applications running and we want to start using airflow. From the documentation it seems that the only way to start a DAG is over command line. Is this true?

For example we have a flask server running and we want to start some workflow controlled by airflow. How can we achieve this? Is there an API to trigger e.g.: "Run DAG now with parameters x,y,h"?

答:
After reading your question i understand your usecase as:

 That you wish to run/trigger a DAG from HTTP server

--> you can just use the provided Airflow webserver(localhost:8080/) from which you can trigger/run the dag manually

Also You Can go HERE ,which is still in experimentation mode and use the api as provided

Please elaborate more so as to understand question better.

Title: Airflow python client


问:
logback is ignoring my logback.xml
I have a sbt/scala project that includes as on of its dependencies "ch.qos.logback" % "logback-classic" % "1.0.13" and includes a logback.xml file whose contents are here:

```<code><configuration debug="true">
    <logger name="com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder" level="ERROR"/>
    <logger name="com.typesafe.sslconfig.ssl.AlgorithmChecker" level="ERROR"/>

    <root level="ERROR">
        <appender class="ch.qos.logback.core.ConsoleAppender">
            <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
                <pattern>%d{ISO8601} | %-5level | %thread | %logger{1} | %m%n</pattern>
            </encoder>
        </appender>
    </root>
</configuration>

https://pastebin.com/S1qauMi9
</code>```

When I run the program, I get the output here:

```<code>[WARN] [07/05/2017 16:01:25.782] [main] [com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder] validateStore: Skipping certificate with weak key size in thawtepremiumserverca: Certificate failed: cert = "1.2.840.113549.1.9.1=#16197072656d69756d2d736572766572407468617774652e636f6d,CN=Thawte Premium Server CA,OU=Certification Services Division,O=Thawte Consulting cc,L=Cape Town,ST=Western Cape,C=ZA" failed on constraint RSA keySize < 2048, algorithm = RSA, keySize = 1024
[WARN] [07/05/2017 16:01:25.782] [main] [com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder] validateStore: Skipping certificate with weak key size in thawteserverca: Certificate failed: cert = "1.2.840.113549.1.9.1=#16177365727665722d6365727473407468617774652e636f6d,CN=Thawte Server CA,OU=Certification Services Division,O=Thawte Consulting cc,L=Cape Town,ST=Western Cape,C=ZA" failed on constraint RSA keySize < 2048, algorithm = RSA, keySize = 1024
</code>```

...

```<code>16:01:25,822 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
16:01:25,822 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
16:01:25,822 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [jar:file:/Users/eswenson/Projects/Modulus/ws/modulus-shared-libraries/modules/dataset-client-cli/target/scala-2.11/dataset-client-cli-assembly-1.0.dev.jar!/logback.xml]
16:01:25,833 |-INFO in ch.qos.logback.core.joran.spi.ConfigurationWatchList@1eaf1e62 - URL [jar:file:/Users/eswenson/Projects/Modulus/ws/modulus-shared-libraries/modules/dataset-client-cli/target/scala-2.11/dataset-client-cli-assembly-1.0.dev.jar!/logback.xml] is not of type file
16:01:25,873 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder] to ERROR
16:01:25,873 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.typesafe.sslconfig.ssl.AlgorithmChecker] to ERROR
16:01:25,873 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to ERROR
16:01:25,907 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
16:01:25,908 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@6fd1660 - Registering current configuration as safe fallback point
[WARN] [07/05/2017 16:01:26.084] [main] [com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder] validateStore: Skipping certificate with weak key size in thawtepremiumserverca: Certificate failed: cert = "1.2.840.113549.1.9.1=#16197072656d69756d2d736572766572407468617774652e636f6d,CN=Thawte Premium Server CA,OU=Certification Services Division,O=Thawte Consulting cc,L=Cape Town,ST=Western Cape,C=ZA" failed on constraint RSA keySize < 2048, algorithm = RSA, keySize = 1024
[WARN] [07/05/2017 16:01:26.085] [main] [com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder] validateStore: Skipping certificate with weak key size in thawteserverca: Certificate failed: cert = "1.2.840.113549.1.9.1=#16177365727665722d6365727473407468617774652e636f6d,CN=Thawte Server CA,OU=Certification Services Division,O=Thawte Consulting cc,L=Cape Town,ST=Western Cape,C=ZA" failed on constraint RSA keySize < 2048, algorithm = RSA, keySize = 1024

Full log here:  https://pastebin.com/6Xd10TZZ
</code>```

Two issues:

1) why is there java logging output BEFORE logback appears to be getting configured?  How can I make sure that logback is initialized first?

2) why are all those warnings from com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder logged, when I explicitly set the level for these to be ERROR?

I've enabled logback configuration debugging so that you can see that logback does claim to be setting the loglevel to ERROR for this class.  But still the messages are logged.

答:
The only tag allowed inside the root-tag is appender-ref, where you reference a previously defined appender via name[1]. Move your appender definition to the start of your configuration and only reference it inside the root. Also, if your understanding of logback configuration is this basic you should first change that by reading the manual[2].

[1] https://logback.qos.ch/manual/configuration.html#rootElement

[2] https://logback.qos.ch/manual/index.html

Title: logback is ignoring my logback.xml

Body:
I have a sbt/scala project that includes as on of its dependencies "ch.qos.logback" % "logback-classic" % "1.0.13" and includes a logback.xml file whose contents are here:

<configuration debug="true">
    <logger name="com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder" level="ERROR"/>
    <logger name="com.typesafe.sslconfig.ssl.AlgorithmChecker" level="ERROR"/>

    <root level="ERROR">
        <appender class="ch.qos.logback.core.ConsoleAppender">
            <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
                <pattern>%d{ISO8601} | %-5level | %thread | %logger{1} | %m%n</pattern>
            </encoder>
        </appender>
    </root>
</configuration>

https://pastebin.com/S1qauMi9

When I run the program, I get the output here:

[WARN] [07/05/2017 16:01:25.782] [main] [com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder] validateStore: Skipping certificate with weak key size in thawtepremiumserverca: Certificate failed: cert = "1.2.840.113549.1.9.1=#16197072656d69756d2d736572766572407468617774652e636f6d,CN=Thawte Premium Server CA,OU=Certification Services Division,O=Thawte Consulting cc,L=Cape Town,ST=Western Cape,C=ZA" failed on constraint RSA keySize < 2048, algorithm = RSA, keySize = 1024
[WARN] [07/05/2017 16:01:25.782] [main] [com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder] validateStore: Skipping certificate with weak key size in thawteserverca: Certificate failed: cert = "1.2.840.113549.1.9.1=#16177365727665722d6365727473407468617774652e636f6d,CN=Thawte Server CA,OU=Certification Services Division,O=Thawte Consulting cc,L=Cape Town,ST=Western Cape,C=ZA" failed on constraint RSA keySize < 2048, algorithm = RSA, keySize = 1024

...

16:01:25,822 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
16:01:25,822 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
16:01:25,822 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [jar:file:/Users/eswenson/Projects/Modulus/ws/modulus-shared-libraries/modules/dataset-client-cli/target/scala-2.11/dataset-client-cli-assembly-1.0.dev.jar!/logback.xml]
16:01:25,833 |-INFO in ch.qos.logback.core.joran.spi.ConfigurationWatchList@1eaf1e62 - URL [jar:file:/Users/eswenson/Projects/Modulus/ws/modulus-shared-libraries/modules/dataset-client-cli/target/scala-2.11/dataset-client-cli-assembly-1.0.dev.jar!/logback.xml] is not of type file
16:01:25,873 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder] to ERROR
16:01:25,873 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.typesafe.sslconfig.ssl.AlgorithmChecker] to ERROR
16:01:25,873 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to ERROR
16:01:25,907 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
16:01:25,908 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@6fd1660 - Registering current configuration as safe fallback point
[WARN] [07/05/2017 16:01:26.084] [main] [com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder] validateStore: Skipping certificate with weak key size in thawtepremiumserverca: Certificate failed: cert = "1.2.840.113549.1.9.1=#16197072656d69756d2d736572766572407468617774652e636f6d,CN=Thawte Premium Server CA,OU=Certification Services Division,O=Thawte Consulting cc,L=Cape Town,ST=Western Cape,C=ZA" failed on constraint RSA keySize < 2048, algorithm = RSA, keySize = 1024
[WARN] [07/05/2017 16:01:26.085] [main] [com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder] validateStore: Skipping certificate with weak key size in thawteserverca: Certificate failed: cert = "1.2.840.113549.1.9.1=#16177365727665722d6365727473407468617774652e636f6d,CN=Thawte Server CA,OU=Certification Services Division,O=Thawte Consulting cc,L=Cape Town,ST=Western Cape,C=ZA" failed on constraint RSA keySize < 2048, algorithm = RSA, keySize = 1024

Full log here:  https://pastebin.com/6Xd10TZZ

Two issues:

1) why is there java logging output BEFORE logback appears to be getting configured?  How can I make sure that logback is initialized first?

2) why are all those warnings from com.typesafe.sslconfig.ssl.ConfigSSLContextBuilder logged, when I explicitly set the level for these to be ERROR?

I've enabled logback configuration debugging so that you can see that logback does claim to be setting the loglevel to ERROR for this class.  But still the messages are logged.


问:
Why does my list reduction over gamepad timestamps result in NaN?
I have a simple reduction in JavaScript:

```<code>navigator.getGamepads().reduce((i, j) => i.timestamp * j.timestamp, 1)
</code>```

When there are no gamepads, the result is 1.

When there is one gamepad, the result is NaN.

However, the list is of number values:

```<code>navigator.getGamepads().map(x => x.timestamp)
Array [ 280868.92 ]

navigator.getGamepads().map(x => typeof x.timestamp)
Array [ "number" ]
</code>```

Why is this?

I am using Firefox 54.0 64-bit

答:
When there are no gamepads, the result is 1. Because your initial value is 1. This is the second argument of your reduce function :

```<code>navigator.getGamepads().reduce((i, j) => i.timestamp * j.timestamp, 1)
</code>```

first argument  : (i, j) => i.timestamp * j.timestamp

second argument : 1

When there is one gamepad, you apply your function to myGamepad, and 1

```<code>(1, myGamepad) => 1.timestamp * myGamepad.timestamp
</code>```

myGamepad has a timestamp, but your initial value has none, so it returns a NaN

Maybe you could create an initial value like this

```<code>let initValue = {timestamp: 1}
navigator.getGamepads().reduce((i, j) => i.timestamp * j.timestamp, initValue )
</code>```

Body:
I have a simple reduction in JavaScript:

navigator.getGamepads().reduce((i, j) => i.timestamp * j.timestamp, 1)

When there are no gamepads, the result is 1.

When there is one gamepad, the result is NaN.

However, the list is of number values:

navigator.getGamepads().map(x => x.timestamp)
Array [ 280868.92 ]

navigator.getGamepads().map(x => typeof x.timestamp)
Array [ "number" ]

Why is this?

I am using Firefox 54.0 64-bit

Body:
When there are no gamepads, the result is 1. Because your initial value is 1. This is the second argument of your reduce function :

navigator.getGamepads().reduce((i, j) => i.timestamp * j.timestamp, 1)

first argument  : (i, j) => i.timestamp * j.timestamp

second argument : 1

When there is one gamepad, you apply your function to myGamepad, and 1

(1, myGamepad) => 1.timestamp * myGamepad.timestamp

myGamepad has a timestamp, but your initial value has none, so it returns a NaN

Maybe you could create an initial value like this

let initValue = {timestamp: 1}
navigator.getGamepads().reduce((i, j) => i.timestamp * j.timestamp, initValue )


问:
Interesting Applications of Interfaces
Why are interfaces useful?

Actually, I have a [small] idea of why interfaces are useful/necessary but...

What are [interesting or realistic] applications of interfaces?

答: One use that I have for interfaces is to help with unit testing framework classes that are hard to mock.  I will create an interface that works basically the same as the framework class and a wrapper class that implements the interface.  The constructor of the wrapper class takes an instance of the framework class as an argument.  The wrapper delegates the interface functionality it supports to the framework class, but I implement to my interface instead of the framework.   Using the interface makes it easy for me to mock out the wrapper class's functionality in my unit tests -- either using a mocking framework or by providing a fake class that also implements the interface and supplying it via dependency injection to any classes that would normally rely on the framework class.</p>

OwnerDisplayName: koldfyre

Title: Interesting Applications of Interfaces

OwnerDisplayName: tvanfosson


问:
What's the likelihood of Orchard CMS running on postgresql database?
And if that is not possible, what are the implications of using SQL Express? Would there be anything wrong with using SQLExpress for the CMS db, and postgresql for my app? </p>

答: I am not deeply familiar with this particular product, but unless they explicitly state that they support a certain SQL implementation, the chances are extremely slim that it would just happen to work.  A quick look around their site suggests that you will need to use Microsoft's SQL Server.</p>


问:
Error while deploying the solr service in tomcat
I am new to tomcat and solr . So solr is running on the tomcat server . When I run the tomcat using the sudo service tomcat7 start then it works perfectly,gets deployed properly. But when I am doing it from eclipse using the tomcat7:run goal then it is giving me some problems like -

```<code>ERROR UpdateLog:120 - Failure to open existing log file (non fatal) /opt/solr-tomcat/solr/collection1/data/tlog/tlog.0000000000000000146:org.apache.solr.common.SolrException: java.io.FileNotFoundException: /opt/solr-tomcat/solr/collection1/data/tlog/tlog.0000000000000000146 (Permission denied)
</code>```

ERROR UpdateLog:1441 - Error deleting file: /opt/solr-tomcat/solr/collection1/data/tlog/tlog.0000000000000000146
2017-07-06 14:39:05 ERROR UpdateLog:120 - Failure to open existing log file (non fatal) /opt/solr-tomcat/solr/collection1/data/tlog/tlog.0000000000000000147:org.apache.solr.common.SolrException: java.io.FileNotFoundException: /opt/solr-tomcat/solr/collection1/data/tlog/tlog.0000000000000000147 (Permission denied)

```<code>Caused by: org.apache.solr.common.SolrException: Error opening new searcher
Caused by: java.io.FileNotFoundException: /opt/solr-tomcat/solr/collection1/data/index/write.lock (Permission denied)
</code>```

I changed the permission of that folder as well now it is a tomcat7.
   In the  solr-tomcat folder.

```<code>  drwxr-xr-x 3 tomcat7 tomcat7 4096 Jul  6 14:11 solr/
    -rw-r--r-- 1 tomcat7 tomcat7 2118 Jul  6 14:11 solr.xml
</code>```

Can any one please help me with this ?

答:
Solr 5.0+ Support for deploying Solr into servers (like tomcat )no longer supported.

Solr should be a standalone server, follow these steps

Body:
I am new to tomcat and solr . So solr is running on the tomcat server . When I run the tomcat using the sudo service tomcat7 start then it works perfectly,gets deployed properly. But when I am doing it from eclipse using the tomcat7:run goal then it is giving me some problems like -

ERROR UpdateLog:120 - Failure to open existing log file (non fatal) /opt/solr-tomcat/solr/collection1/data/tlog/tlog.0000000000000000146:org.apache.solr.common.SolrException: java.io.FileNotFoundException: /opt/solr-tomcat/solr/collection1/data/tlog/tlog.0000000000000000146 (Permission denied)

ERROR UpdateLog:1441 - Error deleting file: /opt/solr-tomcat/solr/collection1/data/tlog/tlog.0000000000000000146
2017-07-06 14:39:05 ERROR UpdateLog:120 - Failure to open existing log file (non fatal) /opt/solr-tomcat/solr/collection1/data/tlog/tlog.0000000000000000147:org.apache.solr.common.SolrException: java.io.FileNotFoundException: /opt/solr-tomcat/solr/collection1/data/tlog/tlog.0000000000000000147 (Permission denied)

Caused by: org.apache.solr.common.SolrException: Error opening new searcher
Caused by: java.io.FileNotFoundException: /opt/solr-tomcat/solr/collection1/data/index/write.lock (Permission denied)

I changed the permission of that folder as well now it is a tomcat7.
   In the  solr-tomcat folder.

  drwxr-xr-x 3 tomcat7 tomcat7 4096 Jul  6 14:11 solr/
    -rw-r--r-- 1 tomcat7 tomcat7 2118 Jul  6 14:11 solr.xml

Can any one please help me with this ?


问:
What is the format of datetime in GET requests?
Some requests to GitLab API, like listing Merge Requests (https://docs.gitlab.com/ee/api/merge_requests.html#list-merge-requests) allow for URL query parameters of datetime type (created_after and created_before params for this particular example).

I can't seem to find a format for the datetime param that would work. Timestamps (both with and without milliseconds) doesn't work, nor do the ISO format like 2017-06-29T11:00:00.000Z.

Maybe this query parameter doesn't work at all?

答:
Found the reason: the created_before and created_after parameters, though listed and described in the official API documentation, are not yet included in any released version.

As of GitLab version 9.3.5 it's still listed under unreleased:

https://github.com/gitlabhq/gitlabhq/blob/master/changelogs/unreleased/12151-add-since-and-until-params-to-issuables.yml

https://github.com/gitlabhq/gitlabhq/commit/9fe6c2b2c2dd92831c93297021b41d6721e4b201


问:
Make bottom borders in line according to the lowest content
I'm developing my homepage using HTML, CSS, JSP and JavaScript, about musical instrument sale and communication of people.

Currently, I'm implementing a site-map for my site's menu configuration chart using div, ul, li and h tags. I would like to create bottom borders under the lowermost submenu items (last li tags) like in the picture below (see the blue indications). They should have bottom borders in line, adjusted to the lowermost (last) li tag.

How can I achieve my goal? This is what I have so far:

#sitemap_menu_container {
  width: 980px;
  height: 200px;
  border: 1px solid violet;
}

.sitemap_menu {
  width: 150px;
  height: 180px;
  float: left;
  margin-left: 5px;
  margin-right: 5px;
  margin-bottom: 5px;
  border-bottom: 1px solid #cbcbcb;
}

.sitemap_menu_header1 {
  font-size: 15pt;
  font-family: Arial;
  padding-bottom: 7px;
  border-bottom: 1px solid #cbcbcb;
}

.sitemap_menu_header2 {
  font-size: 15pt;
  font-family: Arial;
  color: red;
  padding-bottom: 7px;
  border-bottom: 1px solid #cbcbcb;
}

.sitemap_menu ul li {
  list-style: none;
  font-size: 11pt;
  font-family: Arial;
  background: url(../images/bullet1.png)no-repeat 0px 50%;
  padding-left: 10px;
  margin-left: 10px;
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sitemap_menu_container">
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header1">About</h2>
    <ul>
      <li>P&G introduce</li>
      <li>P&G history</li>
      <li>location</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header2">Piano goods</h2>
    <ul>
      <li>All kind of piano</li>
      <li>Upright</li>
      <li>Grand</li>
      <li>Electronics</li>
      <li>Synthesizer</li>
      <li>Management Tools</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header1">Guitar goods</h2>
    <ul>
      <li>Acoustic</li>
      <li>Classic</li>
      <li>Electrics</li>
      <li>Ukulele</li>
      <li>Management Tools</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header2">Community</h2>
    <ul>
      <li>Free Board</li>
      <li>Reviews</li>
      <li>Gallery Board</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header1">Event</h2>
    <ul>
      <li>Ongoing Event</li>
      <li>Announcement</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header2">Help you</h2>
    <ul>
      <li>Guide</li>
      <li>Notice</li>
      <li>FAQ</li>
      <li>Q&A</li>
      <li>Sitemap</li>
    </ul>
  </div>
</div></code>```

答:
In order to do that, you can use flexbox to be more flexible. Indeed, remove the height constraint in #sitemap_menu_container and .sitemap-menu and add display: flex to #sitemap_menu_container. Here is the snippet:

#sitemap_menu_container {
  width: 980px;
  border: 1px solid violet;
  display: flex;
}

.sitemap_menu {
  width: 150px;
  float: left;
  margin-left: 5px;
  margin-right: 5px;
  margin-bottom: 5px;
  border-bottom: 1px solid #cbcbcb;
}

.sitemap_menu_header1 {
  font-size: 15pt;
  font-family: Arial;
  padding-bottom: 7px;
  border-bottom: 1px solid #cbcbcb;
}

.sitemap_menu_header2 {
  font-size: 15pt;
  font-family: Arial;
  color: red;
  padding-bottom: 7px;
  border-bottom: 1px solid #cbcbcb;
}

.sitemap_menu ul li {
  list-style: none;
  font-size: 11pt;
  font-family: Arial;
  background: url(../images/bullet1.png)no-repeat 0px 50%;
  padding-left: 10px;
  margin-left: 10px;
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sitemap_menu_container">
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header1">About</h2>
    <ul>
      <li>P&G introduce</li>
      <li>P&G history</li>
      <li>location</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header2">Piano goods</h2>
    <ul>
      <li>All kind of piano</li>
      <li>Upright</li>
      <li>Grand</li>
      <li>Electronics</li>
      <li>Synthesizer</li>
      <li>Management Tools</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header1">Guitar goods</h2>
    <ul>
      <li>Acoustic</li>
      <li>Classic</li>
      <li>Electrics</li>
      <li>Ukulele</li>
      <li>Management Tools</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header2">Community</h2>
    <ul>
      <li>Free Board</li>
      <li>Reviews</li>
      <li>Gallery Board</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header1">Event</h2>
    <ul>
      <li>Ongoing Event</li>
      <li>Announcement</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header2">Help you</h2>
    <ul>
      <li>Guide</li>
      <li>Notice</li>
      <li>FAQ</li>
      <li>Q&A</li>
      <li>Sitemap</li>
    </ul>
  </div>
</div></code>```

Keep in mind that it's only working in modern browsers: https://caniuse.com/#search=flexbox. If you target older borwser, I think you need to use a table.

Hope this helps

Body:
I'm developing my homepage using HTML, CSS, JSP and JavaScript, about musical instrument sale and communication of people.

Currently, I'm implementing a site-map for my site's menu configuration chart using div, ul, li and h tags. I would like to create bottom borders under the lowermost submenu items (last li tags) like in the picture below (see the blue indications). They should have bottom borders in line, adjusted to the lowermost (last) li tag.

How can I achieve my goal? This is what I have so far:

#sitemap_menu_container {
  width: 980px;
  height: 200px;
  border: 1px solid violet;
}

.sitemap_menu {
  width: 150px;
  height: 180px;
  float: left;
  margin-left: 5px;
  margin-right: 5px;
  margin-bottom: 5px;
  border-bottom: 1px solid #cbcbcb;
}

.sitemap_menu_header1 {
  font-size: 15pt;
  font-family: Arial;
  padding-bottom: 7px;
  border-bottom: 1px solid #cbcbcb;
}

.sitemap_menu_header2 {
  font-size: 15pt;
  font-family: Arial;
  color: red;
  padding-bottom: 7px;
  border-bottom: 1px solid #cbcbcb;
}

.sitemap_menu ul li {
  list-style: none;
  font-size: 11pt;
  font-family: Arial;
  background: url(../images/bullet1.png)no-repeat 0px 50%;
  padding-left: 10px;
  margin-left: 10px;
  cursor: pointer;
}

About

P&G introduce

P&G history

location

Piano goods

All kind of piano

Upright

Grand

Electronics

Synthesizer

Management Tools

Guitar goods

Acoustic

Classic

Electrics

Ukulele

Management Tools

Community

Free Board

Reviews

Gallery Board

Event

Ongoing Event

Announcement

Help you

Guide

Notice

FAQ

Q&A

Sitemap

Body:
In order to do that, you can use flexbox to be more flexible. Indeed, remove the height constraint in #sitemap_menu_container and .sitemap-menu and add display: flex to #sitemap_menu_container. Here is the snippet:

#sitemap_menu_container {
  width: 980px;
  border: 1px solid violet;
  display: flex;
}

.sitemap_menu {
  width: 150px;
  float: left;
  margin-left: 5px;
  margin-right: 5px;
  margin-bottom: 5px;
  border-bottom: 1px solid #cbcbcb;
}

.sitemap_menu_header1 {
  font-size: 15pt;
  font-family: Arial;
  padding-bottom: 7px;
  border-bottom: 1px solid #cbcbcb;
}

.sitemap_menu_header2 {
  font-size: 15pt;
  font-family: Arial;
  color: red;
  padding-bottom: 7px;
  border-bottom: 1px solid #cbcbcb;
}

.sitemap_menu ul li {
  list-style: none;
  font-size: 11pt;
  font-family: Arial;
  background: url(../images/bullet1.png)no-repeat 0px 50%;
  padding-left: 10px;
  margin-left: 10px;
  cursor: pointer;
}

<div id="sitemap_menu_container">
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header1">About</h2>
    <ul>
      <li>P&G introduce</li>
      <li>P&G history</li>
      <li>location</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header2">Piano goods</h2>
    <ul>
      <li>All kind of piano</li>
      <li>Upright</li>
      <li>Grand</li>
      <li>Electronics</li>
      <li>Synthesizer</li>
      <li>Management Tools</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header1">Guitar goods</h2>
    <ul>
      <li>Acoustic</li>
      <li>Classic</li>
      <li>Electrics</li>
      <li>Ukulele</li>
      <li>Management Tools</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header2">Community</h2>
    <ul>
      <li>Free Board</li>
      <li>Reviews</li>
      <li>Gallery Board</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header1">Event</h2>
    <ul>
      <li>Ongoing Event</li>
      <li>Announcement</li>
    </ul>
  </div>
  <div class="sitemap_menu">
    <h2 class="sitemap_menu_header2">Help you</h2>
    <ul>
      <li>Guide</li>
      <li>Notice</li>
      <li>FAQ</li>
      <li>Q&A</li>
      <li>Sitemap</li>
    </ul>
  </div>
</div>

Keep in mind that it's only working in modern browsers: https://caniuse.com/#search=flexbox. If you target older borwser, I think you need to use a table.

Hope this helps


问:
For next loop issue
Gentleman,

I struggle with a small problem and get creasy because of them. I’d really appreciate your advice.

I have in a workbook a worksheet called “najemcy”. In this worksheet: A2=3, A7=2, A12=1. The following cells are merged: A2:A6, A7:A11, A12:A16. In column G are following values: G2=550, G3=55, G7=650, G8=11 G12=550.

The macro should find the last value in the column G in: range A2:A6, A7:A11, A12:A16. It means I expect to get 3 times msgbox with the address: $G$4, $G$8, $G$12, but instead of $G$12 I get $G$1048576.

```<code>Public Sub helpMe()

Dim najemcy As Worksheet
Dim pokoj As Range
Dim pokNr As Integer
Dim obecnyLok As Range

    For pokNr = 3 To 1 Step -1
        Set najemcy = Sheets("Najemcy")

        Set pokoj = najemcy.Range("A1:A100").Find(What:=pokNr, LookIn:=xlValues, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)
'            MsgBox pokoj.Address

        Set obecnyLok = najemcy.Range(pokoj.Offset(0, 6).Address).End(xlDown)
        MsgBox obecnyLok.Address

    Next
End Sub
</code>```

答:
When you use .end(xlDown) it will go down until it hits a blank row but if the first row beneath the current one is blank it will just keep going.

One way around this would be to check if the next row down is blank before using .end(xlDown)

```<code>Public Sub helpMe()

Dim najemcy As Worksheet
Dim pokoj As Range
Dim pokNr As Integer
Dim obecnyLok As Range

For pokNr = 3 To 1 Step -1
    Set najemcy = Sheets("Najemcy")

    Set pokoj = najemcy.Range("A1:A100").Find(What:=pokNr, LookIn:=xlValues, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
        'MsgBox pokoj.Address

    If najemcy.Range("G" & pokoj.Row + 1).Value = "" Then
        Set obecnyLok = najemcy.Range(pokoj.Offset(0, 6).Address)
    Else
        Set obecnyLok = najemcy.Range(pokoj.Offset(0, 6).Address).End(xlDown)
    End If
    MsgBox obecnyLok.Address

Next
End Sub
</code>```

Title: For next loop issue

Body:
Gentleman,

I struggle with a small problem and get creasy because of them. I’d really appreciate your advice.

I have in a workbook a worksheet called “najemcy”. In this worksheet: A2=3, A7=2, A12=1. The following cells are merged: A2:A6, A7:A11, A12:A16. In column G are following values: G2=550, G3=55, G7=650, G8=11 G12=550.

The macro should find the last value in the column G in: range A2:A6, A7:A11, A12:A16. It means I expect to get 3 times msgbox with the address: $G$4, $G$8, $G$12, but instead of $G$12 I get $G$1048576.

Public Sub helpMe()

Dim najemcy As Worksheet
Dim pokoj As Range
Dim pokNr As Integer
Dim obecnyLok As Range

    For pokNr = 3 To 1 Step -1
        Set najemcy = Sheets("Najemcy")

        Set pokoj = najemcy.Range("A1:A100").Find(What:=pokNr, LookIn:=xlValues, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)
'            MsgBox pokoj.Address

        Set obecnyLok = najemcy.Range(pokoj.Offset(0, 6).Address).End(xlDown)
        MsgBox obecnyLok.Address

    Next
End Sub

Body:
When you use .end(xlDown) it will go down until it hits a blank row but if the first row beneath the current one is blank it will just keep going.

One way around this would be to check if the next row down is blank before using .end(xlDown)

Public Sub helpMe()

Dim najemcy As Worksheet
Dim pokoj As Range
Dim pokNr As Integer
Dim obecnyLok As Range

For pokNr = 3 To 1 Step -1
    Set najemcy = Sheets("Najemcy")

    Set pokoj = najemcy.Range("A1:A100").Find(What:=pokNr, LookIn:=xlValues, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
        'MsgBox pokoj.Address

    If najemcy.Range("G" & pokoj.Row + 1).Value = "" Then
        Set obecnyLok = najemcy.Range(pokoj.Offset(0, 6).Address)
    Else
        Set obecnyLok = najemcy.Range(pokoj.Offset(0, 6).Address).End(xlDown)
    End If
    MsgBox obecnyLok.Address

Next
End Sub


问:
Error in code for download a file(txt) in clasic ASP
I have been trying 2 diferent codes this is one:

```<code>nombre="Prueba.txt"
set stream = Server.CreateObject("ADODB.Stream")
stream.Open
stream.Type = 2 ' binary
stream.LoadFromFile(Server.MapPath("./File/"&nombre))
Response.BinaryWrite(stream.Read)
</code>```

And the other code I'm trying is this :

```<code>Response.ContentType = "application/x-unknown" ' arbitrary

FPath = Server.MapPath("./File/"&nombre)
Response.AddHeader "Content-Disposition","attachment; filename=" & nombre

Set adoStream = CreateObject("ADODB.Stream")
adoStream.Open()
adoStream.Type = 1
adoStream.LoadFromFile(FPath)
Response.BinaryWrite adoStream.Read()
adoStream.Close
Set adoStream = Nothing

Response.End
</code>```

And I get that it have found a non especificated/defined data type.

答:
I have some working code, that's pretty much the same, but I use ContentType = "image/jpeg" and Response.Flush at the end.

```<code>Const adTypeBinary = 1

dim strFileName
strFileName = "archivo.jpg"

dim strFilePath
strFilePath = "C:\temp\" + strFileName

dim objStream
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open
objStream.Type = adTypeBinary
objStream.LoadFromFile strFilePath

Response.AddHeader "Content-Disposition", "attachment; filename=" & strFileName
Response.Charset = "UTF-8"
Response.ContentType = "image/jpeg"

Response.BinaryWrite objStream.Read
Response.Flush
</code>```

Body:
I have been trying 2 diferent codes this is one:

nombre="Prueba.txt"
set stream = Server.CreateObject("ADODB.Stream")
stream.Open
stream.Type = 2 ' binary
stream.LoadFromFile(Server.MapPath("./File/"&nombre))
Response.BinaryWrite(stream.Read)

And the other code I'm trying is this :

Response.ContentType = "application/x-unknown" ' arbitrary

FPath = Server.MapPath("./File/"&nombre)
Response.AddHeader "Content-Disposition","attachment; filename=" & nombre

Set adoStream = CreateObject("ADODB.Stream")
adoStream.Open()
adoStream.Type = 1
adoStream.LoadFromFile(FPath)
Response.BinaryWrite adoStream.Read()
adoStream.Close
Set adoStream = Nothing

Response.End

And I get that it have found a non especificated/defined data type.

Body:
I have some working code, that's pretty much the same, but I use ContentType = "image/jpeg" and Response.Flush at the end.

Const adTypeBinary = 1

dim strFileName
strFileName = "archivo.jpg"

dim strFilePath
strFilePath = "C:\temp\" + strFileName

dim objStream
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open
objStream.Type = adTypeBinary
objStream.LoadFromFile strFilePath

Response.AddHeader "Content-Disposition", "attachment; filename=" & strFileName
Response.Charset = "UTF-8"
Response.ContentType = "image/jpeg"

Response.BinaryWrite objStream.Read
Response.Flush


问:
Remove Commas with Jquery
I am in need of some code that removes commas from a string.
I currently have a variety of numbers in the number_format() for PHP.
I use Jquery to post certain things to a update page and I need the commas removed from a class.

for instance here is some code.

```<code><span class="money">1,234,567</span>
</code>```

I want the value of the code I post to be 1234567 instead of 1,234,567.
I would like to use Jquery if that's possible.

Thanks

答:
Could you please try with this , will remove comma on click on textbox , after focusout thousand seperated will be added...

$( "#salary" ).click(function() {

   $( "#salary" ).val(  $("#salary").val().replace(/,/g, ''));

});

$( "#salary" ).blur(function() {

   $( "#salary" ).val( addCommas($( "#salary" ).val());

});

function addCommas(nStr) {

    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;

}```

Title: Remove Commas with Jquery

Body:
I am in need of some code that removes commas from a string.
I currently have a variety of numbers in the number_format() for PHP.
I use Jquery to post certain things to a update page and I need the commas removed from a class.

for instance here is some code.

1,234,567

I want the value of the code I post to be 1234567 instead of 1,234,567.
I would like to use Jquery if that's possible.

Thanks


问:
For R data.table, how to use uniqueN() in order count unique/distinct values in multiple columns?
Let's say we have the following R data.table (though a dataframe is fine in principle as well):

```<code>library(data.table)
new_dt = as.data.table(readcsv(...))
head(new_dt)
    name order_no  overlimit
1    Amy       32  TRUE
2   Jack       14  TRUE
3   Jack       16  TRUE
4   Dave       11  FALSE
5    Amy       22  TRUE
6   Jack       16  TRUE
7    Tom       19  FALSE
8  Larry       22  FALSE
9    Tom       89  FALSE
10  Dave       81  TRUE
11  Jack       67  TRUE
12   Tom       60  TRUE
13   Amy       23  FALSE
14  Jack       16  TRUE
</code>```

For this task, the values of order_no is irrelevant---I would like to count the unique number of rows for name and overlimit:

```<code>name    overlimit  distinct_groups
Amy     TRUE       2
Amy     FALSE      1
Jack    TRUE       4
Jack    FALSE      0
Dave    TRUE       1
Dave    FALSE      1
...
</code>```

Does one simply include more columns in the by argument?

答:
To answer your question, yes, you can just add both columns to the by argument:

```<code>dt[, .(distinct_groups = uniqueN(order_no)), by = c("Name", "Overlimit")]
</code>```

Body:
Let's say we have the following R data.table (though a dataframe is fine in principle as well):

library(data.table)
new_dt = as.data.table(readcsv(...))
head(new_dt)
    name order_no  overlimit
1    Amy       32  TRUE
2   Jack       14  TRUE
3   Jack       16  TRUE
4   Dave       11  FALSE
5    Amy       22  TRUE
6   Jack       16  TRUE
7    Tom       19  FALSE
8  Larry       22  FALSE
9    Tom       89  FALSE
10  Dave       81  TRUE
11  Jack       67  TRUE
12   Tom       60  TRUE
13   Amy       23  FALSE
14  Jack       16  TRUE

For this task, the values of order_no is irrelevant---I would like to count the unique number of rows for name and overlimit:

name    overlimit  distinct_groups
Amy     TRUE       2
Amy     FALSE      1
Jack    TRUE       4
Jack    FALSE      0
Dave    TRUE       1
Dave    FALSE      1
...

Does one simply include more columns in the by argument?

Body:
To answer your question, yes, you can just add both columns to the by argument:

dt[, .(distinct_groups = uniqueN(order_no)), by = c("Name", "Overlimit")]


问:
locating jar file in $PATH environment variable for java -jar command
I want to run a simple executable jar like this:

```<code>java -jar /path/to/my/jar/myjar.jar
</code>```

However, i have to put that absolute path every time I want to run it. Is there a way to tell the OS to look for the jar in $PATH environment variable?

答: I think you'd use the classpath; append your directory to it and java -jar myjar.jar should work.

Body:
I want to run a simple executable jar like this:

java -jar /path/to/my/jar/myjar.jar

However, i have to put that absolute path every time I want to run it. Is there a way to tell the OS to look for the jar in $PATH environment variable?


问:
How to prevent showing a dialog when android app is in background
I start to download/upload a file in a background thread and end up showing up a dialog when the operation fails.

For cases when download/upload is in progress, app can be taken to background and network might get turned off or might face temporary disconnection. I will get the following crash if I try to show the dialog when the app is in background.

```<code>W/System.err(10235): java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
E/ConnectivityService( 455): EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent
D/ConnectivityService( 455): setProvNotificationVisibleIntent: E visible=false networkType=0 extraInfo=null
W/System.err(10235): at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1842)
W/System.err(10235): at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1860)
W/System.err(10235): at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:650)
W/System.err(10235): at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:609)
W/System.err(10235): at android.support.v4.app.DialogFragment.show(DialogFragment.java:143)
W/System.err(10235): at android.os.AsyncTask.finish(AsyncTask.java:636)
W/System.err(10235): at android.os.AsyncTask.access$500(AsyncTask.java:177)
W/System.err(10235): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask)
</code>```

I would certainly want to avoid this situation to show the dialog while the app is in background. The dialog should show when the app resumes. How can I do that gracefully without any need to set boolean flags.

I don't want to check whether the app is currently in background or not. I only intend to show the dialog automatically when app comes to background again.

答:
......
Previous code to check apps in background(Has been Deleted).....

This method will return true if app is in background. You can use this condition to show dialog

```<code>if(!isAppIsInBackground(context)){
  //show the dialog
}else{
  //Do as you need
}
</code>```

Edit

You can show dialog like this using a activity as a dialog

1. Create An Activity

```<code>public class DialogActivity extends Activity {

String message = "";

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

    message = getIntent().getStringExtra("message");
    if(message!=null) {
        displayAlert(message);
    }
}

 private void displayAlert(String msg)
 {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Network alert!");
    builder.setMessage(msg)
            .setCancelable(false)
            .setPositiveButton("OK",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    finish();
                }
            });
    AlertDialog alert = builder.create();
    alert.show();
 }
}
</code>```

2. Edit Activity Theme from Manifest

```<code>    <activity android:name=".DialogActivity"
              android:theme="@android:style/Theme.Holo.Light.Dialog">
    </activity>
</code>```

3. Write this to show dialog

```<code>private void showDialog(String your_message){
   Intent intent=new Intent(this,DialogActivity.class);
   intent.putExtra("message",message);
   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(intent);
}
</code>```

This Way Dialog will show automatically.
It will prevent showing dialog if app on background.
If app is not on background on any activity it can show the dialog.

I do it and tested it 100% works...

Body:
I start to download/upload a file in a background thread and end up showing up a dialog when the operation fails.

For cases when download/upload is in progress, app can be taken to background and network might get turned off or might face temporary disconnection. I will get the following crash if I try to show the dialog when the app is in background.

W/System.err(10235): java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
E/ConnectivityService( 455): EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent
D/ConnectivityService( 455): setProvNotificationVisibleIntent: E visible=false networkType=0 extraInfo=null
W/System.err(10235): at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1842)
W/System.err(10235): at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1860)
W/System.err(10235): at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:650)
W/System.err(10235): at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:609)
W/System.err(10235): at android.support.v4.app.DialogFragment.show(DialogFragment.java:143)
W/System.err(10235): at android.os.AsyncTask.finish(AsyncTask.java:636)
W/System.err(10235): at android.os.AsyncTask.access$500(AsyncTask.java:177)
W/System.err(10235): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask)

I would certainly want to avoid this situation to show the dialog while the app is in background. The dialog should show when the app resumes. How can I do that gracefully without any need to set boolean flags.

I don't want to check whether the app is currently in background or not. I only intend to show the dialog automatically when app comes to background again.

Body:
......
Previous code to check apps in background(Has been Deleted).....

This method will return true if app is in background. You can use this condition to show dialog

if(!isAppIsInBackground(context)){
  //show the dialog
}else{
  //Do as you need
}

Edit

You can show dialog like this using a activity as a dialog

1. Create An Activity

public class DialogActivity extends Activity {

String message = "";

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

    message = getIntent().getStringExtra("message");
    if(message!=null) {
        displayAlert(message);
    }
}

 private void displayAlert(String msg)
 {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Network alert!");
    builder.setMessage(msg)
            .setCancelable(false)
            .setPositiveButton("OK",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    finish();
                }
            });
    AlertDialog alert = builder.create();
    alert.show();
 }
}

2. Edit Activity Theme from Manifest

    <activity android:name=".DialogActivity"
              android:theme="@android:style/Theme.Holo.Light.Dialog">
    </activity>

3. Write this to show dialog

private void showDialog(String your_message){
   Intent intent=new Intent(this,DialogActivity.class);
   intent.putExtra("message",message);
   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(intent);
}

This Way Dialog will show automatically.
It will prevent showing dialog if app on background.
If app is not on background on any activity it can show the dialog.

I do it and tested it 100% works...

ContentLicense: CC BY-SA 4.0


问:
how to run kubelet as docker container
Can I run kubelet as a docker container based on kubernetes v1.6.6? if can do, how to create the image or where to get a image, and also how to run this image?

the following is my ops, but has some problems.

Dockerfile

FROM i71:5000/ubuntu:14.04
ADD iptables /usr/local/bin/iptables
ADD bin/kubelet /usr/local/bin/kubelet

docker runing sh

 #!/bin/bash
    docker rm -f $(docker ps -aq --filter "name=kubelet")
    docker run \
      -d \
      --restart="always" \
      --net="host" \
      -v /data/kubernetes-cluster/ssl:/data/kubernetes-cluster/ssl \
      -v /data/kubernetes-cluster/kube-conf:/data/kubernetes-cluster/kube-conf \
      -v /data/kubernetes-cluster/log:/data/kubernetes-cluster/log \
      -v /data/kubelet:/var/lib/kubelet \
      -v /etc/localtime:/etc/localtime \
      -v /var/run/:/var/run/ \
      -v /var/log/:/var/log/ \
      --privileged=true \
      --name kubelet \
      i71:5000/kubelet:v1.6.6 \
      /usr/local/bin/kubelet \
      --logtostderr=true \
      --v=0 \
      --cgroup-driver=cgroupfs \
      --api-servers=http://192.168.0.97:8080 \
      --docker-endpoint=http://127.0.0.1:4243 \
      --address=192.168.0.97 \
      --hostname-override=192.168.0.97 \
      --allow-privileged=true \
      --pod-infra-container-image=i71:5000/pod-infrastructure:rhel7 \
      --cluster-dns=10.3.0.2 \
      --experimental-bootstrap-kubeconfig=/data/kubernetes-cluster/kube-conf/bootstrap.kubeconfig \
      --kubeconfig=/data/kubernetes-cluster/kube-conf/kubelet.kubeconfig \
      --require-kubeconfig \
      --cert-dir=/data/kubernetes-cluster/ssl \
      --cluster-domain=cluster.local. \
      --hairpin-mode=promiscuous-bridge \
      --serialize-image-pulls=false

kubelet prints these errors(my docker damon pid is 5140):

    E0706 12:11:46.061949       1 container_manager_linux.go:394] open /proc/5140/cgroup: no such file or directory
    E0706 12:11:46.137217       1 container_manager_linux.go:97] Unable to ensure the docker processes run in the desired containers
    E0706 12:16:46.062290       1 container_manager_linux.go:394] open /proc/5140/cgroup: no such file or directory
    E0706 12:16:46.138189       1 container_manager_linux.go:97] Unable to ensure the docker processes run in the desired containers

if i do volume host dir '/proc', an error occurred by docker damon.

    docker: Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "process_linux.go:359: container init caused \"rootfs_linux.go:54: mounting\\\"/proc\\\" to rootfs \\\"/data/docker/local-storage/docker/aufs/mnt/6ad53fff3b30e8d709b1be326f5de1314371e174e34806d4d6c6436275b6fbd3\\\" at \\\"/proc\\\" caused \\\"\\\\\\\"/data/docker/local-storage/docker/aufs/mnt/6ad53fff3b30e8d709b1be326f5de1314371e174e34806d4d6c6436275b6fbd3/proc\\\\\\\" cannot be mounted because it is located inside \\\\\\\"/proc\\\\\\\"\\\"\"".

what should i do, can anyone show me a light?

答:
There is a official docker image called hyperkube which contains all Kubernetes binaries, see https://kubernetes.io/docs/getting-started-guides/scratch/#selecting-images

You can find an example systemd service on how to use it for kubelet here: https://github.com/kubernetes/kubernetes-anywhere/blob/master/phase2/ignition/vanilla/kubelet.service

Title: how to run kubelet as docker container


问:
How do I make cloud-init startup scripts run every time my EC2 instance boots?
I have an EC2 instance running an AMI based on the Amazon Linux AMI. Like all such AMIs, it supports the cloud-init system for running startup scripts based on the User Data passed into every instance. In this particular case, my User Data input happens to be an Include file that sources several other startup scripts:

```<code>#include
http://s3.amazonaws.com/path/to/script/1
http://s3.amazonaws.com/path/to/script/2
</code>```

The first time I boot my instance, the cloud-init startup script runs correctly. However, if I do a soft reboot of the instance (by running sudo shutdown -r now, for instance), the instance comes back up without running the startup script the second time around. If I go into the system logs, I can see:

```<code>Running cloud-init user-scripts
user-scripts already ran once-per-instance
[  OK  ]
</code>```

This is not what I want -- I can see the utility of having startup scripts that only run once per instance lifetime, but in my case these should run every time the instance starts up, like normal startup scripts.

I realize that one possible solution is to manually have my scripts insert themselves into rc.local after running the first time. This seems burdensome, however, since the cloud-init and rc.d environments are subtly different and I would now have to debug scripts on first launch and all subsequent launches separately.

Does anyone know how I can tell cloud-init to always run my scripts? This certainly sounds like something the designers of cloud-init would have considered.

答:
cloud-init supports this now natively, see runcmd vs bootcmd command descriptions in the documentation (http://cloudinit.readthedocs.io/en/latest/topics/examples.html#run-commands-on-first-boot):

"runcmd":

```<code>#cloud-config

# run commands
# default: none
# runcmd contains a list of either lists or a string
# each item will be executed in order at rc.local like level with
# output to the console
# - runcmd only runs during the first boot
# - if the item is a list, the items will be properly executed as if
#   passed to execve(3) (with the first arg as the command).
# - if the item is a string, it will be simply written to the file and
#   will be interpreted by 'sh'
#
# Note, that the list has to be proper yaml, so you have to quote
# any characters yaml would eat (':' can be problematic)
runcmd:
 - [ ls, -l, / ]
 - [ sh, -xc, "echo $(date) ': hello world!'" ]
 - [ sh, -c, echo "=========hello world'=========" ]
 - ls -l /root
 - [ wget, "http://slashdot.org", -O, /tmp/index.html ]
</code>```

"bootcmd":

```<code>#cloud-config

# boot commands
# default: none
# this is very similar to runcmd, but commands run very early
# in the boot process, only slightly after a 'boothook' would run.
# bootcmd should really only be used for things that could not be
# done later in the boot process.  bootcmd is very much like
# boothook, but possibly with more friendly.
# - bootcmd will run on every boot
# - the INSTANCE_ID variable will be set to the current instance id.
# - you can use 'cloud-init-per' command to help only run once
bootcmd:
 - echo 192.168.1.130 us.archive.ubuntu.com >> /etc/hosts
 - [ cloud-init-per, once, mymkfs, mkfs, /dev/vdb ]
</code>```

also note the "cloud-init-per" command example in bootcmd. From it's help:

```<code>Usage: cloud-init-per frequency name cmd [ arg1 [ arg2 [ ... ] ]
   run cmd with arguments provided.

   This utility can make it easier to use boothooks or bootcmd
   on a per "once" or "always" basis.

   If frequency is:
      * once: run only once (do not re-run for new instance-id)
      * instance: run only the first boot for a given instance-id
      * always: run every boot
</code>```

Body:
I have an EC2 instance running an AMI based on the Amazon Linux AMI. Like all such AMIs, it supports the cloud-init system for running startup scripts based on the User Data passed into every instance. In this particular case, my User Data input happens to be an Include file that sources several other startup scripts:

#include
http://s3.amazonaws.com/path/to/script/1
http://s3.amazonaws.com/path/to/script/2

The first time I boot my instance, the cloud-init startup script runs correctly. However, if I do a soft reboot of the instance (by running sudo shutdown -r now, for instance), the instance comes back up without running the startup script the second time around. If I go into the system logs, I can see:

Running cloud-init user-scripts
user-scripts already ran once-per-instance
[  OK  ]

This is not what I want -- I can see the utility of having startup scripts that only run once per instance lifetime, but in my case these should run every time the instance starts up, like normal startup scripts.

I realize that one possible solution is to manually have my scripts insert themselves into rc.local after running the first time. This seems burdensome, however, since the cloud-init and rc.d environments are subtly different and I would now have to debug scripts on first launch and all subsequent launches separately.

Does anyone know how I can tell cloud-init to always run my scripts? This certainly sounds like something the designers of cloud-init would have considered.

Body:
cloud-init supports this now natively, see runcmd vs bootcmd command descriptions in the documentation (http://cloudinit.readthedocs.io/en/latest/topics/examples.html#run-commands-on-first-boot):

"runcmd":

#cloud-config

# run commands
# default: none
# runcmd contains a list of either lists or a string
# each item will be executed in order at rc.local like level with
# output to the console
# - runcmd only runs during the first boot
# - if the item is a list, the items will be properly executed as if
#   passed to execve(3) (with the first arg as the command).
# - if the item is a string, it will be simply written to the file and
#   will be interpreted by 'sh'
#
# Note, that the list has to be proper yaml, so you have to quote
# any characters yaml would eat (':' can be problematic)
runcmd:
 - [ ls, -l, / ]
 - [ sh, -xc, "echo $(date) ': hello world!'" ]
 - [ sh, -c, echo "=========hello world'=========" ]
 - ls -l /root
 - [ wget, "http://slashdot.org", -O, /tmp/index.html ]

"bootcmd":

#cloud-config

# boot commands
# default: none
# this is very similar to runcmd, but commands run very early
# in the boot process, only slightly after a 'boothook' would run.
# bootcmd should really only be used for things that could not be
# done later in the boot process.  bootcmd is very much like
# boothook, but possibly with more friendly.
# - bootcmd will run on every boot
# - the INSTANCE_ID variable will be set to the current instance id.
# - you can use 'cloud-init-per' command to help only run once
bootcmd:
 - echo 192.168.1.130 us.archive.ubuntu.com >> /etc/hosts
 - [ cloud-init-per, once, mymkfs, mkfs, /dev/vdb ]

also note the "cloud-init-per" command example in bootcmd. From it's help:

Usage: cloud-init-per frequency name cmd [ arg1 [ arg2 [ ... ] ]
   run cmd with arguments provided.

   This utility can make it easier to use boothooks or bootcmd
   on a per "once" or "always" basis.

   If frequency is:
      * once: run only once (do not re-run for new instance-id)
      * instance: run only the first boot for a given instance-id
      * always: run every boot


问:
C++ using adodb to read excel file in 64-bit windows 7?
I've a legacy c++ code using adodb to read excel file in 32-bit windows, it's running file and it's something like:

```<code>#import "C:/Program Files/Common Files/System/ado/msado15.dll"  rename("EOF", "adoEOF") rename("BOF", "adoBOF")

string conn_str;
if(*(file_name.back()) == 'x')
    conn_str = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file_name + ";Extended Properties=\"Excel 12.0 Xml;HDR=Yes;IMEX=1\"";
else
    conn_str = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + file_name + ";Extended Properties=\"Excel 8.0;HDR=Yes\"";

::CoInitialize(NULL);

pRec->Open("SELECT * FROM [" + SheetName + "]", conn_str, adOpenStatic, adLockOptimistic, adCmdText));
</code>```

Now moving to the new environment to deploy (64-bit windows + 64-bit excel), the code cannot run, error message is "the Provider could not be found".

Trying to solve the issue, but after searching on Internet I'm a bit confused.

Microsoft FAQ About Windows DAC/MDAC etc seem say, "Microsoft Data Access Components (MDAC)" includes ADO, OLE DB, and ODBC; but MDAC is obsolete, and now the package is called "Windows Data Access Components (Windows DAC)" which is automatically installed in windows 7.

-- So I don't need to install MDAC on 64-bit Windows 7, and the download on  Microsoft Data Access Components (MDAC) 2.8 SP1 is a 32-bit one?

But then how could I use the legacy code calling msado15.dll to read excel?

Shall I install the 32-bit MDAC to SysWOW64 folder and continue use it? But can this 32-bit msado open an excel file created by 64-bit excel?

Or shall I use some other dll from "Windows DAC" to use ado on a 64-bit windows?

Or, I have to give up ado and find some way else to read excel files in c++?

答:
in case any one bumped in here, to access excel data in c++ code on a x64 windows machine with office 64-bit installed, you need

Download Microsoft Access Database Engine 2016 Redistributable
and install

import msadoXX.dll in C++ code

using proper connection string, on the page above expanding "install instructions" there are details such as ConnectionString property to “Microsoft.ACE.OLEDB.12.0”, for Excel 97-2003 Workbook (.xls) use "Excel 8.0", for Excel Workbook (.xlsx) use "Excel 12.0 Xml" etc. Note: "Microsoft.JET.OLEDB" doesn't work.

Body:
I've a legacy c++ code using adodb to read excel file in 32-bit windows, it's running file and it's something like:

#import "C:/Program Files/Common Files/System/ado/msado15.dll"  rename("EOF", "adoEOF") rename("BOF", "adoBOF")

string conn_str;
if(*(file_name.back()) == 'x')
    conn_str = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file_name + ";Extended Properties=\"Excel 12.0 Xml;HDR=Yes;IMEX=1\"";
else
    conn_str = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + file_name + ";Extended Properties=\"Excel 8.0;HDR=Yes\"";

::CoInitialize(NULL);

pRec->Open("SELECT * FROM [" + SheetName + "]", conn_str, adOpenStatic, adLockOptimistic, adCmdText));

Now moving to the new environment to deploy (64-bit windows + 64-bit excel), the code cannot run, error message is "the Provider could not be found".

Trying to solve the issue, but after searching on Internet I'm a bit confused.

Microsoft FAQ About Windows DAC/MDAC etc seem say, "Microsoft Data Access Components (MDAC)" includes ADO, OLE DB, and ODBC; but MDAC is obsolete, and now the package is called "Windows Data Access Components (Windows DAC)" which is automatically installed in windows 7.

-- So I don't need to install MDAC on 64-bit Windows 7, and the download on  Microsoft Data Access Components (MDAC) 2.8 SP1 is a 32-bit one?

But then how could I use the legacy code calling msado15.dll to read excel?

Shall I install the 32-bit MDAC to SysWOW64 folder and continue use it? But can this 32-bit msado open an excel file created by 64-bit excel?

Or shall I use some other dll from "Windows DAC" to use ado on a 64-bit windows?

Or, I have to give up ado and find some way else to read excel files in c++?


问:
Android : Change entire app layout directions programmatically
How can I change entire app layout direction to RTL?
I am writing an app that user must select it's language in first launch and the layout should change based on user selection to RTL or remains LTR.
I used to add android:supportsRtl="true" to the AndroidManifest and android:layoutDirection="rtl" for each layout but this approach have some problems like below :

One problem is when I change the direction to RTL the ActionBar home icon or navigation button (when home as up is enabled) remains LRT and just move to the right.

I also tried to change direction programmatically and the result was the same :

```<code>if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
            getWindows().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
        }
</code>```

Is there any way to force all activities to become RTL at once or we should set direction in each activity separately?

答: I also have this problem, i find that if your view's width set MATCH_PARENT, you should set the view's gravity with Gravity.LEFT in LTR model and set the view's gravity with Gravity.RIGHT in RTL model.

Body:
How can I change entire app layout direction to RTL?
I am writing an app that user must select it's language in first launch and the layout should change based on user selection to RTL or remains LTR.
I used to add android:supportsRtl="true" to the AndroidManifest and android:layoutDirection="rtl" for each layout but this approach have some problems like below :

One problem is when I change the direction to RTL the ActionBar home icon or navigation button (when home as up is enabled) remains LRT and just move to the right.

I also tried to change direction programmatically and the result was the same :

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
            getWindows().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
        }

Is there any way to force all activities to become RTL at once or we should set direction in each activity separately?


问:
C#: Why is my background worker thread signaling done when it isn't?
C#, using VS2010 and I've got something that makes no sense.

At startup my program needs to load several hundred k from text files.  After ensuring the loading code was working fine I threw it in a background thread.  So long as this is run from within the IDE everything's fine but when it's run standalone the thread says it's done when it isn't.  This of course goes boom.

The trigger code:

```<code>BackgroundWorker Background = new BackgroundWorker();
Background.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DatabaseLoaded);
Background.DoWork += new DoWorkEventHandler(delegate { Database.Load(); });
Background.RunWorkerAsync();
</code>```

and the stuff that's going boom is in DatabaseLoaded().

I put some messageboxes to trace what's going on:  The first and last lines of the Load() method and the first line of DatabaseLoaded().

In the IDE this triggers as I expect:  Load() beginning, Load() done, DatabaseLoaded().  However, when run standalone I get Load() beginning, DatabaseLoaded() and then the unhandled exception box (the loader hasn't even gotten to build empty tables, let alone fill them.)

Am I nuts or is Microsoft?

答: RunWorkerCompleted will be invoked in case of an error (such as an unhandled exception in Database.Load()). Check the Error property of the RunWorkerCompletedEventArgs.

Body:
C#, using VS2010 and I've got something that makes no sense.

At startup my program needs to load several hundred k from text files.  After ensuring the loading code was working fine I threw it in a background thread.  So long as this is run from within the IDE everything's fine but when it's run standalone the thread says it's done when it isn't.  This of course goes boom.

The trigger code:

BackgroundWorker Background = new BackgroundWorker();
Background.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DatabaseLoaded);
Background.DoWork += new DoWorkEventHandler(delegate { Database.Load(); });
Background.RunWorkerAsync();

and the stuff that's going boom is in DatabaseLoaded().

I put some messageboxes to trace what's going on:  The first and last lines of the Load() method and the first line of DatabaseLoaded().

In the IDE this triggers as I expect:  Load() beginning, Load() done, DatabaseLoaded().  However, when run standalone I get Load() beginning, DatabaseLoaded() and then the unhandled exception box (the loader hasn't even gotten to build empty tables, let alone fill them.)

Am I nuts or is Microsoft?