问:
How to change property of all buttons in windows from?
I have some buttons on Form1. I want to set their FlatStyle property to FlatStyle.Popup.
I searched and wrote some code as below:

```<code>// List<Control> ButtonsList = new List<Control>();
 List<Button> ButtonsList = new List<Button>();
 public Form1()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.autorun;  //Project->Properties->Resources->
            ButtonsList = GetAccessToAllButtons(this).OfType<Button>.ToList(); //*** hot line ***

            foreach(Button btn in ButtonList)
            {
                btn.FlatStyle = FlatStyle.Popup;
            }

        }

 public IEnumerable<Control> GetAccessToAllButtons(Control thisClass)
        {
            List<Control> ControlsList = new List<Control>();
            foreach (Control child in thisClass.Controls)
            {
                ControlsList.AddRange(GetAccessToAllButtons(child));
            }
            ControlsList.Add(thisClass);
            return ControlsList;
        }
</code>```

But when I use GetAccessToAllButtons() in hot line of my code, VS generates this error:

'System.Linq.Queryable.OfType(Query.Linq.IQueryable)' is a
  'method', which is not valid in the given context

What is my mistake?

Edit: My reference at here missed the (). It is an accepted answer! Do we have a different situation at my reference? or it is only a typo?

答:
```<code>.OfType<Button>
</code>```

OfType is a method so you are are missing the () at the end of it. It should be:

```<code>.OfType<Button>()
</code>```

Body:
I have some buttons on Form1. I want to set their FlatStyle property to FlatStyle.Popup.
I searched and wrote some code as below:

// List<Control> ButtonsList = new List<Control>();
 List<Button> ButtonsList = new List<Button>();
 public Form1()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.autorun;  //Project->Properties->Resources->
            ButtonsList = GetAccessToAllButtons(this).OfType<Button>.ToList(); //*** hot line ***

            foreach(Button btn in ButtonList)
            {
                btn.FlatStyle = FlatStyle.Popup;
            }

        }

 public IEnumerable<Control> GetAccessToAllButtons(Control thisClass)
        {
            List<Control> ControlsList = new List<Control>();
            foreach (Control child in thisClass.Controls)
            {
                ControlsList.AddRange(GetAccessToAllButtons(child));
            }
            ControlsList.Add(thisClass);
            return ControlsList;
        }

But when I use GetAccessToAllButtons() in hot line of my code, VS generates this error:

'System.Linq.Queryable.OfType(Query.Linq.IQueryable)' is a
  'method', which is not valid in the given context

What is my mistake?

Edit: My reference at here missed the (). It is an accepted answer! Do we have a different situation at my reference? or it is only a typo?

Body:
.OfType<Button>

OfType is a method so you are are missing the () at the end of it. It should be:

.OfType<Button>()


来源: stackexchange

问:
C99 compatible nested calls within variadic macros
Need a way to support nested calls in variadic macros with optional argument. same as this but C99 compatible

GNU gcc extension for ## operator prevents nested calls from being expanded, see code below.

```<code>#define send(obj, msg, ...) find_method(obj, msg)(obj, ##__VA_ARGS__)

/* Ok */
send(0, "+", 1);
find_method(0, "+")(0, 1);

/* Ok. nested call as macros named argument */
send(send(5, "increment"), "+", 1);
find_method(find_method(5, "increment")(5), "+")(find_method(5, "increment")(5), 1);

/* Fail. nested call as macros variable argument i.e. `send` macro is not expanded */
send(0, "+", send(5, "increment"));
find_method(0, "+")(0, send(5, "increment"));

/*
 * preprocess with next commands
 *
 * gcc-4.9   -Wall -std=c99 -E -c file.c | less
 * clang-3.8 -Wall -std=c99 -E -c file.c | less
 */
</code>```

I've modified Jens Gustedt solution to place optional comma, see code below.

Are there more concise alternatives ?

```<code>#define _ARG16(              \
    _0,  _1,  _2,  _3,  _4,  \
    _5,  _6,  _7,  _8,  _9,  \
    _10, _11, _12, _13, _14, \
    _15, ...) _15
#define HAS_COMMA(...) \
    _ARG16(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0)
#define _TRIGGER_PARENTHESIS_(...) ,

#define OPTIONAL_COMMA(...)                                             \
    _ISEMPTY(                                                           \
          /* test if there is just one argument, eventually an empty    \
             one */                                                     \
          HAS_COMMA(__VA_ARGS__),                                       \
          /* test if _TRIGGER_PARENTHESIS_ together with the argument   \
             adds a comma */                                            \
          HAS_COMMA(_TRIGGER_PARENTHESIS_ __VA_ARGS__),                 \
          /* test if the argument together with a parenthesis           \
             adds a comma */                                            \
          HAS_COMMA(__VA_ARGS__ (/*empty*/)),                           \
          /* test if placing it between _TRIGGER_PARENTHESIS_ and the   \
             parenthesis adds a comma */                                \
          HAS_COMMA(_TRIGGER_PARENTHESIS_ __VA_ARGS__ (/*empty*/))      \
    )

#define SPACE_SYMBOL
#define COMMA_SYMBOL ,
#define ARG3(_0, _1, _2, ...) _2
#define OPTIONAL_COMMA_FROM(...) ARG3(__VA_ARGS__, SPACE_SYMBOL, COMMA_SYMBOL)

#define PASTE5(_0, _1, _2, _3, _4) _0 ## _1 ## _2 ## _3 ## _4
#define _ISEMPTY(_0, _1, _2, _3) \
    OPTIONAL_COMMA_FROM(PASTE5(_IS_EMPTY_CASE_, _0, _1, _2, _3))
#define _IS_EMPTY_CASE_0001 ,

#define send(obj, msg, ...) \
    find_method(obj, msg)(obj OPTIONAL_COMMA(__VA_ARGS__) __VA_ARGS__)

/* Ok */
send(0, "+", 1);

/* Ok */
send(send(5, "increment"), "+", 1);

/* Ok */
send(0, "+", send(5, "increment"));
</code>```

Update:

H Walters thanks for idea.

Didn't noticed approach with macros overloading in first place

```<code>#define SEND_NO_ARG(obj, msg) find_method(obj, msg)(obj)
#define SEND_ARG(obj, msg, ...) find_method(obj, msg)(obj, __VA_ARGS__)

#define GET_18TH_ARG(arg1, arg2, arg3, arg4, arg5,        \
    arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13,   \
    arg14, arg15, arg16, arg17, arg18, ...) arg18
#define SEND_MACRO_SELECTOR(...)                          \
    GET_18TH_ARG(__VA_ARGS__,                             \
        SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, \
        SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, \
        SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, \
        SEND_NO_ARG, )

#define send(...) SEND_MACRO_SELECTOR(__VA_ARGS__)(__VA_ARGS__)
</code>```

答:
GNU gcc extension for ## operator prevents nested calls from being expanded, see code below.

If you're willing to use the gnu extension, here's an even more concise approach:

```<code>#define COMMAVA(...) ,##__VA_ARGS__
#define send(obj, msg, ...) find_method(obj, msg)(obj COMMAVA(__VA_ARGS__))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Need a way to support nested calls in variadic macros with optional argument. same as this but C99 compatible

GNU gcc extension for ## operator prevents nested calls from being expanded, see code below.

#define send(obj, msg, ...) find_method(obj, msg)(obj, ##__VA_ARGS__)

/* Ok */
send(0, "+", 1);
find_method(0, "+")(0, 1);

/* Ok. nested call as macros named argument */
send(send(5, "increment"), "+", 1);
find_method(find_method(5, "increment")(5), "+")(find_method(5, "increment")(5), 1);

/* Fail. nested call as macros variable argument i.e. `send` macro is not expanded */
send(0, "+", send(5, "increment"));
find_method(0, "+")(0, send(5, "increment"));

/*
 * preprocess with next commands
 *
 * gcc-4.9   -Wall -std=c99 -E -c file.c | less
 * clang-3.8 -Wall -std=c99 -E -c file.c | less
 */

I've modified Jens Gustedt solution to place optional comma, see code below.

Are there more concise alternatives ?

#define _ARG16(              \
    _0,  _1,  _2,  _3,  _4,  \
    _5,  _6,  _7,  _8,  _9,  \
    _10, _11, _12, _13, _14, \
    _15, ...) _15
#define HAS_COMMA(...) \
    _ARG16(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0)
#define _TRIGGER_PARENTHESIS_(...) ,

#define OPTIONAL_COMMA(...)                                             \
    _ISEMPTY(                                                           \
          /* test if there is just one argument, eventually an empty    \
             one */                                                     \
          HAS_COMMA(__VA_ARGS__),                                       \
          /* test if _TRIGGER_PARENTHESIS_ together with the argument   \
             adds a comma */                                            \
          HAS_COMMA(_TRIGGER_PARENTHESIS_ __VA_ARGS__),                 \
          /* test if the argument together with a parenthesis           \
             adds a comma */                                            \
          HAS_COMMA(__VA_ARGS__ (/*empty*/)),                           \
          /* test if placing it between _TRIGGER_PARENTHESIS_ and the   \
             parenthesis adds a comma */                                \
          HAS_COMMA(_TRIGGER_PARENTHESIS_ __VA_ARGS__ (/*empty*/))      \
    )

#define SPACE_SYMBOL
#define COMMA_SYMBOL ,
#define ARG3(_0, _1, _2, ...) _2
#define OPTIONAL_COMMA_FROM(...) ARG3(__VA_ARGS__, SPACE_SYMBOL, COMMA_SYMBOL)

#define PASTE5(_0, _1, _2, _3, _4) _0 ## _1 ## _2 ## _3 ## _4
#define _ISEMPTY(_0, _1, _2, _3) \
    OPTIONAL_COMMA_FROM(PASTE5(_IS_EMPTY_CASE_, _0, _1, _2, _3))
#define _IS_EMPTY_CASE_0001 ,

#define send(obj, msg, ...) \
    find_method(obj, msg)(obj OPTIONAL_COMMA(__VA_ARGS__) __VA_ARGS__)

/* Ok */
send(0, "+", 1);

/* Ok */
send(send(5, "increment"), "+", 1);

/* Ok */
send(0, "+", send(5, "increment"));

Update:

H Walters thanks for idea.

Didn't noticed approach with macros overloading in first place

#define SEND_NO_ARG(obj, msg) find_method(obj, msg)(obj)
#define SEND_ARG(obj, msg, ...) find_method(obj, msg)(obj, __VA_ARGS__)

#define GET_18TH_ARG(arg1, arg2, arg3, arg4, arg5,        \
    arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13,   \
    arg14, arg15, arg16, arg17, arg18, ...) arg18
#define SEND_MACRO_SELECTOR(...)                          \
    GET_18TH_ARG(__VA_ARGS__,                             \
        SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, \
        SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, \
        SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, \
        SEND_NO_ARG, )

#define send(...) SEND_MACRO_SELECTOR(__VA_ARGS__)(__VA_ARGS__)

Body:
GNU gcc extension for ## operator prevents nested calls from being expanded, see code below.

If you're willing to use the gnu extension, here's an even more concise approach:

#define COMMAVA(...) ,##__VA_ARGS__
#define send(obj, msg, ...) find_method(obj, msg)(obj COMMAVA(__VA_ARGS__))


问:
How to change Backend Theano to TensionFlow in keras Unix
After reading many blogs I tried  ~/.keras/keras.json, but got error
bash: /home/user/.keras/keras.json: Permission denied</p>

答:
Based on the official documentation You can define the environment variable KERAS_BACKEND and this will override what is defined in your config file.

KERAS_BACKEND=tensorflow python -c "from keras import backend"

Or you can use nano to edit keras.json file from command line. i.e
nano $HOME/.keras/keras.json.


问:
how to reset form group array in angular
I have a form array, but if I push another form this have setted the validations of previus form.

in this example [https://plnkr.co/edit/ApCn3YicMjfm2vhSOudj?p=preview][1]https://plnkr.co/edit/ApCn3YicMjfm2vhSOudj?p=preview you can see that the second form shows the name validation, how can I solve this?

答:
All the forms share the same FormGroup here,named "user",which kept form data and states ,so you can either create a separate FormGroup for each Form or reset the value of "user" each time in the submit method,but the latter will make the current form lost its data either.Cause they shared the "user".</p>

```<code>onSubmit({ value, valid }: { value: User, valid: boolean }) {
console.log(value, valid);
this.data.push(value)
this.user = this.fb.group({
  name: ['', [Validators.required, Validators.minLength(2)]],
  account: this.fb.group({
    email: ['', Validators.required],
    confirm: ['', Validators.required]
  })
});
console.log(this.data)
</code>```

<p>}  </p>

Body:
All the forms share the same FormGroup here,named "user",which kept form data and states ,so you can either create a separate FormGroup for each Form or reset the value of "user" each time in the submit method,but the latter will make the current form lost its data either.Cause they shared the "user".

onSubmit({ value, valid }: { value: User, valid: boolean }) {
console.log(value, valid);
this.data.push(value)
this.user = this.fb.group({
  name: ['', [Validators.required, Validators.minLength(2)]],
  account: this.fb.group({
    email: ['', Validators.required],
    confirm: ['', Validators.required]
  })
});
console.log(this.data)

}


问:
Error in render function: “TypeError: Cannot read property of undefined”, using Vuex and Vue Router
I have been dealing with an issue using Vue, Vuex and Vue-Router. I'm building a flash cards app, fetching all the cards on main app creation, then using a Vuex getter to get each card by its id which is passed as a route parameter.

Relevant bits:

App.vue

```<code>export default {
  components: {
    'app-header': header,
  },
  data() {
    return {
    }
  },
  created() {
    this.$store.dispatch('getAllCards');
  }
}
</code>```

The dispatch('getAllCards') is just pulling all the cards from the DB and committing to Vuex store.js.

Now I set up a getter:

```<code>getters: {
  cardById: (state) => (id) => {
    return state.allCards.find((card) => card._id === id);
  }
}
</code>```

Here is Card.vue:

```<code><template>
  <div>
    <br>
    <div v-if="flipped" class="container">
      <div class="box">
        <pre v-if="card.code"><code class="preserve-ws">{{card.back}}</code>```

{{card.back}}

{{card.front}}

</template>

```

<p>I am getting the TypeError referenced in the title. My understanding is that the <code>created()</code> hook happens after <code>data()</code> has been set up, so then I can assign <code>{card}</code> using the getter. Unfortunately this displays nothing...</p>

<p>If I assign <code>card()</code> as a computed property:</p>

```computed: {
  card() {
    return this.$store.getters.cardById(this.$route.params.id);
  }
}
```

The card shows, but I still get that error in console. Any idea why? I looked at this and attempted that solution, but to no avail.

答: $route.params.id must be string, so what is the type of card._id? It seems each card._id is number, I think.

Body:
I have been dealing with an issue using Vue, Vuex and Vue-Router. I'm building a flash cards app, fetching all the cards on main app creation, then using a Vuex getter to get each card by its id which is passed as a route parameter.

Relevant bits:

App.vue

export default {
  components: {
    'app-header': header,
  },
  data() {
    return {
    }
  },
  created() {
    this.$store.dispatch('getAllCards');
  }
}

The dispatch('getAllCards') is just pulling all the cards from the DB and committing to Vuex store.js.

Now I set up a getter:

getters: {
  cardById: (state) => (id) => {
    return state.allCards.find((card) => card._id === id);
  }
}

Here is Card.vue:

<template>

{{card.back}}

{{card.back}}

{{card.front}}

</template>

I am getting the TypeError referenced in the title. My understanding is that the created() hook happens after data() has been set up, so then I can assign {card} using the getter. Unfortunately this displays nothing...

If I assign card() as a computed property:

computed: {
  card() {
    return this.$store.getters.cardById(this.$route.params.id);
  }
}

The card shows, but I still get that error in console. Any idea why? I looked at this and attempted that solution, but to no avail.


问:
Running selenium in c9
I am trying to run a python code that uses selenium module. This code ran perfectly with the use of a chromedriver in my PC. I am trying to run it in c9.io. I downloaded the chromedriver 64 bit version and gave permissions as 777 using chmod. Still I can't get it to work

However, I get the following error:

```<code>Traceback (most recent call last):
  File "/home/ubuntu/workspace/vroniplag/vroni.py", line 119, in <module>
    op('Aaf')
  File "/home/ubuntu/workspace/vroniplag/vroni.py", line 104, in op
    plags=getplags(cd)
  File "/home/ubuntu/workspace/vroniplag/vroni.py", line 92, in getplags
    driver = webdriver.Chrome(chromedriver)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/chrome/webdriver.py", line 62, in __init__
    self.service.start()
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 86, in start
    self.assert_process_still_running()
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 99, in assert_process_still_running
    % (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service ./chromedriver unexpectedly exited. Status code was: 127
</code>```

Can anybody tell me how to fix this

答:
I resolved this on Ubuntu 16.04 with the following:</p>

```<code>$ sudo apt install libgconf-2-4
</code>```

Title: Running selenium in c9

Body:
I am trying to run a python code that uses selenium module. This code ran perfectly with the use of a chromedriver in my PC. I am trying to run it in c9.io. I downloaded the chromedriver 64 bit version and gave permissions as 777 using chmod. Still I can't get it to work

However, I get the following error:

Traceback (most recent call last):
  File "/home/ubuntu/workspace/vroniplag/vroni.py", line 119, in <module>
    op('Aaf')
  File "/home/ubuntu/workspace/vroniplag/vroni.py", line 104, in op
    plags=getplags(cd)
  File "/home/ubuntu/workspace/vroniplag/vroni.py", line 92, in getplags
    driver = webdriver.Chrome(chromedriver)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/chrome/webdriver.py", line 62, in __init__
    self.service.start()
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 86, in start
    self.assert_process_still_running()
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 99, in assert_process_still_running
    % (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service ./chromedriver unexpectedly exited. Status code was: 127

Can anybody tell me how to fix this

Body:
I resolved this on Ubuntu 16.04 with the following:

$ sudo apt install libgconf-2-4


问:
how to add custom js into ALL admin models? django
as this url mentioned
https://docs.djangoproject.com/en/dev/topics/forms/media/#assets-as-a-static-definition
I know that and it does work by adding each custom js into each model one by one BUT is there a way to add into ALL models so I do not have to add each model one by one?</p>

答:
Make an admin folder inside the templates folder and then create a base.html file or add below code in html file:

```<code>{% extends 'admin/base.html' %}
{% block extrahead %}
<<< add your css and js >>>
{% endblock %}
</code>```

but make sure project app name must be above from django.contrib.admin in INSTALLED_APP of django settings

Body:
Make an admin folder inside the templates folder and then create a base.html file or add below code in html file:

{% extends 'admin/base.html' %}
{% block extrahead %}
<<< add your css and js >>>
{% endblock %}

but make sure project app name must be above from django.contrib.admin in INSTALLED_APP of django settings

ContentLicense: CC BY-SA 4.0


问:
Error: addView(View, LayoutParams) is not supported in AdapterView
I'm new and only started learning, so pardon if the error is stupid, I just can't figure out what I did wrong, even after looking at other similar answers. Any help would be appreciated.

This is the error:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.android.guessthenumberpuzzle, PID: 2428
                  android.view.InflateException: Binary XML file line #8: addView(View, LayoutParams) is not supported in AdapterView
                  Caused by: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
                      at android.widget.AdapterView.addView(AdapterView.java:495)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:862)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                      at com.example.android.guessthenumberpuzzle.ListAdapter.getView(ListAdapter.java:27)
                      at android.widget.AbsListView.obtainView(AbsListView.java:2362)
                      at android.widget.ListView.measureHeightOfChildren(ListView.java:1326)
                      at android.widget.ListView.onMeasure(ListView.java:1233)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                      at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1117)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:389)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at com.android.internal.policy.DecorView.onMeasure(DecorView.java:687)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271)
                      at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1358)
                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1607)
                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
                      at android.view.Choreographer.doCallbacks(Choreographer.java:683)
                      at android.view.Choreographer.doFrame(Choreographer.java:619)
                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Application terminated.
</code>```

And here are the files:

Game.java

```<code>package com.example.android.guessthenumberpuzzle;

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

import java.util.ArrayList;

public class Game extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
    }
    ArrayList<List> arrayList = new ArrayList<>();

    public void submit(View view) {
        EditText number1 = (EditText)findViewById(R.id.num_1);
        int no1=Integer.parseInt(number1.getText().toString());

        EditText number2 = (EditText)findViewById(R.id.num_2);
        int no2=Integer.parseInt(number2.getText().toString());

        EditText number3 = (EditText)findViewById(R.id.num_3);
        int no3=Integer.parseInt(number3.getText().toString());

        arrayList.add(new List(no1, no2, no3));

        ListAdapter arrayAdapter = new ListAdapter(this, arrayList);
        ListView listView = (ListView)findViewById(R.id.past_answers);
        listView.setAdapter(arrayAdapter);
    }
}
</code>```

activity_game.xml

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_marginTop="10dp"
        android:background="@color/lightPurple"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Make your guess:"
            android:textColor="@android:color/white"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/num_1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:hint="1"
            android:textColor="@android:color/white"
            android:textColorHint="@android:color/white" />

        <EditText
            android:id="@+id/num_2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:hint="1"
            android:textColorHint="@android:color/white" />

        <EditText
            android:id="@+id/num_3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:hint="1"
            android:textColorHint="@android:color/white" />

    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="10dp"
        android:background="@android:color/holo_blue_dark"
        android:gravity="center"
        android:onClick="submit"
        android:text="Submit" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ListView
            android:id="@+id/past_answers"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </ListView>
    </LinearLayout>

</LinearLayout>
</code>```

list_item.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/num_1_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/num_2_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/num_3_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</ListView>
</code>```

List.java

```<code>package com.example.android.guessthenumberpuzzle;

/**
 * Created by Abhijeet on 08-07-2017.
 */

public class List {

    private int mNum1;
    private int mNum2;
    private int mNum3;

    public List(int num1, int num2, int num3){
        mNum1 = num1;
        mNum2 = num2;
        mNum3 = num3;
    }

    public int getNum1(){
        return mNum1;
    }

    public int getNum2(){
        return mNum2;
    }

    public int getNum3(){
        return mNum3;
    }
}
</code>```

ListAdapter.java

```<code>package com.example.android.guessthenumberpuzzle;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class ListAdapter extends ArrayAdapter<List> {

    public ListAdapter(Context context, ArrayList<List> arrayList) {
        super(context, 0, arrayList);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        List currentItem = getItem(position);

        TextView num1View = (TextView)listItemView.findViewById(R.id.num_1_view);
        num1View.setText(currentItem.getNum1());

        TextView num2View = (TextView)listItemView.findViewById(R.id.num_2_view);
        num2View.setText(currentItem.getNum2());

        TextView num3View = (TextView)listItemView.findViewById(R.id.num_3_view);
        num3View.setText(currentItem.getNum3());

        return listItemView;
    }
}
</code>```

答:
The problem is with the layout list_item.xml.

You cannot add items to a ListView like that (it doesn't even make much sense for the ListView item to be a ListView).

I'm pretty sure you meant something like this:

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

    <TextView
        android:id="@+id/num_1_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/num_2_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/num_3_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
</code>```

Body:
I'm new and only started learning, so pardon if the error is stupid, I just can't figure out what I did wrong, even after looking at other similar answers. Any help would be appreciated.

This is the error:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.android.guessthenumberpuzzle, PID: 2428
                  android.view.InflateException: Binary XML file line #8: addView(View, LayoutParams) is not supported in AdapterView
                  Caused by: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
                      at android.widget.AdapterView.addView(AdapterView.java:495)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:862)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                      at com.example.android.guessthenumberpuzzle.ListAdapter.getView(ListAdapter.java:27)
                      at android.widget.AbsListView.obtainView(AbsListView.java:2362)
                      at android.widget.ListView.measureHeightOfChildren(ListView.java:1326)
                      at android.widget.ListView.onMeasure(ListView.java:1233)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                      at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1117)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:389)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6120)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                      at com.android.internal.policy.DecorView.onMeasure(DecorView.java:687)
                      at android.view.View.measure(View.java:19734)
                      at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271)
                      at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1358)
                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1607)
                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
                      at android.view.Choreographer.doCallbacks(Choreographer.java:683)
                      at android.view.Choreographer.doFrame(Choreographer.java:619)
                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Application terminated.

And here are the files:

Game.java

package com.example.android.guessthenumberpuzzle;

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

import java.util.ArrayList;

public class Game extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
    }
    ArrayList<List> arrayList = new ArrayList<>();

    public void submit(View view) {
        EditText number1 = (EditText)findViewById(R.id.num_1);
        int no1=Integer.parseInt(number1.getText().toString());

        EditText number2 = (EditText)findViewById(R.id.num_2);
        int no2=Integer.parseInt(number2.getText().toString());

        EditText number3 = (EditText)findViewById(R.id.num_3);
        int no3=Integer.parseInt(number3.getText().toString());

        arrayList.add(new List(no1, no2, no3));

        ListAdapter arrayAdapter = new ListAdapter(this, arrayList);
        ListView listView = (ListView)findViewById(R.id.past_answers);
        listView.setAdapter(arrayAdapter);
    }
}

activity_game.xml

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_marginTop="10dp"
        android:background="@color/lightPurple"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Make your guess:"
            android:textColor="@android:color/white"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/num_1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:hint="1"
            android:textColor="@android:color/white"
            android:textColorHint="@android:color/white" />

        <EditText
            android:id="@+id/num_2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:hint="1"
            android:textColorHint="@android:color/white" />

        <EditText
            android:id="@+id/num_3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:hint="1"
            android:textColorHint="@android:color/white" />

    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="10dp"
        android:background="@android:color/holo_blue_dark"
        android:gravity="center"
        android:onClick="submit"
        android:text="Submit" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ListView
            android:id="@+id/past_answers"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </ListView>
    </LinearLayout>

</LinearLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/num_1_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/num_2_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/num_3_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</ListView>

List.java

package com.example.android.guessthenumberpuzzle;

/**
 * Created by Abhijeet on 08-07-2017.
 */

public class List {

    private int mNum1;
    private int mNum2;
    private int mNum3;

    public List(int num1, int num2, int num3){
        mNum1 = num1;
        mNum2 = num2;
        mNum3 = num3;
    }

    public int getNum1(){
        return mNum1;
    }

    public int getNum2(){
        return mNum2;
    }

    public int getNum3(){
        return mNum3;
    }
}

ListAdapter.java

package com.example.android.guessthenumberpuzzle;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class ListAdapter extends ArrayAdapter<List> {

    public ListAdapter(Context context, ArrayList<List> arrayList) {
        super(context, 0, arrayList);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        List currentItem = getItem(position);

        TextView num1View = (TextView)listItemView.findViewById(R.id.num_1_view);
        num1View.setText(currentItem.getNum1());

        TextView num2View = (TextView)listItemView.findViewById(R.id.num_2_view);
        num2View.setText(currentItem.getNum2());

        TextView num3View = (TextView)listItemView.findViewById(R.id.num_3_view);
        num3View.setText(currentItem.getNum3());

        return listItemView;
    }
}

Body:
The problem is with the layout list_item.xml.

You cannot add items to a ListView like that (it doesn't even make much sense for the ListView item to be a ListView).

I'm pretty sure you meant something like this:

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

    <TextView
        android:id="@+id/num_1_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/num_2_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/num_3_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>


问:
Ruby haml unexpected ending error
```<code>= simple_form_for @pin, html: { multipart: true} do |f|
- if @pin.errors.any?
    #errors
        %h2
        = pluralize(@pin.errors.count, "errors")
        prevented this Pin from saving
        %ul
            - @pin.errors.full_messages.each do |msg|
            %li= msg
.form-group
    = f.input :title, input_html: { class: 'form-control' }

.form-group
    = f.input :description, input_html:{ class: 'form-control' }

= f.button :submit, class: "btn btn-primary"
</code>```

can someone tell me why this is returing me the error that says below for rails

/Users/frankchen/project/pin_board/app/views/pins/_form.html.haml:17: syntax error, unexpected keyword_ensure, expecting keyword_end ...:Util.html_safe(_erbout);ensure;@haml_buffer = @haml_buffer.... ... ^ /Users/frankchen/project/pin_board/app/views/pins/_form.html.haml:20: syntax error, unexpected end-of-input, expecting keyword_end

答:
In my case, it worked when I remove the indentation between %ul and - @pin.errors.full_messages.each do |msg|. I still don't know the reason though since the - @pin.errors.full_messages.each do |msg| is supposed to be inside the @ul tag.

```<code>%ul
- @pin.errors.full_messages.each do |msg|
  %li= msg
</code>```

Title: Ruby haml unexpected ending error

Body:
= simple_form_for @pin, html: { multipart: true} do |f|
- if @pin.errors.any?
    #errors
        %h2
        = pluralize(@pin.errors.count, "errors")
        prevented this Pin from saving
        %ul
            - @pin.errors.full_messages.each do |msg|
            %li= msg
.form-group
    = f.input :title, input_html: { class: 'form-control' }

.form-group
    = f.input :description, input_html:{ class: 'form-control' }

= f.button :submit, class: "btn btn-primary"

can someone tell me why this is returing me the error that says below for rails

/Users/frankchen/project/pin_board/app/views/pins/_form.html.haml:17: syntax error, unexpected keyword_ensure, expecting keyword_end ...:Util.html_safe(_erbout);ensure;@haml_buffer = @haml_buffer.... ... ^ /Users/frankchen/project/pin_board/app/views/pins/_form.html.haml:20: syntax error, unexpected end-of-input, expecting keyword_end

Body:
In my case, it worked when I remove the indentation between %ul and - @pin.errors.full_messages.each do |msg|. I still don't know the reason though since the - @pin.errors.full_messages.each do |msg| is supposed to be inside the @ul tag.

%ul
- @pin.errors.full_messages.each do |msg|
  %li= msg


问:
share files using ACTION_SEND not working for share IT android
share files using ACTION_SEND not working for share IT android

I am trying to share an Image using

```<code>String path = newString;
                Uri uri = Uri.parse(path);

                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("image/jpeg");
                intent.putExtra(Intent.EXTRA_STREAM, uri);
                startActivity(Intent.createChooser(intent, "Share Image"));
</code>```

however I get the error sending this content type is not supported

Is there a tool or utility which can make sharing easy

what I am looking for is an alternative to Intent.ACTION_SEND

to send files on youtube, FB, share it, mail  or  other social media or other platform

I don't want to use wifi direct as an alternative

答:
This worked</p>

```<code>try {

                    String path = newString;
                    File myFile = new File(path);
                    Intent sharingIntent = new Intent("android.intent.action.SEND");
                    sharingIntent.setType(getMimeType(myFile.getPath()));
                    sharingIntent.putExtra("android.intent.extra.STREAM",Uri.fromFile(myFile));
                    startActivity(Intent.createChooser(sharingIntent,"Share using"));
                } catch (Exception e) {
                    Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
             }

public String getMimeType(String filePath) {
        String type = null;
        String extension = getFileExtensionFromUrl(filePath);
        if (extension != null) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            type = mime.getMimeTypeFromExtension(extension);
        }
        return type;
    }

    public String getFileExtensionFromUrl(String url) {
        int dotPos = url.lastIndexOf('.');
        if (0 <= dotPos) {
            return (url.substring(dotPos + 1)).toLowerCase();
        }
        return "";
    }
</code>```

Body:
share files using ACTION_SEND not working for share IT android

I am trying to share an Image using

String path = newString;
                Uri uri = Uri.parse(path);

                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("image/jpeg");
                intent.putExtra(Intent.EXTRA_STREAM, uri);
                startActivity(Intent.createChooser(intent, "Share Image"));

however I get the error sending this content type is not supported

Is there a tool or utility which can make sharing easy

what I am looking for is an alternative to Intent.ACTION_SEND

to send files on youtube, FB, share it, mail  or  other social media or other platform

I don't want to use wifi direct as an alternative

Body:
This worked

try {

                    String path = newString;
                    File myFile = new File(path);
                    Intent sharingIntent = new Intent("android.intent.action.SEND");
                    sharingIntent.setType(getMimeType(myFile.getPath()));
                    sharingIntent.putExtra("android.intent.extra.STREAM",Uri.fromFile(myFile));
                    startActivity(Intent.createChooser(sharingIntent,"Share using"));
                } catch (Exception e) {
                    Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
             }

public String getMimeType(String filePath) {
        String type = null;
        String extension = getFileExtensionFromUrl(filePath);
        if (extension != null) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            type = mime.getMimeTypeFromExtension(extension);
        }
        return type;
    }

    public String getFileExtensionFromUrl(String url) {
        int dotPos = url.lastIndexOf('.');
        if (0 <= dotPos) {
            return (url.substring(dotPos + 1)).toLowerCase();
        }
        return "";
    }


问:
foreach variable not defined in laravel 5.2
I am new to laravel and want to populate my view using foreach .
This is view:

```<code><thead>
                                <tr>
                                    <th>Sr. No.</th>
                                    <th>Name</th>

                                    <th>Mobile No</th>
                                    <th>Email ID</th>
                                    <th>Address</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php  foreach($result as $res){?>
                                <tr>
                                    <td>1</td>
                                    <td><?php echo $res->vendor_name;?></td>

                                    <td><?php echo $res->mobile;?></td>
                                    <td><?php echo $res->email;?></td>
                                    <td><?php echo $res->city;?></td>
                                    <td>
                                        <a href="#" data-toggle="modal" data-target=".Upcoming" class="btn btn-success btn-sm"><i class="fa fa-edit"></i></a>
                                        <a href="#" class="btn btn-warning btn-sm"><i class="fa fa-trash"></i></a>
                                    </td>
                                </tr>
                               <?php  }?>
</code>```

Controller:

```<code>class VendorController extends Controller
{
  public function getVendorList(){
      $vendors=DB::table('vendor_master')->get();
      $data['result']=$vendors;
       $data['header'] = View::make('header')->render();
        $data['footer'] = View::make('footer')->render();
        return view('vendor_details', $data);
  }
}
</code>```

Route:

```<code>Route::controller('vendor','VendorController');
</code>```

I am trying from quite sometime but not getting through.A liitle help will be appreciated.Thanks in advance

答:
Data should be passed like this using compact() based on version it will little bit change read documentation here laravel documenation

```<code>class VendorController extends Controller
{
  public function getVendorList(){
      $vendors=DB::table('vendor_master')->get();
      $result=$vendors;
       $header = View::make('header')->render();
        $footer = View::make('footer')->render();
        return view('vendor_details',compact( 'result','header','footer'));
  }
}
</code>```

Note : your trying to apply codigniter data send format in laravel

Body:
I am new to laravel and want to populate my view using foreach .
This is view:

                                    Sr. No.
                                    Name

                                    Mobile No
                                    Email ID
                                    Address
                                    Action

                            <?php  foreach($result as $res){?>

                                    1
                                    <?php echo $res->vendor_name;?>

                                    <?php echo $res->mobile;?>
                                    <?php echo $res->email;?>
                                    <?php echo $res->city;?>

                               <?php  }?>

Controller:

class VendorController extends Controller
{
  public function getVendorList(){
      $vendors=DB::table('vendor_master')->get();
      $data['result']=$vendors;
       $data['header'] = View::make('header')->render();
        $data['footer'] = View::make('footer')->render();
        return view('vendor_details', $data);
  }
}

Route:

Route::controller('vendor','VendorController');

I am trying from quite sometime but not getting through.A liitle help will be appreciated.Thanks in advance

Body:
Data should be passed like this using compact() based on version it will little bit change read documentation here laravel documenation

class VendorController extends Controller
{
  public function getVendorList(){
      $vendors=DB::table('vendor_master')->get();
      $result=$vendors;
       $header = View::make('header')->render();
        $footer = View::make('footer')->render();
        return view('vendor_details',compact( 'result','header','footer'));
  }
}

Note : your trying to apply codigniter data send format in laravel


问:
How do I run shell commands from myApp(python) container in myData(mongodb) container?
I have two containers one running python and other one running mongodb. Now I want to run mongoimport command from my application container.

So how do I do it?

答:
docker exec should be reserved for debugging purposes.

Ideally, you would run mongoimport at build time from your Dockerfile, in order to make an image dedicated to seed your mongo database.

For instance, look at "How do I seed a mongo database using docker-compose?"

That way, you avoid any manual runtime operation.

If you must have a regular runtime operation, then you need to add to your image a cron, as I described here.

That way, you can execute that mongoimport on a regular basis, during the time the container is running.


问:
PHP script on mySQL table : FROM_UNIXTIME and INTO OUTFILE issues
This is my first php script for a mysql table.

mySQL table looks as below :

From that table i would like to generate a dynamic HTML table with the following requirements :

HTML table sorted ASC by NEXT_EVENT

HTML table gets a new column showing NEXT_EVENT value as human readable datetime.

Once the table is sorted i need to output ID and NEXT_EVENT values from the very first row to a TXT file, the 2 values will be comma separared.

I tryed to write a PHP script, but it get errors.

Sorting ASC looks working properly, but conversion with FROM UNIXTIME does not and file output won't work either.

mysql table's name is : 'webpilot'

```<code>$result = mysqli_query($conn, "SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

$table = '<table>
            <tr>
                <th>ID</th>
                <th>NAME</th>
                <th>NEXT_EVENT</th>
            </tr>';

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        mysqli_query($conn, "SELECT FROM_UNIXTIME(".$row['NEXT_EVENT'].") as $datetime");

        $table .= '<tr>
                    <td>'.$row['ID'].'</td>
                    <td>'.$row['NAME'].'</td>
                    <td>'.$row['NEXT_EVENT'].'</td>
                    <td>'.$datetime.'</td>
                   </tr>';
    }
} else {
    $table .= '<tr><td colspan="3">No date found</td></tr>';
}
$table .= '</table>';
echo $table;

$fileoutput = mysql_query($conn, "SELECT ID,NAME,NEXT_EVENT FROM webpilot INTO OUTFILE '/next_event.txt' LINES TERMINATED BY '\n'");
</code>```

The live result can be seen here : http://s529471052.onlinehome.fr/bs3/gpio/dyntable.php

but i had to comment out the following line, as it reports an error avoiding the rest of script to be run and php webpage to be displayed.

```<code>mysqli_query($conn,"SELECT FROM_UNIXTIME(.$row['NEXT_EVENT']) as $datetime");
</code>```

Line 203 is related to that line :

```<code>$fileoutput = mysql_query($conn,"SELECT ID,NAME,NEXT_EVENT FROM webpilot INTO OUTFILE '/next_event.txt' LINES TERMINATED BY '\n'");
</code>```

Would you please show me how to get expected result.

答:
can you check mysql function is wrong mysql_query is there u know that
  one you need to change mysqli_query

```<code>$fileoutput = mysqli_query($conn,"SELECT ID,NAME,NEXT_EVENT FROM webpilot INTO `OUTFILE '/next_event.txt' LINES TERMINATED BY '\n'");`
</code>```

and

$datetime you need to assign values. Example like $datetime=date("Y-m-d H:i:s")

Body:
This is my first php script for a mysql table.

mySQL table looks as below :

From that table i would like to generate a dynamic HTML table with the following requirements :

HTML table sorted ASC by NEXT_EVENT

HTML table gets a new column showing NEXT_EVENT value as human readable datetime.

Once the table is sorted i need to output ID and NEXT_EVENT values from the very first row to a TXT file, the 2 values will be comma separared.

I tryed to write a PHP script, but it get errors.

Sorting ASC looks working properly, but conversion with FROM UNIXTIME does not and file output won't work either.

mysql table's name is : 'webpilot'

$result = mysqli_query($conn, "SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

$table = '

                ID
                NAME
                NEXT_EVENT

';

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        mysqli_query($conn, "SELECT FROM_UNIXTIME(".$row['NEXT_EVENT'].") as $datetime");

        $table .= '

                    '.$row['ID'].'
                    '.$row['NAME'].'
                    '.$row['NEXT_EVENT'].'
                    '.$datetime.'

';
    }
} else {
    $table .= '
No date found
';
}
$table .= '
';
echo $table;

$fileoutput = mysql_query($conn, "SELECT ID,NAME,NEXT_EVENT FROM webpilot INTO OUTFILE '/next_event.txt' LINES TERMINATED BY '\n'");

The live result can be seen here : http://s529471052.onlinehome.fr/bs3/gpio/dyntable.php

but i had to comment out the following line, as it reports an error avoiding the rest of script to be run and php webpage to be displayed.

mysqli_query($conn,"SELECT FROM_UNIXTIME(.$row['NEXT_EVENT']) as $datetime");

Line 203 is related to that line :

$fileoutput = mysql_query($conn,"SELECT ID,NAME,NEXT_EVENT FROM webpilot INTO OUTFILE '/next_event.txt' LINES TERMINATED BY '\n'");

Would you please show me how to get expected result.

Body:
can you check mysql function is wrong mysql_query is there u know that
  one you need to change mysqli_query

$fileoutput = mysqli_query($conn,"SELECT ID,NAME,NEXT_EVENT FROM webpilot INTO `OUTFILE '/next_event.txt' LINES TERMINATED BY '\n'");`

and

$datetime you need to assign values. Example like $datetime=date("Y-m-d H:i:s")


问:
How to add the floating numbers in a list in python?
How do I add the sum of the squares in the input file?

Input file is a txt file and is shown below:

```<code>10 9 8 7 1 2 3 4
3 -4 1 -2
0.743 -12.3 5.3333 3
-3.3
</code>```

Hence the output may look like this;

```<code>324.0
30.0
189.28613789000002
10.889999999999999
</code>```

I can't add the floating numbers using sum as it displays an error, so any help would be much appreciated.

Here is my code:

```<code>#Ask the user to input a file name
file_name=input("Enter the Filename: ")

#Opening the desired file to read the content
infile=open(file_name,'r')

#Importing the math library
import math

#Iterating for the number of lines in the file
for line in infile:

    #Converting the file to a list row by row
    line_str=line.split()

    for element in range(len(line_str)):
        line_str[element]=float(line_str[element])
        line_str[element]=math.pow(line_str[element],2)
        total=sum(line_str[0:len(element)])
        print(total)
</code>```

答:
I think you are misunderstanding the split function and what it does.

```<code>$ python
Python 3.5.1 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:49:46) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> line = "10 9 8 7 1 2 3 4"
>>> line_str = line.split()
>>> line_str
['10', '9', '8', '7', '1', '2', '3', '4']
</code>```

split takes the string and at every space splits the string into substrings, each substring is an element in the list

Your loop code is behaving like you need to find the individual numbers in the string.

```<code>>>> for element in range(len(line_str)):
...         line_str[element]=float(line_str[element])
...         line_str[element]=math.pow(line_str[element],2)
...         total=sum(line_str[0:len(element)])
...         print(total)
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
TypeError: object of type 'int' has no len()
</code>```

So now lets loop through the list (using enumerate as suggested above) and convert each element to a float, square it using math.pow and store it back in the same list.  The you can pass the list to sum() to get your total.  The beauty of Python is that you can always drop down into the interpreter and run your commands one by one and investigate the results.

```<code>>>> import math
>>> line = "10 9 8 7 1 2 3 4"
>>> line_str = line.split()
>>> line_str
['10', '9', '8', '7', '1', '2', '3', '4']
>>> for i,value in enumerate(line_str):
...   fvalue = float(value)
...   line_str[i] = math.pow(fvalue,2)
...
>>> line_str
[100.0, 81.0, 64.0, 49.0, 1.0, 4.0, 9.0, 16.0]
>>> sum(line_str)
324.0
>>>
</code>```

Now the question you may one day ask yourself is, why did I want to use math.pow(fvalue,2)  when I could have just done fvalue**2  or even fvalue*fvalue

When you are ready you can read about it here Exponentials in python x.**y vs math.pow(x, y)

Body:
How do I add the sum of the squares in the input file?

Input file is a txt file and is shown below:

10 9 8 7 1 2 3 4
3 -4 1 -2
0.743 -12.3 5.3333 3
-3.3

Hence the output may look like this;

324.0
30.0
189.28613789000002
10.889999999999999

I can't add the floating numbers using sum as it displays an error, so any help would be much appreciated.

Here is my code:

#Ask the user to input a file name
file_name=input("Enter the Filename: ")

#Opening the desired file to read the content
infile=open(file_name,'r')

#Importing the math library
import math

#Iterating for the number of lines in the file
for line in infile:

    #Converting the file to a list row by row
    line_str=line.split()

    for element in range(len(line_str)):
        line_str[element]=float(line_str[element])
        line_str[element]=math.pow(line_str[element],2)
        total=sum(line_str[0:len(element)])
        print(total)

Body:
I think you are misunderstanding the split function and what it does.

$ python
Python 3.5.1 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:49:46) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> line = "10 9 8 7 1 2 3 4"
>>> line_str = line.split()
>>> line_str
['10', '9', '8', '7', '1', '2', '3', '4']

split takes the string and at every space splits the string into substrings, each substring is an element in the list

Your loop code is behaving like you need to find the individual numbers in the string.

>>> for element in range(len(line_str)):
...         line_str[element]=float(line_str[element])
...         line_str[element]=math.pow(line_str[element],2)
...         total=sum(line_str[0:len(element)])
...         print(total)
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
TypeError: object of type 'int' has no len()

So now lets loop through the list (using enumerate as suggested above) and convert each element to a float, square it using math.pow and store it back in the same list.  The you can pass the list to sum() to get your total.  The beauty of Python is that you can always drop down into the interpreter and run your commands one by one and investigate the results.

>>> import math
>>> line = "10 9 8 7 1 2 3 4"
>>> line_str = line.split()
>>> line_str
['10', '9', '8', '7', '1', '2', '3', '4']
>>> for i,value in enumerate(line_str):
...   fvalue = float(value)
...   line_str[i] = math.pow(fvalue,2)
...
>>> line_str
[100.0, 81.0, 64.0, 49.0, 1.0, 4.0, 9.0, 16.0]
>>> sum(line_str)
324.0
>>>

Now the question you may one day ask yourself is, why did I want to use math.pow(fvalue,2)  when I could have just done fvalue**2  or even fvalue*fvalue

When you are ready you can read about it here Exponentials in python x.**y vs math.pow(x, y)


问:
RecyclerView notifyDataSetChanged() freezes UI without ANR
We have a NestedScrollView that contains two different RecyclerView both working with vertical scroll. The scroll layout lays inside SwipeRefreshLayout.

Upd: We know about getItemViewType(pos) method and use it in other places. But here we have complex logic that will be further divided into 2 different screens, therefore we have two separate presenters for each of RecyclerView and combining them into one and separating again in a month is not an option.

From some moment, we noticed that updating the screen using swipe to refresh starts to freeze the UI: skipped frames in logs, impossibility to make any operations with UI, freezing progress bar. It takes up to five seconds, but we don't get ANR. It works well in the beginning and freezes at the end. If we remove notifyDataSetChanged() in adapter, everything looks good.

We tried to remove one of recycler views, to remove all the operations from ViewHolder.onCreate() and onBindViewHolder() but it didn’t help. Also, we cross-checked if the problems come from some data processing (we use RxJava 2 to manipulate threading) and we see that all operations with networking, db and data processing are made in non-UI thread and are already finished to the moment when lag starts.

Here is the layout:

```<code><android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/swipe_refresh"
    android:layout_width="match_parent"
    android:layout_height=«match_parent"
    android:orientation="vertical"
    >
<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content»
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation=«vertical"
        android:paddingBottom="@dimen/spacing_bigger»>
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycle_chats"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white_bg"
            />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycle_friends"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white_bg"
            />

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
</code>```

答:
I was struggling  with this too, finally came to this idea that I can't use RecyclerView inside nestedscrollView WITH notifyData properly so I did it this way:

I put CollapsingToolbarLayout inside AppBarLayout inside CoordinatorLayout .
then I put RecyclerView header inside CollapsingToolbarLayout and the RecyclerView inside CoordinatorLayout below AppBarLayout.

and also I used addOnScrollListener method of RecyclerView TO load new Items for RecyclerView after pagination.

this is my xml file :

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/
 android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/activity_txt_news_detail.app_bar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#00ffffff"
            app:elevation="0dp">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsingToolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:expandedTitleMarginStart="64dp"
                app:layout_scrollFlags="scroll|snap">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    // all other views
                    // as header of
                    // recyclerview comes here
                </LinearLayout>

                <!--todo tgs : here top-->

            </android.support.design.widget.CollapsingToolbarLayout>

        </android.support.design.widget.AppBarLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
             app:layout_behavior="@string/
             appbar_scrolling_view_behavior">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/home_news_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:listitem="@layout/row_news_txt_small" />

        </RelativeLayout>

    </android.support.design.widget.CoordinatorLayout>
</LinearLayout>

</FrameLayout>
</code>```

this line of code app:layout_behavior="@string/appbar_scrolling_view_behavior"
is very important it should be in recyclerview container layout

please inform me if it was useful for you . all the best

Body:
We have a NestedScrollView that contains two different RecyclerView both working with vertical scroll. The scroll layout lays inside SwipeRefreshLayout.

Upd: We know about getItemViewType(pos) method and use it in other places. But here we have complex logic that will be further divided into 2 different screens, therefore we have two separate presenters for each of RecyclerView and combining them into one and separating again in a month is not an option.

From some moment, we noticed that updating the screen using swipe to refresh starts to freeze the UI: skipped frames in logs, impossibility to make any operations with UI, freezing progress bar. It takes up to five seconds, but we don't get ANR. It works well in the beginning and freezes at the end. If we remove notifyDataSetChanged() in adapter, everything looks good.

We tried to remove one of recycler views, to remove all the operations from ViewHolder.onCreate() and onBindViewHolder() but it didn’t help. Also, we cross-checked if the problems come from some data processing (we use RxJava 2 to manipulate threading) and we see that all operations with networking, db and data processing are made in non-UI thread and are already finished to the moment when lag starts.

Here is the layout:

<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/swipe_refresh"
    android:layout_width="match_parent"
    android:layout_height=«match_parent"
    android:orientation="vertical"
    >
<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content»
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation=«vertical"
        android:paddingBottom="@dimen/spacing_bigger»>
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycle_chats"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white_bg"
            />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycle_friends"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white_bg"
            />

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>
</android.support.v4.widget.SwipeRefreshLayout>

Body:
I was struggling  with this too, finally came to this idea that I can't use RecyclerView inside nestedscrollView WITH notifyData properly so I did it this way:

I put CollapsingToolbarLayout inside AppBarLayout inside CoordinatorLayout .
then I put RecyclerView header inside CollapsingToolbarLayout and the RecyclerView inside CoordinatorLayout below AppBarLayout.

and also I used addOnScrollListener method of RecyclerView TO load new Items for RecyclerView after pagination.

this is my xml file :

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/
 android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/activity_txt_news_detail.app_bar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#00ffffff"
            app:elevation="0dp">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsingToolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:expandedTitleMarginStart="64dp"
                app:layout_scrollFlags="scroll|snap">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    // all other views
                    // as header of
                    // recyclerview comes here
                </LinearLayout>

                <!--todo tgs : here top-->

            </android.support.design.widget.CollapsingToolbarLayout>

        </android.support.design.widget.AppBarLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
             app:layout_behavior="@string/
             appbar_scrolling_view_behavior">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/home_news_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:listitem="@layout/row_news_txt_small" />

        </RelativeLayout>

    </android.support.design.widget.CoordinatorLayout>
</LinearLayout>

</FrameLayout>

this line of code app:layout_behavior="@string/appbar_scrolling_view_behavior"
is very important it should be in recyclerview container layout

please inform me if it was useful for you . all the best


答:
U need to call like this : OfType<Button>().ToList();

Below link will help u understand the OfType Method:

https://msdn.microsoft.com/en-us/library/bb360913(v=vs.110).aspx

Better to use this way:

```<code>foreach (var control in this.Controls)
{
   if (control.GetType()== typeof(Button))
   {
       //do stuff with control in form
   }
}
</code>```

Title: How to change property of all buttons in windows from?

Body:
I have some buttons on Form1. I want to set their FlatStyle property to FlatStyle.Popup.
I searched and wrote some code as below:

// List<Control> ButtonsList = new List<Control>();
 List<Button> ButtonsList = new List<Button>();
 public Form1()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.autorun;  //Project->Properties->Resources->
            ButtonsList = GetAccessToAllButtons(this).OfType<Button>.ToList(); //*** hot line ***

            foreach(Button btn in ButtonList)
            {
                btn.FlatStyle = FlatStyle.Popup;
            }

        }

 public IEnumerable<Control> GetAccessToAllButtons(Control thisClass)
        {
            List<Control> ControlsList = new List<Control>();
            foreach (Control child in thisClass.Controls)
            {
                ControlsList.AddRange(GetAccessToAllButtons(child));
            }
            ControlsList.Add(thisClass);
            return ControlsList;
        }

But when I use GetAccessToAllButtons() in hot line of my code, VS generates this error:

'System.Linq.Queryable.OfType(Query.Linq.IQueryable)' is a
  'method', which is not valid in the given context

What is my mistake?

Edit: My reference at here missed the (). It is an accepted answer! Do we have a different situation at my reference? or it is only a typo?

Body:
U need to call like this : OfType<Button>().ToList();

Below link will help u understand the OfType Method:

https://msdn.microsoft.com/en-us/library/bb360913(v=vs.110).aspx

Better to use this way:

foreach (var control in this.Controls)
{
   if (control.GetType()== typeof(Button))
   {
       //do stuff with control in form
   }
}


问:
VBA separate two double digit values by a slash in a single cell
I feel like this should be relatively straight forward, but I cannot seem to find something that works.

I want to be able to separate two values in a VBA macro that are previously defined as values after doing some preliminary calculations. I then want to be able to put both of these values in the same cell, separated by a slash ("/").

Here are two codes I have written by neither seem to get the job done:

```<code>Sub Macro3()

TotalK = 10
BB = 15

ActiveCell.Value = "=TotalK &""/""& BB"

End Sub
</code>```

The other way I have attempted this (which is extremely inefficient):

```<code>If TotalK > 9 Then
     wsNew.Range("E45").NumberFormat = "00""/""0": wsNew.Range("E45").Value = TotalK & BB
ElseIf BB > 9 Then
     wsNew.Range("E45").NumberFormat = "0""/""00": wsNew.Range("E45").Value = TotalK & BB
ElseIf TotalK > 9 And BB > 9 Then
     wsNew.Range("E45").NumberFormat = "00""/""00": wsNew.Range("E45").Value = TotalK & BB
Else
     wsNew.Range("E45").NumberFormat = "0""/""0": wsNew.Range("E45").Value = TotalK & BB
End If
</code>```

The second method words, except for when TotalK and BB both exceed 9. The output is 211/7, for example, when it should be 21/17.

答:
May be you can try this out,</p>

```<code>Sub Macro3()
TotalK = 10
BB = 15
ActiveCell.Value = TotalK & "/" & BB
End Sub
</code>```

Body:
I feel like this should be relatively straight forward, but I cannot seem to find something that works.

I want to be able to separate two values in a VBA macro that are previously defined as values after doing some preliminary calculations. I then want to be able to put both of these values in the same cell, separated by a slash ("/").

Here are two codes I have written by neither seem to get the job done:

Sub Macro3()

TotalK = 10
BB = 15

ActiveCell.Value = "=TotalK &""/""& BB"

End Sub

The other way I have attempted this (which is extremely inefficient):

If TotalK > 9 Then
     wsNew.Range("E45").NumberFormat = "00""/""0": wsNew.Range("E45").Value = TotalK & BB
ElseIf BB > 9 Then
     wsNew.Range("E45").NumberFormat = "0""/""00": wsNew.Range("E45").Value = TotalK & BB
ElseIf TotalK > 9 And BB > 9 Then
     wsNew.Range("E45").NumberFormat = "00""/""00": wsNew.Range("E45").Value = TotalK & BB
Else
     wsNew.Range("E45").NumberFormat = "0""/""0": wsNew.Range("E45").Value = TotalK & BB
End If

The second method words, except for when TotalK and BB both exceed 9. The output is 211/7, for example, when it should be 21/17.

Body:
May be you can try this out,

Sub Macro3()
TotalK = 10
BB = 15
ActiveCell.Value = TotalK & "/" & BB
End Sub


问:
Why Nuget Manager package so slow?
I was trying to update my Nuget Manager.As you can see in picture it is very slow . How to fix this?

答: Are you using a proxy server? That may also be the reason things are slowing down.</p>

Title: Why Nuget Manager package so slow?


问:
adding custom made wheel spinner to layout
In my java application(with Swing) I used a custom made spinner class that extendes JSpinner (which give me the required shape as image attached) ,then used it to  instantiate a spinner object.

Now in my Android version of the application...seems when making the XML layout with Spinner tag and it's attributes, either I couldn’t find a Spinner like that shape or there is none basically.

How to get this Wheel Spinner shape ?

P.S: I’m using Intellij IDEA,  and  Android API 24 .

答:
you can use library for this
there are many number pickers library for android
you may try this https://github.com/ShawnLin013/NumberPicker</p>


问:
Xamarin forms Horizontal listview showing images from ObservableCollection
I want to display Images/Thumbnails of photos that I've been taking in a horizontal view as a part of my content page.
I've stored the images paths as strings in a ObservableCollection. What's the best approach to do this in XAML and PCL.
Would be great if 3 or something images are shown on the screen, and standard image if no images have been added or if string is null, and to have these in a scrollview or listview so that all of the images in the ObservableCollection could be displayed.

maybe something like this

/Oliver

答:
Use Bindable (Horizontal) Scroll View. see this link it's help you.

http://www.fabiocozzolino.eu/a-little-and-simple-bindable-horizontal-scroll-view/


问:
Python Showing:- TypeError: 'int' object is not callable in python While Trying to Run Code
Well, I researched and saw many posts on this but none of them let me fix my code.

I am learning python and is currently learning Object Oriented classes.

This is My Code:-

```<code>class Employee:
    'Common base calss for all employees'
    empCount = 0

    def __init__(self,name,salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1

    def displayCount(self):
        print "Total Employee %d" % Employee.empCount

    def displayEmployee(self):
        print "Name: ", self.name, ",Salary: ", self.salary

"This whould create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This whould create second object of employee class"
emp2 = Employee("Manni", 5000)

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount()
</code>```

And then when I run it:-

```<code>Name:  Zara ,Salary:  2000
Name:  Manni ,Salary:  5000

Traceback (most recent call last):
File "D:/Python Programs/Object Oriented-Classes(Python 2).py", line 46, in
<module>
print "Total Employee %d" % Employee.empCount()
TypeError: 'int' object is not callable
</code>```

答:
change this

```<code>print "Total Employee %d" % Employee.empCount()
</code>```

to this

```<code>print "Total Employee %d" % Employee.empCount
</code>```

Body:
Well, I researched and saw many posts on this but none of them let me fix my code.

I am learning python and is currently learning Object Oriented classes.

This is My Code:-

class Employee:
    'Common base calss for all employees'
    empCount = 0

    def __init__(self,name,salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1

    def displayCount(self):
        print "Total Employee %d" % Employee.empCount

    def displayEmployee(self):
        print "Name: ", self.name, ",Salary: ", self.salary

"This whould create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This whould create second object of employee class"
emp2 = Employee("Manni", 5000)

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount()

And then when I run it:-

Name:  Zara ,Salary:  2000
Name:  Manni ,Salary:  5000

Traceback (most recent call last):
File "D:/Python Programs/Object Oriented-Classes(Python 2).py", line 46, in
<module>
print "Total Employee %d" % Employee.empCount()
TypeError: 'int' object is not callable

Body:
change this

print "Total Employee %d" % Employee.empCount()

to this

print "Total Employee %d" % Employee.empCount


问:
Pandas: How to check if a list-type column is in dataframe
How can I create a new list column from a list column

My dataframe:

```<code>id    x    list_id
1     20   [2, 4]
2     10   [1, 3]
3     10   [1]
4     30   [1, 2]
</code>```

What I want:

```<code>id    x    list_id    list_x
1     20   [2, 4]     [10, 30]
2     10   [1, 3]     [20, 10]
3     10   [1]        [20]
4     30   [1, 2]     [20, 10]
</code>```

My first idea is to iterate on each line then check if the id is in the list

```<code>for index, row in df.iterrows():
  if ( df['id'].isin(row['list_id']) ):
     do_somthing
</code>```

But its not working, any suggestion !!

答:
Creative Solution

Using numpy object arrays with set elements

```<code>i = np.array([set([x]) for x in df.id.values.tolist()])
x = np.empty(i.shape, dtype=object)
x[:] = [[x] for x in df.x.values.tolist()]
y = np.empty_like(x)
y.fill([])
j = np.array([set(x) for x in df.list_id.values.tolist()])

df.assign(list_x=np.where(i <= j[:, None], x, y).sum(1))

   id   x list_id    list_x
0   1  20  [2, 4]  [10, 30]
1   2  10  [1, 3]  [20, 10]
2   3  10     [1]      [20]
3   4  30  [1, 2]  [20, 10]
</code>```

Timing

```<code>%timeit df.assign(list_x=[df.x[df['id'].isin(l)].values for l in df.list_id])

1000 loops, best of 3: 1.21 ms per loop

%%timeit
i = np.array([set([x]) for x in df.id.values.tolist()])
x = np.empty(i.shape, dtype=object)
x[:] = [[x] for x in df.x.values.tolist()]
y = np.empty_like(x)
y.fill([])
j = np.array([set(x) for x in df.list_id.values.tolist()])

df.assign(list_x=np.where(i <= j[:, None], x, y).sum(1))

1000 loops, best of 3: 371 µs per loop
</code>```

Body:
How can I create a new list column from a list column

My dataframe:

id    x    list_id
1     20   [2, 4]
2     10   [1, 3]
3     10   [1]
4     30   [1, 2]

What I want:

id    x    list_id    list_x
1     20   [2, 4]     [10, 30]
2     10   [1, 3]     [20, 10]
3     10   [1]        [20]
4     30   [1, 2]     [20, 10]

My first idea is to iterate on each line then check if the id is in the list

for index, row in df.iterrows():
  if ( df['id'].isin(row['list_id']) ):
     do_somthing

But its not working, any suggestion !!

Body:
Creative Solution

Using numpy object arrays with set elements

i = np.array([set([x]) for x in df.id.values.tolist()])
x = np.empty(i.shape, dtype=object)
x[:] = [[x] for x in df.x.values.tolist()]
y = np.empty_like(x)
y.fill([])
j = np.array([set(x) for x in df.list_id.values.tolist()])

df.assign(list_x=np.where(i <= j[:, None], x, y).sum(1))

   id   x list_id    list_x
0   1  20  [2, 4]  [10, 30]
1   2  10  [1, 3]  [20, 10]
2   3  10     [1]      [20]
3   4  30  [1, 2]  [20, 10]

Timing

%timeit df.assign(list_x=[df.x[df['id'].isin(l)].values for l in df.list_id])

1000 loops, best of 3: 1.21 ms per loop

%%timeit
i = np.array([set([x]) for x in df.id.values.tolist()])
x = np.empty(i.shape, dtype=object)
x[:] = [[x] for x in df.x.values.tolist()]
y = np.empty_like(x)
y.fill([])
j = np.array([set(x) for x in df.list_id.values.tolist()])

df.assign(list_x=np.where(i <= j[:, None], x, y).sum(1))

1000 loops, best of 3: 371 µs per loop


问:
What are the disadvantages of an M:N threading model (e.g. goroutines)?
M:N threading is a model which maps M user threads onto N kernel threads. This enables a large number (M) of user threads to be created, due to their light weight, which still allowing (N-way) parallelism.

This seems like a win-win to me, so why do so few languages/implementations use this threading model? The only examples I am aware of are Go's "goroutines" and Erlang's processes.

What are the disadvantages of M:N threading? Why do other languages not use this threading model that, on the surface, seems so promising?

答:
Partly it's because "it's what everyone else is doing". While M:N threading did exist before Go, all mainstream languages (C, C++, Perl, Java, C#, Python, Ruby, PHP) used threads, and many of them (Python, Ruby) did that poorly. Go is the first popular language that shows M:N threading can work well.

Partly it's because threads are the native primitive of the OS.

Implementing M:N threading makes interop with OS code/C libraries harder and a bit slower. When calling C/OS code, Go has to switch from small goroutine stack to regular OS stack.

Many other popular languages (Python, Ruby) rely more heavily on ability to call C code than Go so it's more important for them to optimize for that.

Good M:N threading interop with OS/C code is not impossible (Go does that decently) but it's easier to do if you do what OS does.


问:
Same partition key's data distribution in DynamoDB
From what I'm understanding, DynamoDB tries to put items with the same partition key into the same partition. My question is how does the hashing work when the partition is full and gets split into 2 different partitions?

For example, a table has a partition key A, and DynamoDB put all items with partition key A into the same partition P, then P is full, dynamo will split P into P1 and P2, now a new item I with a partition key A is inserted by the client, How does dynamo decide which partition (i.e. P1 and P2) to insert I?

答:
Partition Key is used mainly to specify where to store physically the data, this is done using consistent hashing function to distribute your data into different partitions or physical storage. To read the value using partition key, it is going to hash it using the same hashing function to get the correct partition then fetch the data from that partition. While sort key is used to index that data inside each partition.

Partition keys should be designed in away that maintains evenly distribution of your workload instead of having some partitions fully overflown or loaded while having others idle.

You can read more about this here:

http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.Partitions.html

https://cloudacademy.com/blog/dynamodb-replication-and-partitioning-part-4/