问:
Vue 2.0 with click event handler
How do use vue2.0 with jquery onclick event method ? As i research on the particular question with defining an mounted of this.$el.addEventListener('click', this.onClick) on vue . but seems not really clear for me . I need an help from here. Kindly advise

As my code below jquery :

```<code>$(document).on("click",".ballNum li",function(){
        var robj = $(this);
        var value = robj.text();
            var bit = $(this).parents(".ballNum").attr("id");
            if(robj.attr("name")=="choice"){
                robj.removeAttr("name");
            }else{
                robj.attr("name","choice");
            }
            var isSave = saveNum(value,bit,"reverse");
            if(isSave==1){
                $(this).addClass("active");
            }else if(isSave==-1){
                $(this).removeClass("active");
            }else{
                layer.alert('Error',{icon: 0, title:'Alert'});
        }
</code>```

答:
You would need to first understand the basic difference between jQuery and VueJS. Everything that you do in jQuery can be done in VueJS, it is just a matter of understanding the difference. When we are in the jQuery land, we are habituated to the $() to fetch the values and stuff.

VueJS is different, here, there is reactivity at the backend, the library takes care of the complete html. You have to define the html, using the Vue syntax, then define the data array, which stores the variables. The variables are then used inside the templates

```<code>  <div id="app4">
      <ol>
        <li>{{todo}}</li>
        <li>{{todo}}</li>
        <li>{{todo}}</li>
  </ol>
  </div>

  <script>
    var app4 = new Vue({
        el:"#app4",
        data: {
            todo: "do something!"
        }
    })
  </script>
</code>```

This would print "do something!" thrice.

This is the modifications we can do to the above block, after adding the input tag, here is your 'click' method, rather than use jQuery's click method, we use the one which Vue provides.

Vue's click method executes Vue's AddToDo function.

```<code><html>
<script>
 var app4 = new Vue({
    el:"#app4",
data: {
    todo: {title: '', text:''},
    todos: [
        {title: 'Lean JS' , text: "What is JS?"},
        {title:'Learn vue',  text: "Vue has nice docs!"},
        {title:'Build something',  text: "what to build?"}
    ]
},
methods: {
  AddTodo: function (item) {
    alert(item.text + " " + item.title)
  }
}
})
</script>

<body>
<input placeholder="add title" v-model="todo.title" />
<input placeholder="add text" v-model="todo.text" />
<button v-on:click="AddTodo(todo)">Add todo</button>

<ol>
      <li v-for="(todo, index) in todos">
          {{ todo.title }} : {{ todo.text }}
      </li>
</ol>
</body>
</code>```

What this will enable you is this:

create a new todo list item

add that todo list item in your data array, which automatically gets rendered to the html without you having to do any rendering at all.

For more details, read this: https://github.com/thewhitetulip/intro-to-vuejs/

Title: Vue 2.0 with click event handler

Body:
How do use vue2.0 with jquery onclick event method ? As i research on the particular question with defining an mounted of this.$el.addEventListener('click', this.onClick) on vue . but seems not really clear for me . I need an help from here. Kindly advise

As my code below jquery :

$(document).on("click",".ballNum li",function(){
        var robj = $(this);
        var value = robj.text();
            var bit = $(this).parents(".ballNum").attr("id");
            if(robj.attr("name")=="choice"){
                robj.removeAttr("name");
            }else{
                robj.attr("name","choice");
            }
            var isSave = saveNum(value,bit,"reverse");
            if(isSave==1){
                $(this).addClass("active");
            }else if(isSave==-1){
                $(this).removeClass("active");
            }else{
                layer.alert('Error',{icon: 0, title:'Alert'});
        }

Body:
You would need to first understand the basic difference between jQuery and VueJS. Everything that you do in jQuery can be done in VueJS, it is just a matter of understanding the difference. When we are in the jQuery land, we are habituated to the $() to fetch the values and stuff.

VueJS is different, here, there is reactivity at the backend, the library takes care of the complete html. You have to define the html, using the Vue syntax, then define the data array, which stores the variables. The variables are then used inside the templates

  <div id="app4">
      <ol>
        <li>{{todo}}</li>
        <li>{{todo}}</li>
        <li>{{todo}}</li>
  </ol>
  </div>

  <script>
    var app4 = new Vue({
        el:"#app4",
        data: {
            todo: "do something!"
        }
    })
  </script>

This would print "do something!" thrice.

This is the modifications we can do to the above block, after adding the input tag, here is your 'click' method, rather than use jQuery's click method, we use the one which Vue provides.

Vue's click method executes Vue's AddToDo function.

<html>
<script>
 var app4 = new Vue({
    el:"#app4",
data: {
    todo: {title: '', text:''},
    todos: [
        {title: 'Lean JS' , text: "What is JS?"},
        {title:'Learn vue',  text: "Vue has nice docs!"},
        {title:'Build something',  text: "what to build?"}
    ]
},
methods: {
  AddTodo: function (item) {
    alert(item.text + " " + item.title)
  }
}
})
</script>

<body>
<input placeholder="add title" v-model="todo.title" />
<input placeholder="add text" v-model="todo.text" />
<button v-on:click="AddTodo(todo)">Add todo</button>

<ol>
      <li v-for="(todo, index) in todos">
          {{ todo.title }} : {{ todo.text }}
      </li>
</ol>
</body>

What this will enable you is this:

create a new todo list item

add that todo list item in your data array, which automatically gets rendered to the html without you having to do any rendering at all.

For more details, read this: https://github.com/thewhitetulip/intro-to-vuejs/


来源: stackexchange

问:
How to disable the cursor but not only visually?
I want to hide the cursor until my function is done but I can't find how to disable it. I mean I have found how to hide it and show it but when it's hidden I can still click So how to disable it?

window.document.styleSheets[0].insertRule('* {cursor: none;}', window.document.styleSheets[0].cssRules.length);
Meteor.call("lockTheMachine", machine.nameMachine, Session.get("loggedUser"), function(err, res) {
  if (!err) {
    Session.set("lastMachineUsed", machine.nameMachine);
    window.document.styleSheets[0].insertRule('* {cursor: default   ;}', window.document.styleSheets[0].cssRules.length);
  } else {
    console.error(err);
  }
});
}
```

答:
You can solve your problem by simply adding the following style in your CSS file.

```<code>    button {
pointer-events: none;
}
</code>```

The problem with this is that the button is not clickable but the cursor is still displayed when you hover on the button.

To overcome this problem you can add "disable" attribute to the button and add the following CSS.

```<code>button {
cursor: not-allowed; // or cursor: none;
}
</code>```

When you add the css "cursor": "not-allowed" or "none" to a input type or a button, the button is still clickable. For doing the input type or button non clickable you have to add "disable" attribute.

A disabled input element is unusable and un-clickable. The disabled attribute can be set to keep a user from using the  element until some other condition has been met (like selecting a checkbox, etc.). Then, a JavaScript could remove the disabled value, and make the  element usable.

But when you using bootstarp library, when you disabled a button or input type, then you can't see any cursor when hover onto that element. At the newest bootstrap library, we can find this rule:

```<code>.btn.disabled, .btn[disabled], fieldset[disabled] .btn {
pointer-events: none;
cursor: not-allowed;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
opacity: .65;
}
</code>```

So I assume that bootstrap tried to implement the cursor: not-allowed for disabled buttons, or input's.

So for doing this you have to overwrite the bootstrap class for it.

But it works fine when you don't link bootstrap library in your html.

e.g.:

HTML code:

```<code><button class="disabled-button" disabled>
I am disabled and not clickable too
</button>
</code>```

CSS code:

```<code>.disabled-button {
  cursor: not-allowed;
}
</code>```

or you can trigger ".disabled-button" class programmetically by javascript to unclickable it.

ContentLicense: CC BY-SA 3.0

Body:
You can solve your problem by simply adding the following style in your CSS file.

    button {
pointer-events: none;
}

The problem with this is that the button is not clickable but the cursor is still displayed when you hover on the button.

To overcome this problem you can add "disable" attribute to the button and add the following CSS.

button {
cursor: not-allowed; // or cursor: none;
}

When you add the css "cursor": "not-allowed" or "none" to a input type or a button, the button is still clickable. For doing the input type or button non clickable you have to add "disable" attribute.

A disabled input element is unusable and un-clickable. The disabled attribute can be set to keep a user from using the  element until some other condition has been met (like selecting a checkbox, etc.). Then, a JavaScript could remove the disabled value, and make the  element usable.

But when you using bootstarp library, when you disabled a button or input type, then you can't see any cursor when hover onto that element. At the newest bootstrap library, we can find this rule:

.btn.disabled, .btn[disabled], fieldset[disabled] .btn {
pointer-events: none;
cursor: not-allowed;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
opacity: .65;
}

So I assume that bootstrap tried to implement the cursor: not-allowed for disabled buttons, or input's.

So for doing this you have to overwrite the bootstrap class for it.

But it works fine when you don't link bootstrap library in your html.

e.g.:

HTML code:

<button class="disabled-button" disabled>
I am disabled and not clickable too
</button>

CSS code:

.disabled-button {
  cursor: not-allowed;
}

or you can trigger ".disabled-button" class programmetically by javascript to unclickable it.


问:
after restarting terminal, the old ruby version set up
I installed ruby version to my computer 2.1.5, but I have to set up each time with the commands, (eval "$(rbenv init -)) each time I restart the terminal on my mac(system version set back). I set up the system with rbenv and try to use the global command also, but did not work.

Many thanks

答:
Add a .ruby-version file in root of your project

```<code>#.ruby-version
2.1.5
</code>```

This will select the mentioned ruby version automatically

Or simply add the following in Gemfile

```<code>source 'https://rubygems.org'

ruby '2.1.5'
.
.
</code>```

Body:
Add a .ruby-version file in root of your project

#.ruby-version
2.1.5

This will select the mentioned ruby version automatically

Or simply add the following in Gemfile

source 'https://rubygems.org'

ruby '2.1.5'
.
.


问:
Copy everything in a worksheet vba
```<code>' Copy
wb.Sheets(wsSource.Name).Range("A1:W79").Copy
' Paste Special
wbTarget.Sheets("Sheet1").Range("A1:W79").PasteSpecial xlValues
wbTarget.Sheets("Sheet1").Range("A1:W79").PasteSpecial xlFormats
</code>```

<p>This code allows me to copy everything in a range of A1:W79. How can I modify this Range so that it selects everything that contains value in a worksheet. For example, worksheet might contain values from C7:G20 etc. </p>

答:
I'd go like follows:</p>

```<code>With wb.Sheets(wsSource.Name).UsedRange
    .Copy
    With wbTarget.Sheets("Sheet1").Range(.Address)
        .PasteSpecial xlValues
        .PasteSpecial xlFormats
    End With
End With
</code>```

Title: Copy everything in a worksheet vba

Body:
' Copy
wb.Sheets(wsSource.Name).Range("A1:W79").Copy
' Paste Special
wbTarget.Sheets("Sheet1").Range("A1:W79").PasteSpecial xlValues
wbTarget.Sheets("Sheet1").Range("A1:W79").PasteSpecial xlFormats

This code allows me to copy everything in a range of A1:W79. How can I modify this Range so that it selects everything that contains value in a worksheet. For example, worksheet might contain values from C7:G20 etc.

Body:
I'd go like follows:

With wb.Sheets(wsSource.Name).UsedRange
    .Copy
    With wbTarget.Sheets("Sheet1").Range(.Address)
        .PasteSpecial xlValues
        .PasteSpecial xlFormats
    End With
End With


问:
Sorting of array by substrings
I need to sort array by substrings and also input missing parts.

Current version:

“K1\SK1”

“K1\SK2”

“K1\SK1\SSK1”

“K1\SK1\SSK2”

“K2”

“K2\SK1\SSK1”

“K2\SK1\SSK2”

Expected version:

“K1”

“K1\SK1”

“K1\SK1\SSK1”

“K1\SK1\SSK2”

“K1\SK2”

“K2”

“K2\SK1”

“K2\SK1\SSK1”

“K2\SK1\SSK2”

I already have tried to split strings to arrays by("/") then to sort every part of array separately. But eventually it's too inconvenient and hard algoritm!

Maybe someone knows an easier way how to solve this problem.

Thank you!

答:
You create a sorted Set, i.e. a TreeSet<String>, for storing the result.

You then iterate the input strings, and for each string you add it to the result Set. You also scan for all \ characters, and for each \ character found, you grab the substring from the beginning of the string, up to but not including the \, and add that to the result Set.

The Set now contains the result you're after. You can extract that as an array if needed.

Title: Sorting of array by substrings


问:
Designing a responsive web application that supposrts ie6
I am building a responsive web application for one of my client. the requirement of the client is that he wants the app to be also supported by internet explorer 6 and successors along with all other latest browsers. how do I start and what should I use for the responsiveness of the web app ?</p>

答:
Media queries aren't supported in IE6 through to IE8. So forget using native media queries, Bootstrap or Foundation.

This polyfill, called Respond.js, may help you - https://github.com/scottjehl/Respond.

Respond.js is a fast & lightweight polyfill for min/max-width CSS3 Media Queries (for IE 6-8, and more)

Here's a demo example.


问:
Why showing Null Pointer Exception While using JFrame in Eclipse?
Error******************************************************************

```<code>Exception in thread "main" java.lang.NullPointerException
at java.awt.Window.init(Unknown Source)
at java.awt.Window.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at javax.swing.JFrame.<init>(Unknown Source)
at Main.main(Main.java:12)
</code>```

Code********************************************************************

```<code>import javax.swing.JFrame;
import javax.swing.JSlider;

import com.fazecast.jSerialComm.*;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        JFrame w = new JFrame();
        JSlider slider = new JSlider();
        slider.setMinimum(1023);
        w.add(slider);
        w.pack();
        w.setVisible(true);
    }
}
</code>```

答: you hadnt add setbounds(); in your java code try w.setbounds(100,100,200,200);.Usually null pointer exception came when the reference of an object is null.Try this .Hope it will work for you.</p>

Body:
Error******************************************************************

Exception in thread "main" java.lang.NullPointerException
at java.awt.Window.init(Unknown Source)
at java.awt.Window.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at javax.swing.JFrame.<init>(Unknown Source)
at Main.main(Main.java:12)

Code********************************************************************

import javax.swing.JFrame;
import javax.swing.JSlider;

import com.fazecast.jSerialComm.*;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        JFrame w = new JFrame();
        JSlider slider = new JSlider();
        slider.setMinimum(1023);
        w.add(slider);
        w.pack();
        w.setVisible(true);
    }
}


问:
How do I find duplicates in an array and display how many times they occurred?
I'm working on a code that prints out duplicated integers from an array with the number of their occurrence. I'm not allowed to use LINQ, just a simple code. I think I'm so close but confused about how to get a correct output: </p>

```<code>class Program
{
    static void Main(string[] args)
    {
        int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
        int count = 1;
        for (int i = 0; i < array.Length; i++)
        {
            for (int j = i; j < array.Length - 1 ; j++)
            {

               if(array[j] == array[j+1])
                  count = count + 1;
            }
            Console.WriteLine("\t\n " + array[i] + "occurse" + count);
            Console.ReadKey();
        }
    }
}
</code>```

答:
/This is the answer that helps you to find the duplicate integer values using Forloop and it will return only the repeated values apart from its times of occurences/

```<code>    public static void Main(string[] args)
    {
        //Array list to store all the duplicate values
        int[] ary = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
        ArrayList dup = new ArrayList();

        for (int i = 0; i < ary.Length; i++)
        {
            for (int j = i + 1; j < ary.Length; j++)
            {
                if (ary[i].Equals(ary[j]))
                {
                    if (!dup.Contains(ary[i]))
                    {
                        dup.Add(ary[i]);
                    }
                }
            }
        }
        Console.WriteLine("The numbers which duplicates are");
        DisplayArray(dup);
    }
    public static void DisplayArray(ArrayList ary)
    {
        //loop through all the elements
        for (int i = 0; i < ary.Count; i++)
        {
            Console.Write(ary[i] + " ");
        }
        Console.WriteLine();
        Console.ReadKey();
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a code that prints out duplicated integers from an array with the number of their occurrence. I'm not allowed to use LINQ, just a simple code. I think I'm so close but confused about how to get a correct output:

class Program
{
    static void Main(string[] args)
    {
        int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
        int count = 1;
        for (int i = 0; i < array.Length; i++)
        {
            for (int j = i; j < array.Length - 1 ; j++)
            {

               if(array[j] == array[j+1])
                  count = count + 1;
            }
            Console.WriteLine("\t\n " + array[i] + "occurse" + count);
            Console.ReadKey();
        }
    }
}

Body:
/This is the answer that helps you to find the duplicate integer values using Forloop and it will return only the repeated values apart from its times of occurences/

    public static void Main(string[] args)
    {
        //Array list to store all the duplicate values
        int[] ary = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
        ArrayList dup = new ArrayList();

        for (int i = 0; i < ary.Length; i++)
        {
            for (int j = i + 1; j < ary.Length; j++)
            {
                if (ary[i].Equals(ary[j]))
                {
                    if (!dup.Contains(ary[i]))
                    {
                        dup.Add(ary[i]);
                    }
                }
            }
        }
        Console.WriteLine("The numbers which duplicates are");
        DisplayArray(dup);
    }
    public static void DisplayArray(ArrayList ary)
    {
        //loop through all the elements
        for (int i = 0; i < ary.Count; i++)
        {
            Console.Write(ary[i] + " ");
        }
        Console.WriteLine();
        Console.ReadKey();
    }


问:
How do I use FragmentPagerAdapter to have tabs with different content?
I want to have different tabs, where you can swipe through like in the android market. Each tab should use one fragment and use one method for it.

This is my FragmentPagerAdapter class:

```<code>public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment =null;
        switch (position) {
            case 0:
                fragment = new ConnectionFragment();
                break;
            case 1:
                fragment = new DataFragment();
                break;
            case 2:
                fragment = new GraphFragment();
                break;          }
        return fragment;
    }
    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }
}
</code>```

And I have three classes for each fragment type/tab:

```<code>public static class ConnectionFragment extends Fragment {
    public static final String ARG_SECTION_NUMBER = "section_number";
    public String stringConnectionStatus = "Offline";
    public String stringWiflyIp = "0.0.0.0";

    public ConnectionFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View connectionView = inflater.inflate(R.layout.fragment_connection,
                container, false);
        TextView statusView = (TextView) connectionView.findViewById(R.id.status_label);
        statusView.setText("Connection status: " + stringConnectionStatus);
        TextView ipView = (TextView) connectionView.findViewById(R.id.ip_label);
        ipView.setText("WiFly IP: " + stringWiflyIp);
        /**TextView sectionBarView = (TextView) connectionView
                .findViewById(R.id.section_label);
        sectionBarView.setText("pups");"*/

        return connectionView;
    }
}

public static class DataFragment extends Fragment {

    public DataFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View dataView = inflater.inflate(R.layout.fragment_data,
                container, false);
        TextView sectionBarView = (TextView) dataView
                .findViewById(R.id.section_label);
        sectionBarView.setText("pups2");
        return dataView;
    }
}

public static class GraphFragment extends Fragment {

    public GraphFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_graph,
                container, false);
        TextView sectionBarView = (TextView) rootView
                .findViewById(R.id.section_label);
        sectionBarView.setText("pups3");
        return rootView;
    }
}
</code>```

Each Fragment should be customizable, thats why I have three classes.

Nevertheless, the app crashes in the getItem method. Any ideas?
Thank you!

Edit: The complete MainActivity.java:

```<code>import ...
public class MainActivity extends FragmentActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;
    public List<String> fragments = new Vector<String>();

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

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

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager); //pager
        mViewPager.setAdapter(mSectionsPagerAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
            fragments.add(ConnectionFragment.class.getName());
            fragments.add(DataFragment.class.getName());
            fragments.add(GraphFragment.class.getName());
            //fragmentsA = "fragments";

        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            /*Fragment fragment =null;
            switch (position) {
                case 0:
                    fragment = new ConnectionFragment();
                    break;
                case 1:
                    fragment = new DataFragment();
                    break;
                case 2:
                    fragment = new GraphFragment();
                    break;          }
            return fragment;*/
            return Fragment.instantiate(getBaseContext(), fragments.get(position));

        }
        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class ConnectionFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static final String ARG_SECTION_NUMBER = "section_number";
        public String stringConnectionStatus = "Offline";
        public String stringWiflyIp = "0.0.0.0";

        public ConnectionFragment() {}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View connectionView = inflater.inflate(R.layout.fragment_connection,container, false);
            TextView statusView = (TextView) connectionView.findViewById(R.id.status_label);
            statusView.setText("Connection status: " + stringConnectionStatus);
            TextView ipView = (TextView) connectionView.findViewById(R.id.ip_label);
            ipView.setText("WiFly IP: " + stringWiflyIp);
            /**TextView sectionBarView = (TextView) connectionView
                    .findViewById(R.id.section_label);
            sectionBarView.setText("pups");"*/

            return connectionView;
        }
    }
    public static class DataFragment extends Fragment {

        public DataFragment() {}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View dataView = inflater.inflate(R.layout.fragment_data,
                    container, false);
            //TextView sectionBarView = (TextView) dataView.findViewById(R.id.section_label);
            //sectionBarView.setText("pups2");
            return dataView;
        }
    }
    public static class GraphFragment extends Fragment {

        public GraphFragment() {}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_graph,
                    container, false);
            //TextView sectionBarView = (TextView) rootView.findViewById(R.id.section_label);
            //sectionBarView.setText("pups3");
            return rootView;
        }
    }
}
</code>```

答:
See this example:</p>

```<code> public static class MyPagerAdapter extends FragmentPagerAdapter {
    private static int NUM_ITEMS = 3;

    public MyPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    // Returns total number of pages
    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    // Returns the fragment to display for that page
    @Override
    public Fragment getItem(int position) {
        switch (position) {
        case 0: // Fragment # 0 - This will show FirstFragment
            return FirstFragment.newInstance(0, "Page # 1");
        case 1: // Fragment # 0 - This will show FirstFragment different title
            return FirstFragment.newInstance(1, "Page # 2");
        case 2: // Fragment # 1 - This will show SecondFragment
            return SecondFragment.newInstance(2, "Page # 3");
        default:
            return null;
        }
    }

    // Returns the page title for the top indicator
    @Override
    public CharSequence getPageTitle(int position) {
        return "Page " + position;
    }
}
</code>```

Body:
I want to have different tabs, where you can swipe through like in the android market. Each tab should use one fragment and use one method for it.

This is my FragmentPagerAdapter class:

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment =null;
        switch (position) {
            case 0:
                fragment = new ConnectionFragment();
                break;
            case 1:
                fragment = new DataFragment();
                break;
            case 2:
                fragment = new GraphFragment();
                break;          }
        return fragment;
    }
    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }
}

And I have three classes for each fragment type/tab:

public static class ConnectionFragment extends Fragment {
    public static final String ARG_SECTION_NUMBER = "section_number";
    public String stringConnectionStatus = "Offline";
    public String stringWiflyIp = "0.0.0.0";

    public ConnectionFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View connectionView = inflater.inflate(R.layout.fragment_connection,
                container, false);
        TextView statusView = (TextView) connectionView.findViewById(R.id.status_label);
        statusView.setText("Connection status: " + stringConnectionStatus);
        TextView ipView = (TextView) connectionView.findViewById(R.id.ip_label);
        ipView.setText("WiFly IP: " + stringWiflyIp);
        /**TextView sectionBarView = (TextView) connectionView
                .findViewById(R.id.section_label);
        sectionBarView.setText("pups");"*/

        return connectionView;
    }
}

public static class DataFragment extends Fragment {

    public DataFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View dataView = inflater.inflate(R.layout.fragment_data,
                container, false);
        TextView sectionBarView = (TextView) dataView
                .findViewById(R.id.section_label);
        sectionBarView.setText("pups2");
        return dataView;
    }
}

public static class GraphFragment extends Fragment {

    public GraphFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_graph,
                container, false);
        TextView sectionBarView = (TextView) rootView
                .findViewById(R.id.section_label);
        sectionBarView.setText("pups3");
        return rootView;
    }
}

Each Fragment should be customizable, thats why I have three classes.

Nevertheless, the app crashes in the getItem method. Any ideas?
Thank you!

Edit: The complete MainActivity.java:

import ...
public class MainActivity extends FragmentActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;
    public List<String> fragments = new Vector<String>();

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

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

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager); //pager
        mViewPager.setAdapter(mSectionsPagerAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
            fragments.add(ConnectionFragment.class.getName());
            fragments.add(DataFragment.class.getName());
            fragments.add(GraphFragment.class.getName());
            //fragmentsA = "fragments";

        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            /*Fragment fragment =null;
            switch (position) {
                case 0:
                    fragment = new ConnectionFragment();
                    break;
                case 1:
                    fragment = new DataFragment();
                    break;
                case 2:
                    fragment = new GraphFragment();
                    break;          }
            return fragment;*/
            return Fragment.instantiate(getBaseContext(), fragments.get(position));

        }
        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class ConnectionFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static final String ARG_SECTION_NUMBER = "section_number";
        public String stringConnectionStatus = "Offline";
        public String stringWiflyIp = "0.0.0.0";

        public ConnectionFragment() {}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View connectionView = inflater.inflate(R.layout.fragment_connection,container, false);
            TextView statusView = (TextView) connectionView.findViewById(R.id.status_label);
            statusView.setText("Connection status: " + stringConnectionStatus);
            TextView ipView = (TextView) connectionView.findViewById(R.id.ip_label);
            ipView.setText("WiFly IP: " + stringWiflyIp);
            /**TextView sectionBarView = (TextView) connectionView
                    .findViewById(R.id.section_label);
            sectionBarView.setText("pups");"*/

            return connectionView;
        }
    }
    public static class DataFragment extends Fragment {

        public DataFragment() {}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View dataView = inflater.inflate(R.layout.fragment_data,
                    container, false);
            //TextView sectionBarView = (TextView) dataView.findViewById(R.id.section_label);
            //sectionBarView.setText("pups2");
            return dataView;
        }
    }
    public static class GraphFragment extends Fragment {

        public GraphFragment() {}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_graph,
                    container, false);
            //TextView sectionBarView = (TextView) rootView.findViewById(R.id.section_label);
            //sectionBarView.setText("pups3");
            return rootView;
        }
    }
}

Body:
See this example:

 public static class MyPagerAdapter extends FragmentPagerAdapter {
    private static int NUM_ITEMS = 3;

    public MyPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    // Returns total number of pages
    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    // Returns the fragment to display for that page
    @Override
    public Fragment getItem(int position) {
        switch (position) {
        case 0: // Fragment # 0 - This will show FirstFragment
            return FirstFragment.newInstance(0, "Page # 1");
        case 1: // Fragment # 0 - This will show FirstFragment different title
            return FirstFragment.newInstance(1, "Page # 2");
        case 2: // Fragment # 1 - This will show SecondFragment
            return SecondFragment.newInstance(2, "Page # 3");
        default:
            return null;
        }
    }

    // Returns the page title for the top indicator
    @Override
    public CharSequence getPageTitle(int position) {
        return "Page " + position;
    }
}


问:
SSL exception for single folder
I would like to remove my SSL only for one folder.

My url is https://www.example.com
and I would like to remove https for my interactive PDF https://www.example.com/catalog2017 because https does not work with my interactive PDF.

I tried with .htaccess but not work.

答:
You can use the following rules in your .htaccess file. What this does is first check if HTTPs is not on, if not, then it will forward everything to HTTPs except for the directory catalog2017. The second rule checks if HTTPs is on, if so then it will redirect catalog2017 back to HTTP.

```<code>RewriteEngine On

RewriteCond %{HTTP:X-Forwarded-SSL} !on
RewriteCond %{REQUEST_URI} !^\/(catalog2017)
RewriteRule (.*) https://%{HTTP_HOST}/$1 [L,R=301]

RewriteCond %{HTTP:X-Forwarded-SSL} =on
RewriteCond %{REQUEST_URI} ^\/(catalog2017)
RewriteRule (.*) http://%{HTTP_HOST}/$1 [L,R=301]
</code>```

Make sure you clear your cache before testing this. If you have problems with the above rule, then you can also try the following:

```<code>RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/catalog2017
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} ^/catalog2017
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R=301,L]
</code>```

Title: SSL exception for single folder

Body:
You can use the following rules in your .htaccess file. What this does is first check if HTTPs is not on, if not, then it will forward everything to HTTPs except for the directory catalog2017. The second rule checks if HTTPs is on, if so then it will redirect catalog2017 back to HTTP.

RewriteEngine On

RewriteCond %{HTTP:X-Forwarded-SSL} !on
RewriteCond %{REQUEST_URI} !^\/(catalog2017)
RewriteRule (.*) https://%{HTTP_HOST}/$1 [L,R=301]

RewriteCond %{HTTP:X-Forwarded-SSL} =on
RewriteCond %{REQUEST_URI} ^\/(catalog2017)
RewriteRule (.*) http://%{HTTP_HOST}/$1 [L,R=301]

Make sure you clear your cache before testing this. If you have problems with the above rule, then you can also try the following:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/catalog2017
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} ^/catalog2017
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R=301,L]


问:
Polymer 2.0 getting paper-input file
I am using Polymer 2.0.  I have a

```<code><paper-input type="file" id"myFile"></paper-input>
</code>```

Once I selected a file I want to use Polymer (javascript) to get the reference and details of the file.  Previously I had used

```<code>this.$.myFile.inputElement.files[0];
</code>```

But that doesn't seem to work now, it says undefined.  Please help me access the file.  Here is a jsbin:

https://jsbin.com/luledugege/edit?html,console,output

答:
Try this:

```<code>this.$.myFile.inputElement.inputElement.files[0]
</code>```

paper-input has attribute inputElement to get its iron-input. And this element has, in turn, the native input in its shadow root with files attribute.

Your input could be:

```<code><link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="../bower_components/paper-input/paper-input.html">

<dom-module id="my-paper-input-file">
  <template>
    <style>
      :host {
        display: block;
        padding: 10px;
      }
    </style>

    <paper-input type="file" id="myFile" on-change="_handleFiles"></paper-input>

  </template>

  <script>
    class MyPaperInputFile extends Polymer.Element {

      static get is() { return 'my-paper-input-file'; }

      static properties() {

        files: Object

      }

      _handleFiles(e) {
        this.files = this.$.myFile.inputElement.inputElement.files;
        //SAME: this.files = e.target.inputElement.inputElement.files;
      }

    }

    window.customElements.define(MyPaperInputFile.is, MyPaperInputFile);
  </script>
</dom-module>
</code>```

Title: Polymer 2.0 getting paper-input file

Body:
I am using Polymer 2.0.  I have a

<paper-input type="file" id"myFile"></paper-input>

Once I selected a file I want to use Polymer (javascript) to get the reference and details of the file.  Previously I had used

this.$.myFile.inputElement.files[0];

But that doesn't seem to work now, it says undefined.  Please help me access the file.  Here is a jsbin:

https://jsbin.com/luledugege/edit?html,console,output

Body:
Try this:

this.$.myFile.inputElement.inputElement.files[0]

paper-input has attribute inputElement to get its iron-input. And this element has, in turn, the native input in its shadow root with files attribute.

Your input could be:

<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="../bower_components/paper-input/paper-input.html">

<dom-module id="my-paper-input-file">
  <template>
    <style>
      :host {
        display: block;
        padding: 10px;
      }
    </style>

    <paper-input type="file" id="myFile" on-change="_handleFiles"></paper-input>

  </template>

  <script>
    class MyPaperInputFile extends Polymer.Element {

      static get is() { return 'my-paper-input-file'; }

      static properties() {

        files: Object

      }

      _handleFiles(e) {
        this.files = this.$.myFile.inputElement.inputElement.files;
        //SAME: this.files = e.target.inputElement.inputElement.files;
      }

    }

    window.customElements.define(MyPaperInputFile.is, MyPaperInputFile);
  </script>
</dom-module>


问:
Resize image - keep ratio - without background image
Im trying to achieve the effect shown on this site:

http://fofwebdesign.co.uk/template/_testing/scale-img/target-ratio-resize.htm

BUT this site does it using a background image for a div. I cannot use the background image as the image is inside Wordpress and it's being brought in dynamically using the following code:

```<code><div class="featured-image">
   <?php the_post_thumbnail(); ?>
</div>
</code>```

So I have tried the same approach and tried the following things o try and bring the image in as a background image:

```<code>.featured-image {
  max-width: 960px;
  /* actual img width */
  max-height: 150px;
  /* actual img height */*
  height: 150px;
  /* actual img height - IE7 */
  background-image: <?php the_post_thumbnail(); ?>;
  background-size: cover;
  background-position: center;
}
</code>```

and using this:

```<code>background-image: url(<?php the_post_thumbnail(); ?>);
</code>```

Alas, I cant seem to get it to work - Im not even sure I can use PHP inside a CSS document...

So I'm looking for a way to achieve this image resize just on the following class without using a background image...

```<code><div class="featured-image">
   <?php the_post_thumbnail(); ?>
</div>
</code>```

Any help would be massively appreciated - I don't even know if I'm thinking about it correctly or I'm missing something - Thanks!

Example of what I'm trying to achieve here:

答: I hope you are using Bootstrap,don't use the image as background but use it as with the proper  tag and add img-fluid and d-block class to image tag.

Body:
Im trying to achieve the effect shown on this site:

http://fofwebdesign.co.uk/template/_testing/scale-img/target-ratio-resize.htm

BUT this site does it using a background image for a div. I cannot use the background image as the image is inside Wordpress and it's being brought in dynamically using the following code:

   <?php the_post_thumbnail(); ?>

So I have tried the same approach and tried the following things o try and bring the image in as a background image:

.featured-image {
  max-width: 960px;
  /* actual img width */
  max-height: 150px;
  /* actual img height */*
  height: 150px;
  /* actual img height - IE7 */
  background-image: <?php the_post_thumbnail(); ?>;
  background-size: cover;
  background-position: center;
}

and using this:

background-image: url(<?php the_post_thumbnail(); ?>);

Alas, I cant seem to get it to work - Im not even sure I can use PHP inside a CSS document...

So I'm looking for a way to achieve this image resize just on the following class without using a background image...

   <?php the_post_thumbnail(); ?>

Any help would be massively appreciated - I don't even know if I'm thinking about it correctly or I'm missing something - Thanks!

Example of what I'm trying to achieve here:

Body: I hope you are using Bootstrap,don't use the image as background but use it as with the proper <img> tag and add img-fluid and d-block class to image tag.


问:
Liquid Exception: invalid byte sequence in US-ASCII in _layouts/redirect.html
I was using gitlab build of jekyll project, all of a sudden started receiving following error. Not able to solve after a lot of trials. What to do in .gitlab-ci.yml file to resolve this (*error not appearing in local machine, both .gitlab-ci.yml and locally uses "grunt build" command).

Liquid Exception: invalid byte sequence in US-ASCII in _layouts/redirect.html

答:
This solution worked for me.

Put:

```<code>before_script:
  - apt-get update >/dev/null
  - apt-get install -y locales >/dev/null
  - echo "en_US UTF-8" > /etc/locale.gen
  - locale-gen en_US.UTF-8
  - export LANG=en_US.UTF-8
  - export LANGUAGE=en_US:en
  - export LC_ALL=en_US.UTF-8
</code>```

In before_script directive in your .gitlab-ci.yml.

Body:
This solution worked for me.

Put:

before_script:
  - apt-get update >/dev/null
  - apt-get install -y locales >/dev/null
  - echo "en_US UTF-8" > /etc/locale.gen
  - locale-gen en_US.UTF-8
  - export LANG=en_US.UTF-8
  - export LANGUAGE=en_US:en
  - export LC_ALL=en_US.UTF-8

In before_script directive in your .gitlab-ci.yml.


问:
MYSQL Query : get date which was entered on same name of day
I have a bunch of data that contain date and some numbers. The table looks like this.

```<code>ID  |   date                   |   amount  |
--------------------------------------------
1   |   2017-01-01 00:00:00    |   100     |
2   |   2017-02-04 00:00:00    |   5       |
3   |   2017-03-11 00:00:00    |   100     |
4   |   2017-04-14 00:00:00    |   20      |
5   |   2017-05-07 00:00:00    |   5       |
</code>```

So let's say today is monday. What I have to do is get data from table which 'date' is monday, same as today.
I would like to know is there any way do this just using sql query.

答:
```<code>SELECT * FROM your_table WHERE DAYOFWEEK(date) = DAYOFWEEK(CURDATE())
</code>```

use dayofweek function

Body:
I have a bunch of data that contain date and some numbers. The table looks like this.

ID  |   date                   |   amount  |
--------------------------------------------
1   |   2017-01-01 00:00:00    |   100     |
2   |   2017-02-04 00:00:00    |   5       |
3   |   2017-03-11 00:00:00    |   100     |
4   |   2017-04-14 00:00:00    |   20      |
5   |   2017-05-07 00:00:00    |   5       |

So let's say today is monday. What I have to do is get data from table which 'date' is monday, same as today.
I would like to know is there any way do this just using sql query.

Body:
SELECT * FROM your_table WHERE DAYOFWEEK(date) = DAYOFWEEK(CURDATE())

use dayofweek function


问:
Is it possible to have syntax highlighting for HTML/CSS/JS in <textarea>?
Here's a pen of what I mean:

http://codepen.io/archiehicklin/pen/oZQdEG

 <textarea id="html" placeholder="HTML"></textarea>
    <textarea id="css" placeholder="CSS"></textarea>
    <textarea id="js" placeholder="JS"></textarea>
```

Trying to build a small offline wysiwyg editor and was wondering if it's possible to have some form of real-time syntax highlighting for the code input into textarea - similar to codepen or jsfiddle.

I've come across the Codemirror library but it doesn't seem like it would work for live input.

答:
You cannot directly control syntax highlighting in a textarea. You can try JS libraries like http://www.cdolivet.com/editarea/ or if you just wnat to do it all by yourself, you can go for contenteditable .

Contenteditable is an html Attribute that enables textarea like editing in any element like div , span etc.

Although you will have to use a lot of javascript to interpret the language and highlight it accordingly.

This is bold text

This is underlined text

and so on..

class Sample

{

```
</div>
</div>
</p>

<p><strong>UPDATE</strong></p>

<p>If planning some third party libraries you can go for highlight.js:
https://highlightjs.org/</p>

<p>It can be integrated with your contenteditable.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/languages/php.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/styles/purebasic.min.css" />
<script>hljs.initHighlightingOnLoad();</script>
```class test {}```</code>```

Body:
Here's a pen of what I mean:

http://codepen.io/archiehicklin/pen/oZQdEG

 <textarea id="html" placeholder="HTML"></textarea>
    <textarea id="css" placeholder="CSS"></textarea>
    <textarea id="js" placeholder="JS"></textarea>

Trying to build a small offline wysiwyg editor and was wondering if it's possible to have some form of real-time syntax highlighting for the code input into textarea - similar to codepen or jsfiddle.

I've come across the Codemirror library but it doesn't seem like it would work for live input.

Body:
You cannot directly control syntax highlighting in a textarea. You can try JS libraries like http://www.cdolivet.com/editarea/ or if you just wnat to do it all by yourself, you can go for contenteditable .

Contenteditable is an html Attribute that enables textarea like editing in any element like div , span etc.

Although you will have to use a lot of javascript to interpret the language and highlight it accordingly.

<div contenteditable="true" style="width:100%;height:200px;border:1px solid #000">
<b>This is bold text</b><br/>
<u>This is underlined text</u><br/>
and so on..<br/>
<font color="#f00">class</font> <font color="#0f0">Sample</font><br/>
<em>{</em><br/>
</div>

UPDATE

If planning some third party libraries you can go for highlight.js:
https://highlightjs.org/

It can be integrated with your contenteditable.

<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/languages/php.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/styles/purebasic.min.css" />
<script>hljs.initHighlightingOnLoad();</script>
<pre><code class="html">class test {}</code></pre>


问:
Auto-flow process using linked process?
I need auto flow of process in IBM BPM 8.5.5 version.

How Can I do it?

答:
Let me explain step by step

First you need check Automatically flow to next task on the first process's Activity. It's located in Implementation tab

```<code>Second you need do following in the 2nd process's activity
</code>```

Assign to Team

Choose your Team

Choose User Distribution=> Load Balance

Filter the team to one user.

And then Load Balance will automatically assign to the user and autoflow will works.

Title: Auto-flow process using linked process?

Body:
Let me explain step by step

First you need check Automatically flow to next task on the first process's Activity. It's located in Implementation tab

Second you need do following in the 2nd process's activity

Assign to Team

Choose your Team

Choose User Distribution=> Load Balance

Filter the team to one user.

And then Load Balance will automatically assign to the user and autoflow will works.


问:
props not updated in html rendered, but updated in console.log from render()
I've got a nav menu listening to scroll using react-scroll lib.

working :
I save activated Element to my store, so each time I scroll over a new element, my store knows which element is 'active'.

When I display my nav menu, I want to check which element is active from my store and add a class on some nav element. I can't do it with react-scroll because my elements are nested (and I want to highlight some intermediate nav element depending on the current react-scroll active element).

Anyway, when I scroll, store is updated, component listening to this store value is re-rendered, render method is called, console.logs from inside the render() display the right value of "selectedMenu" (this is my store value), ** BUT **, the html generated from the return() of the render() do not update the "selectedMenu" variable value.

For information on first display selectedMenu is empty as nothing has been clicked / scrolled. This empty value remains in the return of the render, but is updated in the console.log inside the render().

Getting crazy...

```<code>render(){
    const {opened, menuId, sub, selectedMenu, selectedCat, setActiveDispatch, anchorKey, titleKey, subClickedDispatch} = this.props;

    console.log('****** selectedMenu : ' + selectedMenu); // displaying the updated value
    console.log('****** selectedCat : ' + selectedCat); // displaying the updated value

    const subData = sub.map((subcat, index)=> {
        console.log("inside map & selectedMenu : " + selectedMenu); // displaying the updated value
        console.log("inside map & selectedCat : " + selectedCat); // displaying the updated value
        return (
            <div key={menuId+'_'+index}>
                <SubMenuChildren>
                    <Link isDynamic={true} offset={-80} onSetActive={(to)=>setActiveDispatch(to)} to={subcat[anchorKey]+"_top_empty"} spy={true} smooth={true} duration={500}><ListItem innerDivStyle={{padding:'0px 0 0px 0px'}} style={{height:'0px'}}></ListItem></Link>
                </SubMenuChildren>
                <SubMenuChildren>
                    {/* selectedMenu NOT UPDATED : is empty, subcat[anchorKey] is ok */}
                    <div>test : {selectedMenu} {subcat[anchorKey]}</div>
                    {/* selectedCat NOT UPDATED : is empty, subcat[anchorKey] is ok */}
                    <div>test : {selectedCat} {subcat[anchorKey]}</div>

                    {/* test is always false as selectedMenu is always empty */}
                    <Link isDynamic={true} className={selectedMenu==subcat[anchorKey]?'active':''} offset={-80} onSetActive={(to)=>setActiveDispatch(to)} to={subcat[anchorKey]} spy={true} smooth={true} duration={500} onClick={()=>subClickedDispatch(subcat)}><ListItem innerDivStyle={{padding:'5px 0 5px 5px'}} style={this.style.navSubElements} hoverColor='transparent' primaryText={ subcat[titleKey] }></ListItem></Link>
                </SubMenuChildren>
            </div>
        );
    });

    return (
        <div className={opened?'subMenu open':'subMenu close'}>
            <div>retest : {selectedMenu}</div> {/* value is updated  !*/}
            {subData}
        </div>
    );
}
</code>```

And here is my mapStateToProps :

```<code>const mapStateToProps=(state)=>({
clickedMain: state.appReducer.clickedMain,
selectedMenu: state.appReducer.selectedMenu,
selectedCat: state.appReducer.selectedCat});
</code>```

答:
Damn it !

Someone from IRC #reactjs just found it.
Problem comes from  component (not posted here) which doesn't update (shouldComponentUpdate always return false). Removing this SCU and all works back.

Body:
I've got a nav menu listening to scroll using react-scroll lib.

working :
I save activated Element to my store, so each time I scroll over a new element, my store knows which element is 'active'.

When I display my nav menu, I want to check which element is active from my store and add a class on some nav element. I can't do it with react-scroll because my elements are nested (and I want to highlight some intermediate nav element depending on the current react-scroll active element).

Anyway, when I scroll, store is updated, component listening to this store value is re-rendered, render method is called, console.logs from inside the render() display the right value of "selectedMenu" (this is my store value), ** BUT **, the html generated from the return() of the render() do not update the "selectedMenu" variable value.

For information on first display selectedMenu is empty as nothing has been clicked / scrolled. This empty value remains in the return of the render, but is updated in the console.log inside the render().

Getting crazy...

render(){
    const {opened, menuId, sub, selectedMenu, selectedCat, setActiveDispatch, anchorKey, titleKey, subClickedDispatch} = this.props;

    console.log('****** selectedMenu : ' + selectedMenu); // displaying the updated value
    console.log('****** selectedCat : ' + selectedCat); // displaying the updated value

    const subData = sub.map((subcat, index)=> {
        console.log("inside map & selectedMenu : " + selectedMenu); // displaying the updated value
        console.log("inside map & selectedCat : " + selectedCat); // displaying the updated value
        return (

                <SubMenuChildren>
                    <Link isDynamic={true} offset={-80} onSetActive={(to)=>setActiveDispatch(to)} to={subcat[anchorKey]+"_top_empty"} spy={true} smooth={true} duration={500}><ListItem innerDivStyle={{padding:'0px 0 0px 0px'}} style={{height:'0px'}}></ListItem></Link>
                </SubMenuChildren>
                <SubMenuChildren>
                    {/* selectedMenu NOT UPDATED : is empty, subcat[anchorKey] is ok */}

test : {selectedMenu} {subcat[anchorKey]}

                    {/* selectedCat NOT UPDATED : is empty, subcat[anchorKey] is ok */}

test : {selectedCat} {subcat[anchorKey]}

                    {/* test is always false as selectedMenu is always empty */}
                    <Link isDynamic={true} className={selectedMenu==subcat[anchorKey]?'active':''} offset={-80} onSetActive={(to)=>setActiveDispatch(to)} to={subcat[anchorKey]} spy={true} smooth={true} duration={500} onClick={()=>subClickedDispatch(subcat)}><ListItem innerDivStyle={{padding:'5px 0 5px 5px'}} style={this.style.navSubElements} hoverColor='transparent' primaryText={ subcat[titleKey] }></ListItem></Link>
                </SubMenuChildren>

        );
    });

    return (

retest : {selectedMenu}
 {/* value is updated  !*/}
            {subData}

    );
}

And here is my mapStateToProps :

const mapStateToProps=(state)=>({
clickedMain: state.appReducer.clickedMain,
selectedMenu: state.appReducer.selectedMenu,
selectedCat: state.appReducer.selectedCat});


问:
What could be solution for this?
I am not finding the solution for the following problem . Any help?

答:
Try the following:

Add this to your gradle compile 'com.android.support:appcompat-v7:22.1.1'

Go to Build -> Clean Project.

Go to File -> Invalidate Caches/Restart.

Title: What could be solution for this?


问:
Scale transition in four divs
This question is related to one that i have already created transition-in-div . I didnot get answer for my next issue there so i decided to create new question.
I have four boxes and i want the transition effect in all four boxes.

What i want is whenever i click on any box, the width of that box must increase from its side to the left and right to fit the full width. Right now it only fills some portion of width.
My Code is

```<code><html>
<head>
    <title>Transition</title>
    <style type="text/css">
    .container {
  display: flex;
  justify-content: space-between;
}

.box {
  width:20%;
  height: 200px;
  transition: transform .5s;
  transform-origin: 0 0;
}
#first {
  background-color: red;
}
#second {
  background-color: green;
  transform-origin: 25% 75%;
}
#third {
  background-color: aqua;
  transform-origin: center center;
}
#fourth {
  background-color: blue;
  transform-origin: 100% 0;
}

.scale {
  transform: scaleX(4);
}
    </style>
</head>
<body>
    <div class="container">
        <div id="first" class="box"></div>
        <div id="second" class="box"></div>
        <div id="third" class="box"></div>
        <div id="fourth" class="box"></div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        var containerWidth = $(".container").width();
        $(".box").click(function() {
          var id = $(this).attr("id");
          $(this).addClass('scale');
        });
    });
</script>
</code>```

Jsfiddle

答:
Why not put the boxes in containers and animate the width, something like this:

https://jsfiddle.net/pt1vk0c1/

```<code>    <div class="container">
        <div id="first" class="box-container">
          <div class="box"> </div>
        </div>
        <div id="second" class="box-container">
          <div class="box"> </div>
        </div>
        <div id="third" class="box-container">
          <div class="box"> </div>
        </div>
        <div id="fourth" class="box-container">
          <div class="box"> </div>
        </div>
    </div>

.container {
  display: flex;
  justify-content: space-between;
}

.box-container {
  width:25%;
  height: 200px;
}

.box {
  width:80%;
  height: 200px;
  transition: width .5s;
  transform-origin: 0 0;
}
#first .box {
  background-color: red;
}
#second .box {
  background-color: green;
  transform-origin: 25% 75%;
}
#third .box {
  background-color: aqua;
  transform-origin: center center;
}
#fourth .box {
  background-color: blue;
  transform-origin: 100% 0;
}

.scale {
  width:100%;
}
</code>```

Title: Scale transition in four divs

Body:
This question is related to one that i have already created transition-in-div . I didnot get answer for my next issue there so i decided to create new question.
I have four boxes and i want the transition effect in all four boxes.

What i want is whenever i click on any box, the width of that box must increase from its side to the left and right to fit the full width. Right now it only fills some portion of width.
My Code is

    <title>Transition</title>

Jsfiddle

Body:
Why not put the boxes in containers and animate the width, something like this:

https://jsfiddle.net/pt1vk0c1/

    <div class="container">
        <div id="first" class="box-container">
          <div class="box"> </div>
        </div>
        <div id="second" class="box-container">
          <div class="box"> </div>
        </div>
        <div id="third" class="box-container">
          <div class="box"> </div>
        </div>
        <div id="fourth" class="box-container">
          <div class="box"> </div>
        </div>
    </div>

.container {
  display: flex;
  justify-content: space-between;
}

.box-container {
  width:25%;
  height: 200px;
}

.box {
  width:80%;
  height: 200px;
  transition: width .5s;
  transform-origin: 0 0;
}
#first .box {
  background-color: red;
}
#second .box {
  background-color: green;
  transform-origin: 25% 75%;
}
#third .box {
  background-color: aqua;
  transform-origin: center center;
}
#fourth .box {
  background-color: blue;
  transform-origin: 100% 0;
}

.scale {
  width:100%;
}


问:
Taxonomy-Related news-block-portion disappear and reappear on Drupal
I have a block which displays all news belonging to terms of a category. However, sometimes, all news related to a term disappear while other terms' news are still visible. This disappear chunk appears on its own later. Is there a way I can fix it.

Both temporary or Permanent solutions are welcomed. Thanks in advance.

I have tried repairing tables, flushing cache but to no avail.

I checked the queries, they seem to be working fine.. I have used APC cache. Could that be a cause of old cached data. I tried flushing APC cache using apc_clear_cache() w and calling apc_clear_cache('user') but it hangs the server into indefinite loop.

答:
Ok, I figured out the problem. The problem was that one of the news belonging to the set of news of a particular taxonomy was saved partially. Though there was an entry in the node table, other related data was missing.

On deleting this partial node manually from the database, the set of missing news articles reappeared.

ContentLicense: CC BY-SA 2.5


问:
Unchecked cast abstract base class
Can someone explain me, why this cast is unchecked. It should be guaranteed that type T is always derived from Base and so the cast from T to Base should not be unchecked.

```<code>abstract class Base
{
    private static final Map<Class<? extends Base>, Consumer<Base>> _CONSUMERS = new HashMap<>();

    @SuppressWarnings( "unchecked" )
    public static <T extends Base> void addConsumer( Class<T> clazz, Consumer<T> consumer )
    {
        _CONSUMERS.put( clazz, (Consumer<Base>) consumer );
    }
}
</code>```

答:
The type of consumer is Consumer<T> = Consumer<? extends Base>, while the put expects a Consumer<Base>.

You should probably declare your _CONSUMERS map as of type:

```<code>Map<Class<? extends Base>, Consumer<? extends Base>>
</code>```

Java does not recognize situations where objects of type X<? extends T> (or X<? super T>) can be used in place of X<T>, you have to explicitly indicate type bounds (see here a more thorough discussion about this).

Title: Unchecked cast abstract base class

Body:
Can someone explain me, why this cast is unchecked. It should be guaranteed that type T is always derived from Base and so the cast from T to Base should not be unchecked.

abstract class Base
{
    private static final Map<Class<? extends Base>, Consumer<Base>> _CONSUMERS = new HashMap<>();

    @SuppressWarnings( "unchecked" )
    public static <T extends Base> void addConsumer( Class<T> clazz, Consumer<T> consumer )
    {
        _CONSUMERS.put( clazz, (Consumer<Base>) consumer );
    }
}

Body:
The type of consumer is Consumer<T> = Consumer<? extends Base>, while the put expects a Consumer<Base>.

You should probably declare your _CONSUMERS map as of type:

Map<Class<? extends Base>, Consumer<? extends Base>>

Java does not recognize situations where objects of type X<? extends T> (or X<? super T>) can be used in place of X<T>, you have to explicitly indicate type bounds (see here a more thorough discussion about this).


问:
put a non static variable into static method in java
guys i have a static method

```<code> public static void method1(){}
</code>```

and i want to put a non static variable in it and access it by setVariable ... is it acceptable to do that ?

example

```<code>private String var;

public setVariable(String var){
    this.var = var;
}

public static void method1(){
    System.out.println(var):
}
</code>```

答:
No. You can, however, call setVariable (from a static context) on a static object, or on the object you get as a parameter. Both of these will work:</p>

```<code>public static MyObj staticObj = new MyObj();

public static void myStaticMethod(MyObj obj) {
    obj.setVariable("newVal");
    staticObj.setVariable("newVal");
}
</code>```

Body:
guys i have a static method

 public static void method1(){}

and i want to put a non static variable in it and access it by setVariable ... is it acceptable to do that ?

example

private String var;

public setVariable(String var){
    this.var = var;
}

public static void method1(){
    System.out.println(var):
}

Body:
No. You can, however, call setVariable (from a static context) on a static object, or on the object you get as a parameter. Both of these will work:

public static MyObj staticObj = new MyObj();

public static void myStaticMethod(MyObj obj) {
    obj.setVariable("newVal");
    staticObj.setVariable("newVal");
}


问:
Call JavaScript in  Pageload in VS2005
```<code><%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<script language="JavaScript" type="text/JavaScript">
CheckBrow();
</script>

function  CheckBrow()
{
  if((navigator.appName == "Microsoft Internet Explorer") ||(navigator.appName == "Netscape"))
  {
   HhdnBrowsertype.value=0;
  }
  else
  {
  alert("please open the application in IE or Fire fox browser")
  HhdnBrowsertype.value=1;
  }
}

<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:HiddenField ID="HhdnBrowsertype" runat="server" />
    </div>
    </form>
</body>
</html>
</code>```

Here is my JavaScript function.  Now I need to execute this function on page load.

Here I will check the browser type based on the hidden field value 0 or 1.

I will check this hidden field value on page load

```<code>    protected void Page_Load(object sender, EventArgs e)
        {
// here  i need to call  my javscript  function
//  can any one  tell me the  syntax
          If(HhdnBrowsertype.Value==”1”)
    {
    // here  go my page load  function
    }

        }
</code>```

Can anyone tell me how I can call this JavaScript function on page load?  I am using VS 2005.

答:
try this

```<code><body onload="CheckBrow()">
</code>```

or you can use.

```<code>Page.ClientScript.RegisterStartupScript(typeof(string), "CheckBrow", "CheckBrow();", true);
</code>```

Title: Call JavaScript in  Pageload in VS2005

Body:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

function  CheckBrow()
{
  if((navigator.appName == "Microsoft Internet Explorer") ||(navigator.appName == "Netscape"))
  {
   HhdnBrowsertype.value=0;
  }
  else
  {
  alert("please open the application in IE or Fire fox browser")
  HhdnBrowsertype.value=1;
  }
}

    <title>Untitled Page</title>

    <form id="form1" runat="server">

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:HiddenField ID="HhdnBrowsertype" runat="server" />

    </form>

Here is my JavaScript function.  Now I need to execute this function on page load.

Here I will check the browser type based on the hidden field value 0 or 1.

I will check this hidden field value on page load

    protected void Page_Load(object sender, EventArgs e)
        {
// here  i need to call  my javscript  function
//  can any one  tell me the  syntax
          If(HhdnBrowsertype.Value==”1”)
    {
    // here  go my page load  function
    }

        }

Can anyone tell me how I can call this JavaScript function on page load?  I am using VS 2005.

Body:
try this

<body onload="CheckBrow()">

or you can use.

Page.ClientScript.RegisterStartupScript(typeof(string), "CheckBrow", "CheckBrow();", true);


问:
Java double colon operator reference (::)
Is

```<code>test::testMethod == test::testMethod
</code>```

true? I want to find out whether they will refer to the same object. This code does not compile. But there may be several situations in which this needs clarification.

I suspect that this will expand to

```<code>Runnable r = () -> test.testMethod()
Runnable r1 = () -> test.testMethod()
</code>```

And whether the below is true.

```<code>r == r1
</code>```

答:
Let's look at the following example:

```<code>Predicate<String> predicate = String::isEmpty;

Function<String,Boolean> function = String::isEmpty;

System.out.println(predicate.equals(function)); // false
</code>```

A lambda doesn't contain any information about it's type. That information is deduced from the context.  The same lamba String::inEmpty can represent different functional interfaces, as we have seen above.

Body:
Is

test::testMethod == test::testMethod

true? I want to find out whether they will refer to the same object. This code does not compile. But there may be several situations in which this needs clarification.

I suspect that this will expand to

Runnable r = () -> test.testMethod()
Runnable r1 = () -> test.testMethod()

And whether the below is true.

r == r1

Body:
Let's look at the following example:

Predicate<String> predicate = String::isEmpty;

Function<String,Boolean> function = String::isEmpty;

System.out.println(predicate.equals(function)); // false

A lambda doesn't contain any information about it's type. That information is deduced from the context.  The same lamba String::inEmpty can represent different functional interfaces, as we have seen above.


问:
How to Serialize Tree Structure Data From Database to JSON
I have data in a data store which represents a tree structure. Following code represents how it can be described in a simple DataTable in C#.

```<code>using System.Data;

namespace DemoConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable treeData = new DataTable();
            treeData.Clear();
            treeData.Columns.Add("NodeId", typeof(int));
            treeData.Columns.Add("ParentNodeId", typeof(int));
            treeData.Columns.Add("Data", typeof(string));
            treeData.Columns.Add("AbsolutePath", typeof(string));

            DataRow record1 = treeData.NewRow();
            record1["NodeId"] = 1;
            record1["ParentNodeId"] = 0;
            record1["Data"] = "Dairy";
            record1["AbsolutePath"] = "/Dairy/";
            treeData.Rows.Add(record1);

            DataRow record2 = treeData.NewRow();
            record2["NodeId"] = 2;
            record2["ParentNodeId"] = 1;
            record2["Data"] = "Yoghurt";
            record2["AbsolutePath"] = "/Dairy/Yoghurt";
            treeData.Rows.Add(record2);

            DataRow record3 = treeData.NewRow();
            record3["NodeId"] = 3;
            record3["ParentNodeId"] = 1;
            record3["Data"] = "Cheese";
            record3["AbsolutePath"] = "/Dairy/Cheese";
            treeData.Rows.Add(record3);

            DataRow record4 = treeData.NewRow();
            record4["NodeId"] = 4;
            record4["ParentNodeId"] = 2;
            record4["Data"] = "Flavored";
            record4["AbsolutePath"] = "/Dairy/Yoghurt/Flavored";
            treeData.Rows.Add(record4);
        }
    }
}
</code>```

I need to serialize the data into the following structure.

```<code>{
  "TreeData": {
    "NodeId" : "1",
    "Data" : "Dairy",
    "Children": [
      {
        "NodeId": "2",
        "Data": "Yohurt",
        "Children": [
          {
              "NodeId": "4",
              "Data": "Flavored",
              "Children": []
          }
        ]
      },
      {
        "NodeId": "3",
        "Data": "Cheese",
        "Children": []
      }
    ]
  }
}
</code>```

How do i go about achieving this?

答:
My aproach would be to create an object (TreeDataNode, for example) and giving this object the following variables

```<code>public class TreeDataNode{
    int nodeId;
    string data;
    List<TreeDataNode> children;

    public void AddChildren(string relativePath, TreeDataNode node)
    {
        string[] path = relativePath.Split('/');
        if(path.Count<2)
        {
            children.Add(node);
        }else
        {
            string newPath = String.Join(@"/", relativePath.Split('\\').Skip(1));
            children.First(n=> n.data==path[0]).AddChildren(newPath,node);
        }
    }
}
</code>```

Once you populate this object, having a parent TreeDataNode and the subsequent children, you just have to serialize it with any standard JSON serializer, and you would have a structure just like the one you are trying to achieve.

Now, you just need to be sure to add your objects in order, never a parent after his children, and it will be alright. Create your parent TreeDataNode with the root object, and then call AddChildren for every object on this parent.

Body:
I have data in a data store which represents a tree structure. Following code represents how it can be described in a simple DataTable in C#.

using System.Data;

namespace DemoConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable treeData = new DataTable();
            treeData.Clear();
            treeData.Columns.Add("NodeId", typeof(int));
            treeData.Columns.Add("ParentNodeId", typeof(int));
            treeData.Columns.Add("Data", typeof(string));
            treeData.Columns.Add("AbsolutePath", typeof(string));

            DataRow record1 = treeData.NewRow();
            record1["NodeId"] = 1;
            record1["ParentNodeId"] = 0;
            record1["Data"] = "Dairy";
            record1["AbsolutePath"] = "/Dairy/";
            treeData.Rows.Add(record1);

            DataRow record2 = treeData.NewRow();
            record2["NodeId"] = 2;
            record2["ParentNodeId"] = 1;
            record2["Data"] = "Yoghurt";
            record2["AbsolutePath"] = "/Dairy/Yoghurt";
            treeData.Rows.Add(record2);

            DataRow record3 = treeData.NewRow();
            record3["NodeId"] = 3;
            record3["ParentNodeId"] = 1;
            record3["Data"] = "Cheese";
            record3["AbsolutePath"] = "/Dairy/Cheese";
            treeData.Rows.Add(record3);

            DataRow record4 = treeData.NewRow();
            record4["NodeId"] = 4;
            record4["ParentNodeId"] = 2;
            record4["Data"] = "Flavored";
            record4["AbsolutePath"] = "/Dairy/Yoghurt/Flavored";
            treeData.Rows.Add(record4);
        }
    }
}

I need to serialize the data into the following structure.

{
  "TreeData": {
    "NodeId" : "1",
    "Data" : "Dairy",
    "Children": [
      {
        "NodeId": "2",
        "Data": "Yohurt",
        "Children": [
          {
              "NodeId": "4",
              "Data": "Flavored",
              "Children": []
          }
        ]
      },
      {
        "NodeId": "3",
        "Data": "Cheese",
        "Children": []
      }
    ]
  }
}

How do i go about achieving this?

Body:
My aproach would be to create an object (TreeDataNode, for example) and giving this object the following variables

public class TreeDataNode{
    int nodeId;
    string data;
    List<TreeDataNode> children;

    public void AddChildren(string relativePath, TreeDataNode node)
    {
        string[] path = relativePath.Split('/');
        if(path.Count<2)
        {
            children.Add(node);
        }else
        {
            string newPath = String.Join(@"/", relativePath.Split('\\').Skip(1));
            children.First(n=> n.data==path[0]).AddChildren(newPath,node);
        }
    }
}

Once you populate this object, having a parent TreeDataNode and the subsequent children, you just have to serialize it with any standard JSON serializer, and you would have a structure just like the one you are trying to achieve.

Now, you just need to be sure to add your objects in order, never a parent after his children, and it will be alright. Create your parent TreeDataNode with the root object, and then call AddChildren for every object on this parent.


问:
PHP - when to use private static properties in the class
I am learning php and there are still alot of unclear areas for me in the language. I wonder when and why would we use private static properties inside the class. From what I understood private properties may only be accessed by the class where it was defined. So, the private part is clear, but the static is still unclear. In the docs it says:

Declaring class properties or methods as static makes them accessible
  without needing an instantiation of the class. A property declared as
  static cannot be accessed with an instantiated class object (though a
  static method can).

Does that mean that I can access static properties without instantiation of the class. So, for example:

```<code>class Foo{

    static $bar;

    public function __construct($bar){
        $this->bar = $bar;
    }
</code>```

So, I can access the $bar property of the class like so?

```<code>Foo::$bar
</code>```

But, if I do this, it wouldn't work?

```<code>$foo = new Foo();
$foo::$bar
</code>```

And, then if do make a property private static for which reason would we do that, since I thought we make them static in order to access them outside of their class and making them private would make that impossible. I would be very grateful if someone could clear this up to me.

答:
Static context within a PHP class (but outside of a function) is context which exists statically, that is without the need for a backing instance of an object.

Example:

```<code>class A {
     public $a = 1;
     public static $b = 2;

     public function instanceFunction() {
           A::$a; //Wrong way
           $this->a //Right way
           A::$b; //Works
           self::$b; // Also works
           static::$b; // Also also works
     }
     public static function staticFunction() {
           A::$a; //Does not work
           $this->a //Error $this within static context
           A::$b; //Works
           self::$b; // Also works
           static::$b; // Also also works
     }

}

A::$a; // Error $a is not static so it needs an instance of an object
A::$b; // Works
$Aobject=new A();
$Aobject->a; //Works
$Aobject->b // Does not work
</code>```

Using self means "refer to the class I've written this in" e.g. in this case it's always A. Using static means "refer to the class I've called this from" which applies if static inheritance is involved which PHP does manage to pull off.

Body:
I am learning php and there are still alot of unclear areas for me in the language. I wonder when and why would we use private static properties inside the class. From what I understood private properties may only be accessed by the class where it was defined. So, the private part is clear, but the static is still unclear. In the docs it says:

Declaring class properties or methods as static makes them accessible
  without needing an instantiation of the class. A property declared as
  static cannot be accessed with an instantiated class object (though a
  static method can).

Does that mean that I can access static properties without instantiation of the class. So, for example:

class Foo{

    static $bar;

    public function __construct($bar){
        $this->bar = $bar;
    }

So, I can access the $bar property of the class like so?

Foo::$bar

But, if I do this, it wouldn't work?

$foo = new Foo();
$foo::$bar

And, then if do make a property private static for which reason would we do that, since I thought we make them static in order to access them outside of their class and making them private would make that impossible. I would be very grateful if someone could clear this up to me.

Body:
Static context within a PHP class (but outside of a function) is context which exists statically, that is without the need for a backing instance of an object.

Example:

class A {
     public $a = 1;
     public static $b = 2;

     public function instanceFunction() {
           A::$a; //Wrong way
           $this->a //Right way
           A::$b; //Works
           self::$b; // Also works
           static::$b; // Also also works
     }
     public static function staticFunction() {
           A::$a; //Does not work
           $this->a //Error $this within static context
           A::$b; //Works
           self::$b; // Also works
           static::$b; // Also also works
     }

}

A::$a; // Error $a is not static so it needs an instance of an object
A::$b; // Works
$Aobject=new A();
$Aobject->a; //Works
$Aobject->b // Does not work

Using self means "refer to the class I've written this in" e.g. in this case it's always A. Using static means "refer to the class I've called this from" which applies if static inheritance is involved which PHP does manage to pull off.


问:
Too many arguments to conversion in gobot
I was trying to test a LDR using gobot framework. I used AnalogSensorDriver device driver and my code is

```<code>    package main

import (
    "time"

    "gobot.io/x/gobot"
    "gobot.io/x/gobot/drivers/aio"
    "gobot.io/x/gobot/platforms/raspi"
)

func main() {
    r := raspi.NewAdaptor()
    ldr := aio.AnalogSensorDriver(r, "7")

    work := func() {
        gobot.Every(1*time.Second, func() {
            ldr.Read()
        })
    }

    robot := gobot.NewRobot("getBot",
        []gobot.Connection{r},
        []gobot.Device{ldr},
        work,
    )

    robot.Start()
}
</code>```

When I execute this, I am getting this error.

./ldrtest.go:13: too many arguments to conversion to aio.AnalogSensorDriver: aio.AnalogSensorDriver(w, "7")
  ./ldrtest.go:22: undefined: w

I am totally new for golang and gobot. So any kind of help to solve this problem would be greatly appreciated.

Thanks in advance.

答:
From a quick glance at gobot's source it seems to me that you cannot use aio.NewAnalogSensorDriver with the raspi.Adaptor. The aio.NewAnalogSensorDriver expects it's first argument to be an interface of type AnalogReader while the raspi.NewAdaptor returns a raspi.Adaptor that, seemingly, does not implement the AnalogRead method required for it to implement the AnalogReader interface.

That's why you get that error ./ldrtest.go:13: cannot use r (type *raspi.Adaptor) as type aio.AnalogReader in argument to aio.NewAnalogSensorDriver: *raspi.Adaptor does not implement aio.AnalogReader (missing AnalogRead method).

Update:
Making your code work depends on what you want to do. If you want to use raspi.Adaptor you cannot use aio.NewAnalogSensorDriver because the raspi.Adaptor does not have analog capabilities. If you want to use the aio.NewAnalogSensorDriver you'll need to use, as its first argument, a value whose type implements the AnalogRead method, like for example the beaglebone.Adaptor does.

```<code>package main

import (
    "time"

    "gobot.io/x/gobot"
    "gobot.io/x/gobot/drivers/aio"
    "gobot.io/x/gobot/platforms/beaglebone"
)

func main() {
    r := beaglebone.NewAdaptor()
    ldr := aio.NewAnalogSensorDriver(r, "7")

    // ...
}
</code>```

This example should get you past that initial error, if the code below causes other issues you should consider consulting the documentation for both Go and gobot.

Body:
I was trying to test a LDR using gobot framework. I used AnalogSensorDriver device driver and my code is

    package main

import (
    "time"

    "gobot.io/x/gobot"
    "gobot.io/x/gobot/drivers/aio"
    "gobot.io/x/gobot/platforms/raspi"
)

func main() {
    r := raspi.NewAdaptor()
    ldr := aio.AnalogSensorDriver(r, "7")

    work := func() {
        gobot.Every(1*time.Second, func() {
            ldr.Read()
        })
    }

    robot := gobot.NewRobot("getBot",
        []gobot.Connection{r},
        []gobot.Device{ldr},
        work,
    )

    robot.Start()
}

When I execute this, I am getting this error.

./ldrtest.go:13: too many arguments to conversion to aio.AnalogSensorDriver: aio.AnalogSensorDriver(w, "7")
  ./ldrtest.go:22: undefined: w

I am totally new for golang and gobot. So any kind of help to solve this problem would be greatly appreciated.

Thanks in advance.

Body:
From a quick glance at gobot's source it seems to me that you cannot use aio.NewAnalogSensorDriver with the raspi.Adaptor. The aio.NewAnalogSensorDriver expects it's first argument to be an interface of type AnalogReader while the raspi.NewAdaptor returns a raspi.Adaptor that, seemingly, does not implement the AnalogRead method required for it to implement the AnalogReader interface.

That's why you get that error ./ldrtest.go:13: cannot use r (type *raspi.Adaptor) as type aio.AnalogReader in argument to aio.NewAnalogSensorDriver: *raspi.Adaptor does not implement aio.AnalogReader (missing AnalogRead method).

Update:
Making your code work depends on what you want to do. If you want to use raspi.Adaptor you cannot use aio.NewAnalogSensorDriver because the raspi.Adaptor does not have analog capabilities. If you want to use the aio.NewAnalogSensorDriver you'll need to use, as its first argument, a value whose type implements the AnalogRead method, like for example the beaglebone.Adaptor does.

package main

import (
    "time"

    "gobot.io/x/gobot"
    "gobot.io/x/gobot/drivers/aio"
    "gobot.io/x/gobot/platforms/beaglebone"
)

func main() {
    r := beaglebone.NewAdaptor()
    ldr := aio.NewAnalogSensorDriver(r, "7")

    // ...
}

This example should get you past that initial error, if the code below causes other issues you should consider consulting the documentation for both Go and gobot.