问:
I want to create an Android Page which looks like this
I am beginner Android Developer. I want to create an Android Page which will dynamically display Three things 1. Question No. 2. Your Answer 3. Right Answer. How can I do this? It should look like this and can grow dynamically</p>

答:
What about something like this (Uses a listview):

Mainactivity:

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ArrayList<Question> questionArrayList;

    private void fillList(){
        questionArrayList = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            questionArrayList.add(new Question(i,"myans","yourans"));
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fillList();
        ListView mlIstView = (ListView)findViewById(R.id.mListview);

        QuestionAdapter adapter = new QuestionAdapter(this,R.layout.listviewlayout,questionArrayList);
        mlIstView.setAdapter(adapter);
    }
}
</code>```

Question.java

```<code>public class Question {
private int numberOfQuestion;
private String yourAnswer;
private String correctAnswer;

public Question(int numberOfQuestion, String yourAnswer, String correctAnswer) {
    this.numberOfQuestion = numberOfQuestion;
    this.yourAnswer = yourAnswer;
    this.correctAnswer = correctAnswer;
}

public int getNumberOfQuestion() {
    return numberOfQuestion;
}

public String getYourAnswer() {
    return yourAnswer;
}

public String getCorrectAnswer() {
    return correctAnswer;
}
}
</code>```

QuestionAdapter

```<code>import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by waro on 6/4/17.
 */

public class QuestionAdapter extends ArrayAdapter<Question> {
    private ArrayList<Question> arrayList;
    public QuestionAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull ArrayList<Question> objects) {
        super(context, resource, objects);
        arrayList = objects;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if(convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.listviewlayout,parent,false);
        }
        Question question = arrayList.get(position);
        TextView questiontv = (TextView)convertView.findViewById(R.id.question);
        TextView yourans = (TextView)convertView.findViewById(R.id.yourans);
        TextView correctans = (TextView)convertView.findViewById(R.id.correctans);

        questiontv.setText(Integer.toString(question.getNumberOfQuestion()));
        yourans.setText(question.getYourAnswer());
        correctans.setText(question.getCorrectAnswer());
        return convertView;
    }
}
</code>```

activity_mail.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.suprentive.waro.myapplication.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:id="@+id/mLinearLayout">
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Question"
            android:layout_weight="1"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Your answer"
            android:layout_weight="1"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Right answer"
            android:layout_weight="1"/>
    </LinearLayout>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/mListview"
        android:layout_below="@id/mLinearLayout">
    </ListView>
</RelativeLayout>
</code>```

listviewlayout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/question"
        android:layout_weight="1"/>
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/yourans"
        android:layout_weight="1"/>
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/correctans"
        android:layout_weight="1"/>
</LinearLayout>
</code>```

Result

Hopefully this helps you out.

Body:
What about something like this (Uses a listview):

Mainactivity:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ArrayList<Question> questionArrayList;

    private void fillList(){
        questionArrayList = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            questionArrayList.add(new Question(i,"myans","yourans"));
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fillList();
        ListView mlIstView = (ListView)findViewById(R.id.mListview);

        QuestionAdapter adapter = new QuestionAdapter(this,R.layout.listviewlayout,questionArrayList);
        mlIstView.setAdapter(adapter);
    }
}

Question.java

public class Question {
private int numberOfQuestion;
private String yourAnswer;
private String correctAnswer;

public Question(int numberOfQuestion, String yourAnswer, String correctAnswer) {
    this.numberOfQuestion = numberOfQuestion;
    this.yourAnswer = yourAnswer;
    this.correctAnswer = correctAnswer;
}

public int getNumberOfQuestion() {
    return numberOfQuestion;
}

public String getYourAnswer() {
    return yourAnswer;
}

public String getCorrectAnswer() {
    return correctAnswer;
}
}

QuestionAdapter

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by waro on 6/4/17.
 */

public class QuestionAdapter extends ArrayAdapter<Question> {
    private ArrayList<Question> arrayList;
    public QuestionAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull ArrayList<Question> objects) {
        super(context, resource, objects);
        arrayList = objects;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if(convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.listviewlayout,parent,false);
        }
        Question question = arrayList.get(position);
        TextView questiontv = (TextView)convertView.findViewById(R.id.question);
        TextView yourans = (TextView)convertView.findViewById(R.id.yourans);
        TextView correctans = (TextView)convertView.findViewById(R.id.correctans);

        questiontv.setText(Integer.toString(question.getNumberOfQuestion()));
        yourans.setText(question.getYourAnswer());
        correctans.setText(question.getCorrectAnswer());
        return convertView;
    }
}

activity_mail.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.suprentive.waro.myapplication.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:id="@+id/mLinearLayout">
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Question"
            android:layout_weight="1"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Your answer"
            android:layout_weight="1"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Right answer"
            android:layout_weight="1"/>
    </LinearLayout>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/mListview"
        android:layout_below="@id/mLinearLayout">
    </ListView>
</RelativeLayout>

listviewlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/question"
        android:layout_weight="1"/>
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/yourans"
        android:layout_weight="1"/>
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/correctans"
        android:layout_weight="1"/>
</LinearLayout>

Result

Hopefully this helps you out.


来源: stackexchange

问:
Why isn't my prop logging or being passed in React Native?
I made a component called IconButton that takes some props and passes any additional props through.

```<code>import Icon from 'react-native-vector-icons/FontAwesome';

const IconButton = ({ icon, title, ...props }) => {
    console.log(props); // Actual: {}, expected: { onPress: [function] }
    return (
        <View style={ iconBox } { ...props }>
           <Icon name={ icon } size={ 48 } color="black" />
           <Text>{ title }</Text>
        </View>
};
</code>```

Then I rendered it:

```<code>const render = () => (
    <IconButton icon='plus' title='add' onPress={ () => console.log('hi') } />
);
</code>```

However when I tried to log it with console.log, onPress did not show up; it logged an empty object. Also, it wasn't passed to my View because it wasn't calling onPress when pressed. But when I pass different props with different types such as numbers and strings, it shows up fine.

Why isn't it being passed to my View and why isn't the prop being logged? I'm also using Expo if that may affect anything. I've set up an issue on GitHub.

答:
The logging issue is a bug with Expo, which uses JSON.stringify and other methods to give an output, but isn't outputting objects correctly. The bug also encompasses functions such as onPress here which are part of objects, and causes console.log to not log it at all, seen here. The issue is on GitHub and is set to be fixed in the next SDK update on June 19, 2017.

Now onto a different issue,View doesn't take an onPress prop, it's not supposed to be touchable. To have a touchable view, try the following wrappers:

TouchableHighlight, on touch, there's a tint added to the view

TouchableNativeFeedback, Android only, regular view that responds to touches

TouchableOpacity, on touch, the view opacity is decreased

TouchableWithoutFeedback, on touch there's no visible feedback but accepts taps (you shouldn't use this, all interactions should have visible feedback for a good UX)

ContentLicense: CC BY-SA 3.0

Body:
I made a component called IconButton that takes some props and passes any additional props through.

import Icon from 'react-native-vector-icons/FontAwesome';

const IconButton = ({ icon, title, ...props }) => {
    console.log(props); // Actual: {}, expected: { onPress: [function] }
    return (
        <View style={ iconBox } { ...props }>
           <Icon name={ icon } size={ 48 } color="black" />
           <Text>{ title }</Text>
        </View>
};

Then I rendered it:

const render = () => (
    <IconButton icon='plus' title='add' onPress={ () => console.log('hi') } />
);

However when I tried to log it with console.log, onPress did not show up; it logged an empty object. Also, it wasn't passed to my View because it wasn't calling onPress when pressed. But when I pass different props with different types such as numbers and strings, it shows up fine.

Why isn't it being passed to my View and why isn't the prop being logged? I'm also using Expo if that may affect anything. I've set up an issue on GitHub.


问:
How to get a particular value from a Url in iOS - Swift 3
I have a url that is reg code attached to it. I just want to retrieve the reg code 7954741093-41547468-3 from the below url </p>

```<code>https://mycode.funny.net/mycode/Registrations/7954741093-41547468-3?api-version=2011-04
</code>```

答:
You can use this:

```<code>let regCode:String = (url.components(separatedBy: "/").last?.components(separatedBy: "?").first)!
</code>```

Where url is

```<code>let url:String = "https://mycode.funny.net/mycode/Registrations/7954741093-41547468-3?api-version=2011-04"
</code>```

Body:
I have a url that is reg code attached to it. I just want to retrieve the reg code 7954741093-41547468-3 from the below url

https://mycode.funny.net/mycode/Registrations/7954741093-41547468-3?api-version=2011-04

Body:
You can use this:

let regCode:String = (url.components(separatedBy: "/").last?.components(separatedBy: "?").first)!

Where url is

let url:String = "https://mycode.funny.net/mycode/Registrations/7954741093-41547468-3?api-version=2011-04"


问:
Unknown dots rendered into page - what causes them?
I have a demo application here and in the upper left corners of the "tweets" there are dots and I have no idea where they come from. The code is written in Ember and the template looks like this

```<code> <h2>Ember.js DEMO Tweet list</h2>

        <div class="tweets-list">
        <h2>Tweets</h2>
<button {{action 'changeAllTweets'}}>Change All Tweets</button>
<button {{action 'changeOneTweet'}}>Change One Tweet</button>
<div class="row input-wrap">
</div>
        {{#each this.model.topTweets as |model|}}
            <li class="media">
<div {{action 'bindNewModel' this}} class="row">
  <a class="pull-left" href="#"><img class="media-object" width="75" height="75" src={{model.avatar}}/></a>
  <div class="media-body">
  <h4 class="media-heading">{{model.favorites}}</h4>
  <p>{{model.text}}</p>
        </div>
</div>
<div class="row">
<div class="col-xs-4">
<a href="#">Expand</a>
        </div>
<div class="col-xs-8">
<ul class="list-inline text-right">
<li href="#">Reply</li>
<li href="#">Retweet</li>
<li href="#">Favorite</li>
<li href="#">More</li>
        </ul>
        </div>
        </div>

</li>
{{/each}}

                </div>
</code>```

P.S. The SHOW LIST button must be pressed for the list to show

答:
It's because you're using list items, i.e.
 tags. They're shown with bullet points by default.

First of all, you should only use
 tags inside an ordered or unordered list (
 /
). You should consider if list items are appropriate here. Maybe
s are more suitable?

If you want to use list items you should wrap them in a
 list and then get rid of the bullet points by applying the styling: list-style-type: none.

Changing the display style of the list item will also get rid of the bullet point.

Body:
I have a demo application here and in the upper left corners of the "tweets" there are dots and I have no idea where they come from. The code is written in Ember and the template looks like this

Ember.js DEMO Tweet list

Tweets

<button {{action 'changeAllTweets'}}>Change All Tweets</button>
<button {{action 'changeOneTweet'}}>Change One Tweet</button>

        {{#each this.model.topTweets as |model|}}

{{model.favorites}}

{{model.text}}

Expand

Reply

Retweet

Favorite

More

{{/each}}

P.S. The SHOW LIST button must be pressed for the list to show

Body:
It's because you're using list items, i.e. <li> tags. They're shown with bullet points by default.

First of all, you should only use <li> tags inside an ordered or unordered list (<ol> / <ul>). You should consider if list items are appropriate here. Maybe <div>s are more suitable?

If you want to use list items you should wrap them in a <ul> list and then get rid of the bullet points by applying the styling: list-style-type: none.

Changing the display style of the list item will also get rid of the bullet point.


问:
What is the difference between localStorage, sessionStorage, session and cookies?
What are the technical pros and cons of localStorage, sessionStorage, session and cookies, and when would I use one over the other?

答:
LocalStorage

Pros:

Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. If you look at the Mozilla source code we can see that 5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.

The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.

The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

Cons:

It works on same-origin policy. So, data stored will only be available on the same origin.

Cookies

Pros:

Compared to others, there's nothing AFAIK.

Cons:

The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.

The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

Typically, the following are allowed:

300 cookies in total

4096 bytes per cookie

20 cookies per domain

81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)

sessionStorage

Pros:

It is similar to localStorage.

The data is not persistent i.e. data is only available per window (or tab in browsers like Chrome and Firefox). Data is only available during the page session. Changes made are saved and available for the current page, as well as future visits to the site on the same tab/window. Once the tab/window is closed, the data is deleted.

Cons:

The data is available only inside the window/tab in which it was set.

Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

Checkout across-tabs - how to facilitate easy communication between cross-origin browser tabs.

ContentLicense: CC BY-SA 4.0


问:
Typescript Interface, enforce the type of extra properties
Let's say I want to create an interface to describe this type of objects:

```<code>let myObj= {
    "count": 3,
    "key1": "foo",
    "key2": "bar",
    "key3": "baz"
};
</code>```

Those object always have a property count of type number and the rest of the properties are strings

If I define my interface using index signatures like this:

```<code>interface MyObect {
    count: number;
    [key: string]: string;
}
</code>```

I got the compiler error:

```<code>[ts] Property 'count' of type 'number' is not assignable to string index type 'string'.
</code>```

So I have to define it like this:

```<code>interface MyObect {
    count: number;
    [key: string]: any;
}
</code>```

But this definition is not as presise.

Is there a way to enforce the type of extra properties ?

答:
I've achieved something like this by using an intersection type:

```<code>type MyObject =
{
    count : number
} & {
    [key : string] : string
}
</code>```

This works (I am using TypeScript 2.3.2) for consuming an object, as follows

```<code>// x : MyObject
const count : number = x.count;
const foo : string = x.foo
</code>```

but as pointed out, this assignment still fails

```<code>const x : MyObject = {
    count: 10,
    foo: 'bar'
}
</code>```

so this may be of use only in some cases.

Body:
Let's say I want to create an interface to describe this type of objects:

let myObj= {
    "count": 3,
    "key1": "foo",
    "key2": "bar",
    "key3": "baz"
};

Those object always have a property count of type number and the rest of the properties are strings

If I define my interface using index signatures like this:

interface MyObect {
    count: number;
    [key: string]: string;
}

I got the compiler error:

[ts] Property 'count' of type 'number' is not assignable to string index type 'string'.

So I have to define it like this:

interface MyObect {
    count: number;
    [key: string]: any;
}

But this definition is not as presise.

Is there a way to enforce the type of extra properties ?

Body:
I've achieved something like this by using an intersection type:

type MyObject =
{
    count : number
} & {
    [key : string] : string
}

This works (I am using TypeScript 2.3.2) for consuming an object, as follows

// x : MyObject
const count : number = x.count;
const foo : string = x.foo

but as pointed out, this assignment still fails

const x : MyObject = {
    count: 10,
    foo: 'bar'
}

so this may be of use only in some cases.


问:
DisplayField - How to format for date?
I need to display a read only view of data.  I've chosen the DisplayField component to do this.  My problem is that I would like an easy way to call BasicForm.setValues(values) and have a date string automagically render correctly in one of the displayFields.  I haven't found anything that will do this for me (e.g. a renderer function), and am about to just format the date string manually prior to calling setValues(values).  Is there some slick way to do this?

Thanks!

答:
I came across this same problem because I like to pass my dates around as Unix timestamps and I had a requirement to display them using various formats depending on context.  Here's how I did it.

If you are loading the data via a store then you can use the convert function provided by Ext.data.Field.  For example:

```<code>var fields = [

  {name: 'sysTestedDateObj', mapping: 'sysTestedDateTS', type: 'date', dateFormat: 'timestamp'},

   /** Converted Fields **/
   {name: 'sysTestedDate', convert: function(v, rec){
      return fmtDate('sysTestedDateTS', rec);
   }},

   {name: 'targetChangeStartDate', convert: function(v, rec){
      return fmtDate('targetChangeStartDateTS', rec);
   }},

   {name: 'createDateTime', convert: function(v, rec){
      return fmtDateTime('createDateTS', rec);
   }},

   {name: 'modifyDateTime', convert: function(v, rec){
      return fmtDateTime('modifyDateTS', rec);
   }},
];

var store = new Ext.data.JsonStore({
  ...
  fields: fields
});
</code>```

Here's some conversion functions:

```<code>function fmtDate(sf, rec) {
  if ( rec[sf] ) {
    var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('l j F Y');
  }
};

function fmtDateShort(sf, rec) {
  if ( rec[sf] ) {
    var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('D j M Y');
  }
};

function fmtDateTime(sf, rec) {
  if ( rec[sf] ) {
    var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('l j F Y h:i a');
  }
};

function fmtDateTimeShort(sf, rec) {
  if ( rec[sf] ) {
    var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('D j M Y h:i a');
  }
};
</code>```

Where sf is the source field we are deriving the formatted date string from.

Note the following, it's important. The convert() function is presented with a copy of the data record as read by the reader (this is in the ExtJS docs). This means you can't use any mapped fields in your conversions. In the fields array above I have a field defined as,

```<code>{name: 'sysTestedDateObj', mapping: 'sysTestedDateTS', type: 'date', dateFormat: 'timestamp'}
</code>```

So I'm creating the sysTestedDateObj date object from the sysTestedDateTS field and I've told the reader that I want it to give me a date object derived from an object containing a Unix timestamp. This is a nice object to have for later on but it won't be part of the data record passed to our conversion function.

Also note that a conversion function can reference fields in the record that are not defined for use by the store. In the example above I an using the field sysTestedDateTS in a conversion function because I know the server is supplying it in it's JSON response, yet because I haven't defined it in the fields array it won't be available via the store to the consuming component.

ContentLicense: CC BY-SA 2.5

Title: DisplayField - How to format for date?

Body:
I came across this same problem because I like to pass my dates around as Unix timestamps and I had a requirement to display them using various formats depending on context.  Here's how I did it.

If you are loading the data via a store then you can use the convert function provided by Ext.data.Field.  For example:

var fields = [

  {name: 'sysTestedDateObj', mapping: 'sysTestedDateTS', type: 'date', dateFormat: 'timestamp'},

   /** Converted Fields **/
   {name: 'sysTestedDate', convert: function(v, rec){
      return fmtDate('sysTestedDateTS', rec);
   }},

   {name: 'targetChangeStartDate', convert: function(v, rec){
      return fmtDate('targetChangeStartDateTS', rec);
   }},

   {name: 'createDateTime', convert: function(v, rec){
      return fmtDateTime('createDateTS', rec);
   }},

   {name: 'modifyDateTime', convert: function(v, rec){
      return fmtDateTime('modifyDateTS', rec);
   }},
];

var store = new Ext.data.JsonStore({
  ...
  fields: fields
});

Here's some conversion functions:

function fmtDate(sf, rec) {
  if ( rec[sf] ) {
    var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('l j F Y');
  }
};

function fmtDateShort(sf, rec) {
  if ( rec[sf] ) {
    var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('D j M Y');
  }
};

function fmtDateTime(sf, rec) {
  if ( rec[sf] ) {
    var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('l j F Y h:i a');
  }
};

function fmtDateTimeShort(sf, rec) {
  if ( rec[sf] ) {
    var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('D j M Y h:i a');
  }
};

Where sf is the source field we are deriving the formatted date string from.

Note the following, it's important. The convert() function is presented with a copy of the data record as read by the reader (this is in the ExtJS docs). This means you can't use any mapped fields in your conversions. In the fields array above I have a field defined as,

{name: 'sysTestedDateObj', mapping: 'sysTestedDateTS', type: 'date', dateFormat: 'timestamp'}

So I'm creating the sysTestedDateObj date object from the sysTestedDateTS field and I've told the reader that I want it to give me a date object derived from an object containing a Unix timestamp. This is a nice object to have for later on but it won't be part of the data record passed to our conversion function.

Also note that a conversion function can reference fields in the record that are not defined for use by the store. In the example above I an using the field sysTestedDateTS in a conversion function because I know the server is supplying it in it's JSON response, yet because I haven't defined it in the fields array it won't be available via the store to the consuming component.


问:
How to choose "start" values in function stats4::mle in R?
It's bad I can't provide a reproducible code of my problem, because I use a big vector. But the question is still rather clear.
What I'm trying to do is to fit a beta distribution with mle function:

```<code>params <- mle(nll, start = list(alpha = 0.1, beta = 10), method = "L-BFGS-B")
</code>```

Where nll is a function counting negative logliklihood. In the documentation for mle function "start" argument is defined like "Initial values for optimizer."

At first I've tried several values and that's how I got 0.1 and 10. But now I want to fit parts of my vector by some factor and this values aren't already suitable for all of them. At some of them I get an error:

```<code> Error in optim(start, f, method = method, hessian = TRUE, ...) :
 L-BFGS-B needs finite values of 'fn'
In addition: Warning messages:
1: In lbeta(shape1[okk] + x[okk], shape2[okk] + size[okk] - x[okk]) :
NaNs produced
2: In lbeta(shape1[okk], shape2[okk]) : NaNs produced
</code>```

Searching the internet I found a reasonable idea to start with values, that are counted by the Method of Moments. So I changed my 0.1 and 10 by its formulas, but I still get the same error.

Do you know some programmatical way to compute 100% suitable initial values for fitting beta with mle?

Sorry for my poor English and thanks a lot in advance for your insights!

答:
I couldn't find a way to compute a 100% guaranteed suitable initial values, but here's how I could avoid this mistakes:

Just change a method to "BFGS". It will show warnings, but no errors.

or

Specify the lower and upper arguments in mle.

Body:
It's bad I can't provide a reproducible code of my problem, because I use a big vector. But the question is still rather clear.
What I'm trying to do is to fit a beta distribution with mle function:

params <- mle(nll, start = list(alpha = 0.1, beta = 10), method = "L-BFGS-B")

Where nll is a function counting negative logliklihood. In the documentation for mle function "start" argument is defined like "Initial values for optimizer."

At first I've tried several values and that's how I got 0.1 and 10. But now I want to fit parts of my vector by some factor and this values aren't already suitable for all of them. At some of them I get an error:

 Error in optim(start, f, method = method, hessian = TRUE, ...) :
 L-BFGS-B needs finite values of 'fn'
In addition: Warning messages:
1: In lbeta(shape1[okk] + x[okk], shape2[okk] + size[okk] - x[okk]) :
NaNs produced
2: In lbeta(shape1[okk], shape2[okk]) : NaNs produced

Searching the internet I found a reasonable idea to start with values, that are counted by the Method of Moments. So I changed my 0.1 and 10 by its formulas, but I still get the same error.

Do you know some programmatical way to compute 100% suitable initial values for fitting beta with mle?

Sorry for my poor English and thanks a lot in advance for your insights!


问:
Why is the logic not working in my rails app?
In my apps navbar, I have the following code:
apps/views/layout/application.html.erb:

```<code>    <ul class="nav navbar-nav navbar-right">
        <% if user_signed_in? %>
            <%if current_user.userinfo(&:info_complete) %>
                <li><%= link_to "My profile", userinfo_path(current_user.userinfo.id) %></li>
            <% elsif current_user.employer(&:info_complete)%>
                <li><%= link_to "My profile", employer_path(current_user.employer.id) %></li>
            <%else%>
                <li><%= link_to "Complete Profile", application_studoremp_path %></li>
            <%end%>
            <li><%= link_to "Sign Out", destroy_user_session_path, method: :delete %></li>
        <% else %>
            <li><%= link_to "Log In", new_user_session_path %></li>
            <li><%= link_to "Sign Up", new_user_registration_path %></li>
        <% end %>
    </ul>
</code>```

When a user signs up, they will be directed to a page to choose if they want to continue as an employer or student, then they will be directed to a page to fill out userinfo if they choose student, or fill out the employer info if they choose employer. So between signing up and filling out one of the forms, the user will not have "userinfo.id" OR "employer.id". That's why I redirect them to "application_studoremp_path". But the app throws an error saying userinfo.id is not found. Obviously it's not found because it's not created yet, that's why there is an "else" part. Why is the logic not working? :info_complete is a function in both the userinfo model and the employer model checking if the information has been filled out. Everything works fine if the user is already existing (If the userinfo.id or employer.id already exists).
This is the error:

My userinfo.rb model:

```<code>class Userinfo < ActiveRecord::Base
    belongs_to :user

    def info_complete?
        name? && email? && college? && gpa? && major?
    end
</code>```

答:
It seems the issue is in your function info_complete that is not returning the right value.

I would suggest you try some test on it, and I guess that when you wanna reference a variable from your model, you should use ":", like this:

```<code>def info_complete
  :name? && :age?
end
</code>```

Body:
In my apps navbar, I have the following code:
apps/views/layout/application.html.erb:

        <% if user_signed_in? %>
            <%if current_user.userinfo(&:info_complete) %>

<%= link_to "My profile", userinfo_path(current_user.userinfo.id) %>

            <% elsif current_user.employer(&:info_complete)%>

<%= link_to "My profile", employer_path(current_user.employer.id) %>

            <%else%>

<%= link_to "Complete Profile", application_studoremp_path %>

            <%end%>

<%= link_to "Sign Out", destroy_user_session_path, method: :delete %>

        <% else %>

<%= link_to "Log In", new_user_session_path %>

<%= link_to "Sign Up", new_user_registration_path %>

        <% end %>

When a user signs up, they will be directed to a page to choose if they want to continue as an employer or student, then they will be directed to a page to fill out userinfo if they choose student, or fill out the employer info if they choose employer. So between signing up and filling out one of the forms, the user will not have "userinfo.id" OR "employer.id". That's why I redirect them to "application_studoremp_path". But the app throws an error saying userinfo.id is not found. Obviously it's not found because it's not created yet, that's why there is an "else" part. Why is the logic not working? :info_complete is a function in both the userinfo model and the employer model checking if the information has been filled out. Everything works fine if the user is already existing (If the userinfo.id or employer.id already exists).
This is the error:

My userinfo.rb model:

class Userinfo < ActiveRecord::Base
    belongs_to :user

    def info_complete?
        name? && email? && college? && gpa? && major?
    end

Body:
It seems the issue is in your function info_complete that is not returning the right value.

I would suggest you try some test on it, and I guess that when you wanna reference a variable from your model, you should use ":", like this:

def info_complete
  :name? && :age?
end


问:
Difference in specifying component as tag or as an attribute
Let's say there is an Angular component with selector: 'my-component'.
It is possible to do the both ways:

```<code><div><my-component/></div>
</code>```

and

```<code><div my-component></div>
</code>```

Is there any difference in rendering or component behavior? If no then why we have 'attribute' option?

答:
selector: 'my-component' precisely means that you want to use a my-component element for the component.

If you want to use an attribute, use [my-component].

If you want to be able to use both, use my-component,[my-component].

The selector is a CSS selector, just like the CSS selectors you would use in a CSS file. They're more restricted, but the syntax is the same.

Body:
Let's say there is an Angular component with selector: 'my-component'.
It is possible to do the both ways:

<my-component/>

and

Is there any difference in rendering or component behavior? If no then why we have 'attribute' option?


问:
Alloy and Alloy* both fail on higher-order quantification
The following Alloy model:

```<code>sig A {}
run {all a : A | some r : A->A | a.r = a} for 3
run {some a : A | all r : A->A | a.r = a} for 3
</code>```

fails for both Alloy and Alloy*. If I run both commands using ordinary Alloy (specifically, using the latest build from http://alloy.mit.edu/alloy/download.html, version 4.2_2015-02-22, build date 2015-02-22 18:21 EST), then the first command works fine but the second fails to skolemize:

However, if I run both commands using Alloy* (specifically, using hola-0.2.jar from http://alloy.mit.edu/alloy/hola/), then the first command fails to skolemize and the second command works fine:

Perhaps there is some sort of bug here? I thought such problems were supposed not to happen in Alloy*; indeed, the Alloy* paper states that it "allows higher-order quantifiers to appear anywhere".

答: Version 0.3 should work correctly.</p>

Body:
The following Alloy model:

sig A {}
run {all a : A | some r : A->A | a.r = a} for 3
run {some a : A | all r : A->A | a.r = a} for 3

fails for both Alloy and Alloy*. If I run both commands using ordinary Alloy (specifically, using the latest build from http://alloy.mit.edu/alloy/download.html, version 4.2_2015-02-22, build date 2015-02-22 18:21 EST), then the first command works fine but the second fails to skolemize:

However, if I run both commands using Alloy* (specifically, using hola-0.2.jar from http://alloy.mit.edu/alloy/hola/), then the first command fails to skolemize and the second command works fine:

Perhaps there is some sort of bug here? I thought such problems were supposed not to happen in Alloy*; indeed, the Alloy* paper states that it "allows higher-order quantifiers to appear anywhere".

Body: Version 0.3 should work correctly.


问:
MDI Child Form Start Position Problem
I am having this strange problem with the start position of the MDI child Form.
Here is my code for the start position, I wanted it to be the middle left of
the MDI Parent Form.

```<code>        //show the task bar
        ChildForm c1 = new ChildForm();

        c1.MdiParent = this;
        c1.StartPosition = FormStartPosition.Manual;
        c1.Location = new Point(0, this.Height/2);
</code>```

Strange thing is every time I start my Mdi parent form, the vertical scrollbar show up
and the mdi child form is position lower than half of the MDI parent form's height.
Then if I scroll the scroll bar down to see the whole mdi child form, the scrollbar disappear.

After this point, no matter how I change the size of the mdi parent form, the scrollbar will
not show up again.

Does Anybody knows Why?

Also, I was wondering if it is possible to hide a mdi child form with only a handle-like control left
in the mdi parent form. If the user click that handle, then the form show up again. If the user
click somewhere else, the form hide. It is kind of like Window taskbar.

I tried to use form.hide(), but it hides the whole mdi child form.

Thanks

Alex

答:
you sholud minuse child form height and width like this</p>

```<code>c1.Location = new Point(0, (this.Height - c1.Height)/2);
</code>```

Title: MDI Child Form Start Position Problem

Body:
I am having this strange problem with the start position of the MDI child Form.
Here is my code for the start position, I wanted it to be the middle left of
the MDI Parent Form.

        //show the task bar
        ChildForm c1 = new ChildForm();

        c1.MdiParent = this;
        c1.StartPosition = FormStartPosition.Manual;
        c1.Location = new Point(0, this.Height/2);

Strange thing is every time I start my Mdi parent form, the vertical scrollbar show up
and the mdi child form is position lower than half of the MDI parent form's height.
Then if I scroll the scroll bar down to see the whole mdi child form, the scrollbar disappear.

After this point, no matter how I change the size of the mdi parent form, the scrollbar will
not show up again.

Does Anybody knows Why?

Also, I was wondering if it is possible to hide a mdi child form with only a handle-like control left
in the mdi parent form. If the user click that handle, then the form show up again. If the user
click somewhere else, the form hide. It is kind of like Window taskbar.

I tried to use form.hide(), but it hides the whole mdi child form.

Thanks

Alex

Body:
you sholud minuse child form height and width like this

c1.Location = new Point(0, (this.Height - c1.Height)/2);


问:
JQuery: start slideToggle() as hidden
I created this:

    $(document).ready(function(){
        var speed = 500;

        $('.brewed').click(function(){
            $('.ifBrewed').slideToggle(speed);
        });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
        background-color: black;
        color: white;
    }

    input[type=checkbox] {
    display:none;
    }

    .step_1, .step_2, .step_3 {
        padding: 2%;
        margin: 0 auto;
        font-weight: 100;
    }

    input[type=checkbox]:checked + label {
        border: 3px solid white;
    }

    .ifBrewed {
        background-color: #181818;
        padding: 2%;
        display: none;
    }</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

How do you enjoy your coffee?

                <input type="checkbox" name="site" id="so" />

Espresso

add the description here about this coffee!

                 <input type="checkbox" name="site" id="sf" />

Brewed

add the description here about this coffee!

                <input type="checkbox" name="site" id="ba" />

Drip coffee

                <input type="checkbox" name="site" id="bb" />

Aeropress

                <input type="checkbox" name="site" id="bc" />

French press

                <input type="checkbox" name="site" id="bd" />

Vacuum pot

                <input type="checkbox" name="site" id="be" />

Syphon

                <input type="checkbox" name="site" id="bf" />

V60

                <input type="checkbox" name="site" id="bg" />

Chemex

                <input type="checkbox" name="site" id="bh" />

Moka pot

                <input type="checkbox" name="site" id="bi" />

Percolato

                <input type="checkbox" name="site" id="bj" />

Eva solo

```

I did like other threads said, Add the display:none feature, and I did try on both CSS and JQuery .css().
It's going well, but I need help with this little bug.

As you can see, when you click the Slide toggle input it toggles then toggles back, but I want it to stay without toggling off until I click it again.

How do I do that?

Thank you!

答:
The click event is triggering twice because you've assigned a click event handler on .brewed and that's in an input/label.  You need to either re-think the event you want to toggle .ifBrewed or you can just assign another click handler to that label and disable the default action.

$(document).ready(function() {
  var speed = 500;
  $('label[for="sf"]').on('click',function(e) {
    e.preventDefault();
  })
  $('.brewed').on('click',function(e) {
    $(".ifBrewed").slideToggle(speed);
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  background-color: black;
  color: white;
}

input[type=checkbox] {
  display: none;
}

.step_1,
.step_2,
.step_3 {
  padding: 2%;
  margin: 0 auto;
  font-weight: 100;
}

input[type=checkbox]:checked+label {
  border: 3px solid white;
}

.ifBrewed {
  background-color: #181818;
  padding: 2%;
  display: none;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

How do you enjoy your coffee?

        <input type="checkbox" name="site" id="so" />

Espresso

add the description here about this coffee!

        <input type="checkbox" name="site" id="sf" />

Brewed

add the description here about this coffee!

          <input type="checkbox" name="site" id="ba" />

Drip coffee

          <input type="checkbox" name="site" id="bb" />

Aeropress

          <input type="checkbox" name="site" id="bc" />

French press

          <input type="checkbox" name="site" id="bd" />

Vacuum pot

          <input type="checkbox" name="site" id="be" />

Syphon

          <input type="checkbox" name="site" id="bf" />

V60

          <input type="checkbox" name="site" id="bg" />

Chemex

          <input type="checkbox" name="site" id="bh" />

Moka pot

          <input type="checkbox" name="site" id="bi" />

Percolato

          <input type="checkbox" name="site" id="bj" />

Eva solo

```

Title: JQuery: start slideToggle() as hidden

Body:
I created this:

    $(document).ready(function(){
        var speed = 500;

        $('.brewed').click(function(){
            $('.ifBrewed').slideToggle(speed);
        });
    });

html, body {
        background-color: black;
        color: white;
    }

    input[type=checkbox] {
    display:none;
    }

    .step_1, .step_2, .step_3 {
        padding: 2%;
        margin: 0 auto;
        font-weight: 100;
    }

    input[type=checkbox]:checked + label {
        border: 3px solid white;
    }

    .ifBrewed {
        background-color: #181818;
        padding: 2%;
        display: none;
    }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

How do you enjoy your coffee?

                <input type="checkbox" name="site" id="so" />

Espresso

add the description here about this coffee!

                 <input type="checkbox" name="site" id="sf" />

Brewed

add the description here about this coffee!

                <input type="checkbox" name="site" id="ba" />

Drip coffee

                <input type="checkbox" name="site" id="bb" />

Aeropress

                <input type="checkbox" name="site" id="bc" />

French press

                <input type="checkbox" name="site" id="bd" />

Vacuum pot

                <input type="checkbox" name="site" id="be" />

Syphon

                <input type="checkbox" name="site" id="bf" />

V60

                <input type="checkbox" name="site" id="bg" />

Chemex

                <input type="checkbox" name="site" id="bh" />

Moka pot

                <input type="checkbox" name="site" id="bi" />

Percolato

                <input type="checkbox" name="site" id="bj" />

Eva solo

I did like other threads said, Add the display:none feature, and I did try on both CSS and JQuery .css().
It's going well, but I need help with this little bug.

As you can see, when you click the Slide toggle input it toggles then toggles back, but I want it to stay without toggling off until I click it again.

How do I do that?

Thank you!

Body:
The click event is triggering twice because you've assigned a click event handler on .brewed and that's in an input/label.  You need to either re-think the event you want to toggle .ifBrewed or you can just assign another click handler to that label and disable the default action.

$(document).ready(function() {
  var speed = 500;
  $('label[for="sf"]').on('click',function(e) {
    e.preventDefault();
  })
  $('.brewed').on('click',function(e) {
    $(".ifBrewed").slideToggle(speed);
  })
});

html,
body {
  background-color: black;
  color: white;
}

input[type=checkbox] {
  display: none;
}

.step_1,
.step_2,
.step_3 {
  padding: 2%;
  margin: 0 auto;
  font-weight: 100;
}

input[type=checkbox]:checked+label {
  border: 3px solid white;
}

.ifBrewed {
  background-color: #181818;
  padding: 2%;
  display: none;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <!-- Step 1 -->
  <div class="row">
    <h2>How do you enjoy your coffee?</h2>
    <div class="col-lg-6 col-sm-6 col-xs-6 step_1 text-center">
      <div>
        <input type="checkbox" name="site" id="so" />
        <label for="so">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Espresso</h3>
                    <p>add the description here about this coffee!</p>
                </label>
      </div>
    </div>
    <div class="col-lg-6 col-sm-6 col-xs-6 step_1 brewed text-center">
      <div>
        <input type="checkbox" name="site" id="sf" />
        <label for="sf">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Brewed</h3>
                    <p>add the description here about this coffee!</p>
                </label>
      </div>
    </div>
  </div>

  <!-- Step 1.5 -->
  <div class="ifBrewed">
    <div class="row">
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="ba" />
          <label for="ba">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Drip coffee</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bb" />
          <label for="bb">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Aeropress</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bc" />
          <label for="bc">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>French press</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bd" />
          <label for="bd">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Vacuum pot</h3>
                </label>
        </div>
      </div>
    </div>
    <!-- Row 2 -->
    <div class="row">
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="be" />
          <label for="be">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Syphon</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bf" />
          <label for="bf">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>V60</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bg" />
          <label for="bg">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Chemex</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bh" />
          <label for="bh">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Moka pot</h3>
                </label>
        </div>
      </div>
    </div>
    <!-- Row 3 -->
    <div class="row">
      <div class="col-lg-3 col-md-3"></div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bi" />
          <label for="bi">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Percolato</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 step_1.5 text-center">
        <div>
          <input type="checkbox" name="site" id="bj" />
          <label for="bj">
                    <img class="img-responsive" src="https://villagecraftandcandle.com/image/cache/data/products/fresh-brewed-coffee-800x518.jpg" />
                    <h3>Eva solo</h3>
                </label>
        </div>
      </div>
      <div class="col-lg-3 col-md-3"></div>
    </div>
  </div>
</div>


问:
How to map chars to (playing) cards?
I have an android card game app.
In my app i send data about the game cards that has been played between the players, and i try to make the messages as short as possible.
I have a class that represents each card.
Now, in order to make the messages smaller, i refer to each card as a single char.
For example ace of spades would be 'a'
Ace of diamonds would be 'b' and so on..

My question is, how can i map the chars back to the corresponding card, in the most effective way?
(For example hashmap of chars and cards)
For example if a player receives 'a, b' he translates it to aces of spades and diamonds.

Thanks!

答:
I believe Switch-case/if-else are ok in this situation. It would get large, but any kind of code where you define 50 mappings would be big.

One other approach would be to "store" your Character<-->Card Relationship somehow and use methods to retrieve the values. You would have the relationships in an easily read manner and it is easy to register mappings and work with it.

I think there is a Map for 1:1 relationships (BiMap from Googles Guava?). You can just register your Characters and Cards in that map so you always can identify in both directions.

If you want to do it without third Party libs, you should be able to easily do it using two maps:

```<code>/** used to find the correct Card by Character */
private final static Map<Character, Card> mapCharToCard = new HashMap<>();

/** used to find the correct Character by Card (for sending over network) */
private final static Map<Card, Character> mapCardToChar = new HashMap<>();

/* Always stores boths ways so you can always map it back and forth */
public final static void register(Character character, Card card) {

    mapCharToCard.put(character, card);
    mapCardToChar.put(card, character);
}

public final static Character map(Card card) {

    return mapCardToChar.get(card);
}

public final static Card map(Character character) {

    return mapCharToCard.get(character);
}

public static void main(String[] args) {

    register('a', new Card("Spades", "Ace"));
    register('b', new Card("Heart", "King"));

    System.out.println(map('a'));
    System.out.println(map('b'));

    // Even works with new cards as hashmap uses equals() to check
    System.out.println(map(new Card("Spades", "Ace")));
}

public static class Card {

    private String color;
    private String value;

    public Card(String color, String value) {
        super();
        this.color = color;
        this.value = value;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String toString() {
        return "Card [getColor()=" + getColor() + ", getValue()=" + getValue() + "]";
    }

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((color == null) ? 0 : color.hashCode());
        result = prime * result + ((value == null) ? 0 : value.hashCode());
        return result;
    }

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Card other = (Card) obj;
        if (color == null) {
            if (other.color != null)
                return false;
        } else if (!color.equals(other.color))
            return false;
        if (value == null) {
            if (other.value != null)
                return false;
        } else if (!value.equals(other.value))
            return false;
        return true;
    }
}
</code>```

Title: How to map chars to (playing) cards?

Body:
I believe Switch-case/if-else are ok in this situation. It would get large, but any kind of code where you define 50 mappings would be big.

One other approach would be to "store" your Character<-->Card Relationship somehow and use methods to retrieve the values. You would have the relationships in an easily read manner and it is easy to register mappings and work with it.

I think there is a Map for 1:1 relationships (BiMap from Googles Guava?). You can just register your Characters and Cards in that map so you always can identify in both directions.

If you want to do it without third Party libs, you should be able to easily do it using two maps:

/** used to find the correct Card by Character */
private final static Map<Character, Card> mapCharToCard = new HashMap<>();

/** used to find the correct Character by Card (for sending over network) */
private final static Map<Card, Character> mapCardToChar = new HashMap<>();

/* Always stores boths ways so you can always map it back and forth */
public final static void register(Character character, Card card) {

    mapCharToCard.put(character, card);
    mapCardToChar.put(card, character);
}

public final static Character map(Card card) {

    return mapCardToChar.get(card);
}

public final static Card map(Character character) {

    return mapCharToCard.get(character);
}

public static void main(String[] args) {

    register('a', new Card("Spades", "Ace"));
    register('b', new Card("Heart", "King"));

    System.out.println(map('a'));
    System.out.println(map('b'));

    // Even works with new cards as hashmap uses equals() to check
    System.out.println(map(new Card("Spades", "Ace")));
}

public static class Card {

    private String color;
    private String value;

    public Card(String color, String value) {
        super();
        this.color = color;
        this.value = value;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String toString() {
        return "Card [getColor()=" + getColor() + ", getValue()=" + getValue() + "]";
    }

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((color == null) ? 0 : color.hashCode());
        result = prime * result + ((value == null) ? 0 : value.hashCode());
        return result;
    }

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Card other = (Card) obj;
        if (color == null) {
            if (other.color != null)
                return false;
        } else if (!color.equals(other.color))
            return false;
        if (value == null) {
            if (other.value != null)
                return false;
        } else if (!value.equals(other.value))
            return false;
        return true;
    }
}


问:
Is there an easy way to remove/ignore rows above column names in an Excel file using OleDbConnection?
I have code like this for reading an Excel file:

```string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" +
    "Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=YES\";";

using (OleDbConnection conn = new OleDbConnection(connStr))
{
    conn.Open();
    DataTable dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
    string sheetName = dtSchema.Rows[0].Field("TABLE_NAME");
    OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
    sheetAdapter.Fill(sheetData);

    DataTable dtColumns = conn.GetSchema("Columns", new string[] { null, null, sheetName, null });

    ...
}```

My code needs to use/look at the column headers. The above only works if the column headers are the first row. Sometimes the Excel files that we receive from clients have a couple rows above the column headers with some metadata about the data in the excel. When this happens the column headers will be on something like row 10.

I can open the Excel file and manually delete the extra rows above the column headers and this solves the issue. But we want to remove this manual step.

Is there any easy way to remove/ignore these extra starting rows above the column headers? Or do I have to come up with custom code? The best way I can think of is to turn off HDR and then the first row that has a value in every column is the column header row. Is there an easier way?

答:
As far as i know (checked that issue in the past) there is no way to select a table with System.Data.OleDb from excel file using SQL query if headers are not placed in row 1.
 the solution for me (like you do) is to delete all the rows above the header row before querying the worksheet - just opening the workbook with Microsoft.Office.Interop deleting the extra rows, closing it and than querying it.

Excel is a very powerful tool but was never designed to behave like database (SQL \ access file for example).

Body:
I have code like this for reading an Excel file:

string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" +
    "Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=YES\";";

using (OleDbConnection conn = new OleDbConnection(connStr))
{
    conn.Open();
    DataTable dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
    string sheetName = dtSchema.Rows[0].Field("TABLE_NAME");
    OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
    sheetAdapter.Fill(sheetData);

    DataTable dtColumns = conn.GetSchema("Columns", new string[] { null, null, sheetName, null });

    ...
}

My code needs to use/look at the column headers. The above only works if the column headers are the first row. Sometimes the Excel files that we receive from clients have a couple rows above the column headers with some metadata about the data in the excel. When this happens the column headers will be on something like row 10.

I can open the Excel file and manually delete the extra rows above the column headers and this solves the issue. But we want to remove this manual step.

Is there any easy way to remove/ignore these extra starting rows above the column headers? Or do I have to come up with custom code? The best way I can think of is to turn off HDR and then the first row that has a value in every column is the column header row. Is there an easier way?


问:
jquery selector wont find body

I cant select the body tag in the above, everything is coming back as an empty object.  I can select the body in google ok, whats causing this. the page was fine in w3s validation

答:
I was assuming that I would get an HTML response back when the selector had 1 or more results like:

Instead of a function styled response such as above, but I can see that one response was found now and have fixed the issue that was causing the error

Title: jquery selector wont find body


问:
This code can't find first element
```<code>def c(stringenter):
    last = 1
    commandsline = [['a', 'first'], ['b', 'second'], ['c', 'third']]
    for commandblock in commandsline:
        last = last + 1
        if commandblock[0] == stringenter:
            realcommand = str(commandblock[1])
        elif last == len(commandsline):
            realcommand = stringenter
    return realcommand
</code>```

Hello!!! This code can find and return second, third but can't find first how  resolve problem?

答:
You can try something like this:

```<code>def c(stringenter):
    commandsline = [['a', 'first'], ['b', 'second'], ['c', 'third']]
    for commandblock in commandsline:
        if commandblock[0] == stringenter:
            return commandblock[1]
    return stringenter
</code>```

It goes through your commandsline list if stringenter is equal to any of the ones in commandblock[0] it returns commandblock[1]

If it doesnt find it. It returns stringenter.

Title: This code can't find first element

Body:
def c(stringenter):
    last = 1
    commandsline = [['a', 'first'], ['b', 'second'], ['c', 'third']]
    for commandblock in commandsline:
        last = last + 1
        if commandblock[0] == stringenter:
            realcommand = str(commandblock[1])
        elif last == len(commandsline):
            realcommand = stringenter
    return realcommand

Hello!!! This code can find and return second, third but can't find first how  resolve problem?

Body:
You can try something like this:

def c(stringenter):
    commandsline = [['a', 'first'], ['b', 'second'], ['c', 'third']]
    for commandblock in commandsline:
        if commandblock[0] == stringenter:
            return commandblock[1]
    return stringenter

It goes through your commandsline list if stringenter is equal to any of the ones in commandblock[0] it returns commandblock[1]

If it doesnt find it. It returns stringenter.


问:
How I can access docker data volumes on Windows machine?
I have docker-compose.yml like this:

```<code>version: '3'
services:
  mysql:
    image: mysql
    volumes:
      - data:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=$ROOT_PASSWORD

volumes:
  data:
</code>```

And my mount point looks like: /var/lib/docker/volumes/some_app/_data and I want to access data from that mount point and I'm not sure how to do it on Windows machine. Maybe I can create some additional container which can pass data from docker virtual machine to my directory?

When I'm mounting folder like this:

```<code>volumes:
  - ./data:/var/lib/mysql
</code>```

to use my local directory - I had no success because of permissions issue. And read that "right way" is using docker volumes.

UPD: MySQL container it's just example. I want to use such behaviour for my codebase and use docker foe local development.

答:
For Linux containers under Windows, docker runs actually over a Linux virtual machine, so your named volume is a mapping of a local directory in that VM to a directory in the container.

So what you got as /var/lib/docker/volumes/some_app/_data is a directory inside that VM. To inspect it you can:

```<code>docker run --rm -it -v /:/vm-root alpine:edge ls -l /vm-root/var/lib/docker/volumes/some_app/_data
total 188476
-rw-r-----    1 999      ping            56 Jun  4 04:49 auto.cnf
-rw-------    1 999      ping          1675 Jun  4 04:49 ca-key.pem
-rw-r--r--    1 999      ping          1074 Jun  4 04:49 ca.pem
-rw-r--r--    1 999      ping          1078 Jun  4 04:49 client-cert.pem
-rw-------    1 999      ping          1679 Jun  4 04:49 client-key.pem
-rw-r-----    1 999      ping          1321 Jun  4 04:50 ib_buffer_pool
-rw-r-----    1 999      ping      50331648 Jun  4 04:50 ib_logfile0
-rw-r-----    1 999      ping      50331648 Jun  4 04:49 ib_logfile1
-rw-r-----    1 999      ping      79691776 Jun  4 04:50 ibdata1
-rw-r-----    1 999      ping      12582912 Jun  4 04:50 ibtmp1
drwxr-x---    2 999      ping          4096 Jun  4 04:49 mysql
drwxr-x---    2 999      ping          4096 Jun  4 04:49 performance_schema
-rw-------    1 999      ping          1679 Jun  4 04:49 private_key.pem
-rw-r--r--    1 999      ping           451 Jun  4 04:49 public_key.pem
-rw-r--r--    1 999      ping          1078 Jun  4 04:49 server-cert.pem
-rw-------    1 999      ping          1675 Jun  4 04:49 server-key.pem
drwxr-x---    2 999      ping         12288 Jun  4 04:49 sys
</code>```

That is running an auxiliar container which has mounted the hole root filesystem of that VM / into the container dir /vm-root.

To get some file run the container with some command in background (tail -f /dev/null in my case), then you can use docker cp:

```<code>docker run --name volume-holder -d -it -v /:/vm-root alpine:edge tail -f /dev/null
docker cp volume-holder:/vm-root/var/lib/docker/volumes/volumes_data/_data/public_key.pem .
</code>```

If you want a transparent SSH to that VM, it seems that is not supported yet, as of Jun-2017. Here a docker staff member said that.

Body:
I have docker-compose.yml like this:

version: '3'
services:
  mysql:
    image: mysql
    volumes:
      - data:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=$ROOT_PASSWORD

volumes:
  data:

And my mount point looks like: /var/lib/docker/volumes/some_app/_data and I want to access data from that mount point and I'm not sure how to do it on Windows machine. Maybe I can create some additional container which can pass data from docker virtual machine to my directory?

When I'm mounting folder like this:

volumes:
  - ./data:/var/lib/mysql

to use my local directory - I had no success because of permissions issue. And read that "right way" is using docker volumes.

UPD: MySQL container it's just example. I want to use such behaviour for my codebase and use docker foe local development.

Body:
For Linux containers under Windows, docker runs actually over a Linux virtual machine, so your named volume is a mapping of a local directory in that VM to a directory in the container.

So what you got as /var/lib/docker/volumes/some_app/_data is a directory inside that VM. To inspect it you can:

docker run --rm -it -v /:/vm-root alpine:edge ls -l /vm-root/var/lib/docker/volumes/some_app/_data
total 188476
-rw-r-----    1 999      ping            56 Jun  4 04:49 auto.cnf
-rw-------    1 999      ping          1675 Jun  4 04:49 ca-key.pem
-rw-r--r--    1 999      ping          1074 Jun  4 04:49 ca.pem
-rw-r--r--    1 999      ping          1078 Jun  4 04:49 client-cert.pem
-rw-------    1 999      ping          1679 Jun  4 04:49 client-key.pem
-rw-r-----    1 999      ping          1321 Jun  4 04:50 ib_buffer_pool
-rw-r-----    1 999      ping      50331648 Jun  4 04:50 ib_logfile0
-rw-r-----    1 999      ping      50331648 Jun  4 04:49 ib_logfile1
-rw-r-----    1 999      ping      79691776 Jun  4 04:50 ibdata1
-rw-r-----    1 999      ping      12582912 Jun  4 04:50 ibtmp1
drwxr-x---    2 999      ping          4096 Jun  4 04:49 mysql
drwxr-x---    2 999      ping          4096 Jun  4 04:49 performance_schema
-rw-------    1 999      ping          1679 Jun  4 04:49 private_key.pem
-rw-r--r--    1 999      ping           451 Jun  4 04:49 public_key.pem
-rw-r--r--    1 999      ping          1078 Jun  4 04:49 server-cert.pem
-rw-------    1 999      ping          1675 Jun  4 04:49 server-key.pem
drwxr-x---    2 999      ping         12288 Jun  4 04:49 sys

That is running an auxiliar container which has mounted the hole root filesystem of that VM / into the container dir /vm-root.

To get some file run the container with some command in background (tail -f /dev/null in my case), then you can use docker cp:

docker run --name volume-holder -d -it -v /:/vm-root alpine:edge tail -f /dev/null
docker cp volume-holder:/vm-root/var/lib/docker/volumes/volumes_data/_data/public_key.pem .

If you want a transparent SSH to that VM, it seems that is not supported yet, as of Jun-2017. Here a docker staff member said that.


问:
How to parse the data of xml of elements with same names using python
Hi I have this xml and I want get the strings related with the Name and Type of each Branch element and the FullProductName string element ("Cisco Unified Computing System (Management Software) 3.0(1)c"). I am trying to do it with python using bs4. But I don't know how can I do it.

XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<cvrfdoc xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.icasi.org/CVRF/schema/cvrf/1.1">
  <DocumentTitle>Cisco Integrated Management Controller Remote Code Execution Vulnerability</DocumentTitle>
  <DocumentType>Cisco Security Advisory</DocumentType>
  <DocumentPublisher Type="Vendor">
    <ContactDetails>Emergency Support:
+1 877 228 7302 (toll-free within North America)
+1 408 525 6532 (International direct-dial)
Non-emergency Support:
Email: psirt@cisco.com
Support requests that are received via e-mail are typically acknowledged within 48 hours.</ContactDetails>
    <IssuingAuthority>Cisco product security incident response is the responsibility of the Cisco Product Security Incident Response Team (PSIRT). The Cisco PSIRT is a dedicated, global team that manages the receipt, investigation, and public reporting of security vulnerability information that is related to Cisco products and networks. The on-call Cisco PSIRT works 24x7 with Cisco customers, independent security researchers, consultants, industry organizations, and other vendors to identify possible security issues with Cisco products and networks.
More information can be found in Cisco Security Vulnerability Policy available at http://www.cisco.com/web/about/security/psirt/security_vulnerability_policy.html</IssuingAuthority>
  </DocumentPublisher>
  <DocumentTracking>
    <Identification>
      <ID>cisco-sa-20170419-cimc3</ID>
    </Identification>
    <Status>Final</Status>
    <Version>1.2</Version>
    <RevisionHistory>
      <Revision>
        <Number>1.0</Number>
        <Date>2017-04-18T16:50:37</Date>
        <Description>Initial public release.</Description>
      </Revision>
      <Revision>
        <Number>1.1</Number>
        <Date>2017-05-22T17:55:14</Date>
        <Description>Updated affected products.</Description>
      </Revision>
      <Revision>
        <Number>1.2</Number>
        <Date>2017-05-31T20:33:19</Date>
        <Description>Added vulnerable releases.</Description>
      </Revision>
    </RevisionHistory>
    <InitialReleaseDate>2017-04-19T16:00:00</InitialReleaseDate>
    <CurrentReleaseDate>2017-05-31T20:33:19</CurrentReleaseDate>
    <Generator>
      <Engine>TVCE</Engine>
    </Generator>
  </DocumentTracking>
  <DocumentNotes>
    <Note Title="Summary" Type="General" Ordinal="1">A vulnerability in the web-based GUI of Cisco Integrated Management Controller (IMC) could allow an unauthenticated, remote attacker to perform unauthorized remote command execution on the affected device.

The vulnerability exists because the affected software does not sufficiently sanitize specific values that are received as part of a user-supplied HTTP request. An attacker could exploit this vulnerability by sending a crafted HTTP request to the affected software. Successful exploitation could allow an unauthenticated attacker to execute system commands with root-level privileges.

There are no workarounds that address this vulnerability.

This advisory is available at the following link:
https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20170419-cimc3 ["https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20170419-cimc3"]</Note>
    <Note Title="CVSS 3.0 Notice" Type="Other" Ordinal="2">Although CVRF version 1.1 does not support CVSS version 3, the CVSS score in this CVRF file is a CVSSv3 base and temporal score, as Cisco is now scoring vulnerabilities in CVSSv3.</Note>
  </DocumentNotes>
  <DocumentReferences>
    <Reference Type="Self">
      <URL>https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20170419-cimc3</URL>
      <Description>Cisco Integrated Management Controller Remote Code Execution Vulnerability</Description>
    </Reference>
  </DocumentReferences>
  <ProductTree xmlns="http://www.icasi.org/CVRF/schema/prod/1.1">
    <Branch Name="Cisco" Type="Vendor">
      <Branch Name="Cisco Unified Computing System (Management Software)" Type="Product Name">
        <Branch Name="3.0" Type="Product Version">
          <Branch Name="(1)c" Type="Service Pack">
            <FullProductName ProductID="CVRFPID-203522">Cisco Unified Computing System (Management Software) 3.0(1)c</FullProductName>
          </Branch>
        </Branch>
      </Branch>
    </Branch>
  </ProductTree>
  <Vulnerability Ordinal="1" xmlns="http://www.icasi.org/CVRF/schema/vuln/1.1">
    <Title>Cisco Integrated Management Controller Remote Code Execution Vulnerability</Title>
    <ID SystemName="Cisco Bug ID">CSCvd14578</ID>
    <Notes>
      <Note Title="Summary" Type="Summary" Ordinal="1">A vulnerability in the web-based GUI of Cisco Integrated Management Controller (IMC) could allow an unauthenticated, remote attacker to perform unauthorized remote command execution on the affected device.

The vulnerability exists because the affected software does not sufficiently sanitize specific values that are received as part of a user-supplied HTTP request. An attacker could exploit this vulnerability by sending a crafted HTTP request to the affected software. Successful exploitation could allow an unauthenticated attacker to execute system commands with root-level privileges.</Note>
      <Note Title="Cisco Bug IDs" Type="Other" Ordinal="3">CSCvd14578</Note>
    </Notes>
    <CVE>CVE-2017-6616</CVE>
    <ProductStatuses>
      <Status Type="Known Affected">
        <ProductID>CVRFPID-203522</ProductID>
      </Status>
    </ProductStatuses>
    <CVSSScoreSets>
      <ScoreSet>
        <BaseScore>9.8</BaseScore>
        <Vector>CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H</Vector>
      </ScoreSet>
    </CVSSScoreSets>
    <Remediations>
      <Remediation Type="Workaround">
        <Description>There are no workarounds that address this vulnerability.</Description>
      </Remediation>
    </Remediations>
    <References>
      <Reference Type="Self">
        <URL>https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20170419-cimc3</URL>
        <Description>Cisco Integrated Management Controller Remote Code Execution Vulnerability</Description>
      </Reference>
    </References>
  </Vulnerability>
</cvrfdoc>
</code>```

Python:

```<code>from bs4 import BeautifulSoup

xmlData = open("test.xml")
soup = BeautifulSoup(xmlData, "lxml")
preoductTree = soup.producttree

vendor = preoductTree.find_all("branch", attrs={"type": "Vendor"})
</code>```

Any idea?

Thank you in advance.

答:
So you have to first find the tags so we can iterate through the file. I'm going to be using the inherent python xml package.

```<code>import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
</code>```

Then let's find the first child tag so we can run through the file.

```<code>for child in root:
    print child.tag, child.attrib

>>{http://www.icasi.org/CVRF/schema/prod/1.1}Branch, {'Type': 'Vendor', 'Name': 'Cisco'}
</code>```

So as you can see it's not just branch as you specified it.

Now we can run through the whole file recursively and grab all these elements. Since you didn't specify the desired output structure I am going to put it in a dictionary for you.

```<code>val_dict = dict()
for schild in root.iter('{http://www.icasi.org/CVRF/schema/prod/1.1}Branch'):
        val = schild.attrib
        val_dict[val.get('Type')] = val.get('Name')

>>{'Product Name': 'Cisco Unified Computing System (Management Software)',
 'Product Version': '3.0',
 'Service Pack': '(1)c',
 'Vendor': 'Cisco'}
</code>```

Body:
Hi I have this xml and I want get the strings related with the Name and Type of each Branch element and the FullProductName string element ("Cisco Unified Computing System (Management Software) 3.0(1)c"). I am trying to do it with python using bs4. But I don't know how can I do it.

XML:

<?xml version="1.0" encoding="UTF-8"?>
<cvrfdoc xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.icasi.org/CVRF/schema/cvrf/1.1">
  <DocumentTitle>Cisco Integrated Management Controller Remote Code Execution Vulnerability</DocumentTitle>
  <DocumentType>Cisco Security Advisory</DocumentType>
  <DocumentPublisher Type="Vendor">
    <ContactDetails>Emergency Support:
+1 877 228 7302 (toll-free within North America)
+1 408 525 6532 (International direct-dial)
Non-emergency Support:
Email: psirt@cisco.com
Support requests that are received via e-mail are typically acknowledged within 48 hours.</ContactDetails>
    <IssuingAuthority>Cisco product security incident response is the responsibility of the Cisco Product Security Incident Response Team (PSIRT). The Cisco PSIRT is a dedicated, global team that manages the receipt, investigation, and public reporting of security vulnerability information that is related to Cisco products and networks. The on-call Cisco PSIRT works 24x7 with Cisco customers, independent security researchers, consultants, industry organizations, and other vendors to identify possible security issues with Cisco products and networks.
More information can be found in Cisco Security Vulnerability Policy available at http://www.cisco.com/web/about/security/psirt/security_vulnerability_policy.html</IssuingAuthority>
  </DocumentPublisher>
  <DocumentTracking>
    <Identification>
      <ID>cisco-sa-20170419-cimc3</ID>
    </Identification>
    <Status>Final</Status>
    <Version>1.2</Version>
    <RevisionHistory>
      <Revision>
        <Number>1.0</Number>
        <Date>2017-04-18T16:50:37</Date>
        <Description>Initial public release.</Description>
      </Revision>
      <Revision>
        <Number>1.1</Number>
        <Date>2017-05-22T17:55:14</Date>
        <Description>Updated affected products.</Description>
      </Revision>
      <Revision>
        <Number>1.2</Number>
        <Date>2017-05-31T20:33:19</Date>
        <Description>Added vulnerable releases.</Description>
      </Revision>
    </RevisionHistory>
    <InitialReleaseDate>2017-04-19T16:00:00</InitialReleaseDate>
    <CurrentReleaseDate>2017-05-31T20:33:19</CurrentReleaseDate>
    <Generator>
      <Engine>TVCE</Engine>
    </Generator>
  </DocumentTracking>
  <DocumentNotes>
    <Note Title="Summary" Type="General" Ordinal="1">A vulnerability in the web-based GUI of Cisco Integrated Management Controller (IMC) could allow an unauthenticated, remote attacker to perform unauthorized remote command execution on the affected device.

The vulnerability exists because the affected software does not sufficiently sanitize specific values that are received as part of a user-supplied HTTP request. An attacker could exploit this vulnerability by sending a crafted HTTP request to the affected software. Successful exploitation could allow an unauthenticated attacker to execute system commands with root-level privileges.

There are no workarounds that address this vulnerability.

This advisory is available at the following link:
https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20170419-cimc3 ["https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20170419-cimc3"]</Note>
    <Note Title="CVSS 3.0 Notice" Type="Other" Ordinal="2">Although CVRF version 1.1 does not support CVSS version 3, the CVSS score in this CVRF file is a CVSSv3 base and temporal score, as Cisco is now scoring vulnerabilities in CVSSv3.</Note>
  </DocumentNotes>
  <DocumentReferences>
    <Reference Type="Self">
      <URL>https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20170419-cimc3</URL>
      <Description>Cisco Integrated Management Controller Remote Code Execution Vulnerability</Description>
    </Reference>
  </DocumentReferences>
  <ProductTree xmlns="http://www.icasi.org/CVRF/schema/prod/1.1">
    <Branch Name="Cisco" Type="Vendor">
      <Branch Name="Cisco Unified Computing System (Management Software)" Type="Product Name">
        <Branch Name="3.0" Type="Product Version">
          <Branch Name="(1)c" Type="Service Pack">
            <FullProductName ProductID="CVRFPID-203522">Cisco Unified Computing System (Management Software) 3.0(1)c</FullProductName>
          </Branch>
        </Branch>
      </Branch>
    </Branch>
  </ProductTree>
  <Vulnerability Ordinal="1" xmlns="http://www.icasi.org/CVRF/schema/vuln/1.1">
    <Title>Cisco Integrated Management Controller Remote Code Execution Vulnerability</Title>
    <ID SystemName="Cisco Bug ID">CSCvd14578</ID>
    <Notes>
      <Note Title="Summary" Type="Summary" Ordinal="1">A vulnerability in the web-based GUI of Cisco Integrated Management Controller (IMC) could allow an unauthenticated, remote attacker to perform unauthorized remote command execution on the affected device.

The vulnerability exists because the affected software does not sufficiently sanitize specific values that are received as part of a user-supplied HTTP request. An attacker could exploit this vulnerability by sending a crafted HTTP request to the affected software. Successful exploitation could allow an unauthenticated attacker to execute system commands with root-level privileges.</Note>
      <Note Title="Cisco Bug IDs" Type="Other" Ordinal="3">CSCvd14578</Note>
    </Notes>
    <CVE>CVE-2017-6616</CVE>
    <ProductStatuses>
      <Status Type="Known Affected">
        <ProductID>CVRFPID-203522</ProductID>
      </Status>
    </ProductStatuses>
    <CVSSScoreSets>
      <ScoreSet>
        <BaseScore>9.8</BaseScore>
        <Vector>CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H</Vector>
      </ScoreSet>
    </CVSSScoreSets>
    <Remediations>
      <Remediation Type="Workaround">
        <Description>There are no workarounds that address this vulnerability.</Description>
      </Remediation>
    </Remediations>
    <References>
      <Reference Type="Self">
        <URL>https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20170419-cimc3</URL>
        <Description>Cisco Integrated Management Controller Remote Code Execution Vulnerability</Description>
      </Reference>
    </References>
  </Vulnerability>
</cvrfdoc>

Python:

from bs4 import BeautifulSoup

xmlData = open("test.xml")
soup = BeautifulSoup(xmlData, "lxml")
preoductTree = soup.producttree

vendor = preoductTree.find_all("branch", attrs={"type": "Vendor"})

Any idea?

Thank you in advance.

Body:
So you have to first find the tags so we can iterate through the file. I'm going to be using the inherent python xml package.

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()

Then let's find the first child tag so we can run through the file.

for child in root:
    print child.tag, child.attrib

>>{http://www.icasi.org/CVRF/schema/prod/1.1}Branch, {'Type': 'Vendor', 'Name': 'Cisco'}

So as you can see it's not just branch as you specified it.

Now we can run through the whole file recursively and grab all these elements. Since you didn't specify the desired output structure I am going to put it in a dictionary for you.

val_dict = dict()
for schild in root.iter('{http://www.icasi.org/CVRF/schema/prod/1.1}Branch'):
        val = schild.attrib
        val_dict[val.get('Type')] = val.get('Name')

>>{'Product Name': 'Cisco Unified Computing System (Management Software)',
 'Product Version': '3.0',
 'Service Pack': '(1)c',
 'Vendor': 'Cisco'}


答:
There is HTML structural error.
Wrap the
 with an
 tag. I can assume you are using Bootstrap. If yes then wrap the
 tag with
 and add list-group-item class to the
 tag like this:

Title: Unknown dots rendered into page - what causes them?

Body:
I have a demo application here and in the upper left corners of the "tweets" there are dots and I have no idea where they come from. The code is written in Ember and the template looks like this

Ember.js DEMO Tweet list

Tweets

<button {{action 'changeAllTweets'}}>Change All Tweets</button>
<button {{action 'changeOneTweet'}}>Change One Tweet</button>

        {{#each this.model.topTweets as |model|}}

{{model.favorites}}

{{model.text}}

Expand

Reply

Retweet

Favorite

More

{{/each}}

P.S. The SHOW LIST button must be pressed for the list to show

Body:
There is HTML structural error.
Wrap the <li class="media"> with an <ul> tag. I can assume you are using Bootstrap. If yes then wrap the <li> tag with <ul class="list-group"> and add list-group-item class to the <li> tag like this: <li class="media list-group-item">


问:
Remove Item Without Mutating State in Redux
The first thing I tried was this:

```<code>const initialState = {
  items: {},
  showCart: false,
  showCheckout: false,
  userID: null
};

export default function reducer(state=Immutable.fromJS(initialState), action) {
  case 'REMOVE_FROM_CART':
    return state.deleteIn(['items', String(action.id)]);
}
</code>```

When console logging the deleteIn above, it does actually remove the item from the Map correctly. However, the app doesn't re-render again, because I assume I'm mutating the state(?). (mapStateToProps gets called, but no new state).

So next I tried this:

```<code>case 'REMOVE_FROM_CART':
  const removed = state.deleteIn(['items', String(action.id)]);
  const removeItemState = {
    ...state,
    items: { removed }
  }
  return state.mergeDeep(removeItemState);
</code>```

But I'm just adding the deleted item to the items again, creating a duplication.

How can I handle this?

答:
Posting more code (such as my reducers setup) may  have helped more, but here's what was going on:

First, this code was the right way to remove the item from the state.

```<code>return state.deleteIn(['items', String(action.id)]);
</code>```

However, because I was using the immutable library and not redux-immutable for my combineReducers, my state was not properly being handled. This was allowing me to do things like state.cart.items (in mapStateToProps) where really I should've been using state.getIn(['cart', 'items']).

Changing that magically made the delete work.

Thanks to @jslatts in the Reactiflux Immutable Slack channel for help with figuring this out!

Body:
The first thing I tried was this:

const initialState = {
  items: {},
  showCart: false,
  showCheckout: false,
  userID: null
};

export default function reducer(state=Immutable.fromJS(initialState), action) {
  case 'REMOVE_FROM_CART':
    return state.deleteIn(['items', String(action.id)]);
}

When console logging the deleteIn above, it does actually remove the item from the Map correctly. However, the app doesn't re-render again, because I assume I'm mutating the state(?). (mapStateToProps gets called, but no new state).

So next I tried this:

case 'REMOVE_FROM_CART':
  const removed = state.deleteIn(['items', String(action.id)]);
  const removeItemState = {
    ...state,
    items: { removed }
  }
  return state.mergeDeep(removeItemState);

But I'm just adding the deleted item to the items again, creating a duplication.

How can I handle this?

Body:
Posting more code (such as my reducers setup) may  have helped more, but here's what was going on:

First, this code was the right way to remove the item from the state.

return state.deleteIn(['items', String(action.id)]);

However, because I was using the immutable library and not redux-immutable for my combineReducers, my state was not properly being handled. This was allowing me to do things like state.cart.items (in mapStateToProps) where really I should've been using state.getIn(['cart', 'items']).

Changing that magically made the delete work.

Thanks to @jslatts in the Reactiflux Immutable Slack channel for help with figuring this out!