Body:
I have a String which is mentioned below i am extracting a 2D array from this string (which i am doing successfully) The problem is that I dont know how to exit the while loop.

00000000,00000000,10100111,10100101,11111101,11111111,00000111,00000000,
00000000,00000000,11100010,00100010,11111111,11111111,00000000,10000000,
00000000,00000000,00001001,00001000,00111111,00111111,00000000,00000000,
00100000,00100000,10101110,10100010,10111110,10111110,00000000,00001000,
00000000,00111000,00100011,01111110,01111111,01000011,01000000,01111000,
00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,
00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,

I tried to put "x" at the end of string  and ran my while loop like this and it works but Its not feasible for me beacuase I have to read this string from like hundreds of files.

while (Data_string[counter] !=  'x' )
{
    while (Data_string[counter] != ',')
    {
        if (Data_string[counter] != '\n')
            SubString += Data_string[counter];

        counter++;
    }
    // here I use Substring to covert to int and then set Substring to empty string
}

So I am looking for an efficient solution so i dont have to alter the string,

Thanks..

Body:
If you just want iterate over each binary record, then no need to convert your string into 2D array and adding X at the end of string.

You can easily split array by , and iterate over each element of array, something like

string input ="00000000,00000000,10100111,10100101,11111101,11111111,00000111,00000000, 00000000,00000000,11100010,00100010,11111111,11111111,00000000,10000000, 00000000,00000000,00001001,00001000,00111111,00111111,00000000,00000000, 00100000,00100000,10101110,10100010,10111110,10111110,00000000,00001000, 00000000,00111000,00100011,01111110,01111111,01000011,01000000,01111000, 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000, 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000";

string inputArr = input.TrimEnd(',').split(',');
foreach(string item in inputArr)
{
    Console.WriteLine(item);
}

From your updated code, it seems like you want to remove all , and join all array elements to single string i.e. SubString. If you are trying to do this, then you can achieve it in single line

string SubString = String.Join("",input.Split(','));

No need to use while/for loop and/or if loop, this is clear and more readable approach.

POC: .net fiddle


来源: stackexchange

问:
looping a training model over model classes and changing dataframe name by model class
I am trying to automate a training pipeline and having some troubles to rename the input dataframes over changing model classes.

```<code>sample_train = [9]
sample_test = [18]
model_class = [0]

for i in sample_train:
    for j in model_class:
        # Define the training datasets -Filter the datasets with model selections
        trainX_M[j] = mldata_pd[(mldata_pd.sample_id == i) & (mldata_pd.training_set_band == j)].drop(
            ['conv_gv_band', 'sample_id', 'training_set_band'], axis=1)
        trainy_M[j] = mldata_pd[(mldata_pd.sample_id == i) & (
            mldata_pd.training_set_band == j)].iloc[:, mldata_pd.columns == 'conv_gv_band']

    trainX_M0, testX, trainy_M0, testy = train_test_split(trainX_M0, trainy_M0,
                                                          test_size=0.2,
                                                          random_state=42)
</code>```

I expect to have trainX_M0 when model_class=0 but receive the error:

NameError: name 'trainX_M' is not defined

答:
your variable is trainX_M and not trainX_M0 , cahgne to

```<code>trainX_M0[j] = mldata_pd[(mldata_pd.sample_id == i) & (mldata_pd.training_set_band == j)].drop(['conv_gv_band','sample_id','training_set_band'], axis=1)
</code>```

or crete a list trainX_M and df append to it all of the matrixes per class

ContentLicense: CC BY-SA 4.0

Body:
I am trying to automate a training pipeline and having some troubles to rename the input dataframes over changing model classes.

sample_train = [9]
sample_test = [18]
model_class = [0]

for i in sample_train:
    for j in model_class:
        # Define the training datasets -Filter the datasets with model selections
        trainX_M[j] = mldata_pd[(mldata_pd.sample_id == i) & (mldata_pd.training_set_band == j)].drop(
            ['conv_gv_band', 'sample_id', 'training_set_band'], axis=1)
        trainy_M[j] = mldata_pd[(mldata_pd.sample_id == i) & (
            mldata_pd.training_set_band == j)].iloc[:, mldata_pd.columns == 'conv_gv_band']

    trainX_M0, testX, trainy_M0, testy = train_test_split(trainX_M0, trainy_M0,
                                                          test_size=0.2,
                                                          random_state=42)

I expect to have trainX_M0 when model_class=0 but receive the error:

NameError: name 'trainX_M' is not defined

Body:
your variable is trainX_M and not trainX_M0 , cahgne to

trainX_M0[j] = mldata_pd[(mldata_pd.sample_id == i) & (mldata_pd.training_set_band == j)].drop(['conv_gv_band','sample_id','training_set_band'], axis=1)

or crete a list trainX_M and df append to it all of the matrixes per class


问:
Is there an alternative to turnScreenOn() that acutally wakes the screen?
The following tag, to turn the screen on, is currently deprecated:

```<code>tizen.power.turnScreenOn();
</code>```

However, with this function, I was able to wake the screen after it has been turned off by, for example, a palm gesture. As there is no way to disable the palm gesture temporarily, I added this line in a screen off listener, which works perfectly, but I'm getting deprecation warnings. The following alternative:

```<code>tizen.power.request("SCREEN", "SCREEN_NORMAL");
</code>```

does, in fact, keep the screen from turning off automatically, but doesn't actually wake it if it does turn off.

Is there a function which isn't deprecated, but does, in fact, wake the screen again?

答:
There is no way to disable the palm-cover event of the device. This is the system capability to allow user to disable a screen. I think that holding the screen on even though user's explicit order to turn it off (with the palm gesture) is not very good idea. Battery drain could be high with the screen constantly enabled.

turnScreenOn/Off methods were used in older Tizen API versions because of lack of background support, to ensure the application execution. Currently apps could work also in background, maybe this would be enough for your scenario (refer to background-support property).

Body:
The following tag, to turn the screen on, is currently deprecated:

tizen.power.turnScreenOn();

However, with this function, I was able to wake the screen after it has been turned off by, for example, a palm gesture. As there is no way to disable the palm gesture temporarily, I added this line in a screen off listener, which works perfectly, but I'm getting deprecation warnings. The following alternative:

tizen.power.request("SCREEN", "SCREEN_NORMAL");

does, in fact, keep the screen from turning off automatically, but doesn't actually wake it if it does turn off.

Is there a function which isn't deprecated, but does, in fact, wake the screen again?


问:
OpenCart 3 common/header variable in extension
I would like to add a variable/display in common/header twig file, which can be managed from an new extension. The new extension is created. starter_module

I added in:
admin/view/template/extension/module/starter_module.twig

```<code><div class="form-group">
        <label class="col-sm-2 control-label" for="input-new">New</label>
        <div class="col-sm-10">
        <select name="new" id="input-new" class="form-control">
            {% if new %}
            <option value="1" selected="selected">Enabled</option>
            <option value="0">Disabled</option>
            {% else %}
            <option value="1">Enabled</option>
            <option value="0" selected="selected">Disabled</option>
            {% endif %}
        </select>
        </div>
</div>
</code>```

in admin/controller/extension/module/starter_module.php

```<code>if (isset($this->request->post['new'])) {
  $data['new'] = $this->request->post['new'];
} elseif (!empty($module_info)) {
  $data['new'] = $module_info['new'];
} else {
  $data['new'] = '';
}
</code>```

in catalog/controller/extension/module/starter_module.php

```<code>            $data['new'] = $this->config->get('new');

            $data['new'] = (int) $setting['new'];
</code>```

in catalog/view/theme/default/template/common/header.twig

```<code>{% if new %}Enabled {% else %} disabled{% endif %}
</code>```

But always I got the result only disabled, what is missing? cannot be sent variable from extension to common header?

Please, help me if you know the issue, the non working files are here https://github.com/bblori/Opencart3

You can see here one of my working variable which was set in setting/setting files and is working.

https://github.com/bblori/Enable-Style-OC3

XML code

```<code><modification>
<name>Starter Module</name>
<code>starter-module</code>
<version>1.0.0</version>
<author>Author</author>
<link>http://domain/</link>
    <file path="catalog/controller/common/header.php">
        <operation>
            <search><![CDATA[return $this->load->view('common/header', $data);]]></search>
            <add position="before"><![CDATA[
                    $data['config_new'] = $this->config->get('config_new');
           ]]></add>
        </operation>
    </file>
</code>```

Many thanks

答:
move your code from your starter module to header.php</p>

```<code>$data['new'] = $this->config->get('new');
$data['new'] = (int) $setting['new'];
</code>```

Body:
I would like to add a variable/display in common/header twig file, which can be managed from an new extension. The new extension is created. starter_module

I added in:
admin/view/template/extension/module/starter_module.twig

        New

        <select name="new" id="input-new" class="form-control">
            {% if new %}
            <option value="1" selected="selected">Enabled</option>
            <option value="0">Disabled</option>
            {% else %}
            <option value="1">Enabled</option>
            <option value="0" selected="selected">Disabled</option>
            {% endif %}
        </select>

in admin/controller/extension/module/starter_module.php

if (isset($this->request->post['new'])) {
  $data['new'] = $this->request->post['new'];
} elseif (!empty($module_info)) {
  $data['new'] = $module_info['new'];
} else {
  $data['new'] = '';
}

in catalog/controller/extension/module/starter_module.php

            $data['new'] = $this->config->get('new');

            $data['new'] = (int) $setting['new'];

in catalog/view/theme/default/template/common/header.twig

{% if new %}Enabled {% else %} disabled{% endif %}

But always I got the result only disabled, what is missing? cannot be sent variable from extension to common header?

Please, help me if you know the issue, the non working files are here https://github.com/bblori/Opencart3

You can see here one of my working variable which was set in setting/setting files and is working.

https://github.com/bblori/Enable-Style-OC3

XML code

<modification>
<name>Starter Module</name>
starter-module
<version>1.0.0</version>
<author>Author</author>
<link>http://domain/</link>
    <file path="catalog/controller/common/header.php">
        <operation>
            <search><![CDATA[return $this->load->view('common/header', $data);]]></search>
            <add position="before"><![CDATA[
                    $data['config_new'] = $this->config->get('config_new');
           ]]></add>
        </operation>
    </file>

Many thanks

Body:
move your code from your starter module to header.php

$data['new'] = $this->config->get('new');
$data['new'] = (int) $setting['new'];


问:
Binding redux form input.value to a datetimepicker
I have a react native/redux/redux form setup which is (mostly) working, so everything is hooked up and running.

When I set up a form with an asynchronous update, I get a date field, for which I defined a custom component to be used as <Field> in redux-form.

Here's my component:

import React, { Component } from "react";
import { TouchableOpacity, StyleSheet } from "react-native";
import { Text, theme, Button, Block, Input } from "galio-framework";
import DateTimePicker from "react-native-modal-datetime-picker";

export class DateInputField extends Component {
  constructor(props) {
    super(props);
    this.state = { isDateTimePickerVisible: false };
    this.handleChange = this.handleChange.bind(this);
  }
  showDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: true });
  };
  hideDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: false });
  };
  handleChange = date => {
    console.log("date->" + date);
    this.setState({ isDateTimePickerVisible: false, date: date });
    this.props.input.onChange(date);
  };
  render() {
    const { input, meta, ...inputProps } = this.props;
    return (
      <Block style={styles.container}>
        <TouchableOpacity onPress={this.showDateTimePicker}>
          <DateTimePicker
            date={new Date(input.value)}
            cancelTextIOS="Annulla"
            confirmTextIOS="Conferma"
            isVisible={this.state.isDateTimePickerVisible}
            onConfirm={this.handleChange}
            onCancel={() => this.setState({ isDateTimePickerVisible: false })}
          />

          <Input
            color={"black"}
            editable={false}
            // onTouch={this.showDateTimePicker}
            // onFocus={this.showDateTimePicker}
            label={this.props.label}
            style={styles.input}
            placeholder={this.props.placeholder}
            value={
              this.state.date != undefined
                ? this.state.date.getDate() +
                  "/" +
                  (this.state.date.getMonth() + 1) +
                  "/" +
                  this.state.date.getFullYear()
                : "gg/mm/aaaa"
            }
          />
        </TouchableOpacity>
      </Block>
    );
  }
}
export const styles = StyleSheet.create({
  container: {},
  label: {},
  input: { flex: 1, color: "red", padding: 0, height: 50 }
});
```

<p>and my field:</p>

<pre class="lang-javascript prettyprint-override"><code><Field name={"consignment_date"} label="Fine" component={DateInputField} />
</code>```

This component works, when I press the field the datepicker shows up with the correct date coming from the connected "model" field connected to it.

Now my problem is I can't figure way an elegant way to update the field value when the field is not updated by a human "onChange" event but the component's state is updated (and subsequently the component is rendered). I tried many combinations of setting the state date field, but I always ended in infinite loops because updating the state would cause a render, and so on.

I tried many Component lifecycle events to put my reading of the input.value and setting it on a state.displayedDate property, but I guess I am missing a very obvious way to do this because of my scarce knowledge of React's dynamics.

Any help is really appreciated.

答:
Posting the solution that works:

import React, { Component } from "react";
import { TouchableOpacity, StyleSheet } from "react-native";
import { Text, theme, Button, Block, Input } from "galio-framework";
import DateTimePicker from "react-native-modal-datetime-picker";

export class DateInputField extends Component {
  constructor(props) {
    super(props);
    this.state = { isDateTimePickerVisible: false }; //no more date in state
    this.handleChange = this.handleChange.bind(this);
  }
  showDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: true });
  };
  hideDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: false });
  };
  handleChange = date => {
    this.setState({ isDateTimePickerVisible: false });
    this.props.input.onChange(date);
  };
  render() {
    const { input, meta, ...inputProps } = this.props;
    return (
      <Block style={styles.container}>
        <TouchableOpacity onPress={this.showDateTimePicker}>
<DateTimePicker
            style={styles.label}
            date={new Date(input.value)}//date is transformed from input
            onDateChange={this.handleChange}
            cancelTextIOS="Annulla"
            confirmTextIOS="Conferma"
            isVisible={this.state.isDateTimePickerVisible}
            onConfirm={this.handleChange}
            onCancel={() => this.setState({ isDateTimePickerVisible: false })}
          />
          <Input
            color={"gray"}
            editable={false}
            enabled={false}
            label={this.props.label}
            style={styles.input}
            placeholder={this.props.placeholder}
            value={ //value is transformed to a date, then to the local string representation
              input.value !== ""
                ? new Date(input.value).toLocaleDateString()
                : new Date().toLocaleDateString()
            }
          />

        </TouchableOpacity>
      </Block>
    );
  }
}
export const styles = StyleSheet.create({
  container: {},

  input: {
    flex: 1,
    color: "red",
    height: 50,
    borderWidth: 0,
    borderBottomWidth: 1
  }
});
```

Body:
I have a react native/redux/redux form setup which is (mostly) working, so everything is hooked up and running.

When I set up a form with an asynchronous update, I get a date field, for which I defined a custom component to be used as <Field> in redux-form.

Here's my component:

import React, { Component } from "react";
import { TouchableOpacity, StyleSheet } from "react-native";
import { Text, theme, Button, Block, Input } from "galio-framework";
import DateTimePicker from "react-native-modal-datetime-picker";

export class DateInputField extends Component {
  constructor(props) {
    super(props);
    this.state = { isDateTimePickerVisible: false };
    this.handleChange = this.handleChange.bind(this);
  }
  showDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: true });
  };
  hideDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: false });
  };
  handleChange = date => {
    console.log("date->" + date);
    this.setState({ isDateTimePickerVisible: false, date: date });
    this.props.input.onChange(date);
  };
  render() {
    const { input, meta, ...inputProps } = this.props;
    return (
      <Block style={styles.container}>
        <TouchableOpacity onPress={this.showDateTimePicker}>
          <DateTimePicker
            date={new Date(input.value)}
            cancelTextIOS="Annulla"
            confirmTextIOS="Conferma"
            isVisible={this.state.isDateTimePickerVisible}
            onConfirm={this.handleChange}
            onCancel={() => this.setState({ isDateTimePickerVisible: false })}
          />

          <Input
            color={"black"}
            editable={false}
            // onTouch={this.showDateTimePicker}
            // onFocus={this.showDateTimePicker}
            label={this.props.label}
            style={styles.input}
            placeholder={this.props.placeholder}
            value={
              this.state.date != undefined
                ? this.state.date.getDate() +
                  "/" +
                  (this.state.date.getMonth() + 1) +
                  "/" +
                  this.state.date.getFullYear()
                : "gg/mm/aaaa"
            }
          />
        </TouchableOpacity>
      </Block>
    );
  }
}
export const styles = StyleSheet.create({
  container: {},
  label: {},
  input: { flex: 1, color: "red", padding: 0, height: 50 }
});

and my field:

<Field name={"consignment_date"} label="Fine" component={DateInputField} />

This component works, when I press the field the datepicker shows up with the correct date coming from the connected "model" field connected to it.

Now my problem is I can't figure way an elegant way to update the field value when the field is not updated by a human "onChange" event but the component's state is updated (and subsequently the component is rendered). I tried many combinations of setting the state date field, but I always ended in infinite loops because updating the state would cause a render, and so on.

I tried many Component lifecycle events to put my reading of the input.value and setting it on a state.displayedDate property, but I guess I am missing a very obvious way to do this because of my scarce knowledge of React's dynamics.

Any help is really appreciated.


问:
How to get data from properties file inside JavaScript in a maven dynamic web project
My project is a maven dynamic web project. I have a drop-down for usernames and a text box for password in JSP file. Based on the selection of the user name in the drop-down, I need to auto-fill corresponding password in the text box. The mapping of username and password is from properties file.

```<code>login.properties
username1=password1
username2=password2
username3=password3
</code>```

The properties file is directly in src/main/resources folder.
The jsp file is directly in WebContent folder.

Attached image contains a snippet of form elements in JSP file and the JavaScript. The username drop down options are dynamically populated using another JavaScript which works fine.

Code snippet

Also, I tried using below code but unable to provide right path.

```<code>var props = new java.util.Properties();
props.load(new java.io.FileInputStream("login.properties"));
var password = props.getProperty(account);
</code>```

Is it possible to access properties file inside this JavaScript code? Any help is appreciated.

答:
I found a workaround. Since I am unable to format the code even after using {} button, I have provided the code as an image.

Code snippet

Body:
My project is a maven dynamic web project. I have a drop-down for usernames and a text box for password in JSP file. Based on the selection of the user name in the drop-down, I need to auto-fill corresponding password in the text box. The mapping of username and password is from properties file.

login.properties
username1=password1
username2=password2
username3=password3

The properties file is directly in src/main/resources folder.
The jsp file is directly in WebContent folder.

Attached image contains a snippet of form elements in JSP file and the JavaScript. The username drop down options are dynamically populated using another JavaScript which works fine.

Code snippet

Also, I tried using below code but unable to provide right path.

var props = new java.util.Properties();
props.load(new java.io.FileInputStream("login.properties"));
var password = props.getProperty(account);

Is it possible to access properties file inside this JavaScript code? Any help is appreciated.


问:
for and foreach statements in D
Besides the syntactic differences, are the two inherently the same?  Are both of them implemented in the core language? or is foreach part of the standard library?  And as far as performance, does it make a difference if I choose one over the other?

答:
You should always use foreach if possible.

foreach iterate over practically anything (even metadata, like compile-time data types); for can't.

```<code>foreach (Type; TypeTuple!(int, long, short)) { pragma(msg, Type); }
</code>```

but you can't do that with a for loop.

foreach can be used to perform actions at compile-time (extension of above); for example, if you have a piece of code that repeats 10 times, you can say:

```<code>template Iota(size_t a, size_t b) //All integers in the range [a, b)
{
    static if (a < b) { alias TypeTuple!(a, Iota!(a + 1, b)) Iota; }
    else { alias TypeTuple!() Iota; }
}

foreach (i; Iota!(0, 10)) { int[i] arr; } //Not possible with 'for'
</code>```

and this will occur at compile-time, with i treated as a constant. (This doesn't normally work with for.)

foreach can be overloaded with opApply and also with range constructs, but for can't. This is very handy when iterating a tree structure (like all the folders in a file system), because it actually allows you to use entirely stack-based memory rather than allocating on the heap (because you can use recursion).

foreach is preferred in most situations because it prevents the need for you to type your data explicitly, which is useful in preventing some bugs. For example,

```<code>for (int i = 0; i < n; i++) { arr[i]++; }
</code>```

is dangerous if n is greater than 2^32 - 1, but

```<code>foreach (i; 0 .. n) { arr[i]++; }
</code>```

is not, because the compiler automatically chooses the correct type for iteration. This also improves readability.

ContentLicense: CC BY-SA 3.0

Title: for and foreach statements in D

Body:
You should always use foreach if possible.

foreach iterate over practically anything (even metadata, like compile-time data types); for can't.

foreach (Type; TypeTuple!(int, long, short)) { pragma(msg, Type); }

but you can't do that with a for loop.

foreach can be used to perform actions at compile-time (extension of above); for example, if you have a piece of code that repeats 10 times, you can say:

template Iota(size_t a, size_t b) //All integers in the range [a, b)
{
    static if (a < b) { alias TypeTuple!(a, Iota!(a + 1, b)) Iota; }
    else { alias TypeTuple!() Iota; }
}

foreach (i; Iota!(0, 10)) { int[i] arr; } //Not possible with 'for'

and this will occur at compile-time, with i treated as a constant. (This doesn't normally work with for.)

foreach can be overloaded with opApply and also with range constructs, but for can't. This is very handy when iterating a tree structure (like all the folders in a file system), because it actually allows you to use entirely stack-based memory rather than allocating on the heap (because you can use recursion).

foreach is preferred in most situations because it prevents the need for you to type your data explicitly, which is useful in preventing some bugs. For example,

for (int i = 0; i < n; i++) { arr[i]++; }

is dangerous if n is greater than 2^32 - 1, but

foreach (i; 0 .. n) { arr[i]++; }

is not, because the compiler automatically chooses the correct type for iteration. This also improves readability.


问:
Radio buttons are not switching
I have radio buttons and one of them :checked and they have the same name. When I click another radio button they are both selected.

My code is:

```<code><input name="a" type="radio">
<input name="a "type="radio" checked>
</code>```

JS

```<code>$("input[type='radio']").each(function () {
    if ($(this).is(":checked")) {
    $(this).addClass("some");
   }
 });
</code>```

CSS

```<code>  .some {
      background-color:#06c!important;
  }
</code>```

My approach is to first check if my inputs are :checked and if they are, put some css class with background color.  I achieve that, the next thing I want to is remove that :checked when users click on radio button or any other (better) idea. Right now both radio buttons are selected. Can anybody help me with this?

Fiddle:

```<code>https://jsfiddle.net/0ns58xcq/
</code>```

答:
Look at your markup:

```<code><input name="a" type="radio">
<input name="a "type="radio" checked>
              ^
              ----- There is a space
</code>```

Remove the space and it should work.

<input name="a" type="radio">
<input name="a" type="radio" checked>```

Title: Radio buttons are not switching

Body:
I have radio buttons and one of them :checked and they have the same name. When I click another radio button they are both selected.

My code is:

<input name="a" type="radio">
<input name="a "type="radio" checked>

JS

$("input[type='radio']").each(function () {
    if ($(this).is(":checked")) {
    $(this).addClass("some");
   }
 });

CSS

  .some {
      background-color:#06c!important;
  }

My approach is to first check if my inputs are :checked and if they are, put some css class with background color.  I achieve that, the next thing I want to is remove that :checked when users click on radio button or any other (better) idea. Right now both radio buttons are selected. Can anybody help me with this?

Fiddle:

https://jsfiddle.net/0ns58xcq/

Body:
Look at your markup:

<input name="a" type="radio">
<input name="a "type="radio" checked>
              ^
              ----- There is a space

Remove the space and it should work.

<input name="a" type="radio">
<input name="a" type="radio" checked>


问:
How to get city and state name in Autocomplete Places _ Places API
Iam using Places Autocomplete for selecting city from user, its working fine,
But now i want both city and state name..
my code..

Initialising

```<code>  List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
            Intent intent = new Autocomplete.IntentBuilder(
                    AutocompleteActivityMode.OVERLAY, fields)
                    .setTypeFilter(TypeFilter.CITIES)
                    .setCountry("IN")
                    .build(this);
            startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
</code>```

onActivity Result

```<code>if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                //Place place = Autocomplete.getPlaceFromIntent(data);
                Place place = Autocomplete.getPlaceFromIntent(data);

                edit_profile_city_editText.setText(place.getName());

            } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
                Status status = Autocomplete.getStatusFromIntent(data);
                Log.i("Autocomplete error", status.getStatusMessage());
            } else if (resultCode == RESULT_CANCELED) {
            }
        }
</code>```

While selecting city from search bar its showing both city and state..
eg:Chennai
TamilNadu, India
Kindly help how to get state name also...

答:
Use like this:-

and onActivityResult

```<code> if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Place place = Autocomplete.getPlaceFromIntent(data);
            LatLng latLng = place.getLatLng();
            double MyLat = latLng.latitude;
            double MyLong = latLng.longitude;
            Geocoder geocoder = new Geocoder(EditProfileActivity.this, Locale.getDefault());
            try {
                List<Address> addresses = geocoder.getFromLocation(MyLat, MyLong, 1);
                String stateName = addresses.get(0).getAdminArea();
                String cityName = addresses.get(0).getLocality();
                edit_profile_city_editText.setText(place.getName() + "," + stateName);
            } catch (IOException e) {
                e.printStackTrace();

            }
</code>```

Hope this will help you.Thanks..

Body:
Iam using Places Autocomplete for selecting city from user, its working fine,
But now i want both city and state name..
my code..

Initialising

  List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
            Intent intent = new Autocomplete.IntentBuilder(
                    AutocompleteActivityMode.OVERLAY, fields)
                    .setTypeFilter(TypeFilter.CITIES)
                    .setCountry("IN")
                    .build(this);
            startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);

onActivity Result

if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                //Place place = Autocomplete.getPlaceFromIntent(data);
                Place place = Autocomplete.getPlaceFromIntent(data);

                edit_profile_city_editText.setText(place.getName());

            } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
                Status status = Autocomplete.getStatusFromIntent(data);
                Log.i("Autocomplete error", status.getStatusMessage());
            } else if (resultCode == RESULT_CANCELED) {
            }
        }

While selecting city from search bar its showing both city and state..
eg:Chennai
TamilNadu, India
Kindly help how to get state name also...

Body:
Use like this:-

and onActivityResult

 if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Place place = Autocomplete.getPlaceFromIntent(data);
            LatLng latLng = place.getLatLng();
            double MyLat = latLng.latitude;
            double MyLong = latLng.longitude;
            Geocoder geocoder = new Geocoder(EditProfileActivity.this, Locale.getDefault());
            try {
                List<Address> addresses = geocoder.getFromLocation(MyLat, MyLong, 1);
                String stateName = addresses.get(0).getAdminArea();
                String cityName = addresses.get(0).getLocality();
                edit_profile_city_editText.setText(place.getName() + "," + stateName);
            } catch (IOException e) {
                e.printStackTrace();

            }

Hope this will help you.Thanks..


问:
Load data from odoo in html with ajax
I'm in odoo create eg.

```<code>import xmlrpclib

username = 'admin'
pwd = 'admin'
dbname = 'odoo9'

sock_common = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/common')
uid = sock_common.login(dbname, username, pwd)

sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/object')

contact_ids = sock.execute(dbname, uid, pwd, 'res.partner', 'search', [])
for contact_id in contact_ids:
    contact = sock.execute(dbname, uid, pwd, 'res.partner', 'read', contact_id, [])
    print('Name is: ' + contact['name'])
</code>```

after call xml_rpc.py file in terminal get:

Name is: Admin

Name is: Marc

Name is: Ronald

Now I want all names (Admin, Marc, Ronald) load in my html div with ajax.

```<code>$.ajax({
      ???
      ???
    });
</code>```

How with ajax load data?

答:
```<code>$.ajax({
url:"http://localhost:8069/connect_with_odoo",
        type:"POST",
        data:{},
})
</code>```

put your data into the data:{<here>}

Title: Load data from odoo in html with ajax

Body:
I'm in odoo create eg.

import xmlrpclib

username = 'admin'
pwd = 'admin'
dbname = 'odoo9'

sock_common = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/common')
uid = sock_common.login(dbname, username, pwd)

sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/object')

contact_ids = sock.execute(dbname, uid, pwd, 'res.partner', 'search', [])
for contact_id in contact_ids:
    contact = sock.execute(dbname, uid, pwd, 'res.partner', 'read', contact_id, [])
    print('Name is: ' + contact['name'])

after call xml_rpc.py file in terminal get:

Name is: Admin

Name is: Marc

Name is: Ronald

Now I want all names (Admin, Marc, Ronald) load in my html div with ajax.

$.ajax({
      ???
      ???
    });

How with ajax load data?

Body:
$.ajax({
url:"http://localhost:8069/connect_with_odoo",
        type:"POST",
        data:{},
})

put your data into the data:{<here>}


问:
bootstrap 4 pull-right is not working on navbar

I am working with bootstrap 4.

I didn't get navbar right to the page I don't know what the problem is going on.

Is Somebody else can help to fix this issue.

I have tried to add class pull-right to navbar-collapse div but its don't work. So I have also tried to add float right property and set to !important but its also not get helpful.

```<code><div class="collapse navbar-collapse pull-right" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
            <a class="nav-link" href="#">HOME</a>
        </li>

        <li class="nav-item">
            <a class="nav-link" href="#">FAQS & HELPS</a>
        </li>

        <li class="nav-item">
            <a class="nav-link" href="#">CONTACT</a>
        </li>

        <li class="nav-item">
            <a class="nav-link" href="#">LOGIN</a>
        </li>
    </ul>
</div>
</code>```

I want div content(nav links) to the right of the page.

答:
Please check the following Stack Overflow post

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

Hope this helps you out.

Body:
I am working with bootstrap 4.

I didn't get navbar right to the page I don't know what the problem is going on.

Is Somebody else can help to fix this issue.

I have tried to add class pull-right to navbar-collapse div but its don't work. So I have also tried to add float right property and set to !important but its also not get helpful.

            HOME

            FAQS & HELPS

            CONTACT

            LOGIN

I want div content(nav links) to the right of the page.


问:
Is there an implicit default constructor in C++?
In the book I'm reading at the moment (C++ Without Fear) it says that if you don't declare a default constructor for a class, the compiler supplies one for you, which "zeroes out each data member". I've experimented with this, and I'm not seeing any zeroing -out behaviour. I also can't find anything that mentions this on Google. Is this just an error or a quirk of a specific compiler?</p>

答: C++ generates a default constructor.  If needed (determined at compile time I believe), it will also generate a default copy constructor and a default assignment constructor.  I haven't heard anything about guarantees for zeroing memory though.</p>

OwnerDisplayName: Skilldrick

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: JPunyon


问:
Customizing the Login Control in ASP.NET
I'm making a Library Management System using ASP.NET using C#. I have a problem creating a custom login page in my website. I've tried using the ASP.NET Web Configuration but my boss doesnt allow me to install the Aspnet_regsql.exe in the main database. </p>

<p>I have two tables, one table for the username and password and the other one is for the username status (in case the username is deleted or not used anymore). So is there any alternatives or workaround? </p>

答: I think its good idea to implement your own role and membership provider. Its easy, you have to overide just a few methots and create your own view. Try this tutorial for start.</p>

Body:
I'm making a Library Management System using ASP.NET using C#. I have a problem creating a custom login page in my website. I've tried using the ASP.NET Web Configuration but my boss doesnt allow me to install the Aspnet_regsql.exe in the main database.

I have two tables, one table for the username and password and the other one is for the username status (in case the username is deleted or not used anymore). So is there any alternatives or workaround?


问:
YII2: I am getting 500 error while i logged out from backend
```mydomain.com is currently unable to handle this request HTTP ERROR 500```

<p>This error i am getting after i logged out from backend.
It is working fine on my localhost but problem is coming when site is live.
What are the reasons of this kind of error.And there are no entries in my server error logs. I don't know what is wrong.
Please help thank you in advance. </p>

答: In Yii2, logout must be POST, your link to logout can't be GET.

Body:
mydomain.com is currently unable to handle this request HTTP ERROR 500

This error i am getting after i logged out from backend.
It is working fine on my localhost but problem is coming when site is live.
What are the reasons of this kind of error.And there are no entries in my server error logs. I don't know what is wrong.
Please help thank you in advance.


问:
Is there an array function which produces more elements than it receives?
If we use map on array - we will get the same number of elements.

If we want less elements - we can use filter, find or reduce, depending on situation.

Is there a build in function which would work the other way?

For example, let's say I have an array like this:

```<code>myArray = [
  {nodes: Array(5)}, // some array with 5 elements
  {nodes: Array(3)},
  {nodes: Array(3)}
]
</code>```

I want to split every array with more than 3 elements into array which maximum 3 elements. So in the end I want to get:

```<code>splittedArray = [
  {nodes: Array(3)},
  {nodes: Array(2)},
  {nodes: Array(3)},
  {nodes: Array(3)}
]
</code>```

I know how to achive this with looping over myArray with forEach and pushing items to some new array, but is there some ready-to-go function for it?

答:
map, filter and find callbacks only return a boolean, and the method itself decides what to return in the end. With reduce, your callback can return anything, and exactly that will be the return value of reduce. So:

console.log(['foo', 'bar', 'baz'].reduce((a, i) => [...a, ...a, i], []))```

An example of a reduce which produces more elements than its input has.

Body:
If we use map on array - we will get the same number of elements.

If we want less elements - we can use filter, find or reduce, depending on situation.

Is there a build in function which would work the other way?

For example, let's say I have an array like this:

myArray = [
  {nodes: Array(5)}, // some array with 5 elements
  {nodes: Array(3)},
  {nodes: Array(3)}
]

I want to split every array with more than 3 elements into array which maximum 3 elements. So in the end I want to get:

splittedArray = [
  {nodes: Array(3)},
  {nodes: Array(2)},
  {nodes: Array(3)},
  {nodes: Array(3)}
]

I know how to achive this with looping over myArray with forEach and pushing items to some new array, but is there some ready-to-go function for it?

Body:
map, filter and find callbacks only return a boolean, and the method itself decides what to return in the end. With reduce, your callback can return anything, and exactly that will be the return value of reduce. So:

console.log(['foo', 'bar', 'baz'].reduce((a, i) => [...a, ...a, i], []))

An example of a reduce which produces more elements than its input has.


问:
Removing last 9 characters from a string and then reformatting the remaining date characters
My question has 2 parts. First I would like to remove the last 9 characters from a generated string using jQuery eg

2011-04-04T15:05:54

which would then leave the date remaining. I know to use the .substring function.
After the time is removed I need to reformat the date into this format

08.04.11 (for eg)

I am learning how to write jQuery and would appreciate any help with this code.

答:
This is what you do with pure javascript, jQuery is not needed.

```<code>var d1=new Date();
d1.toString('yyyy-MM-dd');       //returns "2009-06-29"
d1.toString('dddd, MMMM ,yyyy')  //returns "Monday, June 29,2009"
</code>```

Another example to fit your case:

```<code>var d1=new Date();
d1.toString('dd.MM.yy');       //returns "08.04.11"
</code>```

More:

Where can I find documentation on formatting a date in JavaScript?

Body:
This is what you do with pure javascript, jQuery is not needed.

var d1=new Date();
d1.toString('yyyy-MM-dd');       //returns "2009-06-29"
d1.toString('dddd, MMMM ,yyyy')  //returns "Monday, June 29,2009"

Another example to fit your case:

var d1=new Date();
d1.toString('dd.MM.yy');       //returns "08.04.11"

More:

Where can I find documentation on formatting a date in JavaScript?


问:
alexa sdk: saving sessionAttributes in https response
i have a skill and i want to load some data from an url and store it in the SessionAttributes.

so i wrote this into my handle(handlerInput)of my LaunchRequestHandler:

```<code>require('https').get(url, (resp) => {

  resp.on('data', (chunk) => {
    data += chunk;
  });

  resp.on('end', () => {
    let attributes = JSON.parse(data);
    console.log(attributes);
    handlerInput.attributesManager.setSessionAttributes(attributes);
  });
});
</code>```

the log shows me the correct object, but when i try to load the sessionAttributes in the next intent it's empty. I Assume it has something to do with the setSessionAttributes being in the response function, because if i set something directly after this code, it works. Any ideas?

答:
This might be because of the asynchronous operation. Please use async/await to make the API call and then save. Sample example,</p>

```<code>const getData = () => {
  return new Promise((resolve, reject) => {
    require("https").get(url, resp => {
      resp.on("data", chunk => {
        data += chunk;
      });

      resp.on("end", () => {
        resolve(data);
      });
    });
  });
};

const LaunchRequestHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === "LaunchRequest";
  },
  async handle(handlerInput) {
    const speechText = "welcome";
    const data = await getData(); //asynchronous operation
    const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
    sessionAttributes.data = data;
    handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
    return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .withSimpleCard("Welcome to the Skill", speechText)
      .getResponse();
  }
};
</code>```

Body:
i have a skill and i want to load some data from an url and store it in the SessionAttributes.

so i wrote this into my handle(handlerInput)of my LaunchRequestHandler:

require('https').get(url, (resp) => {

  resp.on('data', (chunk) => {
    data += chunk;
  });

  resp.on('end', () => {
    let attributes = JSON.parse(data);
    console.log(attributes);
    handlerInput.attributesManager.setSessionAttributes(attributes);
  });
});

the log shows me the correct object, but when i try to load the sessionAttributes in the next intent it's empty. I Assume it has something to do with the setSessionAttributes being in the response function, because if i set something directly after this code, it works. Any ideas?

Body:
This might be because of the asynchronous operation. Please use async/await to make the API call and then save. Sample example,

const getData = () => {
  return new Promise((resolve, reject) => {
    require("https").get(url, resp => {
      resp.on("data", chunk => {
        data += chunk;
      });

      resp.on("end", () => {
        resolve(data);
      });
    });
  });
};

const LaunchRequestHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === "LaunchRequest";
  },
  async handle(handlerInput) {
    const speechText = "welcome";
    const data = await getData(); //asynchronous operation
    const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
    sessionAttributes.data = data;
    handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
    return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .withSimpleCard("Welcome to the Skill", speechText)
      .getResponse();
  }
};


问:
Client authentication at Apache DS
I am new to LDAP with SSL. I am working on 2 way SSL authentication on Apache Directory server/studio, but I am not getting how to store client certificate in Truststore of Apache DS. I have followed http://directory.apache.org/apacheds/advanced-ug/4.1.4-certificate-authn.html (Page is empty) link. Anyone can tell me how can I authenticate client at server?

答:
If you were on the server you could connect without client certificate to the ldapi socket.

You can do the same from your remote workstation by tunneling the ldapi socket to a local tcp port, via ssh.

Run this in a terminal:

```<code>ssh -L localhost:9696:/var/run/ldapi someuser@ldapserver
</code>```

Then point directory studio to the host/port localhost:9696.

This is similar to what the

https://blog.laimbock.com/2013/02/26/apache-directory-studio-and-client-certificate-authentication/

tells, but I only use ssh (the blog uses socat which in turn uses ssh).

Title: Client authentication at Apache DS

Body:
If you were on the server you could connect without client certificate to the ldapi socket.

You can do the same from your remote workstation by tunneling the ldapi socket to a local tcp port, via ssh.

Run this in a terminal:

ssh -L localhost:9696:/var/run/ldapi someuser@ldapserver

Then point directory studio to the host/port localhost:9696.

This is similar to what the

https://blog.laimbock.com/2013/02/26/apache-directory-studio-and-client-certificate-authentication/

tells, but I only use ssh (the blog uses socat which in turn uses ssh).


问:
Changing Button Color using Listbox
I need to change background color of Button using ListBox. I have 3 ListBoxItems for 3 colors ( green, yellow and red). I am not sure how to do this. Any help will be greatly appreciated.</p>

```<code><StackPanel Grid.Column="1" Grid.Row="3">
  <ToggleButton Height="50" Content="Change!" Name="button">
   </ToggleButton>
    <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False">
     <Border Background="LightYellow">
       <ListBox>
        <ListBoxItem>Green</ListBoxItem>
         <ListBoxItem>Yellow</ListBoxItem>
        <ListBoxItem>Red</ListBoxItem>
      </ListBox>
    </Border>
  </Popup>
</StackPanel>
</code>```

答:
Give your ListBox a name and attach an event handler SelectionChanged.

```<code><ToggleButton Height="50" Content="Change!" Name="button">
<ListBox x:Name="myListBx" SelectionChanged="MyListBx_OnSelectionChanged">
    <ListBoxItem>Green</ListBoxItem>
    <ListBoxItem>Yellow</ListBoxItem>
    <ListBoxItem>Red</ListBoxItem>
</ListBox>
</code>```

Then on back end you can do something like this (Tested working)

```<code>private void MyListBx_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string SelectedColor = (myListBx.SelectedItem as ListBoxItem).Content.ToString();

    switch (SelectedColor)
    {
        case "Yellow":
            button.Background = Brushes.Yellow;
            break;
        case "Green":
            button.Background = Brushes.Green;
            break;
        case "Pink":
            button.Background = Brushes.Pink;
            break;
    }
}
</code>```

Title: Changing Button Color using Listbox

Body:
I need to change background color of Button using ListBox. I have 3 ListBoxItems for 3 colors ( green, yellow and red). I am not sure how to do this. Any help will be greatly appreciated.

<StackPanel Grid.Column="1" Grid.Row="3">
  <ToggleButton Height="50" Content="Change!" Name="button">
   </ToggleButton>
    <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False">
     <Border Background="LightYellow">
       <ListBox>
        <ListBoxItem>Green</ListBoxItem>
         <ListBoxItem>Yellow</ListBoxItem>
        <ListBoxItem>Red</ListBoxItem>
      </ListBox>
    </Border>
  </Popup>
</StackPanel>

Body:
Give your ListBox a name and attach an event handler SelectionChanged.

<ToggleButton Height="50" Content="Change!" Name="button">
<ListBox x:Name="myListBx" SelectionChanged="MyListBx_OnSelectionChanged">
    <ListBoxItem>Green</ListBoxItem>
    <ListBoxItem>Yellow</ListBoxItem>
    <ListBoxItem>Red</ListBoxItem>
</ListBox>

Then on back end you can do something like this (Tested working)

private void MyListBx_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string SelectedColor = (myListBx.SelectedItem as ListBoxItem).Content.ToString();

    switch (SelectedColor)
    {
        case "Yellow":
            button.Background = Brushes.Yellow;
            break;
        case "Green":
            button.Background = Brushes.Green;
            break;
        case "Pink":
            button.Background = Brushes.Pink;
            break;
    }
}


问:
Comparing two columns and if it matches both the columns should be highlighted
I have two columns J and L.

If the value of J column matches with the corresponding value of L column, both the cells should be highlighted in red.

I am new to this Excel. I am not able to develop this macro.

I tried the below code but it is highlighting J, K and L column if it matches I want only the J and K column to be highlighted and also this macro should start checking from J11 and L11

```<code>Sub test()
    Dim LastRow As Long, i As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")
        LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
        arr = .Range("J2" & ":L" & LastRow)

        For i = LBound(arr) To UBound(arr)
            If arr(i, 1) = arr(i, 3) Then
                .Range("J" & i + 1 & ":L" & i + 1).Interior.Color = vbRed
            End If
        Next i
    End With
End Sub
</code>```

答:
I think this is the desired output:

```<code>Sub test()
    Dim LastRow As Long, i As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")
        LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
        arr = .Range("J2" & ":L" & LastRow)

        For i = LBound(arr) To UBound(arr)
            If arr(i, 1) = arr(i, 3) Then
                .Range("J" & i + 1).Interior.Color = vbRed
                .Range("L" & i + 1).Interior.Color = vbRed
            End If
        Next i
    End With
End Sub
</code>```

Just take them separately.

Body:
I have two columns J and L.

If the value of J column matches with the corresponding value of L column, both the cells should be highlighted in red.

I am new to this Excel. I am not able to develop this macro.

I tried the below code but it is highlighting J, K and L column if it matches I want only the J and K column to be highlighted and also this macro should start checking from J11 and L11

Sub test()
    Dim LastRow As Long, i As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")
        LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
        arr = .Range("J2" & ":L" & LastRow)

        For i = LBound(arr) To UBound(arr)
            If arr(i, 1) = arr(i, 3) Then
                .Range("J" & i + 1 & ":L" & i + 1).Interior.Color = vbRed
            End If
        Next i
    End With
End Sub

Body:
I think this is the desired output:

Sub test()
    Dim LastRow As Long, i As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")
        LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
        arr = .Range("J2" & ":L" & LastRow)

        For i = LBound(arr) To UBound(arr)
            If arr(i, 1) = arr(i, 3) Then
                .Range("J" & i + 1).Interior.Color = vbRed
                .Range("L" & i + 1).Interior.Color = vbRed
            End If
        Next i
    End With
End Sub

Just take them separately.


问:
Insert text or Edit Image in iPhone
I am stuck with this problem and not getting any idea about this.?

I do have some images in the application, and I want to insert some text in to that images which I take as input from the user?

I don't have any idea how to accomplish this task? Is it possible or not.

Basic Idea is : I do have images in to the application resources.
I want to insert text at certain place or at some cordinate.
Lets say, User insert: Merry Christmas, so the text get include in the image. at specific cordinate of the image.

答:
Reference 1

How do I use the NSString draw functionality to create a UIImage from text

may help you a bit

Title: Insert text or Edit Image in iPhone


问:
How to fix syntax in UNPIVOT command? Parenthesis as Unexpected syntax error
I am trying to unpivot this table as I need the days in rows not in columns. I am relatively new, but I thing the Unpivot should work. However, it says Syntax Error, unexpected (, when from everywhere I have seen there is a parenthesis after the UNPIVOT command.

I have tried other clauses to encapsulate it, or not using at all, but always appears the same mistake. It should be in Standard SQL.

standardSQL

```<code>SELECT service_id, day, service
FROM calendar
UNPIVOT
(
    service
    FOR day in ( monday, tuesday, wednesday, thursday, friday, saturday, sunday )
) AS unpvt;
</code>```

Should get a list whose column titles should be: service_id, day, service

答:
You can try this way-</p>

```<code>SELECT service_id, service, day
FROM calendar
UNPIVOT
(
    S FOR day in ( [monday], [tuesday], [wednesday], [thursday], [friday], [saturday], [sunday] )
) AS unpvt;
</code>```

Body:
I am trying to unpivot this table as I need the days in rows not in columns. I am relatively new, but I thing the Unpivot should work. However, it says Syntax Error, unexpected (, when from everywhere I have seen there is a parenthesis after the UNPIVOT command.

I have tried other clauses to encapsulate it, or not using at all, but always appears the same mistake. It should be in Standard SQL.

standardSQL

SELECT service_id, day, service
FROM calendar
UNPIVOT
(
    service
    FOR day in ( monday, tuesday, wednesday, thursday, friday, saturday, sunday )
) AS unpvt;

Should get a list whose column titles should be: service_id, day, service

Body:
You can try this way-

SELECT service_id, service, day
FROM calendar
UNPIVOT
(
    S FOR day in ( [monday], [tuesday], [wednesday], [thursday], [friday], [saturday], [sunday] )
) AS unpvt;


问:
How can I avoid writing many very similar setter methods?
I am working on a piece of code where the following applies:

I need to instanciate a lot of similar objects within an instance of Class A

Each of these objects will then get their own setter in Class B, which corresponds 1:1 to the objects created in the instance of Class A
i.e.
In class A:

```<code>    B b = new B();

    final SomethingA somethingA1 = new SomethingA("input1");
    b.setSomethingA();

    ...
    final SomethingB somethingB15 = new SomethingB("input15");
    b.setSomethingB15();
    ...

    final SomethingA somethingA23 = new SomethingA("input23");
    b.setSomethingA23();
</code>```

Where all "somethings" inherit from the same class.

The setter does nothing but:

```<code>public void setSomethingX(somethingX){
this.somethingX = somethingX;
}
</code>```

I really do not want to write 23 setters that all do almost the same. Is there something like a multi-purpose setter?

The context of this is preparing an HTTP response in a very specific context and using some very specific frameworks. Apparently, this way of doing saves lot of work somewhere else (that I have no influence on).
Also, as you can probably tell I am a novice developer.

答:
There are couple technics to reduce setters:

1) Create constructor with B as parameter

```<code>class A {

    private B b;

    public A(B b) {
        this.b = b;
    }
}

A a = new A(new B());
</code>```

2) Use builder pattern (with lombok will be easy to implement):

```<code>@Builder // lombok annotation
class A {
    private B b;
}

A a = A.builder().withB(b).build();
</code>```

3) Use factory method:

```<code>class A {

    private B b;

    public static A newInstance(B b) {
        A a = new A();
        a.b = b;
        return a;
    }

}

A a = A.newInstance(new B());
</code>```

Body:
I am working on a piece of code where the following applies:

I need to instanciate a lot of similar objects within an instance of Class A

Each of these objects will then get their own setter in Class B, which corresponds 1:1 to the objects created in the instance of Class A
i.e.
In class A:

    B b = new B();

    final SomethingA somethingA1 = new SomethingA("input1");
    b.setSomethingA();

    ...
    final SomethingB somethingB15 = new SomethingB("input15");
    b.setSomethingB15();
    ...

    final SomethingA somethingA23 = new SomethingA("input23");
    b.setSomethingA23();

Where all "somethings" inherit from the same class.

The setter does nothing but:

public void setSomethingX(somethingX){
this.somethingX = somethingX;
}

I really do not want to write 23 setters that all do almost the same. Is there something like a multi-purpose setter?

The context of this is preparing an HTTP response in a very specific context and using some very specific frameworks. Apparently, this way of doing saves lot of work somewhere else (that I have no influence on).
Also, as you can probably tell I am a novice developer.

Body:
There are couple technics to reduce setters:

1) Create constructor with B as parameter

class A {

    private B b;

    public A(B b) {
        this.b = b;
    }
}

A a = new A(new B());

2) Use builder pattern (with lombok will be easy to implement):

@Builder // lombok annotation
class A {
    private B b;
}

A a = A.builder().withB(b).build();

3) Use factory method:

class A {

    private B b;

    public static A newInstance(B b) {
        A a = new A();
        a.b = b;
        return a;
    }

}

A a = A.newInstance(new B());


问:
Code not reachable in Visual Studio Code with Javascript and Go To Definition (F12) functionality
I would like to write javascript module and access methods with "Go To Definition" functionality of Visual Studio Code (F12 or ctrl+ left mouse click)

It works well with simples modules but each time I want to extend a module with an variable in argument, Visual Studio code is not able to reach function inside my module.

I have written a small example in order to reproduce it.
Simple copy and paste it in a new file into Visual Studio Code.

For information, I use the version 1.34 of Visual Studio Code.

```<code>//////////////////////////////////////////////////////////////////////////////
// Example 1:
// - Function fntBad() from libFntBad.fntBad(); is not reachable with ctrl + left mouse click

////////////////////////////////////////
////// Library 1
var libFntBad = (function(moduleExtended) {
    var self = moduleExtended;

    self.fntBad = function() {
        console.log("libFntBad - fntBad");
        return false;
    };

    return self;
})(libFntBad || {});
////////////////////////////////////////

////////////////////////////////////////
////// Library 2
var libFntGood = (function() {
    var self = {};

    self.fntGood = function() {
        console.log("libFntGood - fntGood");
        return true;
    };

    return self;
})();
////////////////////////////////////////

////////////////////////////////////////
////// Program that use libraries
var libCallFnt = (function() {
    var self = {};

    self.callFnt1 = function(s) {
        console.log(s);
        libFntBad.fntBad(); // Not found
    };

    self.callFnt2 = function(s) {
        console.log(s);
        libFntGood.fntGood();   // Found in Library 2
    };

    return self;
})();

libCallFnt.callFnt1("Fnt1");        // Reachable
libCallFnt.callFnt2("Fnt2");        // Reachable

libFntBad.fntBad();                 // Not reachable
libFntGood.fntGood();               // Reachable

//////////////////////////////////////////////////////////////////////////////
// Example 2:
// - Function extension from ModuleTwo.extension is not reachable with ctrl + left mouse click

var Module = (function () {
    var _privateMethod = function () {
        // private
        console.log("_privateMethod");
    };

    var oneMethod = function () {
        // public
        console.log("oneMethod");
        _privateMethod();
    };

    var anotherMethod = function () {
        // public
        console.log("anotherMethod");
    };

    return {
        oneMethod: oneMethod,
        anotherMethod: anotherMethod
    };
})();

var ModuleTwo = (function (mod) {
    mod.extension = function () {
        // another method!
        console.log("Module.extension");
    };

    return mod;
})(Module || {});

Module.oneMethod();
ModuleTwo.extension();              // Not reachable
</code>```

I expect to reach piece of code that are marked as "Not reachable".

What's wrong with my code?
Is there another way to make it works in Visual Studio Code?

NetBeans editor is able to navigate correctly between methods so I suppose that my piece of code is not to bad.

答:
What about using debbuger statement ? Then youn will break into your function anytime you go through it

More informations here: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/debugger

Body:
I would like to write javascript module and access methods with "Go To Definition" functionality of Visual Studio Code (F12 or ctrl+ left mouse click)

It works well with simples modules but each time I want to extend a module with an variable in argument, Visual Studio code is not able to reach function inside my module.

I have written a small example in order to reproduce it.
Simple copy and paste it in a new file into Visual Studio Code.

For information, I use the version 1.34 of Visual Studio Code.

//////////////////////////////////////////////////////////////////////////////
// Example 1:
// - Function fntBad() from libFntBad.fntBad(); is not reachable with ctrl + left mouse click

////////////////////////////////////////
////// Library 1
var libFntBad = (function(moduleExtended) {
    var self = moduleExtended;

    self.fntBad = function() {
        console.log("libFntBad - fntBad");
        return false;
    };

    return self;
})(libFntBad || {});
////////////////////////////////////////

////////////////////////////////////////
////// Library 2
var libFntGood = (function() {
    var self = {};

    self.fntGood = function() {
        console.log("libFntGood - fntGood");
        return true;
    };

    return self;
})();
////////////////////////////////////////

////////////////////////////////////////
////// Program that use libraries
var libCallFnt = (function() {
    var self = {};

    self.callFnt1 = function(s) {
        console.log(s);
        libFntBad.fntBad(); // Not found
    };

    self.callFnt2 = function(s) {
        console.log(s);
        libFntGood.fntGood();   // Found in Library 2
    };

    return self;
})();

libCallFnt.callFnt1("Fnt1");        // Reachable
libCallFnt.callFnt2("Fnt2");        // Reachable

libFntBad.fntBad();                 // Not reachable
libFntGood.fntGood();               // Reachable

//////////////////////////////////////////////////////////////////////////////
// Example 2:
// - Function extension from ModuleTwo.extension is not reachable with ctrl + left mouse click

var Module = (function () {
    var _privateMethod = function () {
        // private
        console.log("_privateMethod");
    };

    var oneMethod = function () {
        // public
        console.log("oneMethod");
        _privateMethod();
    };

    var anotherMethod = function () {
        // public
        console.log("anotherMethod");
    };

    return {
        oneMethod: oneMethod,
        anotherMethod: anotherMethod
    };
})();

var ModuleTwo = (function (mod) {
    mod.extension = function () {
        // another method!
        console.log("Module.extension");
    };

    return mod;
})(Module || {});

Module.oneMethod();
ModuleTwo.extension();              // Not reachable

I expect to reach piece of code that are marked as "Not reachable".

What's wrong with my code?
Is there another way to make it works in Visual Studio Code?

NetBeans editor is able to navigate correctly between methods so I suppose that my piece of code is not to bad.


问:
Change client IP to proxy IP for API requests
Original client IP does not change when I use a reverse-proxy to use some API from an internal corporate server.

So far I've done what most people suggested on Internet.
Just putting in proxyPass stuff in Apache config files.
Basically the setup is like this.

Client browser -> Reverse Proxy server -> Internal server

Internal API that I'm trying to use is only open to reverse proxy because of obvious security considerations.
If I can just pass the Reverse Proxy server's IP to the internal server, it would just work.

```<code><Location />
  ProxyPass ${internalServer}
  ProxyPassReverse ${internalServer}
</Location>
</code>```

I've also tried
RemoteIPHeader ${myProxyIP}

It should connect and let me use API from internal server.

答:
Try:</p>

```<code><Location />
  ProxyAddHeaders Off
  ProxyPass ${internalServer}
  ProxyPassReverse ${internalServer}
</Location>
</code>```

Body:
Original client IP does not change when I use a reverse-proxy to use some API from an internal corporate server.

So far I've done what most people suggested on Internet.
Just putting in proxyPass stuff in Apache config files.
Basically the setup is like this.

Client browser -> Reverse Proxy server -> Internal server

Internal API that I'm trying to use is only open to reverse proxy because of obvious security considerations.
If I can just pass the Reverse Proxy server's IP to the internal server, it would just work.

<Location />
  ProxyPass ${internalServer}
  ProxyPassReverse ${internalServer}
</Location>

I've also tried
RemoteIPHeader ${myProxyIP}

It should connect and let me use API from internal server.

Body:
Try:

<Location />
  ProxyAddHeaders Off
  ProxyPass ${internalServer}
  ProxyPassReverse ${internalServer}
</Location>


问:
Security issue with allow-navigation on PhoneGap app - Blank screen
We have just moved servers and our PhoneGap app has stopped working, suddenly showing a blank screen with no explanation. I've tried debugging Android with Chrome dev tools but that whole process seems to be totally broken in 2019 (I can debug webpages fine, the app just does not appear in the list no matter what I try).

Our app's index.html simply redirects to a url on our server. It was working fine yesterday. We did not change the domain or app url and everything works totally fine in the browser.

Is there a DNS cache on PhoneGap or something with the page headers conflicting with PhoneGap perhaps?

In config.xml we have these settings:

```<code><allow-navigation href="https://www.example.com/*" />
<plugin name="cordova-plugin-whitelist" spec="1.3.3" />
<plugin name="cordova-plugin-inappbrowser" spec="3.0.0" />
<access origin="*" />
</code>```

Update:

I tried using a plain text file as the app homepage in config.xml and it still doesn't work. The whole domain seems to be blocked despite the allow-navigation rule I posted above.

```<code><content src="https://www.example.com/test.txt" /> //DOES NOT WORK
<content src="https://www.youtube.com/" />         //WORKS FINE
</code>```

答:
This issue was caused by a missing OpenSSL cert on the new server. PHP 7 requires an SSL cert for use with certain requests. More info here. For some reason, the Cordova app was detecting the missing cert and blocking the app from loading. We were fixing the PHP cert to solve another issue and it happily solved this one too!

You can also fix the blank screen issue or workaround it temporarily by building your app without a certificate. In PhoneGap Build, choose "no key selected" from the dropdown before building. Note however, the Play store wont accept apps built without a cert.

Body:
We have just moved servers and our PhoneGap app has stopped working, suddenly showing a blank screen with no explanation. I've tried debugging Android with Chrome dev tools but that whole process seems to be totally broken in 2019 (I can debug webpages fine, the app just does not appear in the list no matter what I try).

Our app's index.html simply redirects to a url on our server. It was working fine yesterday. We did not change the domain or app url and everything works totally fine in the browser.

Is there a DNS cache on PhoneGap or something with the page headers conflicting with PhoneGap perhaps?

In config.xml we have these settings:

<allow-navigation href="https://www.example.com/*" />
<plugin name="cordova-plugin-whitelist" spec="1.3.3" />
<plugin name="cordova-plugin-inappbrowser" spec="3.0.0" />
<access origin="*" />

Update:

I tried using a plain text file as the app homepage in config.xml and it still doesn't work. The whole domain seems to be blocked despite the allow-navigation rule I posted above.

<content src="https://www.example.com/test.txt" /> //DOES NOT WORK
<content src="https://www.youtube.com/" />         //WORKS FINE


问:
Allow Apache to execute command in root?
I am setting up a bash/html CGI that will allow me to generate graphs with GnuPlot under RedHat 7.6.
My tutor ask me to create a cgi script that will be able to return a sudo id (root) without a password, only using the " id " command, not " sudo id "

I've just add the id command in my cgi source code in order to display the result of this command on the first page of my cgi :

Actually, if I add the id command in one of my cgi-script, the return is :

```<code>uid=48(apache) gid=48(apache) groups=48(apache) context=system_u:system_r:httpd_sys_script_t:s0
</code>```

So I going on the the visudo file and I try to add this at the end of the visudo file :

```<code>httpd ALL=(root) NOPASSWD: id
</code>```

Or

```<code>apache ALL=(root) NOPASSWD: id
</code>```

My cgi return this again and again :

```<code>uid=48(apache) gid=48(apache) groups=48(apache) context=system_u:system_r:httpd_sys_script_t:s0
</code>```

But I want this return :

```<code>uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
</code>```

Could you show me how to do that ?

答:
If you add the username as the first parameter to id you get the desired output.

```<code>[user@host ~]# id root
uid=0(root) gid=0(root) Gruppen=0(root)
</code>```

Body:
I am setting up a bash/html CGI that will allow me to generate graphs with GnuPlot under RedHat 7.6.
My tutor ask me to create a cgi script that will be able to return a sudo id (root) without a password, only using the " id " command, not " sudo id "

I've just add the id command in my cgi source code in order to display the result of this command on the first page of my cgi :

Actually, if I add the id command in one of my cgi-script, the return is :

uid=48(apache) gid=48(apache) groups=48(apache) context=system_u:system_r:httpd_sys_script_t:s0

So I going on the the visudo file and I try to add this at the end of the visudo file :

httpd ALL=(root) NOPASSWD: id

Or

apache ALL=(root) NOPASSWD: id

My cgi return this again and again :

uid=48(apache) gid=48(apache) groups=48(apache) context=system_u:system_r:httpd_sys_script_t:s0

But I want this return :

uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

Could you show me how to do that ?

Body:
If you add the username as the first parameter to id you get the desired output.

[user@host ~]# id root
uid=0(root) gid=0(root) Gruppen=0(root)


问:
How do I tackle with the "[Errno 30] Read-only file system" error, while trying to open an xlsx in a firebase cloud function?
I am trying to attach this fileX to an email using a python-based cloud-function. The code runs fine on localhost while it gives this error when I deploy the cloud-function:
[Errno 30] Read-only file system: 'fileX.xlsx'

Have tried writing to the /tmp directory in google cloud storage, but to no resolve.

```<code>    df_en.to_excel(writer, sheet_name='en')
    df_hi.to_excel(writer, sheet_name='hi')
    writer.save()
</code>```

```<code>    filename = "fileX.xlsx"
    attachment = open("/tmp/fileX.xlsx", "r+b")
</code>```

答: Depending on your need, you can either change your file's permissions in order to make it both readable and writable or change the way you attach it by changing the "r+b" in "r".

Body:
I am trying to attach this fileX to an email using a python-based cloud-function. The code runs fine on localhost while it gives this error when I deploy the cloud-function:
[Errno 30] Read-only file system: 'fileX.xlsx'

Have tried writing to the /tmp directory in google cloud storage, but to no resolve.

    df_en.to_excel(writer, sheet_name='en')
    df_hi.to_excel(writer, sheet_name='hi')
    writer.save()

    filename = "fileX.xlsx"
    attachment = open("/tmp/fileX.xlsx", "r+b")


问:
Allocating more memory to an existing Global memory array
is it possible to add memory to a previously allocated array in global memory?

what i need to do is this:

```<code>//cudamalloc memory for d_A
int n=0;int N=100;
do
{
 Kernel<<< , >>> (d_A,n++);
 //add N memory to d_A
 while(n!=5)}
</code>```

does doing another cudamalloc removes the values of the previously allocated array? in my case the values of the previous allocated array should be kept...

答:
I'm not sure what complications cuda adds to the mix(?) but in c you can't add memory to an already allocated array.

If you want to grow a malloc'd array, you need to malloc a new array of the size you need and copy the contents from the existing array.

If you're doing this often then it's probably worth mallocing more than you need each time to avoid costly (in terms of processing time) re-allocation operations.

Body:
is it possible to add memory to a previously allocated array in global memory?

what i need to do is this:

//cudamalloc memory for d_A
int n=0;int N=100;
do
{
 Kernel<<< , >>> (d_A,n++);
 //add N memory to d_A
 while(n!=5)}

does doing another cudamalloc removes the values of the previously allocated array? in my case the values of the previous allocated array should be kept...


问:
JSON no value for "column" but JSON data is available
I'm facing an issue whereas I retrieve JSON data from my server to then display it in a recyclerview in Android. The data is available as if I log it it does display as follows:

```<code>D/------>: onSuccess: {"{\"vtmtransaction\":\"f53fa6ba-ccbf-4aa0-b948-b4305f279cfd\",\"vtmowner\":\"a8dd0bd7-1d6f-4262-ab66-14492ce183ac\",\"vtmoriginname\":\"Dar es Salaam\",\"vtmdestinationname\":\"Arusha\",\"vtmpickupdate\":\"2019-05-26T22:00:00.000Z\",\"vtmpickuptime\":\"08:30:00\",\"vtmvehicletype\":1,\"vtmmodel\":\"Land cruisera\",\"vtmfueltype\":1,\"vtmenginenumber\":\"sdasda\",\"vtmchassisnumber\":\"sdasd\",\"vtmenginecapacity\":2000,\"vtminsurance\":false,\"vtminsurancetype\":null,\"vtmclearingandforwarding\":false,\"vtmvehicleservice\":false,\"vtmvehicleservicetype\":null,\"vtmvehiclemake\":1,\"vtmorigincountry\":\"Tanzania\",\"vtmdestinationcountry\":\"Tanzania\",\"vtmbookedwhen\":\"2019-05-26T22:00:00.000Z\",\"vtmorigincoords\":\"0101000020E6100000FC694881AA9A43404C6BD3D85E2B1BC0\",\"vtmdestinationcoords\":\"0101000020E610000010F4064E6C5742400AEF17586C180BC0\"}":{"vtmtransaction":"f53fa6ba-ccbf-4aa0-b948-b4305f279cfd","vtmowner":"a8dd0bd7-1d6f-4262-ab66-14492ce183ac","vtmoriginname":"Dar es Salaam","vtmdestinationname":"Arusha","vtmpickupdate":"2019-05-26T22:00:00.000Z","vtmpickuptime":"08:30:00","vtmvehicletype":1,"vtmmodel":"Land cruisera","vtmfueltype":1,"vtmenginenumber":"sdasda","vtmchassisnumber":"sdasd","vtmenginecapacity":2000,"vtminsurance":false,"vtminsurancetype":null,"vtmclearingandforwarding":false,"vtmvehicleservice":false,"vtmvehicleservicetype":null,"vtmvehiclemake":1,"vtmorigincountry":"Tanzania","vtmdestinationcountry":"Tanzania","vtmbookedwhen":"2019-05-26T22:00:00.000Z","vtmorigincoords":"0101000020E6100000FC694881AA9A43404C6BD3D85E2B1BC0","vtmdestinationcoords":"0101000020E610000010F4064E6C5742400AEF17586C180BC0"}}
</code>```

Once I receive the JSONArray, I convert it to a JSONObject as I do not want to work with indexes but the column names directly from the data but I always get the following error:

```<code>W/System.err: org.json.JSONException: No value for vtmoriginname
</code>```

This is the relevant part in the fragment that retrieves the data with AsyncHttpRequest and fires the process on completion of the request. The data comes from node.

```<code>public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable final Bundle savedInstanceState) {
        View mybookings = inflater.inflate(R.layout.fragment_mybookings, container, false);
        preferences = Objects.requireNonNull(getActivity()).getSharedPreferences("mykago-cars", Context.MODE_PRIVATE);
        t = new Tools(getActivity().getApplication(), getContext(), getActivity());
        prgBookings = mybookings.findViewById(R.id.prgBookings);
        final RecyclerView recyclerViewMyBookings = mybookings.findViewById(R.id.recyclerViewMyBookings);

        AsyncHttpRequest.client.setMaxRetriesAndTimeout(2, 5000);
        RequestParams params = new RequestParams();
        params.put("uuid", preferences.getString("myUUID", ""));
        AsyncHttpRequest.get("my_bookings", params, new JsonHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                t.myDialog(R.string.dataError, R.string.databaseDataNotAvailable, true, false);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                prgBookings.setVisibility(View.INVISIBLE);
                // Covert the JSONArray to a JSONObject so we can reference the columns by name and not index. Makes things easier and avoids mistakes..
                try {
                    JSONObject jsonObject = response.toJSONObject(response);
                    Log.d(TAG, "onSuccess: " + jsonObject);
                    // Loop through response and add all items to the mybooking list
                    for (int i = 0; i < jsonObject.length(); i++) {
                        MyBookings_Data myBookings_data = new MyBookings_Data();
                        try {
                            myBookings_data.setMbdorigin(jsonObject.getString("vtmoriginname"));
                            myBookings_data.setMbddestination(jsonObject.getString("vtmdestinationname"));
                            myBookings_data.setMbdpickupdate(jsonObject.getString("vtmpickupdate"));
                            myBookings_data.setMbdpickuptime(jsonObject.getString("vtmpickuptime"));
                            myBookings_data.setMdbdate(jsonObject.getString("vtmbookedwhen"));
                            myBookings_data_list.add(myBookings_data);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    MyBookingsRecyclerViewAdapter myBookingsRecyclerViewAdapter = new MyBookingsRecyclerViewAdapter(getContext(), myBookings_data_list);
                    recyclerViewMyBookings.setAdapter(myBookingsRecyclerViewAdapter);
                    recyclerViewMyBookings.setLayoutManager(new LinearLayoutManager(getContext()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        return mybookings;
    }
</code>```

答:
Please remove for loop and try again because in your json response JsonArray not available.
So don't need to use for loop

Body:
I'm facing an issue whereas I retrieve JSON data from my server to then display it in a recyclerview in Android. The data is available as if I log it it does display as follows:

D/------>: onSuccess: {"{\"vtmtransaction\":\"f53fa6ba-ccbf-4aa0-b948-b4305f279cfd\",\"vtmowner\":\"a8dd0bd7-1d6f-4262-ab66-14492ce183ac\",\"vtmoriginname\":\"Dar es Salaam\",\"vtmdestinationname\":\"Arusha\",\"vtmpickupdate\":\"2019-05-26T22:00:00.000Z\",\"vtmpickuptime\":\"08:30:00\",\"vtmvehicletype\":1,\"vtmmodel\":\"Land cruisera\",\"vtmfueltype\":1,\"vtmenginenumber\":\"sdasda\",\"vtmchassisnumber\":\"sdasd\",\"vtmenginecapacity\":2000,\"vtminsurance\":false,\"vtminsurancetype\":null,\"vtmclearingandforwarding\":false,\"vtmvehicleservice\":false,\"vtmvehicleservicetype\":null,\"vtmvehiclemake\":1,\"vtmorigincountry\":\"Tanzania\",\"vtmdestinationcountry\":\"Tanzania\",\"vtmbookedwhen\":\"2019-05-26T22:00:00.000Z\",\"vtmorigincoords\":\"0101000020E6100000FC694881AA9A43404C6BD3D85E2B1BC0\",\"vtmdestinationcoords\":\"0101000020E610000010F4064E6C5742400AEF17586C180BC0\"}":{"vtmtransaction":"f53fa6ba-ccbf-4aa0-b948-b4305f279cfd","vtmowner":"a8dd0bd7-1d6f-4262-ab66-14492ce183ac","vtmoriginname":"Dar es Salaam","vtmdestinationname":"Arusha","vtmpickupdate":"2019-05-26T22:00:00.000Z","vtmpickuptime":"08:30:00","vtmvehicletype":1,"vtmmodel":"Land cruisera","vtmfueltype":1,"vtmenginenumber":"sdasda","vtmchassisnumber":"sdasd","vtmenginecapacity":2000,"vtminsurance":false,"vtminsurancetype":null,"vtmclearingandforwarding":false,"vtmvehicleservice":false,"vtmvehicleservicetype":null,"vtmvehiclemake":1,"vtmorigincountry":"Tanzania","vtmdestinationcountry":"Tanzania","vtmbookedwhen":"2019-05-26T22:00:00.000Z","vtmorigincoords":"0101000020E6100000FC694881AA9A43404C6BD3D85E2B1BC0","vtmdestinationcoords":"0101000020E610000010F4064E6C5742400AEF17586C180BC0"}}

Once I receive the JSONArray, I convert it to a JSONObject as I do not want to work with indexes but the column names directly from the data but I always get the following error:

W/System.err: org.json.JSONException: No value for vtmoriginname

This is the relevant part in the fragment that retrieves the data with AsyncHttpRequest and fires the process on completion of the request. The data comes from node.

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable final Bundle savedInstanceState) {
        View mybookings = inflater.inflate(R.layout.fragment_mybookings, container, false);
        preferences = Objects.requireNonNull(getActivity()).getSharedPreferences("mykago-cars", Context.MODE_PRIVATE);
        t = new Tools(getActivity().getApplication(), getContext(), getActivity());
        prgBookings = mybookings.findViewById(R.id.prgBookings);
        final RecyclerView recyclerViewMyBookings = mybookings.findViewById(R.id.recyclerViewMyBookings);

        AsyncHttpRequest.client.setMaxRetriesAndTimeout(2, 5000);
        RequestParams params = new RequestParams();
        params.put("uuid", preferences.getString("myUUID", ""));
        AsyncHttpRequest.get("my_bookings", params, new JsonHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                t.myDialog(R.string.dataError, R.string.databaseDataNotAvailable, true, false);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                prgBookings.setVisibility(View.INVISIBLE);
                // Covert the JSONArray to a JSONObject so we can reference the columns by name and not index. Makes things easier and avoids mistakes..
                try {
                    JSONObject jsonObject = response.toJSONObject(response);
                    Log.d(TAG, "onSuccess: " + jsonObject);
                    // Loop through response and add all items to the mybooking list
                    for (int i = 0; i < jsonObject.length(); i++) {
                        MyBookings_Data myBookings_data = new MyBookings_Data();
                        try {
                            myBookings_data.setMbdorigin(jsonObject.getString("vtmoriginname"));
                            myBookings_data.setMbddestination(jsonObject.getString("vtmdestinationname"));
                            myBookings_data.setMbdpickupdate(jsonObject.getString("vtmpickupdate"));
                            myBookings_data.setMbdpickuptime(jsonObject.getString("vtmpickuptime"));
                            myBookings_data.setMdbdate(jsonObject.getString("vtmbookedwhen"));
                            myBookings_data_list.add(myBookings_data);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    MyBookingsRecyclerViewAdapter myBookingsRecyclerViewAdapter = new MyBookingsRecyclerViewAdapter(getContext(), myBookings_data_list);
                    recyclerViewMyBookings.setAdapter(myBookingsRecyclerViewAdapter);
                    recyclerViewMyBookings.setLayoutManager(new LinearLayoutManager(getContext()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        return mybookings;
    }


问:
bootstrap 4 pull-right is not working on navbar

I am working with bootstrap 4.

I didn't get navbar right to the page I don't know what the problem is going on.

Is Somebody else can help to fix this issue.

I have tried to add class pull-right to navbar-collapse div but its don't work. So I have also tried to add float right property and set to !important but its also not get helpful.

```<code><div class="collapse navbar-collapse pull-right" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
            <a class="nav-link" href="#">HOME</a>
        </li>

        <li class="nav-item">
            <a class="nav-link" href="#">FAQS & HELPS</a>
        </li>

        <li class="nav-item">
            <a class="nav-link" href="#">CONTACT</a>
        </li>

        <li class="nav-item">
            <a class="nav-link" href="#">LOGIN</a>
        </li>
    </ul>
</div>
</code>```

I want div content(nav links) to the right of the page.

答:
Can you please try ml-auto instead of mr-auto?

So the ul tag will be like this

```<code><ul class="navbar-nav ml-auto">
</code>```

Body:
I am working with bootstrap 4.

I didn't get navbar right to the page I don't know what the problem is going on.

Is Somebody else can help to fix this issue.

I have tried to add class pull-right to navbar-collapse div but its don't work. So I have also tried to add float right property and set to !important but its also not get helpful.

            HOME

            FAQS & HELPS

            CONTACT

            LOGIN

I want div content(nav links) to the right of the page.

Body:
Can you please try ml-auto instead of mr-auto?

So the ul tag will be like this

<ul class="navbar-nav ml-auto">


问:
export from sql server to excel file using asp.net and vb.net?
is there a way to export the whole data in one table from sql server 2008 directly using asp.net and vb.net without using datagridview to EXCEL FILE?</p>

答:
for me this is was the right answer

```<code> Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim ad As New results()
    Dim dt As results.ResultsDataTable
    dt = ad.Read()

    Dim attachment As String = "attachment; filename=USurvey.xls"
    Response.ClearContent()
    Response.AddHeader("content-disposition", attachment)
    Response.ContentType = "application/vnd.ms-excel"
    Dim tab As String = ""
    For Each dc As DataColumn In dt.Columns
        Response.Write(tab + dc.ColumnName)
        tab = vbTab
    Next
    Response.Write(vbLf)

    Dim i As Integer
    For Each dr As DataRow In dt.Rows
        tab = ""
        For i = 0 To dt.Columns.Count - 1
            Response.Write(tab & dr(i).ToString())
            tab = vbTab
        Next
        Response.Write(vbLf)
    Next
    Response.[End]()
    'export to excel
End Sub
</code>```

thanks a lot every one !!!

Body:
for me this is was the right answer

 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim ad As New results()
    Dim dt As results.ResultsDataTable
    dt = ad.Read()

    Dim attachment As String = "attachment; filename=USurvey.xls"
    Response.ClearContent()
    Response.AddHeader("content-disposition", attachment)
    Response.ContentType = "application/vnd.ms-excel"
    Dim tab As String = ""
    For Each dc As DataColumn In dt.Columns
        Response.Write(tab + dc.ColumnName)
        tab = vbTab
    Next
    Response.Write(vbLf)

    Dim i As Integer
    For Each dr As DataRow In dt.Rows
        tab = ""
        For i = 0 To dt.Columns.Count - 1
            Response.Write(tab & dr(i).ToString())
            tab = vbTab
        Next
        Response.Write(vbLf)
    Next
    Response.[End]()
    'export to excel
End Sub

thanks a lot every one !!!