问:
How to rerender the page on alert ok button
Here in my code I am trying to reload the page on Alert ok button . But its not working . How can I rerender the page on ok button , this is written on same page that I have to reload .
In my code I am sung form and inputfield compont for my login screen . All code is there below . I am tryning to is , when I am getting any respons like wrong username and password in alere then ok button I have to clear my form field . While here ists not happning . For this I am deleting my value mannully.
 Please sugget .

```<code>   import React from 'react';
import { Alert, Dimensions, ImageBackground, Text, View, TouchableOpacity, Platform , StatusBar} from 'react-native';
import  Formbox from './ui/form';
import { RegularText, } from './ui/text';
import pkg from '../../package';
import _ from 'lodash';
import { LOGIN_BACKGROUND , LOGIN_BACKGROUND_DARK} from '../images'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import parentStyle from '../themes/parent.style'
import LottieView from 'lottie-react-native';

const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;

const styles = {
  imgBG: { width: '100%', height: '100%' },
  mainContainer: {
    flex: 1,
    alignItems: 'stretch',
    justifyContent: 'flex-start',
    height: deviceHeight,
    paddingLeft: 20,
    paddingRight: 20
  },
  logoContainer: { justifyContent: 'center', alignItems: 'center', background: 'red', marginTop: -50 },
  logoView: {
    borderWidth: 3,
    borderColor: '#FFFFFF',
    borderRadius: 4,
    zIndex: -1,
    ...Platform.select({
      ios: {
        shadowOpacity: 0.45,
        shadowRadius: 3,
        shadowColor: '#090909',
        shadowOffset: { height: 1, width: 0 }
      },
      android: {
        elevation: 3
      }
    })
  }
};

export default class Login extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.error) {
      if (this.props.error.graphQLErrors[0] !== undefined) {
        const errorDetails = _.map(_.split(this.props.error.graphQLErrors[0].message, '#'), _.trim)
        const header = errorDetails[0];
        const message = errorDetails[1];
        Alert.alert(header, message, [{
          text: 'OK',
          onPress: () => this.props.navigation.push('Auth')
        },]);
      } else {
        Alert.alert('Network Error', this.props.error.networkError.message, [{
          text: 'OK',
          onPress: () => this.props.navigation.navigate('Auth')
        },]);
      }
    }
  }
  componentDidMount(){
    StatusBar.setBarStyle('dark-content');
  }

  render() {
    let loginForm = [
      { label: 'Username', icon: 'person', type: 'text' },
      { label: 'Password', icon: 'key', type: 'password' }
    ];
    let submitBtn = { label: 'Login', OnSubmit: this.props.onLogin };
    let appliedTheme = this.props.theme;
    let appliedMode = this.props.mode;
    return (
      <ImageBackground source={appliedMode === 'light' ? LOGIN_BACKGROUND : LOGIN_BACKGROUND_DARK} style={styles.imgBG}>
        <View style={styles.mainContainer}>
          <View style={{ flexDirection: 'column', alignContent: 'center', justifyContent: 'center', flex: 1 }}>
            <View style={{ flex: 0.75, justifyContent: 'center' }}>
              <RegularText text={'Welcome,'} textColor='#57606F' style={{ fontSize: hp('5%') }} />
              <RegularText text={'Sign in to continue'} textColor='#ABAFB7' style={{ fontSize: hp('3.5%') }} />
            </View>
            <View style={{ flex: 2 }}>
              <View style={{ flex: 2 }}>
                <Formbox
                  theme={parentStyle[appliedTheme] ? parentStyle[appliedTheme][appliedMode].primaryButtonColor : undefined}
                  mode={this.props.mode}
                  formFields={loginForm}
                  submit={submitBtn}
                  that={this}
                  mutation={this.props.token}
                />
                <View style={{ height: hp(20), zIndex:10, top: -25}}>
                  {this.props.loading && (
                    <LottieView source={require('./animations/login_authentication.json')} autoPlay loop />
                  )}
                </View>
                <View style={{top:-70,  zIndex:10}}>
                  {false && <View style={{ alignItems: 'center' }}>
                    <RegularText text={`v${pkg.version}`} textColor='#ABAFB7' style={{ fontSize: hp('2%') }} />
                  </View>}
                  <View style={{ alignItems: 'flex-end' }}>
                    <View style={{ flexDirection: 'row' }}>
                      <RegularText text={`New User?`} textColor='#4A494A' style={{ fontSize: hp('2%') }} />
                      <TouchableOpacity>
                        <RegularText text={` REGISTER`} textColor={parentStyle[appliedTheme] ? parentStyle[appliedTheme][appliedMode].primaryButtonColor : '#fff'} style={{ fontSize: hp('2%'), fontWeight: 'bold' }} />
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              </View>
            </View>

          </View>
        </View>
      </ImageBackground>

    );
  }
}
</code>```

////// Form ,js

```<code>import React, { Component } from 'react';
import { View, Platform, Dimensions } from 'react-native';
import { PrimaryBtn,PrimaryAbsoluteGradientBtn } from './buttons';
import { InputField, PasswordField } from './inputField';
import { Form } from 'native-base';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';

const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
export default class Formbox extends Component {
  constructor(props) {
    super(props);
  }

  OnSubmit() {
    let { formFields, that, submit, mutation } = this.props;
    submit.OnSubmit.bind(that, formFields, mutation)();
  }

  OnChange(field, target) {
    this.props.formFields.forEach(function (formField, indx) {
      if (formField.label === field.label) {
        formField.value = target;
      }
    });

  }

  renderFields(field, indx) {
    let { label, icon, type } = field;
    if (label && icon) {
      if (type === 'password') {
        return <PasswordField key={label + indx} type={type ? type : ''} label={label} icon={icon}
          OnChange={this.OnChange} that={this} />;
      }
      return <InputField key={label + indx} type={type ? type : ''} label={label} icon={icon} OnChange={this.OnChange}
        that={this} />;
    }
  }

  render() {
    let { formFields, submit, that , theme, mode} = this.props;
    return (
      <View style={{ width: '100%' }}>
        <Form style={{ width: '95%' }}>
          {formFields.map((field, indx) => this.renderFields(field, indx))}
          <View style={{ marginTop: 60 }}>
            <PrimaryAbsoluteGradientBtn label={submit.label} OnClick={this.OnSubmit} that={this} backgroundColor={theme}/></View>
        </Form>
      </View>
    );
  }
}
</code>```

/// input fields js

```<code>import React, { Component } from 'react';
import { Icon, Input, Item, Label } from 'native-base';
import { View } from 'react-native';
import { DoNothing } from '../services/services';

class InputField extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    let { label, OnChange, icon, that,type, keyboardType } = this.props;
    return (
      <View>
        <Item floatingLabel>
          {icon && <Icon active name={icon}/>}
          {label && <Label>{label}</Label>}
          <Input
            secureTextEntry={type === 'password'}
            onChangeText={OnChange ? (e) => OnChange.bind(that, this.props, e)() : DoNothing.bind(this)}
            keyboardType={keyboardType || 'default'}
            autoCapitalize = 'none'
            autoCorrect={false}
          />
        </Item>
      </View>
    );
  }
}

class PasswordField extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isMasked: true
    };
  }

  _toggleMask = () => {
    this.setState({
      isMasked: !this.state.isMasked
    });
  };

  render() {
    let { label, OnChange, icon, that, type } = this.props;
    const { isMasked } = this.state;
    return (
      <View>
        <Item floatingLabel>
          {icon && <Icon active name={icon}/>}
          <Label>{label}</Label>
          <Input
            autoCapitalize = 'none'
            secureTextEntry={isMasked}
            onChangeText={OnChange ? (e) => OnChange.bind(that, this.props, e)() : DoNothing.bind(this)}
          />
          <Icon name={isMasked ? "md-eye-off" : "md-eye"} active  type="Ionicons" onPress={() => this._toggleMask()}/>
        </Item>
      </View>
    );
  }
}

const styles = {
  dark: {
    color: "#000000"
  },
  light: {
    color: "#EAEAEA"
  }
}

export { InputField, PasswordField };
</code>```

答:
You can either do :

```<code>onPress: () => this.props.navigation.push('Auth')
</code>```

or do something like :

```<code>onPress: () => this.setState({name:'random'})
</code>```

These both will trigger re rendering, Hope it helps. feel free for doubts

Body:
Here in my code I am trying to reload the page on Alert ok button . But its not working . How can I rerender the page on ok button , this is written on same page that I have to reload .
In my code I am sung form and inputfield compont for my login screen . All code is there below . I am tryning to is , when I am getting any respons like wrong username and password in alere then ok button I have to clear my form field . While here ists not happning . For this I am deleting my value mannully.
 Please sugget .

   import React from 'react';
import { Alert, Dimensions, ImageBackground, Text, View, TouchableOpacity, Platform , StatusBar} from 'react-native';
import  Formbox from './ui/form';
import { RegularText, } from './ui/text';
import pkg from '../../package';
import _ from 'lodash';
import { LOGIN_BACKGROUND , LOGIN_BACKGROUND_DARK} from '../images'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import parentStyle from '../themes/parent.style'
import LottieView from 'lottie-react-native';

const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;

const styles = {
  imgBG: { width: '100%', height: '100%' },
  mainContainer: {
    flex: 1,
    alignItems: 'stretch',
    justifyContent: 'flex-start',
    height: deviceHeight,
    paddingLeft: 20,
    paddingRight: 20
  },
  logoContainer: { justifyContent: 'center', alignItems: 'center', background: 'red', marginTop: -50 },
  logoView: {
    borderWidth: 3,
    borderColor: '#FFFFFF',
    borderRadius: 4,
    zIndex: -1,
    ...Platform.select({
      ios: {
        shadowOpacity: 0.45,
        shadowRadius: 3,
        shadowColor: '#090909',
        shadowOffset: { height: 1, width: 0 }
      },
      android: {
        elevation: 3
      }
    })
  }
};

export default class Login extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.error) {
      if (this.props.error.graphQLErrors[0] !== undefined) {
        const errorDetails = _.map(_.split(this.props.error.graphQLErrors[0].message, '#'), _.trim)
        const header = errorDetails[0];
        const message = errorDetails[1];
        Alert.alert(header, message, [{
          text: 'OK',
          onPress: () => this.props.navigation.push('Auth')
        },]);
      } else {
        Alert.alert('Network Error', this.props.error.networkError.message, [{
          text: 'OK',
          onPress: () => this.props.navigation.navigate('Auth')
        },]);
      }
    }
  }
  componentDidMount(){
    StatusBar.setBarStyle('dark-content');
  }

  render() {
    let loginForm = [
      { label: 'Username', icon: 'person', type: 'text' },
      { label: 'Password', icon: 'key', type: 'password' }
    ];
    let submitBtn = { label: 'Login', OnSubmit: this.props.onLogin };
    let appliedTheme = this.props.theme;
    let appliedMode = this.props.mode;
    return (
      <ImageBackground source={appliedMode === 'light' ? LOGIN_BACKGROUND : LOGIN_BACKGROUND_DARK} style={styles.imgBG}>
        <View style={styles.mainContainer}>
          <View style={{ flexDirection: 'column', alignContent: 'center', justifyContent: 'center', flex: 1 }}>
            <View style={{ flex: 0.75, justifyContent: 'center' }}>
              <RegularText text={'Welcome,'} textColor='#57606F' style={{ fontSize: hp('5%') }} />
              <RegularText text={'Sign in to continue'} textColor='#ABAFB7' style={{ fontSize: hp('3.5%') }} />
            </View>
            <View style={{ flex: 2 }}>
              <View style={{ flex: 2 }}>
                <Formbox
                  theme={parentStyle[appliedTheme] ? parentStyle[appliedTheme][appliedMode].primaryButtonColor : undefined}
                  mode={this.props.mode}
                  formFields={loginForm}
                  submit={submitBtn}
                  that={this}
                  mutation={this.props.token}
                />
                <View style={{ height: hp(20), zIndex:10, top: -25}}>
                  {this.props.loading && (
                    <LottieView source={require('./animations/login_authentication.json')} autoPlay loop />
                  )}
                </View>
                <View style={{top:-70,  zIndex:10}}>
                  {false && <View style={{ alignItems: 'center' }}>
                    <RegularText text={`v${pkg.version}`} textColor='#ABAFB7' style={{ fontSize: hp('2%') }} />
                  </View>}
                  <View style={{ alignItems: 'flex-end' }}>
                    <View style={{ flexDirection: 'row' }}>
                      <RegularText text={`New User?`} textColor='#4A494A' style={{ fontSize: hp('2%') }} />
                      <TouchableOpacity>
                        <RegularText text={` REGISTER`} textColor={parentStyle[appliedTheme] ? parentStyle[appliedTheme][appliedMode].primaryButtonColor : '#fff'} style={{ fontSize: hp('2%'), fontWeight: 'bold' }} />
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              </View>
            </View>

          </View>
        </View>
      </ImageBackground>

    );
  }
}

////// Form ,js

import React, { Component } from 'react';
import { View, Platform, Dimensions } from 'react-native';
import { PrimaryBtn,PrimaryAbsoluteGradientBtn } from './buttons';
import { InputField, PasswordField } from './inputField';
import { Form } from 'native-base';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';

const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
export default class Formbox extends Component {
  constructor(props) {
    super(props);
  }

  OnSubmit() {
    let { formFields, that, submit, mutation } = this.props;
    submit.OnSubmit.bind(that, formFields, mutation)();
  }

  OnChange(field, target) {
    this.props.formFields.forEach(function (formField, indx) {
      if (formField.label === field.label) {
        formField.value = target;
      }
    });

  }

  renderFields(field, indx) {
    let { label, icon, type } = field;
    if (label && icon) {
      if (type === 'password') {
        return <PasswordField key={label + indx} type={type ? type : ''} label={label} icon={icon}
          OnChange={this.OnChange} that={this} />;
      }
      return <InputField key={label + indx} type={type ? type : ''} label={label} icon={icon} OnChange={this.OnChange}
        that={this} />;
    }
  }

  render() {
    let { formFields, submit, that , theme, mode} = this.props;
    return (
      <View style={{ width: '100%' }}>
        <Form style={{ width: '95%' }}>
          {formFields.map((field, indx) => this.renderFields(field, indx))}
          <View style={{ marginTop: 60 }}>
            <PrimaryAbsoluteGradientBtn label={submit.label} OnClick={this.OnSubmit} that={this} backgroundColor={theme}/></View>
        </Form>
      </View>
    );
  }
}

/// input fields js

import React, { Component } from 'react';
import { Icon, Input, Item, Label } from 'native-base';
import { View } from 'react-native';
import { DoNothing } from '../services/services';

class InputField extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    let { label, OnChange, icon, that,type, keyboardType } = this.props;
    return (
      <View>
        <Item floatingLabel>
          {icon && <Icon active name={icon}/>}
          {label && {label}}
          <Input
            secureTextEntry={type === 'password'}
            onChangeText={OnChange ? (e) => OnChange.bind(that, this.props, e)() : DoNothing.bind(this)}
            keyboardType={keyboardType || 'default'}
            autoCapitalize = 'none'
            autoCorrect={false}
          />
        </Item>
      </View>
    );
  }
}

class PasswordField extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isMasked: true
    };
  }

  _toggleMask = () => {
    this.setState({
      isMasked: !this.state.isMasked
    });
  };

  render() {
    let { label, OnChange, icon, that, type } = this.props;
    const { isMasked } = this.state;
    return (
      <View>
        <Item floatingLabel>
          {icon && <Icon active name={icon}/>}
          {label}
          <Input
            autoCapitalize = 'none'
            secureTextEntry={isMasked}
            onChangeText={OnChange ? (e) => OnChange.bind(that, this.props, e)() : DoNothing.bind(this)}
          />
          <Icon name={isMasked ? "md-eye-off" : "md-eye"} active  type="Ionicons" onPress={() => this._toggleMask()}/>
        </Item>
      </View>
    );
  }
}

const styles = {
  dark: {
    color: "#000000"
  },
  light: {
    color: "#EAEAEA"
  }
}

export { InputField, PasswordField };

Body:
You can either do :

onPress: () => this.props.navigation.push('Auth')

or do something like :

onPress: () => this.setState({name:'random'})

These both will trigger re rendering, Hope it helps. feel free for doubts


来源: stackexchange

问:
Querying a list based on a string input
I'm trying to accomplish what I feel like should be a straightforward task, but have found it much more complicated than I expected.

Essentially, given:

```<code>public class MyObject
{
    public int A;
    public float B;
    public string C;
}

List<MyObject> objectList;
</code>```

I would like to be able to read in strings something like:

```<code>"A < 1"
"B > 0.5"
"C = \"text\""
</code>```

and for each of those get a List of items in objectList satisfying the requirement.

I've been working with LINQ queries like:

```<code>objectList.Where(obj => obj.A < 1)
</code>```

so far, but am unable to figure out how to create queries like that with the field name.

Is there something straightforward that I am missing? Or is my whole approach here flawed?

答:
You can apply AND operator (&&):

```<code>objectList.Where(obj => obj.A < 1 && obj.B > 0.5 && obj.C == "text").ToList();
</code>```

More to read Filtering in LINQ

EDIT:

If you want to query based on string you can use System.Linq.Dynamic

```<code>objectList.Where("string predicate ..");
</code>```

ContentLicense: CC BY-SA 4.0

Title: Querying a list based on a string input

Body:
I'm trying to accomplish what I feel like should be a straightforward task, but have found it much more complicated than I expected.

Essentially, given:

public class MyObject
{
    public int A;
    public float B;
    public string C;
}

List<MyObject> objectList;

I would like to be able to read in strings something like:

"A < 1"
"B > 0.5"
"C = \"text\""

and for each of those get a List of items in objectList satisfying the requirement.

I've been working with LINQ queries like:

objectList.Where(obj => obj.A < 1)

so far, but am unable to figure out how to create queries like that with the field name.

Is there something straightforward that I am missing? Or is my whole approach here flawed?

Body:
You can apply AND operator (&&):

objectList.Where(obj => obj.A < 1 && obj.B > 0.5 && obj.C == "text").ToList();

More to read Filtering in LINQ

EDIT:

If you want to query based on string you can use System.Linq.Dynamic

objectList.Where("string predicate ..");


问:
Populating Bootstrap dual list boxes with pre-selected items
I am using ASP.NET core 2.1 for my web app. I have multiple lists in one of the views, each has thousands of items to be shown to the user and I am using Bootstrap Dual List Box to display the lists (http://www.virtuosoft.eu/code/bootstrap-duallistbox/). Once the user hits submit, I write the selected items to the database.
My questions is: if user goes back to the same view to edit his selections, how can I populate the previously selected items (retrieved from the database) in the right box maintaining the same functionality of the dual list box </p>

答:
I created a SelectedData class to store the items selected by the corresponding listbox:

public class SelectedData
    {
        [Key]
        public int Id { get; set; }
        public string SelectedTradeKey{ get; set; }
        public string SelectedLocationKey { get; set; }
    }
```
<p>When you bind the data of dual listbox in index method, you need to assign the saved items in SelectedData to the corresponding fields in ViewModel for reverse binding.</p>
<pre class="lang-c# prettyprint-override"><code>public IActionResult Index()
    {
        ViewModel viewModel = new ViewModel()
        {
            LocationList = _dbContext.DimLocation.ToList(),
            TradeList = _dbContext.DimTrade.ToList(),
            SelectedTradeKeyList = _dbContext.SelectedData.Select(x => x.SelectedTradeKey).ToList(),
            SelectedLocationKeyList = _dbContext.SelectedData.Select(x => x.SelectedLocationKey).ToList(),
        };
        return View(viewModel);
    }
</code>```

In the Edit method, after you get the corresponding selected items in the ViewModel, you need to clear all the previously saved data in the SelectedData, and then cycle the selectkeylist datas in the ViewModel and save it in the SelectedData table.

[HttpPost]
public IActionResult Edit(ViewModel model)
    {
        if (ModelState.IsValid)
        {
            _dbContext.Database.ExecuteSqlCommand("TRUNCATE TABLE SelectedData");
            foreach (var item in model.SelectedLocationKeyList)
            {
                SelectedData data = new SelectedData();
                data.SelectedLocationKey = item;
                _dbContext.SelectedData.Add(data);
            }
            foreach (var item in model.SelectedTradeKeyList)
            {
                SelectedData data = new SelectedData();
                data.SelectedTradeKey = item;
                _dbContext.SelectedData.Add(data);
            }
            _dbContext.SaveChanges();
        }
       return RedirectToAction("Index");
    }
```
<p>Index.cshtml:</p>
<pre class="lang-html prettyprint-override"><code>@model WebApplication_core2_1.Models.ViewModel;
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link href="~/duallistbox/bootstrap-duallistbox.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <script src="~/duallistbox/jquery.bootstrap-duallistbox.js"></script>
</head>
<body>
    @using (@Html.BeginForm("Edit", "DualListbox", FormMethod.Post))
    {
    <div class="col-8">
        <select id="ddlTrade" class="form-control" asp-for="@Model.SelectedTradeKeyList" asp-items="@(new SelectList(Model.TradeList, "TradeKey", "Name"))"
                placeholder="Please select" multiple="multiple"></select>
    </div>

    <div class="col-8">
        <select id="ddlLocation" class="form-control" asp-for="@Model.SelectedLocationKeyList" asp-items="@(new SelectList(Model.LocationList, "LocationKey", "Name"))"
                placeholder="Please select" multiple="multiple"></select>
    </div>
    <div class="col-6">
        <input class="btn btn-primary" type="submit" value="submit" id="showValue" />
    </div>
    }
    <script>
        $('#ddlTrade').bootstrapDualListbox();
        $('#ddlLocation').bootstrapDualListbox();
    </script>

</body>
</html>
</code>```

Body:
I created a SelectedData class to store the items selected by the corresponding listbox:

public class SelectedData
    {
        [Key]
        public int Id { get; set; }
        public string SelectedTradeKey{ get; set; }
        public string SelectedLocationKey { get; set; }
    }

When you bind the data of dual listbox in index method, you need to assign the saved items in SelectedData to the corresponding fields in ViewModel for reverse binding.

public IActionResult Index()
    {
        ViewModel viewModel = new ViewModel()
        {
            LocationList = _dbContext.DimLocation.ToList(),
            TradeList = _dbContext.DimTrade.ToList(),
            SelectedTradeKeyList = _dbContext.SelectedData.Select(x => x.SelectedTradeKey).ToList(),
            SelectedLocationKeyList = _dbContext.SelectedData.Select(x => x.SelectedLocationKey).ToList(),
        };
        return View(viewModel);
    }

In the Edit method, after you get the corresponding selected items in the ViewModel, you need to clear all the previously saved data in the SelectedData, and then cycle the selectkeylist datas in the ViewModel and save it in the SelectedData table.

[HttpPost]
public IActionResult Edit(ViewModel model)
    {
        if (ModelState.IsValid)
        {
            _dbContext.Database.ExecuteSqlCommand("TRUNCATE TABLE SelectedData");
            foreach (var item in model.SelectedLocationKeyList)
            {
                SelectedData data = new SelectedData();
                data.SelectedLocationKey = item;
                _dbContext.SelectedData.Add(data);
            }
            foreach (var item in model.SelectedTradeKeyList)
            {
                SelectedData data = new SelectedData();
                data.SelectedTradeKey = item;
                _dbContext.SelectedData.Add(data);
            }
            _dbContext.SaveChanges();
        }
       return RedirectToAction("Index");
    }

Index.cshtml:

@model WebApplication_core2_1.Models.ViewModel;
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link href="~/duallistbox/bootstrap-duallistbox.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <script src="~/duallistbox/jquery.bootstrap-duallistbox.js"></script>
</head>
<body>
    @using (@Html.BeginForm("Edit", "DualListbox", FormMethod.Post))
    {
    <div class="col-8">
        <select id="ddlTrade" class="form-control" asp-for="@Model.SelectedTradeKeyList" asp-items="@(new SelectList(Model.TradeList, "TradeKey", "Name"))"
                placeholder="Please select" multiple="multiple"></select>
    </div>

    <div class="col-8">
        <select id="ddlLocation" class="form-control" asp-for="@Model.SelectedLocationKeyList" asp-items="@(new SelectList(Model.LocationList, "LocationKey", "Name"))"
                placeholder="Please select" multiple="multiple"></select>
    </div>
    <div class="col-6">
        <input class="btn btn-primary" type="submit" value="submit" id="showValue" />
    </div>
    }
    <script>
        $('#ddlTrade').bootstrapDualListbox();
        $('#ddlLocation').bootstrapDualListbox();
    </script>

</body>
</html>


问:
How to access Activity UI from my class?
I have an activity which creates an object instance of my class:

```<code>file MyActivity.java:
public class MyActivity extends Activity {
    TextView myView = (TextView)findViewById(R.id.myView);
    ...
    Points myPoints new Points();
    ...
}
--------------------------------------------------------------

file Points.java:
private class Points {
    ...
    HOW TO USE myView HERE ???
    ...
}
--------------------------------------------------------------
</code>```

How do I use the UI objects in my class (which does not extend an
Activity)? Should I pass some context to my Points class? How do I do, exactly?

答:
see you post, i've edited it , to fix the problem

hope it helps :=)

here is the Edit :

```<code>file MyActivity.java:
    public class MyActivity extends Activity {
    TextView myView ;
    protected void onCreate(android.os.Bundle savedInstanceState) {
        myView = (TextView)findViewById(R.id.myView);
            Points myPoints = new Points(this);
            myPoints.displayMsg("Hello World !!!");
    }
    }

--------------------------------------------------------------

file Points.java:
private class Points {
    protected MyActivity context;
    //add a constructor with the Context of your activity
    public Points(MyActivity _context){
        context = _context;
    }

    public void displayMsg( final String msg){
        context.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                context.myView.setText(msg);
            }
        });
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an activity which creates an object instance of my class:

file MyActivity.java:
public class MyActivity extends Activity {
    TextView myView = (TextView)findViewById(R.id.myView);
    ...
    Points myPoints new Points();
    ...
}
--------------------------------------------------------------

file Points.java:
private class Points {
    ...
    HOW TO USE myView HERE ???
    ...
}
--------------------------------------------------------------

How do I use the UI objects in my class (which does not extend an
Activity)? Should I pass some context to my Points class? How do I do, exactly?

Body:
see you post, i've edited it , to fix the problem

hope it helps :=)

here is the Edit :

file MyActivity.java:
    public class MyActivity extends Activity {
    TextView myView ;
    protected void onCreate(android.os.Bundle savedInstanceState) {
        myView = (TextView)findViewById(R.id.myView);
            Points myPoints = new Points(this);
            myPoints.displayMsg("Hello World !!!");
    }
    }

--------------------------------------------------------------

file Points.java:
private class Points {
    protected MyActivity context;
    //add a constructor with the Context of your activity
    public Points(MyActivity _context){
        context = _context;
    }

    public void displayMsg( final String msg){
        context.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                context.myView.setText(msg);
            }
        });
    }
}


问:
Trying to display image in a different DIV tag when using mouseover
I have a drop down menu with a list of links. The list of links is in a  tag drop down menu and I am trying to display a diffferent image in a seperate  tag using a mouseover event. When the users cursor is over the text link a different image will appear in the picture location. Can I do this using CSS and not JavaScript? I am trying to code this so I can use it in other drop down menus so I need a way to code it where I dont have to do it using screen location like z positioning. I want the picture to display where it says no pic available which is in a different div tag than the list of links. This list of links and picture paths come from a database so it is created dynamically.

Example of code is:

```<code><div>
<ul>
list of links...
</ul>
</div>

<div>
<img src="image location">
</div>
</code>```

Picture of dropdown menu

答:
You can try this way or it can be improvised as well. Hope it will help you

/* jquery script */

$(document).ready(function(){
    $('.linktag').mouseover(function(){
        var _datahref = $(this).attr('data-href');
        $('#targetdiv').attr('src', _datahref);
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- HTML -->

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

    <div>
        <ul>
            <li>
                link1
            </li>
            <li>
                link2
            </li>
        </ul>
    </div>
    <img id="targetdiv" width="100" height="100" src="https://www.laxmipharma.net/img/product/No_Image_Available.jpg">

</body>
</html></code>```

Body:
I have a drop down menu with a list of links. The list of links is in a  tag drop down menu and I am trying to display a diffferent image in a seperate  tag using a mouseover event. When the users cursor is over the text link a different image will appear in the picture location. Can I do this using CSS and not JavaScript? I am trying to code this so I can use it in other drop down menus so I need a way to code it where I dont have to do it using screen location like z positioning. I want the picture to display where it says no pic available which is in a different div tag than the list of links. This list of links and picture paths come from a database so it is created dynamically.

Example of code is:

list of links...

Picture of dropdown menu

Body:
You can try this way or it can be improvised as well. Hope it will help you

/* jquery script */

$(document).ready(function(){
    $('.linktag').mouseover(function(){
        var _datahref = $(this).attr('data-href');
        $('#targetdiv').attr('src', _datahref);
    });
});

<!-- HTML -->

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

    <div>
        <ul>
            <li>
                <a class="linktag" href="javascript:void(0);" data-href="https://www.jobboardfinder.com/upload/1c7f578db0e8d9673c95dd5b1c7122c5a36081b0/logo_jobboard.png">link1</a>
            </li>
            <li>
                <a class="linktag" href="javascript:void(0);" data-href="https://jessehouwing.net/content/images/size/w2000/2018/07/stackoverflow-1.png">link2</a>
            </li>
        </ul>
    </div>
    <img id="targetdiv" width="100" height="100" src="https://www.laxmipharma.net/img/product/No_Image_Available.jpg">

</body>
</html>


问:
Google Cloud DataFlow: ModuleNotFoundError: No module named 'main'
I am trying to run an apache-beam pipeline on cloud Dataflow. The original function has been deployed as a cloud function which is supposed to create a Dataflow job that reads a text file and inserts into big query. But it fails to run on Dataflow. The function and error are given below.

```<code>from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import GoogleCloudOptions
from apache_beam.options.pipeline_options import StandardOptions
import apache_beam as beam

class Split(beam.DoFn):

    def process(self, element):

        element = element.split(',')

        return [{
            'field_1': element[0],
            'field_2': element[1],
            'field_3': element[2]}]

def main(data, context):

    options = PipelineOptions()

    google_cloud_options = options.view_as(GoogleCloudOptions)
    google_cloud_options.project = my-project
    google_cloud_options.job_name = job_name
    google_cloud_options.staging_location = staging_location
    google_cloud_options.temp_location = temp_location
    google_cloud_options.service_account_email = service_account_email
    options.view_as(StandardOptions).runner = 'DataflowRunner'

    p = beam.Pipeline(options=options)

    with p:
        (
            p
            | 'ReadData' >> beam.io.ReadFromText(gs://source_file_location)
            | 'ParseCSV' >> beam.ParDo(Split())
            | 'WriteToBigQuery' >> beam.io.WriteToBigQuery(table=bq_table,
                                                           schema=schema,
                                                           write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND)
        )

    result = p.run()
    result.wait_until_finish()

if __name__ == '__main__':

    main('data', 'context')
</code>```

The error that I get on Dataflow is

```<code>Error message from worker: Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/apache_beam/internal/pickler.py",
line 286, in loads return dill.loads(s) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 275, in loads return load(file, ignore, **kwds) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 270, in load return Unpickler(file, ignore=ignore, **kwds).load() File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 472, in load obj = StockUnpickler.load(self) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 462, in find_class return StockUnpickler.find_class(self, module, name) ModuleNotFoundError:
No module named 'main' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/dataflow_worker/batchworker.py", line 648, in do_work work_executor.execute() File "/usr/local/lib/python3.7/site-packages/dataflow_worker/executor.py", line 176, in execute op.start() File "apache_beam/runners/worker/operations.py",
line 649, in apache_beam.runners.worker.operations.DoOperation.start File "apache_beam/runners/worker/operations.py",
line 651, in apache_beam.runners.worker.operations.DoOperation.start File "apache_beam/runners/worker/operations.py",
line 652, in apache_beam.runners.worker.operations.DoOperation.start File "apache_beam/runners/worker/operations.py",
line 261, in apache_beam.runners.worker.operations.Operation.start File "apache_beam/runners/worker/operations.py",
line 266, in apache_beam.runners.worker.operations.Operation.start File "apache_beam/runners/worker/operations.py",
line 597, in apache_beam.runners.worker.operations.DoOperation.setup File "apache_beam/runners/worker/operations.py",
line 602, in apache_beam.runners.worker.operations.DoOperation.setup File "/usr/local/lib/python3.7/site-packages/apache_beam/internal/pickler.py",
line 290, in loads return dill.loads(s) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 275, in loads return load(file, ignore, **kwds) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py", line 270, in load return Unpickler(file, ignore=ignore, **kwds).load() File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 472, in load obj = StockUnpickler.load(self) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 462, in find_class return StockUnpickler.find_class(self, module, name)
ModuleNotFoundError: No module named 'main'
</code>```

答:
You may have to bundle up your code (including your DoFn) as a dependency in a separate file; see https://beam.apache.org/documentation/sdks/python-pipeline-dependencies/

In this case, it sounds like cloud functions execs your file from a file named main.py; that would give this kind of error. I would suggest packaging up your code as a dependency and the code here would simply be from my_lib import main.

Body:
I am trying to run an apache-beam pipeline on cloud Dataflow. The original function has been deployed as a cloud function which is supposed to create a Dataflow job that reads a text file and inserts into big query. But it fails to run on Dataflow. The function and error are given below.

from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import GoogleCloudOptions
from apache_beam.options.pipeline_options import StandardOptions
import apache_beam as beam

class Split(beam.DoFn):

    def process(self, element):

        element = element.split(',')

        return [{
            'field_1': element[0],
            'field_2': element[1],
            'field_3': element[2]}]

def main(data, context):

    options = PipelineOptions()

    google_cloud_options = options.view_as(GoogleCloudOptions)
    google_cloud_options.project = my-project
    google_cloud_options.job_name = job_name
    google_cloud_options.staging_location = staging_location
    google_cloud_options.temp_location = temp_location
    google_cloud_options.service_account_email = service_account_email
    options.view_as(StandardOptions).runner = 'DataflowRunner'

    p = beam.Pipeline(options=options)

    with p:
        (
            p
            | 'ReadData' >> beam.io.ReadFromText(gs://source_file_location)
            | 'ParseCSV' >> beam.ParDo(Split())
            | 'WriteToBigQuery' >> beam.io.WriteToBigQuery(table=bq_table,
                                                           schema=schema,
                                                           write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND)
        )

    result = p.run()
    result.wait_until_finish()

if __name__ == '__main__':

    main('data', 'context')

The error that I get on Dataflow is

Error message from worker: Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/apache_beam/internal/pickler.py",
line 286, in loads return dill.loads(s) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 275, in loads return load(file, ignore, **kwds) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 270, in load return Unpickler(file, ignore=ignore, **kwds).load() File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 472, in load obj = StockUnpickler.load(self) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 462, in find_class return StockUnpickler.find_class(self, module, name) ModuleNotFoundError:
No module named 'main' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/dataflow_worker/batchworker.py", line 648, in do_work work_executor.execute() File "/usr/local/lib/python3.7/site-packages/dataflow_worker/executor.py", line 176, in execute op.start() File "apache_beam/runners/worker/operations.py",
line 649, in apache_beam.runners.worker.operations.DoOperation.start File "apache_beam/runners/worker/operations.py",
line 651, in apache_beam.runners.worker.operations.DoOperation.start File "apache_beam/runners/worker/operations.py",
line 652, in apache_beam.runners.worker.operations.DoOperation.start File "apache_beam/runners/worker/operations.py",
line 261, in apache_beam.runners.worker.operations.Operation.start File "apache_beam/runners/worker/operations.py",
line 266, in apache_beam.runners.worker.operations.Operation.start File "apache_beam/runners/worker/operations.py",
line 597, in apache_beam.runners.worker.operations.DoOperation.setup File "apache_beam/runners/worker/operations.py",
line 602, in apache_beam.runners.worker.operations.DoOperation.setup File "/usr/local/lib/python3.7/site-packages/apache_beam/internal/pickler.py",
line 290, in loads return dill.loads(s) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 275, in loads return load(file, ignore, **kwds) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py", line 270, in load return Unpickler(file, ignore=ignore, **kwds).load() File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 472, in load obj = StockUnpickler.load(self) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py",
line 462, in find_class return StockUnpickler.find_class(self, module, name)
ModuleNotFoundError: No module named 'main'


问:
Using google speech cloud api from android give error in GOOGLE_APPLICATION_CREDENTIALS
I am trying to build an app that use google speech cloud api in android kotlin

here is my code

```<code>launch {
             googleTextToSpeech = TextToSpeechClient.create()
             googleTextToSpeech?.let {
             viewModel.speakGoogle(googleTextToSpeech!!, totalMessage, player)
          }
       }

 fun speakGoogle(textToSpeech: com.google.cloud.texttospeech.v1.TextToSpeechClient, message: String, player: MediaPlayer) {

        val filePath = Environment.getExternalStorageDirectory().absolutePath + "/google_" + System.currentTimeMillis() + ".mp3"

        launch {

            var msg = android.text.Html.fromHtml(message).toString()
            msg = msg.replace("\"", "")

            var input = SynthesisInput.newBuilder().setText(msg).build()
            var voice = VoiceSelectionParams.newBuilder().setLanguageCode("en-US").setSsmlGender(SsmlVoiceGender.FEMALE).build()
            var audio = AudioConfig.newBuilder().setAudioEncoding(AudioEncoding.MP3).build()

            var response = textToSpeech.synthesizeSpeech(input, voice, audio)

            response?.let {

                try {
                    val inputStream = response.audioContent.toByteArray()

                    File(filePath).outputStream().use { inputStream }

                    player.setDataSource(filePath)
                    player.prepare()
                    player.start()
                } catch (e: IOException) {
                    Log.i("AMIRA00000", e.toString())
                } catch (e: IllegalStateException) {
                    Log.i("AMIRA00000", e.toString())
                }
            }
        }
    }
</code>```

I am also having my google-service.json file included in the app

but I am getting the following error

```<code>java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:134)
at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:119)
at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:91)
at com.google.api.gax.core.GoogleCredentialsProvider.getCredentials(GoogleCredentialsProvider.java:67)
at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:135)
at com.google.cloud.texttospeech.v1.stub.GrpcTextToSpeechStub.create(GrpcTextToSpeechStub.java:74)
at com.google.cloud.texttospeech.v1.stub.TextToSpeechStubSettings.createStub(TextToSpeechStubSettings.java:100)
at com.google.cloud.texttospeech.v1.TextToSpeechClient.<init>(TextToSpeechClient.java:128)
at com.google.cloud.texttospeech.v1.TextToSpeechClient.create(TextToSpeechClient.java:109)
at com.google.cloud.texttospeech.v1.TextToSpeechClient.create(TextToSpeechClient.java:101)
at com.sbs16.ensofia.view.main.MainFragment$setupBinding$3$$special$$inlined$let$lambda$2.invokeSuspend(MainFragment.kt:186)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)
</code>```

I am also having another json file thathave private key and other credential settings but I do not know how to use it

答:
I'm not an Android developer, but my feeling is that you shouldn't call the TextToSpeech directly from your Android app. You should call it through a backend (On AppEngine for example, or on Firebase Functions).

This backend is authenticated by the TextToSpeech API, and your Android client is authenticated on your backend.

Thereby, you can control who use your app, and your TextToSpeech feature. In any case, never put the service account secret key file in your app, either anybody that download you app can steal the key and perform call on the service account behalf and you will pay the bill!

Body:
I am trying to build an app that use google speech cloud api in android kotlin

here is my code

launch {
             googleTextToSpeech = TextToSpeechClient.create()
             googleTextToSpeech?.let {
             viewModel.speakGoogle(googleTextToSpeech!!, totalMessage, player)
          }
       }

 fun speakGoogle(textToSpeech: com.google.cloud.texttospeech.v1.TextToSpeechClient, message: String, player: MediaPlayer) {

        val filePath = Environment.getExternalStorageDirectory().absolutePath + "/google_" + System.currentTimeMillis() + ".mp3"

        launch {

            var msg = android.text.Html.fromHtml(message).toString()
            msg = msg.replace("\"", "")

            var input = SynthesisInput.newBuilder().setText(msg).build()
            var voice = VoiceSelectionParams.newBuilder().setLanguageCode("en-US").setSsmlGender(SsmlVoiceGender.FEMALE).build()
            var audio = AudioConfig.newBuilder().setAudioEncoding(AudioEncoding.MP3).build()

            var response = textToSpeech.synthesizeSpeech(input, voice, audio)

            response?.let {

                try {
                    val inputStream = response.audioContent.toByteArray()

                    File(filePath).outputStream().use { inputStream }

                    player.setDataSource(filePath)
                    player.prepare()
                    player.start()
                } catch (e: IOException) {
                    Log.i("AMIRA00000", e.toString())
                } catch (e: IllegalStateException) {
                    Log.i("AMIRA00000", e.toString())
                }
            }
        }
    }

I am also having my google-service.json file included in the app

but I am getting the following error

java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:134)
at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:119)
at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:91)
at com.google.api.gax.core.GoogleCredentialsProvider.getCredentials(GoogleCredentialsProvider.java:67)
at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:135)
at com.google.cloud.texttospeech.v1.stub.GrpcTextToSpeechStub.create(GrpcTextToSpeechStub.java:74)
at com.google.cloud.texttospeech.v1.stub.TextToSpeechStubSettings.createStub(TextToSpeechStubSettings.java:100)
at com.google.cloud.texttospeech.v1.TextToSpeechClient.<init>(TextToSpeechClient.java:128)
at com.google.cloud.texttospeech.v1.TextToSpeechClient.create(TextToSpeechClient.java:109)
at com.google.cloud.texttospeech.v1.TextToSpeechClient.create(TextToSpeechClient.java:101)
at com.sbs16.ensofia.view.main.MainFragment$setupBinding$3$$special$$inlined$let$lambda$2.invokeSuspend(MainFragment.kt:186)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:742)

I am also having another json file thathave private key and other credential settings but I do not know how to use it


问:
How would I find the row and column length of this matrix? (Python)
I'm given a matrix from a file that looks like this:

```<code>1 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0

0 0 0 0 1 1 0 1 0 0 1 0 0 0 0 0

0 0 1 1 0 0 0 1 0 0 1 0 0 1 0 0

0 0 1 1 0 0 0 1 0 1 0 0 0 1 0 0

0 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0

0 0 1 0 1 0 0 1 0 1 1 1 1 1 0 0

0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0

0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 1 0 0 0 0 1 1 1 0 0 1 0

0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0

1 1 1 1 1 0 0 1 1 1 0 0 0 0 G 0
</code>```

The goal is to be able to read in the matrix to another function and also find the row and column length. I'm also not trying to import any additional libraries. Here's what I have so far:

```<code>    with open('matrix.txt','r') as txt:
        data = txt.readlines()

    for row in data:
        print(row)
        for column in row:
            print(column)
</code>```

Body:
I'm given a matrix from a file that looks like this:

1 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0

0 0 0 0 1 1 0 1 0 0 1 0 0 0 0 0

0 0 1 1 0 0 0 1 0 0 1 0 0 1 0 0

0 0 1 1 0 0 0 1 0 1 0 0 0 1 0 0

0 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0

0 0 1 0 1 0 0 1 0 1 1 1 1 1 0 0

0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0

0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 1 0 0 0 0 1 1 1 0 0 1 0

0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0

1 1 1 1 1 0 0 1 1 1 0 0 0 0 G 0

The goal is to be able to read in the matrix to another function and also find the row and column length. I'm also not trying to import any additional libraries. Here's what I have so far:

    with open('matrix.txt','r') as txt:
        data = txt.readlines()

    for row in data:
        print(row)
        for column in row:
            print(column)

Body:
with open('matrix.txt','r') as txt:
    data = txt.readlines()

data=[l.strip() for l in data if len(l)>1]
print (data)
['1 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0',
 '0 0 0 0 1 1 0 1 0 0 1 0 0 0 0 0',
 '0 0 1 1 0 0 0 1 0 0 1 0 0 1 0 0',
 '0 0 1 1 0 0 0 1 0 1 0 0 0 1 0 0',
 '0 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0',
 '0 0 1 0 1 0 0 1 0 1 1 1 1 1 0 0',
 '0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0',
 '0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0',
 '0 0 0 0 1 0 0 0 0 1 1 1 0 0 1 0',
 '0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0',
 '1 1 1 1 1 0 0 1 1 1 0 0 0 0 G 0']

print("length of the row is:",len(data))
print("length of the columns is:",len(data[0].split()))

length of the row is: 11
length of the columns is: 16


问:
in graphite server - actuator/metrics/http.server.requests count not updating
I have a spring boot project up and running. I have also configured dependency for micrometer-registry-graphite in pom file. And I have installed graphite using docker (downloaded latest version - 1.1.6) and it is running in localhost:80

When I hit the below url it properly shows the hit count.
http://localhost:5080/api/v1/actuator/metrics/http.server.requests?tag=uri:/queue/{queueId}&tag=status:200

Below is the response,

```<code>{
    "name": "http.server.requests",
    "description": null,
    "baseUnit": "milliseconds",
    "measurements": [
        {
            "statistic": "COUNT",
            "value": 29.0
        },
        {
            "statistic": "TOTAL_TIME",
            "value": 942.520949
        },
        {
            "statistic": "MAX",
            "value": 0.0
        }
    ],
    "availableTags": [
        {
            "tag": "exception",
            "values": [
                "None"
            ]
        },
        {
            "tag": "method",
            "values": [
                "GET"
            ]
        },
        {
            "tag": "outcome",
            "values": [
                "SUCCESS"
            ]
        }
    ]
}
</code>```

When I navigate to Graphite Browser, I'm not able to get the count value which I got previously using actuator/metrics url. [We can see the service's url queue/queueId is transformed to some hierarchy form].
And I can see different hierarchical structure (attached the image), why it is showing under exception, None and other unrelated hierarchy. Can someone please explain this and I'm in need of solution to get the hit count in graphite server.

Spring boot version: 2.2.4 RELEASE and
  micrometer-registry-graphite version: 1.3.2

答: I have wrongly pointing my graphite server with port-80 in bootstrap.yml. But port-80 listening fo nginx, where it should point to port-2004 which is listening for carbon receiver. After this change in bootstrap.yml I'm able to resolve this issue.

Body:
I have a spring boot project up and running. I have also configured dependency for micrometer-registry-graphite in pom file. And I have installed graphite using docker (downloaded latest version - 1.1.6) and it is running in localhost:80

When I hit the below url it properly shows the hit count.
http://localhost:5080/api/v1/actuator/metrics/http.server.requests?tag=uri:/queue/{queueId}&tag=status:200

Below is the response,

{
    "name": "http.server.requests",
    "description": null,
    "baseUnit": "milliseconds",
    "measurements": [
        {
            "statistic": "COUNT",
            "value": 29.0
        },
        {
            "statistic": "TOTAL_TIME",
            "value": 942.520949
        },
        {
            "statistic": "MAX",
            "value": 0.0
        }
    ],
    "availableTags": [
        {
            "tag": "exception",
            "values": [
                "None"
            ]
        },
        {
            "tag": "method",
            "values": [
                "GET"
            ]
        },
        {
            "tag": "outcome",
            "values": [
                "SUCCESS"
            ]
        }
    ]
}

When I navigate to Graphite Browser, I'm not able to get the count value which I got previously using actuator/metrics url. [We can see the service's url queue/queueId is transformed to some hierarchy form].
And I can see different hierarchical structure (attached the image), why it is showing under exception, None and other unrelated hierarchy. Can someone please explain this and I'm in need of solution to get the hit count in graphite server.

Spring boot version: 2.2.4 RELEASE and
  micrometer-registry-graphite version: 1.3.2


问:
Date of birth restriction
I want to restrict my date picker dialog to select a minimum of 18 years of age</p>

```<code>    val c = Calendar.getInstance()
    val year = c.get(Calendar.YEAR)
    val month = c.get(Calendar.MONTH)
    val day = c.get(Calendar.DAY_OF_MONTH)

    val abc = findViewById<Button>(R.id.birth)

    abc.setOnClickListener {
        DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, mYear, mMonth, mDay ->
            date.setText("" + mDay +"/" + mMonth +"/" + mYear)
        }, year, month, day).show()
   }
}
</code>```

答:
use below</p>

```<code>  val year = c.get(Calendar.YEAR,-18)
</code>```

Title: Date of birth restriction

Body:
I want to restrict my date picker dialog to select a minimum of 18 years of age

    val c = Calendar.getInstance()
    val year = c.get(Calendar.YEAR)
    val month = c.get(Calendar.MONTH)
    val day = c.get(Calendar.DAY_OF_MONTH)

    val abc = findViewById<Button>(R.id.birth)

    abc.setOnClickListener {
        DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, mYear, mMonth, mDay ->
            date.setText("" + mDay +"/" + mMonth +"/" + mYear)
        }, year, month, day).show()
   }
}

Body:
use below

  val year = c.get(Calendar.YEAR,-18)


问:
Matplotlib scatter plot how to give same color for same size
I am having two arrays and a difference arrays of first two arrays

```<code>X = [1, 5, 63, 77, 103, 148, 156, 177, 183]
Y = [3, 46, 65, 87, 129, 150, 166, 181, 186]
Diff  = [ 2 41  2 10 26  2 10  4  3  3]
</code>```

How to plot a scatter plot for this data with x,y,diff where the same difference value show same color using matplotlib in python?

答:
You should use 'c' parameter to color the differences.
Please see the below code:

```<code>X = [1, 5, 63, 77, 103, 148, 156, 177, 183]
Y = [3, 46, 65, 87, 129, 150, 166, 181, 186]
Diff  = [ 2, 41, 2, 10, 26, 2, 10, 4, 3]

import matplotlib.pyplot as plt
plt.scatter(X,Y,c=Diff)
</code>```

Body:
I am having two arrays and a difference arrays of first two arrays

X = [1, 5, 63, 77, 103, 148, 156, 177, 183]
Y = [3, 46, 65, 87, 129, 150, 166, 181, 186]
Diff  = [ 2 41  2 10 26  2 10  4  3  3]

How to plot a scatter plot for this data with x,y,diff where the same difference value show same color using matplotlib in python?

Body:
You should use 'c' parameter to color the differences.
Please see the below code:

X = [1, 5, 63, 77, 103, 148, 156, 177, 183]
Y = [3, 46, 65, 87, 129, 150, 166, 181, 186]
Diff  = [ 2, 41, 2, 10, 26, 2, 10, 4, 3]

import matplotlib.pyplot as plt
plt.scatter(X,Y,c=Diff)


问:
search values using like clause on alias column
I have table which contain comma separated string I want to perform like query on 'name' column  but 'name' is comma separated so it will not retrieve data easily so I am using replace to eliminate comma and than perform like query on alias column ,but It is not working.is there any way to perform like query on comma separated string

Table:

```<code>id        name

i         school,education
</code>```

mysql query :

```<code>    SELECT id,name, lower((REPLACE(name, ',', ''))) as test FROM `list`
    where test like '%education%'
</code>```

答:
You should seriously avoid storing CSV data into single table columns as you are currently doing.  That being said, here is one possible workaround:

```<code>SELECT id, name
FROM list
WHERE CONCAT(',', LOWER(name), ',') LIKE '%,education,%';
</code>```

The idea behind the above trick is to build a CSV name string looking something like:

```<code>,A,B,C,D,
</code>```

That is, every single name value is always surrounded by comma boundaries on both sides.  Then, we only need to check that ,somename, be present in this CSV string.

Body:
I have table which contain comma separated string I want to perform like query on 'name' column  but 'name' is comma separated so it will not retrieve data easily so I am using replace to eliminate comma and than perform like query on alias column ,but It is not working.is there any way to perform like query on comma separated string

Table:

id        name

i         school,education

mysql query :

    SELECT id,name, lower((REPLACE(name, ',', ''))) as test FROM `list`
    where test like '%education%'

Body:
You should seriously avoid storing CSV data into single table columns as you are currently doing.  That being said, here is one possible workaround:

SELECT id, name
FROM list
WHERE CONCAT(',', LOWER(name), ',') LIKE '%,education,%';

The idea behind the above trick is to build a CSV name string looking something like:

,A,B,C,D,

That is, every single name value is always surrounded by comma boundaries on both sides.  Then, we only need to check that ,somename, be present in this CSV string.


问:
Is it possible and how to implement selects using Jackcess?
I'm trying to find out if it is possible to use select in the jackcess (v3.0.0).
I have a database from which I would like to display items in the range from x to y. It is possible to write this in jackcess? I search in documentation of jackces something about queries but only what i find is something like this - public List<String> getFromTables() but don't know how to implement's it.
Before, i used ucanaccess library, but this one table didn't want to show the results and only displayed warnings.

The samplest select i need to write:

```<code>select MAX(X_ID+1) from TABLENAME t1 where X_ID> 500000 and X_ID< 1000000"
            + "and not exists (select 1 from TABLENAME t2 where t2.X_ID=t1.X_ID+1)";
</code>```

Does anyone know how to do this?

答:
Jackcess does not provide any support for executing selects like this on the data. The "query" in the documentation likely refer to the fact that MS Access DB can contain defined queries that can be the base for more advanced functionality in access itself.

Jackcess mostly only provides a simple read/write interface, so you will probably look for some ODBC-JDBC driver/bridge to allow executing normal JDBC queries.

Also http://ucanaccess.sourceforge.net/site.html sounds interesting, although I did not try it myself yet.

Body:
I'm trying to find out if it is possible to use select in the jackcess (v3.0.0).
I have a database from which I would like to display items in the range from x to y. It is possible to write this in jackcess? I search in documentation of jackces something about queries but only what i find is something like this - public List<String> getFromTables() but don't know how to implement's it.
Before, i used ucanaccess library, but this one table didn't want to show the results and only displayed warnings.

The samplest select i need to write:

select MAX(X_ID+1) from TABLENAME t1 where X_ID> 500000 and X_ID< 1000000"
            + "and not exists (select 1 from TABLENAME t2 where t2.X_ID=t1.X_ID+1)";

Does anyone know how to do this?


问:
googlesheets script is not formatting my content correctly
My googlesheet script is not formatting my content correctly. Can someone help me out?  Here is my script.

```<code>function NewIssue() {
  var spreadsheet = SpreadsheetApp.getActive();
  var cell = spreadsheet.getCurrentCell();
  var user = Session.getActiveUser().getEmail().substring(0, 2).toUpperCase();
  var oldContent = cell.getValue();
  var newContent1 = '********************ISSUE********************\n';
  var newContent2 = 'Group:\n\nDescription:\n\nExpected Results:\n\nActual Results:\n\nTest Results:\n\nTest Data:\n\n\n';
  var space = " ";

  //Keep the format of the old content and add format to newContent1
  var newStyles = [{
    start: 0,
    end: newContent1.length,
    style: SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor("red").build()
  }];
  var richTextValue = cell.getRichTextValue();
  var offset = newContent1.length + newContent2.length + space.length;
  var oldContent = richTextValue.getText();
  if (oldContent.length > 0) {
    richTextValue.getRuns().forEach(function(e) {
      newStyles.push({
        start: offset + e.getStartIndex(),
        end: offset + e.getEndIndex(),
        style: e.getTextStyle()
      });
    });
  }

  var d = new Date();
  var richText = SpreadsheetApp.newRichTextValue().setText(user + "_" + d.dateNow() + "_" + d.timeNow() + "\n" + newContent1 + newContent2 + space + oldContent);
  newStyles.forEach(function(e) {richText.setTextStyle(e.start, e.end, e.style)});
  cell.setRichTextValue(richText.build());

  Date.prototype.timeNow = function ()
{
     return ((this.getHours() < 10)?"0":"") + ((this.getHours()>12)?(this.getHours()-12):this.getHours()) +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() + ((this.getHours()>=12)?('pm'):'am');
}
// Returns the current date with formatting like: 6.16.19
Date.prototype.dateNow = function ()

{
     return (this.getMonth()+1 +"."+ this.getDate() +"."+ this.getYear().toString().substr(-2));
}

}
</code>```

When running the above script, I get the following:

image1

I want it to look like this:

image2

I want user, date, time to be all black and non bold as
AO_2.19.20_11:57pm

I want ********************ISSUE******************** to be all red and bold.

I can't figure out how to make this happen.  Any suggestions will be helpful.

答:
You want to give the text styles of the red ForegroundColor and bold to only ********************ISSUE******************** of newContent1.

You don't want to change the text style to newContent2 and user + "_" + d.dateNow() + "_" + d.timeNow() + "\n".

You want to add the old value in the cell to the last value of newContent2 and user + "_" + d.dateNow() + "_" + d.timeNow() + "\n" + newContent1 + newContent2.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification points:

In your script, the start index and end index of newContent1 is not correct. Because user + "_" + d.dateNow() + "_" + d.timeNow() + "\n" is added by setText(user + "_" + d.dateNow() + "_" + d.timeNow() + "\n" + newContent1 + newContent2 + space + oldContent).

In this modification, it declares user + "_" + d.dateNow() + "_" + d.timeNow() + "\n" as newContent0. And the start and end indexes of each value are set.

When you want to give the default text style to the values except for newContent1, in this case, it is required to give null as the style.

When above points are reflected to your script, it becomes as follows.

Modified script:

```<code>function NewIssue() {
  Date.prototype.timeNow = function () {
     return ((this.getHours() < 10)?"0":"") + ((this.getHours()>12)?(this.getHours()-12):this.getHours()) +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() + ((this.getHours()>=12)?('pm'):'am');
  }
  Date.prototype.dateNow = function (){
    return (this.getMonth()+1 +"."+ this.getDate() +"."+ this.getYear().toString().substr(-2));
  }

  var spreadsheet = SpreadsheetApp.getActive();
  var cell = spreadsheet.getCurrentCell();
  var user = Session.getActiveUser().getEmail().substring(0, 2).toUpperCase();
  var oldContent = cell.getValue();
  var d = new Date();
  var newContent0 = user + "_" + d.dateNow() + "_" + d.timeNow() + "\n";  // Added
  var newContent1 = '********************ISSUE********************\n';
  var newContent2 = 'Group:\n\nDescription:\n\nExpected Results:\n\nActual Results:\n\nTest Results:\n\nTest Data:\n\n\n';
  var space = " ";
  var content0Len = newContent0.length;  // Added
  var content1Len = newContent1.length;  // Added
  var content2Len = newContent2.length;  // Added
  var newStyles = [  // Modified
    {start: 0, end: content0Len, style: null},
    {start: content0Len, end: content0Len + content1Len, style: SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor("red").build()},
    {start: content0Len + content1Len, end: content0Len + content1Len + content2Len, style: null}
  ];
  var richTextValue = cell.getRichTextValue();
  var offset = newContent0.length + newContent1.length + newContent2.length + space.length;
  var oldContent = richTextValue.getText();
  if (oldContent.length > 0) {
    richTextValue.getRuns().forEach(function(e) {
      newStyles.push({
        start: offset + e.getStartIndex(),
        end: offset + e.getEndIndex(),
        style: e.getTextStyle()
      });
    });
  }
  var richText = SpreadsheetApp.newRichTextValue().setText(newContent0 + newContent1 + newContent2 + space + oldContent);  // Modified
  newStyles.forEach(function(e) {richText.setTextStyle(e.start, e.end, e.style)});
  cell.setRichTextValue(richText.build());
}
</code>```

Note:

In your sample output image, it seems that user + "_" + d.dateNow() + "_" + d.timeNow() has 2 line breaks. If it's so, please modify as follows.

From

```<code>var newContent0 = user + "_" + d.dateNow() + "_" + d.timeNow() + "\n";
</code>```

To

```<code>var newContent0 = user + "_" + d.dateNow() + "_" + d.timeNow() + "\n\n";
</code>```

Reference:

Class RichTextValueBuilder

If I misunderstood your question and this was not the direction you want, I apologize.

Body:
My googlesheet script is not formatting my content correctly. Can someone help me out?  Here is my script.

function NewIssue() {
  var spreadsheet = SpreadsheetApp.getActive();
  var cell = spreadsheet.getCurrentCell();
  var user = Session.getActiveUser().getEmail().substring(0, 2).toUpperCase();
  var oldContent = cell.getValue();
  var newContent1 = '********************ISSUE********************\n';
  var newContent2 = 'Group:\n\nDescription:\n\nExpected Results:\n\nActual Results:\n\nTest Results:\n\nTest Data:\n\n\n';
  var space = " ";

  //Keep the format of the old content and add format to newContent1
  var newStyles = [{
    start: 0,
    end: newContent1.length,
    style: SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor("red").build()
  }];
  var richTextValue = cell.getRichTextValue();
  var offset = newContent1.length + newContent2.length + space.length;
  var oldContent = richTextValue.getText();
  if (oldContent.length > 0) {
    richTextValue.getRuns().forEach(function(e) {
      newStyles.push({
        start: offset + e.getStartIndex(),
        end: offset + e.getEndIndex(),
        style: e.getTextStyle()
      });
    });
  }

  var d = new Date();
  var richText = SpreadsheetApp.newRichTextValue().setText(user + "_" + d.dateNow() + "_" + d.timeNow() + "\n" + newContent1 + newContent2 + space + oldContent);
  newStyles.forEach(function(e) {richText.setTextStyle(e.start, e.end, e.style)});
  cell.setRichTextValue(richText.build());

  Date.prototype.timeNow = function ()
{
     return ((this.getHours() < 10)?"0":"") + ((this.getHours()>12)?(this.getHours()-12):this.getHours()) +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() + ((this.getHours()>=12)?('pm'):'am');
}
// Returns the current date with formatting like: 6.16.19
Date.prototype.dateNow = function ()

{
     return (this.getMonth()+1 +"."+ this.getDate() +"."+ this.getYear().toString().substr(-2));
}

}

When running the above script, I get the following:

image1

I want it to look like this:

image2

I want user, date, time to be all black and non bold as
AO_2.19.20_11:57pm

I want ********************ISSUE******************** to be all red and bold.

I can't figure out how to make this happen.  Any suggestions will be helpful.

Body:
You want to give the text styles of the red ForegroundColor and bold to only ********************ISSUE******************** of newContent1.

You don't want to change the text style to newContent2 and user + "_" + d.dateNow() + "_" + d.timeNow() + "\n".

You want to add the old value in the cell to the last value of newContent2 and user + "_" + d.dateNow() + "_" + d.timeNow() + "\n" + newContent1 + newContent2.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification points:

In your script, the start index and end index of newContent1 is not correct. Because user + "_" + d.dateNow() + "_" + d.timeNow() + "\n" is added by setText(user + "_" + d.dateNow() + "_" + d.timeNow() + "\n" + newContent1 + newContent2 + space + oldContent).

In this modification, it declares user + "_" + d.dateNow() + "_" + d.timeNow() + "\n" as newContent0. And the start and end indexes of each value are set.

When you want to give the default text style to the values except for newContent1, in this case, it is required to give null as the style.

When above points are reflected to your script, it becomes as follows.

Modified script:

function NewIssue() {
  Date.prototype.timeNow = function () {
     return ((this.getHours() < 10)?"0":"") + ((this.getHours()>12)?(this.getHours()-12):this.getHours()) +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() + ((this.getHours()>=12)?('pm'):'am');
  }
  Date.prototype.dateNow = function (){
    return (this.getMonth()+1 +"."+ this.getDate() +"."+ this.getYear().toString().substr(-2));
  }

  var spreadsheet = SpreadsheetApp.getActive();
  var cell = spreadsheet.getCurrentCell();
  var user = Session.getActiveUser().getEmail().substring(0, 2).toUpperCase();
  var oldContent = cell.getValue();
  var d = new Date();
  var newContent0 = user + "_" + d.dateNow() + "_" + d.timeNow() + "\n";  // Added
  var newContent1 = '********************ISSUE********************\n';
  var newContent2 = 'Group:\n\nDescription:\n\nExpected Results:\n\nActual Results:\n\nTest Results:\n\nTest Data:\n\n\n';
  var space = " ";
  var content0Len = newContent0.length;  // Added
  var content1Len = newContent1.length;  // Added
  var content2Len = newContent2.length;  // Added
  var newStyles = [  // Modified
    {start: 0, end: content0Len, style: null},
    {start: content0Len, end: content0Len + content1Len, style: SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor("red").build()},
    {start: content0Len + content1Len, end: content0Len + content1Len + content2Len, style: null}
  ];
  var richTextValue = cell.getRichTextValue();
  var offset = newContent0.length + newContent1.length + newContent2.length + space.length;
  var oldContent = richTextValue.getText();
  if (oldContent.length > 0) {
    richTextValue.getRuns().forEach(function(e) {
      newStyles.push({
        start: offset + e.getStartIndex(),
        end: offset + e.getEndIndex(),
        style: e.getTextStyle()
      });
    });
  }
  var richText = SpreadsheetApp.newRichTextValue().setText(newContent0 + newContent1 + newContent2 + space + oldContent);  // Modified
  newStyles.forEach(function(e) {richText.setTextStyle(e.start, e.end, e.style)});
  cell.setRichTextValue(richText.build());
}

Note:

In your sample output image, it seems that user + "_" + d.dateNow() + "_" + d.timeNow() has 2 line breaks. If it's so, please modify as follows.

From

var newContent0 = user + "_" + d.dateNow() + "_" + d.timeNow() + "\n";

To

var newContent0 = user + "_" + d.dateNow() + "_" + d.timeNow() + "\n\n";

Reference:

Class RichTextValueBuilder

If I misunderstood your question and this was not the direction you want, I apologize.


问:
Create folder with current date as name in powershell
I am writing a powershell script. I would like to know how to create a folder with current date as name. The folder name should be "yyyy-MM-dd" (acording to the .NET custom format strings).

I know that to create folder I need to use this command:

```<code>New-Item -ItemType directory -Path "some path"
</code>```

A possible solution could be (if I want to create the folder in the same directory as the script is:

```<code>$date = Get-Date
$date = $date.ToString("yyyy-MM-dd")
New-Item -ItemType directory -Path ".\$date"
</code>```

Is there a way to chain the commands so I do not need to create the variable?

答:
```<code>$datecurrent = get-date -Format dd-MM-yy

New-Item -ItemType directory -Path ".\$datecurrent"
</code>```

Body:
I am writing a powershell script. I would like to know how to create a folder with current date as name. The folder name should be "yyyy-MM-dd" (acording to the .NET custom format strings).

I know that to create folder I need to use this command:

New-Item -ItemType directory -Path "some path"

A possible solution could be (if I want to create the folder in the same directory as the script is:

$date = Get-Date
$date = $date.ToString("yyyy-MM-dd")
New-Item -ItemType directory -Path ".\$date"

Is there a way to chain the commands so I do not need to create the variable?


问:
How does Javascript's sort() work?
How does the following code sort this array to be in numerical order?

```<code>var array=[25, 8, 7, 41]

array.sort(function(a,b){
  return a - b
})
</code>```

I know that if the result of the computation is...

Less than 0: "a" is sorted to be a lower index than "b".

Zero: "a" and "b" are considered equal, and no sorting is performed.

Greater than 0: "b" is sorted to be a lower index than "a".

Is the array sort callback function called many times during the course of the sort?

If so, I'd like to know which two numbers are passed into the function each time. I assumed it first took "25"(a) and "8"(b), followed by "7"(a) and "41"(b), so:

25(a) - 8(b) = 17 (greater than zero, so sort "b" to be a lower index than "a"): 8, 25

7(a) - 41(b) = -34 (less than zero, so sort "a" to be a lower index than "b": 7, 41

How are the two sets of numbers then sorted in relation to one another?

Please help a struggling newbie!

答:
Deeply Knowledge

If the result is negative a is sorted before b.

If the result is positive b is sorted before a.

If the result is 0 no changes are done with the sort order of the two values.

NOTE:

This code is the view inside of the sort method step by step.

OUTPUT:

let arr = [90, 1, 20, 14, 3, 55];
var sortRes = [];
var copy = arr.slice();  //create duplicate array
var inc = 0; //inc meant increment
copy.sort((a, b) => {
 sortRes[inc] = [ a, b, a-b ];
 inc += 1;
 return a - b;
});
var p = 0;
for (var i = 0; i < inc; i++) {
 copy = arr.slice();
 copy.sort((a, b) => {
  p += 1;
  if (p <= i ) {
   return a - b;
  }
  else{
   return false;
  }
 });
 p = 0;
 console.log(copy +' \t a: '+ sortRes[i][0] +' \tb: '+ sortRes[i][1] +'\tTotal: '+ sortRes[i][2]);
}```

Title: How does Javascript's sort() work?

Body:
How does the following code sort this array to be in numerical order?

var array=[25, 8, 7, 41]

array.sort(function(a,b){
  return a - b
})

I know that if the result of the computation is...

Less than 0: "a" is sorted to be a lower index than "b".

Zero: "a" and "b" are considered equal, and no sorting is performed.

Greater than 0: "b" is sorted to be a lower index than "a".

Is the array sort callback function called many times during the course of the sort?

If so, I'd like to know which two numbers are passed into the function each time. I assumed it first took "25"(a) and "8"(b), followed by "7"(a) and "41"(b), so:

25(a) - 8(b) = 17 (greater than zero, so sort "b" to be a lower index than "a"): 8, 25

7(a) - 41(b) = -34 (less than zero, so sort "a" to be a lower index than "b": 7, 41

How are the two sets of numbers then sorted in relation to one another?

Please help a struggling newbie!


问:
django-rest-auth handling expired confirmation email
I am using django-rest-auth and django-allauth to handle user authentication in my rest api. When a user tries to verify their email after the link has expired, I get an unpleasant error page.

Please, how can I display a better error page or send a message telling them it wasn't successful because the link had expired?

答:
write your own custom exception handler</p>

```<code>from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)

# Now add the HTTP status code to the response.
if response is not None:
    response.data['status_code'] = response.status_code

return response
</code>```

Body:
write your own custom exception handler

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)

# Now add the HTTP status code to the response.
if response is not None:
    response.data['status_code'] = response.status_code

return response


问:
Trying to send a json encoded array from php to a js file, "Unexpected end of input"
So im trying to send an object array to a js function anytime I push a button.

```<code><button onclick="actualizarProcesos(<?php echo json_encode($p_array)?>);">X</button>
</code>```

I've made sure my json isnt sending any weird characters as it is mostly int except for the object attribute "name" which is string.

That function is in a different js file:

```<code>   function actualizarProcesos(p_array){
    var p = JSON.parse(p_array);
}
</code>```

At the moment I'm trying to send make sure the function is receiving the data but it keeps throwing the error Uncaught SyntaxError: Unexpected end of inputSo I'm stuck trying to find out how to fix the error.

I plan afterwards on sending that array to another php file using ajax, something like this:

```<code>$.ajax({
            type: "POST",
            url: "post.php",
            data: JSON.stringify(values),
            success: function(data){
                alert(data)
            }
    });
</code>```

This is the full json I'm trying to send

```<code>[{"name":"A","t_arrival":7,"t_est":25,"state":1,"pages":5,"mem_data":[[1,8,13,5,0,1],[0,0,0,0,0,0],[1,11,17,3,1,1],[1,12,16,4,0,1],[0,0,0,0,0,0]],"t_rem":25,"t_wait":0,"rem_quantum":0},{"name":"B","t_arrival":6,"t_est":13,"state":2,"pages":4,"mem_data":[[0,0,0,0,0,0],[1,9,16,5,0,1],[1,7,14,6,1,0],[0,0,0,0,0,0]],"t_rem":13,"t_wait":0,"rem_quantum":0},{"name":"C","t_arrival":8,"t_est":37,"state":3,"pages":3,"mem_data":[[1,9,12,2,0,0],[0,0,0,0,0,0],[1,13,21,7,0,1]],"t_rem":37,"t_wait":0,"rem_quantum":0}]
</code>```

答:
you can do it by this way</p>

```<code><p id="test" style="display:none"><?php echo json_encode($p_array); ?></p>

<button onclick="actualizarProcesos(test)" id="">X</button>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function actualizarProcesos(test){
var p_array = $('#test').html();
var p = JSON.parse(p_array);

alert(p);
</code>```

<p>}
   </p>

Body:
So im trying to send an object array to a js function anytime I push a button.

<button onclick="actualizarProcesos(<?php echo json_encode($p_array)?>);">X</button>

I've made sure my json isnt sending any weird characters as it is mostly int except for the object attribute "name" which is string.

That function is in a different js file:

   function actualizarProcesos(p_array){
    var p = JSON.parse(p_array);
}

At the moment I'm trying to send make sure the function is receiving the data but it keeps throwing the error Uncaught SyntaxError: Unexpected end of inputSo I'm stuck trying to find out how to fix the error.

I plan afterwards on sending that array to another php file using ajax, something like this:

$.ajax({
            type: "POST",
            url: "post.php",
            data: JSON.stringify(values),
            success: function(data){
                alert(data)
            }
    });

This is the full json I'm trying to send

[{"name":"A","t_arrival":7,"t_est":25,"state":1,"pages":5,"mem_data":[[1,8,13,5,0,1],[0,0,0,0,0,0],[1,11,17,3,1,1],[1,12,16,4,0,1],[0,0,0,0,0,0]],"t_rem":25,"t_wait":0,"rem_quantum":0},{"name":"B","t_arrival":6,"t_est":13,"state":2,"pages":4,"mem_data":[[0,0,0,0,0,0],[1,9,16,5,0,1],[1,7,14,6,1,0],[0,0,0,0,0,0]],"t_rem":13,"t_wait":0,"rem_quantum":0},{"name":"C","t_arrival":8,"t_est":37,"state":3,"pages":3,"mem_data":[[1,9,12,2,0,0],[0,0,0,0,0,0],[1,13,21,7,0,1]],"t_rem":37,"t_wait":0,"rem_quantum":0}]

Body:
you can do it by this way

<p id="test" style="display:none"><?php echo json_encode($p_array); ?></p>

<button onclick="actualizarProcesos(test)" id="">X</button>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function actualizarProcesos(test){
var p_array = $('#test').html();
var p = JSON.parse(p_array);

alert(p);

}


问:
How to migrate from SQLite database to Room about "String" field?
I am trying to migrate a database from SQLite to Room in Android.

But I got an error:

Migration didn't properly handle:
  staff_message(db.entity.StaffMessage).
       Expected:
      TableInfo{message=Column{name='message', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0,
  defaultValue='null'}}
       Found:
      TableInfo{message=Column{name='message', type='String', affinity='1', notNull=true, primaryKeyPosition=0,
  defaultValue='null'}}

Origin table was written like:

```<code>db.execSQL("CREATE TABLE IF NOT EXISTS staff_message( " +
                    "message String NOT NULL");");
</code>```

And new table scheme is like:

```<code>@Entity(tableName = "staff_message")
data class StaffMessage(
        @ColumnInfo(name = "message") val message: String
)
</code>```

The only difference is the type.

String VS. TEXT

How can I migrate this table to the Room?

答:
I should have migrated by myself.

```<code>static final Migration MIGRATION_3_4 = new Migration(3, 4) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        // Create the new table
        database.execSQL(
                "CREATE TABLE users_new (userid TEXT, username TEXT, last_update INTEGER, PRIMARY KEY(userid))");
// Copy the data
        database.execSQL(
                "INSERT INTO users_new (userid, username, last_update) SELECT userid, username, last_update FROM users");
// Remove the old table
        database.execSQL("DROP TABLE users");
// Change the table name to the correct one
        database.execSQL("ALTER TABLE users_new RENAME TO users");
    }
};
</code>```

Thanks to @Raghunandan

Body:
I am trying to migrate a database from SQLite to Room in Android.

But I got an error:

Migration didn't properly handle:
  staff_message(db.entity.StaffMessage).
       Expected:
      TableInfo{message=Column{name='message', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0,
  defaultValue='null'}}
       Found:
      TableInfo{message=Column{name='message', type='String', affinity='1', notNull=true, primaryKeyPosition=0,
  defaultValue='null'}}

Origin table was written like:

db.execSQL("CREATE TABLE IF NOT EXISTS staff_message( " +
                    "message String NOT NULL");");

And new table scheme is like:

@Entity(tableName = "staff_message")
data class StaffMessage(
        @ColumnInfo(name = "message") val message: String
)

The only difference is the type.

String VS. TEXT

How can I migrate this table to the Room?

Body:
I should have migrated by myself.

static final Migration MIGRATION_3_4 = new Migration(3, 4) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        // Create the new table
        database.execSQL(
                "CREATE TABLE users_new (userid TEXT, username TEXT, last_update INTEGER, PRIMARY KEY(userid))");
// Copy the data
        database.execSQL(
                "INSERT INTO users_new (userid, username, last_update) SELECT userid, username, last_update FROM users");
// Remove the old table
        database.execSQL("DROP TABLE users");
// Change the table name to the correct one
        database.execSQL("ALTER TABLE users_new RENAME TO users");
    }
};

Thanks to @Raghunandan


问:
Can yarn be used to fetch packages from an on-prem Azure Artifacts repository?
We use on-prem Azure DevOps Server 2019.

In my project dir I have the following .yarnrc file:

```<code>C:\xyz\tip\ui\EngagementCommon.UI [master ≡ +3 ~1 -1 !]> cat .\.yarnrc
registry "http://tfsserver.xyz.com:8080/tfs/DefaultCollection/_packaging/platform_catalog/npm/registry/"
C:\xyz\tip\ui\EngagementCommon.UI [master ≡ +3 ~1 -1 !]>
</code>```

Where platform_catalog is the name of the feed:

But when I run yarn I get this:

```<code>C:\xyz\tip\ui\EngagementCommon.UI [master ≡ +3 ~1 -1 !]> yarn
yarn install v1.22.0
[1/4] Resolving packages...
error Couldn't find package "@platform/catalog" on the "npm" registry.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
C:\xyz\tip\ui\EngagementCommon.UI [master ≡ +3 ~1 -1 !]> cat .\package.json|sls catalog

    "@platform/catalog": "^1.0.71",

C:\xyz\tip\ui\EngagementCommon.UI [master ≡ +3 ~1 -1 !]>
</code>```

As you can see on the image, the package is there on our Azure Artifacts npm feed, however yarn does not seem to inspect it at all, despite .yarnrc file asking to.

What am I missing?

EDIT 1

The --verbose flag helps to understand what is going on:

```<code>yarn --verbose
yarn install v1.22.0
verbose 0.1522596 Checking for configuration file "C:\\xyz\\tip\\UI\\EngagementCommon.UI\\.npmrc".
verbose 0.153013699 Found configuration file "C:\\xyz\\tip\\UI\\EngagementCommon.UI\\.npmrc".
verbose 0.154160399 Checking for configuration file "C:\\Users\\mkharitonov\\.npmrc".
verbose 0.15491 Found configuration file "C:\\Users\\mkharitonov\\.npmrc".
verbose 0.1557871 Checking for configuration file "C:\\Program Files\\nodejs\\etc\\npmrc".
verbose 0.1565483 Checking for configuration file "C:\\xyz\\tip\\UI\\EngagementCommon.UI\\.npmrc".
verbose 0.157282799 Found configuration file "C:\\xyz\\tip\\UI\\EngagementCommon.UI\\.npmrc".
verbose 0.158124099 Checking for configuration file "C:\\xyz\\tip\\UI\\.npmrc".
verbose 0.158851699 Checking for configuration file "C:\\xyz\\tip\\.npmrc".
verbose 0.159633599 Checking for configuration file "C:\\xyz\\.npmrc".
verbose 0.1642738 Checking for configuration file "C:\\xyz\\tip\\UI\\EngagementCommon.UI\\.yarnrc".
verbose 0.1689344 Checking for configuration file "C:\\Users\\mkharitonov\\.yarnrc".
verbose 0.1744512 Found configuration file "C:\\Users\\mkharitonov\\.yarnrc".
verbose 0.175591399 Checking for configuration file "C:\\Program Files\\nodejs\\etc\\yarnrc".
verbose 0.1781605 Checking for configuration file "C:\\xyz\\tip\\UI\\EngagementCommon.UI\\.yarnrc".
verbose 0.1789498 Checking for configuration file "C:\\xyz\\tip\\UI\\.yarnrc".
verbose 0.1796986 Checking for configuration file "C:\\xyz\\tip\\.yarnrc".
verbose 0.1804712 Checking for configuration file "C:\\xyz\\.yarnrc".
verbose 0.1856058 current time: 2020-02-20T15:19:28.047Z
[1/4] Resolving packages...
verbose 0.268615799 Performing "GET" request to "http://tfsserver.xyz.com:8080/tfs/DefaultCollection/_packaging/platform_catalog/npm/registry/@platform%2fcatalog".
verbose 0.2893787 Request "http://tfsserver.xyz.com:8080/tfs/DefaultCollection/_packaging/platform_catalog/npm/registry/@platform%2fcatalog" finished with status code 401.
verbose 0.3031119 Error: Couldn't find package "@platform/catalog" on the "npm" registry.
    at MessageError.ExtendableBuiltin (C:\Program Files (x86)\Yarn\lib\cli.js:721:66)
    at new MessageError (C:\Program Files (x86)\Yarn\lib\cli.js:750:123)
    at NpmResolver.<anonymous> (C:\Program Files (x86)\Yarn\lib\cli.js:50302:15)
    at Generator.next (<anonymous>)
    at step (C:\Program Files (x86)\Yarn\lib\cli.js:310:30)
    at C:\Program Files (x86)\Yarn\lib\cli.js:321:13
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
error Couldn't find package "@platform/catalog" on the "npm" registry.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
</code>```

Yarn gets 401 talking to the custom repository, but it silently swallows it and proceeds to check the package in the npm, where it certainly does not exist. The fact that yarn does not surface 401 is a usability issue, I think.

答:
Can yarn be used to fetch packages from an on-prem Azure Artifacts
  repository?

Answer this question, don't worry, TFS support yarn to consume the artifacts.

The error message more relevant with yarn itself.

Here some troubleshooting method you can try:

1) Whether it has any network issues, e.g Firewall and etc.

2) Confirm that there's no different registry set for any of .yarnrc or .npmrc files.

If the issue still occurred after above checked, you can add --verbose to command to get detailed execution log and analyze it.

Body:
We use on-prem Azure DevOps Server 2019.

In my project dir I have the following .yarnrc file:

C:\xyz\tip\ui\EngagementCommon.UI [master ≡ +3 ~1 -1 !]> cat .\.yarnrc
registry "http://tfsserver.xyz.com:8080/tfs/DefaultCollection/_packaging/platform_catalog/npm/registry/"
C:\xyz\tip\ui\EngagementCommon.UI [master ≡ +3 ~1 -1 !]>

Where platform_catalog is the name of the feed:

But when I run yarn I get this:

C:\xyz\tip\ui\EngagementCommon.UI [master ≡ +3 ~1 -1 !]> yarn
yarn install v1.22.0
[1/4] Resolving packages...
error Couldn't find package "@platform/catalog" on the "npm" registry.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
C:\xyz\tip\ui\EngagementCommon.UI [master ≡ +3 ~1 -1 !]> cat .\package.json|sls catalog

    "@platform/catalog": "^1.0.71",

C:\xyz\tip\ui\EngagementCommon.UI [master ≡ +3 ~1 -1 !]>

As you can see on the image, the package is there on our Azure Artifacts npm feed, however yarn does not seem to inspect it at all, despite .yarnrc file asking to.

What am I missing?

EDIT 1

The --verbose flag helps to understand what is going on:

yarn --verbose
yarn install v1.22.0
verbose 0.1522596 Checking for configuration file "C:\\xyz\\tip\\UI\\EngagementCommon.UI\\.npmrc".
verbose 0.153013699 Found configuration file "C:\\xyz\\tip\\UI\\EngagementCommon.UI\\.npmrc".
verbose 0.154160399 Checking for configuration file "C:\\Users\\mkharitonov\\.npmrc".
verbose 0.15491 Found configuration file "C:\\Users\\mkharitonov\\.npmrc".
verbose 0.1557871 Checking for configuration file "C:\\Program Files\\nodejs\\etc\\npmrc".
verbose 0.1565483 Checking for configuration file "C:\\xyz\\tip\\UI\\EngagementCommon.UI\\.npmrc".
verbose 0.157282799 Found configuration file "C:\\xyz\\tip\\UI\\EngagementCommon.UI\\.npmrc".
verbose 0.158124099 Checking for configuration file "C:\\xyz\\tip\\UI\\.npmrc".
verbose 0.158851699 Checking for configuration file "C:\\xyz\\tip\\.npmrc".
verbose 0.159633599 Checking for configuration file "C:\\xyz\\.npmrc".
verbose 0.1642738 Checking for configuration file "C:\\xyz\\tip\\UI\\EngagementCommon.UI\\.yarnrc".
verbose 0.1689344 Checking for configuration file "C:\\Users\\mkharitonov\\.yarnrc".
verbose 0.1744512 Found configuration file "C:\\Users\\mkharitonov\\.yarnrc".
verbose 0.175591399 Checking for configuration file "C:\\Program Files\\nodejs\\etc\\yarnrc".
verbose 0.1781605 Checking for configuration file "C:\\xyz\\tip\\UI\\EngagementCommon.UI\\.yarnrc".
verbose 0.1789498 Checking for configuration file "C:\\xyz\\tip\\UI\\.yarnrc".
verbose 0.1796986 Checking for configuration file "C:\\xyz\\tip\\.yarnrc".
verbose 0.1804712 Checking for configuration file "C:\\xyz\\.yarnrc".
verbose 0.1856058 current time: 2020-02-20T15:19:28.047Z
[1/4] Resolving packages...
verbose 0.268615799 Performing "GET" request to "http://tfsserver.xyz.com:8080/tfs/DefaultCollection/_packaging/platform_catalog/npm/registry/@platform%2fcatalog".
verbose 0.2893787 Request "http://tfsserver.xyz.com:8080/tfs/DefaultCollection/_packaging/platform_catalog/npm/registry/@platform%2fcatalog" finished with status code 401.
verbose 0.3031119 Error: Couldn't find package "@platform/catalog" on the "npm" registry.
    at MessageError.ExtendableBuiltin (C:\Program Files (x86)\Yarn\lib\cli.js:721:66)
    at new MessageError (C:\Program Files (x86)\Yarn\lib\cli.js:750:123)
    at NpmResolver.<anonymous> (C:\Program Files (x86)\Yarn\lib\cli.js:50302:15)
    at Generator.next (<anonymous>)
    at step (C:\Program Files (x86)\Yarn\lib\cli.js:310:30)
    at C:\Program Files (x86)\Yarn\lib\cli.js:321:13
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
error Couldn't find package "@platform/catalog" on the "npm" registry.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

Yarn gets 401 talking to the custom repository, but it silently swallows it and proceeds to check the package in the npm, where it certainly does not exist. The fact that yarn does not surface 401 is a usability issue, I think.