问:
How to send value to another screen in React Native with hooks?
I am building a weather app. The in-home screen of the app I fetch data from IP/read API every 5 seconds and that works fine. What I want to do now is to fetch data from IP/insert when I press the button in Links Screen and then send that value to HomeScreen. I found a lot of tutorials for that but not any with react hooks.

This is my HomeScreen.js file:

```<code>import React, {useState, useEffect} from 'react';
import {Image, Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View, StatusBar, ActivityIndicator} from 'react-native';
import { Icon } from 'react-native-elements';
import * as Font from 'expo-font'

HomeScreen.navigationOptions = {
  header: null,
};

export default function HomeScreen() {
  const [city, setCity] = useState('--');
  const [countrycode, setCountryCode] = useState('0');
  const [icon, setIcon] = useState('ios-sunny');
  const [date, setDate] = useState('00.00');
  const [temperature, setTemperature] = useState('0');
  const [wind, setWind] = useState('0');
  const [humidity, setHumidity] = useState('0');
  const [temperatureInside, setTemperatureInside] = useState('0');
  const [humidityInside, setHumidityInside] = useState('0');
  const [pressure, setPressure] = useState('0');
  const [spinner, setSpinner] = useState(false);
  const [fontLoaded, setFontLoaded] = useState(false);
  useEffect(() => {
    Font.loadAsync({
      'raleway-regular': require('../assets/fonts/Raleway-Regular.ttf'),
      'raleway-light': require('../assets/fonts/Raleway-Light.ttf'),
    });
    setFontLoaded(true);
    const interval = setInterval(() => {
      fetch('http://192.168.88.253:5000/read')
    .then((response) => response.json())
    .then((responseJson) => {
      setCity(responseJson.city);
      setCountryCode(responseJson.countrycode);
      //setIcon
      if(responseJson.description === 'clear sky'){
        setIcon('ios-sunny');
      }if(responseJson.description === 'few clouds' || responseJson.description === 'scattered clouds',responseJson.description === 'broken clouds'){
        setIcon('ios-partly-sunny');
      }if(responseJson.description === 'light rain' || responseJson.description === 'shgower rain' || responseJson.description === 'shower rain'){
        setIcon('md-rainy');
      }if(responseJson.description === 'thunderstorm'){
        setIcon('md-thunderstorm');
      }if(responseJson.description === 'snow'){
        setIcon('md-snow');
      }if(responseJson.description === 'mist'){
        setIcon('md-partly-sunny');
      }
      setTemperature(responseJson.temperature);
      setWind(responseJson.wind_speed);
      setHumidity(responseJson.humidity);
      setTemperatureInside(responseJson.temperatureInside);
      setHumidityInside(responseJson.humidityInside);
      setDate(responseJson.time);
      setTemperatureInside(responseJson.temperatureInside);
      setHumidityInside(responseJson.humidityInside);
      setPressure(responseJson.pressure);
    })
    .catch((error) => {
      console.warn(error);
    });
    }, 5000);
    return () => clearInterval(interval);
  }, []);

  return (
    <View style={styles.container}>
      <View style={styles.upperContainer}>
        <View style={styles.oneVertical}>
          <Text style={styles.city}>{city.toUpperCase()}, </Text>
          <Text style={styles.countrycode}>{countrycode}</Text>
        </View>
        <View style={styles.twoVertical}>
          <Icon name={icon} type='ionicon' iconStyle={styles.icon}></Icon>
          <Text style={styles.date}>{date}</Text>
        </View>
        <View style={styles.threeVertical}>
          <View style={styles.tempView}>
            <Text style={styles.temperature}>{Math.round(temperature)}°</Text>
          </View>
          <View style={styles.otherView}>
            <View style={styles.humidityTemp}>
              <Icon iconStyle={styles.otherViewIcon} type='ionicon' name='ios-jet'></Icon>
              <Text style={{color:'#fff', fontSize:20, fontFamily: 'raleway-regular',}}> {Math.round(wind)} km/h</Text>
            </View>
            <View style={styles.humidityTemp}>
              <Icon iconStyle={styles.otherViewIcon} type='ionicon' name='ios-water'></Icon>
              <Text style={{color:'#fff', fontSize:20, fontFamily: 'raleway-regular',}}>  {humidity} %</Text>
            </View>
          </View>
        </View>
      </View>
      <View style={styles.lowerContainer}>
        <View style={styles.ChamberView}>
          <Text style={{color:'#fff', fontFamily: 'raleway-regular',}}>TEMP.</Text>
          <Icon iconStyle={{color:'#fff', fontSize:30, marginVertical:10, }} type='ionicon' name='md-thermometer'></Icon>
          <Text style={{color:'#fff', fontSize:20, fontFamily: 'raleway-regular',}}>{temperatureInside}°</Text>
        </View>
        <View style={styles.ChamberView}>
          <Text style={{color:'#fff', fontFamily: 'raleway-regular',}}>VLAGA</Text>
          <Icon iconStyle={{color:'#fff', fontSize:30, marginVertical:10, }} type='ionicon' name='ios-water'></Icon>
          <Text style={{color:'#fff', fontSize:20, fontFamily: 'raleway-regular',}}>{humidityInside} %</Text>
        </View>
        <View style={styles.ChamberView}>
          <Text style={{color:'#fff', fontFamily: 'raleway-regular',}}>TLAK</Text>
          <Icon iconStyle={{color:'#fff', fontSize:30, marginVertical:10, }} type='ionicon' name='ios-hand'></Icon>
          <Text style={{color:'#fff', fontSize:20, fontFamily: 'raleway-regular',}}>{pressure} bar</Text>
        </View>
      </View>
    </View>
  );
}
</code>```

and there is LinksScreen.js file:

```<code>import React, {useState} from 'react';
import { View, StyleSheet, Alert, ActivityIndicator } from 'react-native';
import {SearchBar, Button} from 'react-native-elements';
import MapView from 'react-native-maps';
import Spinner from 'react-native-loading-spinner-overlay';
import { NavigationEvents } from 'react-navigation';

export default function LinksScreen() {
  const [spinner, setSpinner] = useState(false);
  const [search, setSearch] = useState('');
  const handleChange = event => {
    setSearch(event);
  }
  const [latitudePress, setLatitude] = useState('46.54306');
  const [longitudePress,setLongitude] = useState('14.96917');
  function addMarkerAndRequest(e){
    setLatitude(e.nativeEvent.coordinate.latitude);
    setLongitude(e.nativeEvent.coordinate.longitude);
    const coords = {
      latitude: e.nativeEvent.coordinate.latitude,
      longitude: e.nativeEvent.coordinate.longitude
    };
    Alert.alert(
      'Sprememba mesta',
      'Stanje v komori se bo spremenilo. Ali ste prepričani?',
      [
        {
          text: 'NE',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
        {
          text: 'OK',
          onPress: () => {
            fetch(`http://192.168.88.253:5000/insert/${coords.longitude}/${coords.latitude}`);
            setSpinner(true);
            setTimeout(() => setSpinner(false), 2000);
          }
        },
      ],
      {cancelable: false},
    )
  }

  return (
    <View style={styles.container}>
      <Spinner
          visible={spinner}
          textStyle={styles.spinnerTextStyle}
      />
      <SearchBar
        containerStyle={{borderColor:'#eee', borderWidth:1}}
        placeholder="Vnesi mesto.."
        onChangeText={(e) => {setSearch(e)}}
        value={search}
        platform='android'
      />
      <MapView
        style={{width:'100%', height:'80%'}}
        initialRegion={{
        latitude: Number(latitudePress),
        longitude: Number(longitudePress),
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        }}
        onPress={ (event) => addMarkerAndRequest(event) }
      >
        <MapView.Marker
            coordinate={{latitude: Number(latitudePress),
            longitude: Number(longitudePress)}}
            title={`ZŠ: ${latitudePress}, ZD: ${longitudePress}`}
         />
      </MapView>
      <Button
        onPress={()=>Alert.alert(
          'Sprememba mesta',
          'Stanje v komori se bo spremenilo. Ali ste prepričani?',
          [
            {
              text: 'NE',
              onPress: () => console.log('Cancel Pressed'),
              style: 'cancel',
            },
            {
              text: 'OK',
              onPress: () => {
                fetch(`http://192.168.88.253:5000/insertcity/${search}`);
                setSpinner(true);
                setTimeout(() => setSpinner(false), 2000);
                setSearch('');
              }
            },
          ],
          {cancelable: false},
        )}
        title='POTRDI'
      ></Button>
    </View>
  );
}

LinksScreen.navigationOptions = {
  title: 'Zemljevid',
};
</code>```

答: You need to use either context api or redux to achieve this.</p>

Body:
I am building a weather app. The in-home screen of the app I fetch data from IP/read API every 5 seconds and that works fine. What I want to do now is to fetch data from IP/insert when I press the button in Links Screen and then send that value to HomeScreen. I found a lot of tutorials for that but not any with react hooks.

This is my HomeScreen.js file:

import React, {useState, useEffect} from 'react';
import {Image, Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View, StatusBar, ActivityIndicator} from 'react-native';
import { Icon } from 'react-native-elements';
import * as Font from 'expo-font'

HomeScreen.navigationOptions = {
  header: null,
};

export default function HomeScreen() {
  const [city, setCity] = useState('--');
  const [countrycode, setCountryCode] = useState('0');
  const [icon, setIcon] = useState('ios-sunny');
  const [date, setDate] = useState('00.00');
  const [temperature, setTemperature] = useState('0');
  const [wind, setWind] = useState('0');
  const [humidity, setHumidity] = useState('0');
  const [temperatureInside, setTemperatureInside] = useState('0');
  const [humidityInside, setHumidityInside] = useState('0');
  const [pressure, setPressure] = useState('0');
  const [spinner, setSpinner] = useState(false);
  const [fontLoaded, setFontLoaded] = useState(false);
  useEffect(() => {
    Font.loadAsync({
      'raleway-regular': require('../assets/fonts/Raleway-Regular.ttf'),
      'raleway-light': require('../assets/fonts/Raleway-Light.ttf'),
    });
    setFontLoaded(true);
    const interval = setInterval(() => {
      fetch('http://192.168.88.253:5000/read')
    .then((response) => response.json())
    .then((responseJson) => {
      setCity(responseJson.city);
      setCountryCode(responseJson.countrycode);
      //setIcon
      if(responseJson.description === 'clear sky'){
        setIcon('ios-sunny');
      }if(responseJson.description === 'few clouds' || responseJson.description === 'scattered clouds',responseJson.description === 'broken clouds'){
        setIcon('ios-partly-sunny');
      }if(responseJson.description === 'light rain' || responseJson.description === 'shgower rain' || responseJson.description === 'shower rain'){
        setIcon('md-rainy');
      }if(responseJson.description === 'thunderstorm'){
        setIcon('md-thunderstorm');
      }if(responseJson.description === 'snow'){
        setIcon('md-snow');
      }if(responseJson.description === 'mist'){
        setIcon('md-partly-sunny');
      }
      setTemperature(responseJson.temperature);
      setWind(responseJson.wind_speed);
      setHumidity(responseJson.humidity);
      setTemperatureInside(responseJson.temperatureInside);
      setHumidityInside(responseJson.humidityInside);
      setDate(responseJson.time);
      setTemperatureInside(responseJson.temperatureInside);
      setHumidityInside(responseJson.humidityInside);
      setPressure(responseJson.pressure);
    })
    .catch((error) => {
      console.warn(error);
    });
    }, 5000);
    return () => clearInterval(interval);
  }, []);

  return (
    <View style={styles.container}>
      <View style={styles.upperContainer}>
        <View style={styles.oneVertical}>
          <Text style={styles.city}>{city.toUpperCase()}, </Text>
          <Text style={styles.countrycode}>{countrycode}</Text>
        </View>
        <View style={styles.twoVertical}>
          <Icon name={icon} type='ionicon' iconStyle={styles.icon}></Icon>
          <Text style={styles.date}>{date}</Text>
        </View>
        <View style={styles.threeVertical}>
          <View style={styles.tempView}>
            <Text style={styles.temperature}>{Math.round(temperature)}°</Text>
          </View>
          <View style={styles.otherView}>
            <View style={styles.humidityTemp}>
              <Icon iconStyle={styles.otherViewIcon} type='ionicon' name='ios-jet'></Icon>
              <Text style={{color:'#fff', fontSize:20, fontFamily: 'raleway-regular',}}> {Math.round(wind)} km/h</Text>
            </View>
            <View style={styles.humidityTemp}>
              <Icon iconStyle={styles.otherViewIcon} type='ionicon' name='ios-water'></Icon>
              <Text style={{color:'#fff', fontSize:20, fontFamily: 'raleway-regular',}}>  {humidity} %</Text>
            </View>
          </View>
        </View>
      </View>
      <View style={styles.lowerContainer}>
        <View style={styles.ChamberView}>
          <Text style={{color:'#fff', fontFamily: 'raleway-regular',}}>TEMP.</Text>
          <Icon iconStyle={{color:'#fff', fontSize:30, marginVertical:10, }} type='ionicon' name='md-thermometer'></Icon>
          <Text style={{color:'#fff', fontSize:20, fontFamily: 'raleway-regular',}}>{temperatureInside}°</Text>
        </View>
        <View style={styles.ChamberView}>
          <Text style={{color:'#fff', fontFamily: 'raleway-regular',}}>VLAGA</Text>
          <Icon iconStyle={{color:'#fff', fontSize:30, marginVertical:10, }} type='ionicon' name='ios-water'></Icon>
          <Text style={{color:'#fff', fontSize:20, fontFamily: 'raleway-regular',}}>{humidityInside} %</Text>
        </View>
        <View style={styles.ChamberView}>
          <Text style={{color:'#fff', fontFamily: 'raleway-regular',}}>TLAK</Text>
          <Icon iconStyle={{color:'#fff', fontSize:30, marginVertical:10, }} type='ionicon' name='ios-hand'></Icon>
          <Text style={{color:'#fff', fontSize:20, fontFamily: 'raleway-regular',}}>{pressure} bar</Text>
        </View>
      </View>
    </View>
  );
}

and there is LinksScreen.js file:

import React, {useState} from 'react';
import { View, StyleSheet, Alert, ActivityIndicator } from 'react-native';
import {SearchBar, Button} from 'react-native-elements';
import MapView from 'react-native-maps';
import Spinner from 'react-native-loading-spinner-overlay';
import { NavigationEvents } from 'react-navigation';

export default function LinksScreen() {
  const [spinner, setSpinner] = useState(false);
  const [search, setSearch] = useState('');
  const handleChange = event => {
    setSearch(event);
  }
  const [latitudePress, setLatitude] = useState('46.54306');
  const [longitudePress,setLongitude] = useState('14.96917');
  function addMarkerAndRequest(e){
    setLatitude(e.nativeEvent.coordinate.latitude);
    setLongitude(e.nativeEvent.coordinate.longitude);
    const coords = {
      latitude: e.nativeEvent.coordinate.latitude,
      longitude: e.nativeEvent.coordinate.longitude
    };
    Alert.alert(
      'Sprememba mesta',
      'Stanje v komori se bo spremenilo. Ali ste prepričani?',
      [
        {
          text: 'NE',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
        {
          text: 'OK',
          onPress: () => {
            fetch(`http://192.168.88.253:5000/insert/${coords.longitude}/${coords.latitude}`);
            setSpinner(true);
            setTimeout(() => setSpinner(false), 2000);
          }
        },
      ],
      {cancelable: false},
    )
  }

  return (
    <View style={styles.container}>
      <Spinner
          visible={spinner}
          textStyle={styles.spinnerTextStyle}
      />
      <SearchBar
        containerStyle={{borderColor:'#eee', borderWidth:1}}
        placeholder="Vnesi mesto.."
        onChangeText={(e) => {setSearch(e)}}
        value={search}
        platform='android'
      />
      <MapView
        style={{width:'100%', height:'80%'}}
        initialRegion={{
        latitude: Number(latitudePress),
        longitude: Number(longitudePress),
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        }}
        onPress={ (event) => addMarkerAndRequest(event) }
      >
        <MapView.Marker
            coordinate={{latitude: Number(latitudePress),
            longitude: Number(longitudePress)}}
            title={`ZŠ: ${latitudePress}, ZD: ${longitudePress}`}
         />
      </MapView>
      <Button
        onPress={()=>Alert.alert(
          'Sprememba mesta',
          'Stanje v komori se bo spremenilo. Ali ste prepričani?',
          [
            {
              text: 'NE',
              onPress: () => console.log('Cancel Pressed'),
              style: 'cancel',
            },
            {
              text: 'OK',
              onPress: () => {
                fetch(`http://192.168.88.253:5000/insertcity/${search}`);
                setSpinner(true);
                setTimeout(() => setSpinner(false), 2000);
                setSearch('');
              }
            },
          ],
          {cancelable: false},
        )}
        title='POTRDI'
      ></Button>
    </View>
  );
}

LinksScreen.navigationOptions = {
  title: 'Zemljevid',
};


来源: stackexchange

问:
Why is there a syntax error - at 0 in this Couchbase N1QL query?
I have a document in Couchbase:

```<code>{
  "ResponseMessage": {
    "0": {
      "y2": "1",
      "y1": "2"
    },
    "1": {
      "x1": "499",
      "x2": "O"
    },
    "CacheTimeOut": "0",
    "ObjectID": "6632 87d7"
  }
}
</code>```

when I execute this query,

```<code>select ResponseMessage.0.y1 from `my-bucket`
</code>```

I receive this response:

```<code>[
  {
    "code": 3000,
    "msg": "syntax error - at 0",
    "query": "select ResponseMessage.0.y1 from `my-bucket`"
  }
]
</code>```

If "0" is "a0" instead, it is does not return an error.

Is it possible to write reference the "0" JSON key name in a N1QL query?

答:
0 is a literal number (in both JSON and N1QL). Therefore, you will need to escape it.

The solution is :

```<code>select ResponseMessage.`0`.y1 from `my-bucket`
</code>```

Use this character ` (backtick) to escape

https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/identifiers.html

ContentLicense: CC BY-SA 4.0

Body:
I have a document in Couchbase:

{
  "ResponseMessage": {
    "0": {
      "y2": "1",
      "y1": "2"
    },
    "1": {
      "x1": "499",
      "x2": "O"
    },
    "CacheTimeOut": "0",
    "ObjectID": "6632 87d7"
  }
}

when I execute this query,

select ResponseMessage.0.y1 from `my-bucket`

I receive this response:

[
  {
    "code": 3000,
    "msg": "syntax error - at 0",
    "query": "select ResponseMessage.0.y1 from `my-bucket`"
  }
]

If "0" is "a0" instead, it is does not return an error.

Is it possible to write reference the "0" JSON key name in a N1QL query?

Body:
0 is a literal number (in both JSON and N1QL). Therefore, you will need to escape it.

The solution is :

select ResponseMessage.`0`.y1 from `my-bucket`

Use this character ` (backtick) to escape

https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/identifiers.html


问:
How to create a left navbar with bootstrap?
How to create a left navbar with bootstrap ?
I did it

```<code><nav class="btn-group-vertical float-left navbar">
    <button routerLink="product/home" routerLinkActive="is-active" class="btn btn-outline-dark">Home</button>
    <button routerLink="product/favorite" routerLinkActive="is-active" class="btn btn-outline-dark">Favorite</button>
</nav>
</code>```

But the problem that i see it as unexpected

I want that all hoe work be with good position
but use bootstrap 4 well

Thank for help :-)

答:
As I understood,you're trying to create side navbar and want to show component on the right side.In this case when you call a component by routerLink,a specific css should be applied to each called component in order to see them on the right.

```<code><style>
      router-outlet + * {
        float:right;
        position:absolute;
}
</style>
</code>```

This css code will be applied for each component brought by router-outlet.If you want you can add some margin.

Here you can see what I've done for you :

https://stackblitz.com/edit/angular-router-basic-example-pgr1tv?file=index.html

Body:
How to create a left navbar with bootstrap ?
I did it

    <button routerLink="product/home" routerLinkActive="is-active" class="btn btn-outline-dark">Home</button>
    <button routerLink="product/favorite" routerLinkActive="is-active" class="btn btn-outline-dark">Favorite</button>

But the problem that i see it as unexpected

I want that all hoe work be with good position
but use bootstrap 4 well

Thank for help :-)

Body:
As I understood,you're trying to create side navbar and want to show component on the right side.In this case when you call a component by routerLink,a specific css should be applied to each called component in order to see them on the right.

<style>
      router-outlet + * {
        float:right;
        position:absolute;
}
</style>

This css code will be applied for each component brought by router-outlet.If you want you can add some margin.

Here you can see what I've done for you :

https://stackblitz.com/edit/angular-router-basic-example-pgr1tv?file=index.html


问:
I have Problem with AJAX post using laravel
I am working on simple private chat application ,when i send message to selected user so message is sending perfectly but meassage is showing  on browser  relaod i have used ajax but unfortunatly ajax is not working please help me thanks.

Controller

```<code>             public function chataction(REQUEST $request)
             {
             $chat_message = $request->get('message');
             $from_user_id=Auth::user()->id;
             $to_user_id =$request->get('myid');
             $user = Auth::user();
             $response = $user->Chats()->create([

             'chat_message'=>  $chat_message,
             'from_user_id' => $from_user_id,
             'to_user_id'  => $to_user_id,
              ]);
             $response = array(
              'status' => 'success',
              'msg' => 'Setting created successfully',
              );
              return Response::json($response);

              }
</code>```

html view

```<code>          <!-- /.card-body -->
          <div class="card-footer">
          <form id="myform" action="{{route('chat.action')}}" method="post">
          {{csrf_field()}}
          <input type="hidden" name="myid" value="{{$single_chat->id}}" >
          <div class="input-group">
          <input type="text" id="chatmessage" name="message" placeholder="Type Message
          ..." class="form-control">
          <span class="input-group-append">
          <button type="submit" name="btnsubmit" id="btnsubmit"  class="btn btn-
          primary">Send</button>
          </span>
          </div>
          </form>
          </div>
          <!-- /.card-footer-->
         </div>
</code>```

Ajax

```<code>             <script type="text/javascript">
             $(document).ready(function() {

             $("#btnsubmit").click(function(){
             event.preventDefault();
             var form_data = $("#chatmessage").val();
             $.ajax({
             url:"{{ route('chat.action') }}",
              data:   {
              "_token": "{{ csrf_token() }}",
              "form_data": form_data
              }
             dataType:"json",
             success:function(data)
            {

            }

            });
            });
            });

            </script>
</code>```

Route

```<code>        Route::post('chat/action','HomeController@chataction')->name('chat.action');
</code>```

答:
You can also use the .reload() method inside an Ajax success callback function.</p>

```<code>success:function(data)
{
   setInterval('location.reload()', 3000);
}
</code>```

Body:
I am working on simple private chat application ,when i send message to selected user so message is sending perfectly but meassage is showing  on browser  relaod i have used ajax but unfortunatly ajax is not working please help me thanks.

Controller

             public function chataction(REQUEST $request)
             {
             $chat_message = $request->get('message');
             $from_user_id=Auth::user()->id;
             $to_user_id =$request->get('myid');
             $user = Auth::user();
             $response = $user->Chats()->create([

             'chat_message'=>  $chat_message,
             'from_user_id' => $from_user_id,
             'to_user_id'  => $to_user_id,
              ]);
             $response = array(
              'status' => 'success',
              'msg' => 'Setting created successfully',
              );
              return Response::json($response);

              }

html view

          <form id="myform" action="{{route('chat.action')}}" method="post">
          {{csrf_field()}}
          <input type="hidden" name="myid" value="{{$single_chat->id}}" >

          <input type="text" id="chatmessage" name="message" placeholder="Type Message
          ..." class="form-control">

          <button type="submit" name="btnsubmit" id="btnsubmit"  class="btn btn-
          primary">Send</button>

          </form>

Ajax

Route

        Route::post('chat/action','HomeController@chataction')->name('chat.action');

Body:
You can also use the .reload() method inside an Ajax success callback function.

success:function(data)
{
   setInterval('location.reload()', 3000);
}


问:
Cosine similarity between sentences using Google news corpus word2vec model python
I am trying to find cosine similarity between two sentences of unequal length using word2vec google news corpus but i am getting the error: AxisError: axis 1 is out of bounds for array of dimension 1

Below is my code:

```<code>from gensim.models import KeyedVectors
EMBEDDING_FILE = '/root/input/GoogleNews-vectors-negative300.bin.gz' # from above
word2vec = KeyedVectors.load_word2vec_format(EMBEDDING_FILE, binary=True)

vocab = word2vec.vocab.keys()
wordsInVocab = len(vocab)

import numpy as np

def sent_vectorizer(sent, model):
    sent_vec = np.zeros(50)
    numw = 0
    for w in sent:
        try:
            vc=model[w]
            vc=vc[0:50]

            sent_vec = np.add(sent_vec, vc)
            numw+=1
        except:
            pass
    return sent_vec / np.sqrt(sent_vec.dot(sent_vec))

a = sent_vectorizer('Football is played in Brazil',word2vec)
b =sent_vectorizer('Cricket is played in India',word2vec)

word2vec.cosine_similarities(b,a)
</code>```

I am converting the sentences into vectors as cosine_similarity takes vector array as input.
How do i resolve this?

答:
word2vec.cosine_similarities takes in a vector as first argument and a matrix as second argument.

You are passing vector for second argument. Add one more axis or use np.stack to stack a and b together.

Body:
I am trying to find cosine similarity between two sentences of unequal length using word2vec google news corpus but i am getting the error: AxisError: axis 1 is out of bounds for array of dimension 1

Below is my code:

from gensim.models import KeyedVectors
EMBEDDING_FILE = '/root/input/GoogleNews-vectors-negative300.bin.gz' # from above
word2vec = KeyedVectors.load_word2vec_format(EMBEDDING_FILE, binary=True)

vocab = word2vec.vocab.keys()
wordsInVocab = len(vocab)

import numpy as np

def sent_vectorizer(sent, model):
    sent_vec = np.zeros(50)
    numw = 0
    for w in sent:
        try:
            vc=model[w]
            vc=vc[0:50]

            sent_vec = np.add(sent_vec, vc)
            numw+=1
        except:
            pass
    return sent_vec / np.sqrt(sent_vec.dot(sent_vec))

a = sent_vectorizer('Football is played in Brazil',word2vec)
b =sent_vectorizer('Cricket is played in India',word2vec)

word2vec.cosine_similarities(b,a)

I am converting the sentences into vectors as cosine_similarity takes vector array as input.
How do i resolve this?


问:
What should be the tenant admin url while creating SPO site collections in PnP PowerShell
I am using PnP PowerShell commandlets to create Site collection in SPO. I understand that we need to first connect to Tenant admin site before creating site collections as below

$tenantadminUrl = "https://tenantname-admin.sharepoint.com"

Connect-PnPOnline -url $tenantadminUrl -UseWebLogin

New-PnPTenantSite -Owner $item.Owner -TimeZone $item.TimeZone -Title $item.Title -Url $siteUrl -Template $item.Template -Lcid $item.Locale -Wait

for adminUrl, can we also run the above code if the url is "https://tenantname.sharepoint.com" i.e. without "-admin" part in the url?

Sample code of PnP PowerShell in Github uses without "-admin" part in its url(Link: https://github.com/SharePoint/PnP-PowerShell/blob/master/Samples/Provisioning.CreateSitesFromCsv/CreateSites.ps1)

$adminurl1 = "https://tenantname-admin.sharepoint.com"

$adminurl2 = "https://tenantname.sharepoint.com"

which of the above two urls is valid tenantAdmin Url?

Thanks,

答:
If you want to create site collection from the tenant, as willman's reply, the tenant admin url is "https://tenant-admin.sharepoint.com".

The following PnP PowerShell for your reference.

```<code>$tenantUrl="https://tenant-admin.sharepoint.com"
$siteOwner="admin@tenant.onmicrosoft.com"
$siteTitle="contoso"
$siteUrl="/sites/contososite"
Connect-PnPOnline $tenantUrl -UseWebLogin

Write-Host "Provisioning site collection $siteUrl" -ForegroundColor Yellow
if(Get-PnPTenantSite | where-Object -FilterScript {$_.Url -eq $siteUrl})
{
    Write-Host "Site collection $siteUrl exists. Moving to the next one." -ForegroundColor Yellow
}
# Creates new site collection.
New-PnPTenantSite -Title $siteTitle -Url $siteUrl -Owner $siteOwner -TimeZone 4 -Template STS#0 -Lcid 1033
Write-Host "SiteCollection $siteUrl successfully created." -ForegroundColor Green
</code>```

Body:
If you want to create site collection from the tenant, as willman's reply, the tenant admin url is "https://tenant-admin.sharepoint.com".

The following PnP PowerShell for your reference.

$tenantUrl="https://tenant-admin.sharepoint.com"
$siteOwner="admin@tenant.onmicrosoft.com"
$siteTitle="contoso"
$siteUrl="/sites/contososite"
Connect-PnPOnline $tenantUrl -UseWebLogin

Write-Host "Provisioning site collection $siteUrl" -ForegroundColor Yellow
if(Get-PnPTenantSite | where-Object -FilterScript {$_.Url -eq $siteUrl})
{
    Write-Host "Site collection $siteUrl exists. Moving to the next one." -ForegroundColor Yellow
}
# Creates new site collection.
New-PnPTenantSite -Title $siteTitle -Url $siteUrl -Owner $siteOwner -TimeZone 4 -Template STS#0 -Lcid 1033
Write-Host "SiteCollection $siteUrl successfully created." -ForegroundColor Green


问:
How to add Ajax response to div in html
How to append Ajax response to div in HTML

This is my ajax Code

```<code>$(document).ready(function(){
    $('.credit,.debit').change(function(){
        var value=$(this).val();
        $.ajax({
            type:"POST",
            url:"<?php echo base_url();>index.php/Transactions/getamountbyid",
            data:{id:value},
            success:function(result){
                console.log(result);
                $(".bal").html(result);
            }
        });
    });
});
</code>```

This is my controller Code

```<code>public function getamountbyid(){
    $id=$this->input->post('id');
    $this->Transaction_model->getamountbyid($id);
    print_r($data1);
}
</code>```

And THIS is my Ajax Response

```<code>Array ( [0] => stdClass Object ( [Accounts_id] => 1 [Accounts_number] => 123123123 [Account_Name] => Qualight [account_nickname] => Qualight [Address] => hyderabad [Mobile] => 9123912345 [account_type] => 1 [PAN_NO] => 1231231231 [GST_NO] => 123 [credit] => 20000.00 [debit] => [balance] => 20000.00 [Time_stamp] => 2020-02-13 18:51:49 ) )
</code>```

I want to display account debit and credit balance after selecting the account from drop down it should be display below drop down can you please help me how to append required response data to required field or div

答: if you only want to append then you need to use append() function. else Please provide the HTML as well so that I can understand your requirement and concept </p>

Title: How to add Ajax response to div in html

Body:
How to append Ajax response to div in HTML

This is my ajax Code

$(document).ready(function(){
    $('.credit,.debit').change(function(){
        var value=$(this).val();
        $.ajax({
            type:"POST",
            url:"<?php echo base_url();>index.php/Transactions/getamountbyid",
            data:{id:value},
            success:function(result){
                console.log(result);
                $(".bal").html(result);
            }
        });
    });
});

This is my controller Code

public function getamountbyid(){
    $id=$this->input->post('id');
    $this->Transaction_model->getamountbyid($id);
    print_r($data1);
}

And THIS is my Ajax Response

Array ( [0] => stdClass Object ( [Accounts_id] => 1 [Accounts_number] => 123123123 [Account_Name] => Qualight [account_nickname] => Qualight [Address] => hyderabad [Mobile] => 9123912345 [account_type] => 1 [PAN_NO] => 1231231231 [GST_NO] => 123 [credit] => 20000.00 [debit] => [balance] => 20000.00 [Time_stamp] => 2020-02-13 18:51:49 ) )

I want to display account debit and credit balance after selecting the account from drop down it should be display below drop down can you please help me how to append required response data to required field or div


问:
Specify Python tag for wheel using Poetry
I'm thinking of migrating my Python library from Pipenv with setup.py to just Poetry. Previously, in order to build my project, I would run

```<code>python setup.py sdist bdist_wheel
</code>```

For the package I'm building, the minimum supported Python version is 3.6, so I've added the following in a setup.cfg file so that this is specified in the built wheel (based on this):

```<code>[bdist_wheel]
python-tag = py36
</code>```

However, with Poetry, the poetry build comamnd is used, which ignores this section in setup.cfg and instead puts a general py3 tag on the wheel. Is there any equivalent way to get the tag onto the generated wheel using Poetry?

答:
The only config file that poetry considers is pyproject.toml. It is documented here, which should help you port all relevant info over. The particular tag that you're asking for would be the python version:

```<code>[tool.poetry]
name = "example"
version = "0.1.0"
...

[tool.poetry.dependencies]
python = "^3.6"  # having something here is mandatory for a build to work
</code>```

A wheels-build will then contain the following in example.whl/example-0.1.0.dist-info/METADATA:

```<code>...

Requires-Python: >=3.6,<4.0
...
</code>```

Body:
I'm thinking of migrating my Python library from Pipenv with setup.py to just Poetry. Previously, in order to build my project, I would run

python setup.py sdist bdist_wheel

For the package I'm building, the minimum supported Python version is 3.6, so I've added the following in a setup.cfg file so that this is specified in the built wheel (based on this):

[bdist_wheel]
python-tag = py36

However, with Poetry, the poetry build comamnd is used, which ignores this section in setup.cfg and instead puts a general py3 tag on the wheel. Is there any equivalent way to get the tag onto the generated wheel using Poetry?

Body:
The only config file that poetry considers is pyproject.toml. It is documented here, which should help you port all relevant info over. The particular tag that you're asking for would be the python version:

[tool.poetry]
name = "example"
version = "0.1.0"
...

[tool.poetry.dependencies]
python = "^3.6"  # having something here is mandatory for a build to work

A wheels-build will then contain the following in example.whl/example-0.1.0.dist-info/METADATA:

...

Requires-Python: >=3.6,<4.0
...


问:
VSCode How do I install Laravel code completions?
I'm in the process of learning Laravel 6.0 and I'm using the current version of VSCode to write my code. At the moment, my instance of VSCode doesn't offer any Laravel code completions. How do I tell VSCode to offer those completions? If there is no such setting, is there some kind of add-on for VSCode that provides code completions for Laravel? Where would I find this add-on?</p>

答:
This extension works for Laravel 6 because the features are still there.

For PHP, this extension is really great for VSCode.


问:
Site's JavaScript is not working which is loaded inside the Angular iFrame with custom headers
It is required to load a site inside an iFrame in Angular 8.
The site has several JavaScripts.
To load that site we have to send Authorization header with the request.
I could simply load a javascript site with the approach mentioned in the following blog https://stackblitz.com/edit/angular-iframe-src?file=src%2Fapp%2Fapp.component.html but with this approach, I cannot send authorization headers. So, I tried following StackOverflow answer Angular 2 - Inject custom headers on iframe. With that approach, I could successfully send the custom headers and load the site but loaded site's javascript is not working since we have to bypassSecurityTrustResourceUrl. The issue is the return type of bypassSecurityTrustResourceUrl() (SafeResourceUrl) cannot be pass to get() since it requires a string. How I can overcome this issue ?

答:
I could overcome the issue by using the sandbox element for the  as follows.

```<code><iframe #iframe width="100%" height="400px" sandbox="allow-forms allow-modals allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation"></iframe>
</code>```

I had to allow the above set of permission for the iFrame.

Body:
I could overcome the issue by using the sandbox element for the <iFrame> as follows.

<iframe #iframe width="100%" height="400px" sandbox="allow-forms allow-modals allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation"></iframe>

I had to allow the above set of permission for the iFrame.


问:
Get LatLng from Zip Code - Google Maps API
All I want is some simple example code that shows me how to obtain a latlng element from an inputted zip code OR a city/state.</p>

答:
```<code><script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
<script>
    var latitude = '';
    var longitude = '';

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode(
    {
       componentRestrictions: {
           country: 'IN',
           postalCode: '744102'
       }
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
            console.log(latitude + ", " + longitude);
        } else {
            alert("Request failed.")
        }
    });
</script>
</code>```

https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering

ContentLicense: CC BY-SA 3.0

Body:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
<script>
    var latitude = '';
    var longitude = '';

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode(
    {
       componentRestrictions: {
           country: 'IN',
           postalCode: '744102'
       }
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
            console.log(latitude + ", " + longitude);
        } else {
            alert("Request failed.")
        }
    });
</script>

https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering


问:
Why is this SQL/DDL violating the wrong Integrity constraint?
So it is showing me that the first insert is failing IC4, but it should be good to go as far as IC2 is concerned. IC2 states that 'DB guru' should be above 200--which the first entry is!

For example you'll see that the first entry on the insert list below is:

```<code>INSERT INTO Employee VALUES (10, 'Gray', 'DB guru', 240);
</code>```

But this fails IC4... why?!

How do I specify that a CONSTRAINT has to apply to only a certain categorical value like I am attempting here? Am I missing an important notion with respect to the way that CHECK is implemented? I'm really new to SQL and trying to wrap my head around this:

```<code>SPOOL ddl.out
SET ECHO ON

--
-- IMPORTANT: use the names IC1, IC2, etc. as given below.
-- --------------------------------------------------------------------
/*The following DROP command is inserted for convenience so that if you need to recompile
your code, it will drop the table (if it already exists).
*/
DROP TABLE Employee CASCADE CONSTRAINTS;
DROP TABLE Dependent CASCADE CONSTRAINTS;
--
CREATE TABLE Employee
(
id INTEGER PRIMARY KEY,
name CHAR(10) NOT NULL,
rank CHAR(10) NOT NULL,
salary INTEGER NOT NULL,
/*
IC1: The rank is one of: 'DB guru', 'DB expert', or 'DB rookie'
*/
CONSTRAINT IC1 CHECK (rank IN ('DB guru', 'DB expert', 'DB rookie')),
/*
IC2: The salary of a 'DB guru' is above 200.
*/
CONSTRAINT IC2 CHECK (rank != 'DB guru' OR salary > 200),
/*
IC3: The salary of a 'DB expert' is between 80 and 220 (inclusive).
*/
CONSTRAINT IC3 CHECK (rank != 'DB expert' OR (salary >= 80 AND salary <= 220 )),
/*
IC4: The salary of a 'DB rookie' is less than 100.
*/
CONSTRAINT IC4 CHECK (rank != 'DB rookie' OR salary < 100)
);
--
--
CREATE TABLE Dependent
(
empID INTEGER,
dependentName CHAR(20) NOT NULL,
relationship CHAR(20) NOT NULL,
PRIMARY KEY (empID, dependentName),
/*
IC5: empID must refer to an employee in the company. Also:
if an employee is deleted then his/her dependents must be deleted.
IMPORTANT: DO NOT declare this IC as DEFERRABLE.
*/
CONSTRAINT IC5 FOREIGN KEY (empID) REFERENCES Employee(id)
          ON DELETE CASCADE
);
--
-- ----------------------------------------------------------------
-- TESTING THE SCHEMA
-- ----------------------------------------------------------------
INSERT INTO Employee VALUES (10, 'Gray', 'DB guru', 240);
INSERT INTO Employee VALUES (20, 'Garland', 'DB guru', 190);
INSERT INTO Employee VALUES (30, 'Edison', 'DB expert', 210);
INSERT INTO Employee VALUES (40, 'Eckerd', 'DB expert', 70);
INSERT INTO Employee VALUES (50, 'Roberts', 'DB rookie', 110);
INSERT INTO Employee VALUES (60, 'Rush', 'DB rookie', 90);
SELECT * from Employee;
-- ----------------------------------------------------------------
INSERT INTO Dependent VALUES (10, 'Grace', 'daughter');
INSERT INTO Dependent VALUES (10, 'George', 'son');
INSERT INTO Dependent VALUES (60, 'Reba', 'daughter');
INSERT INTO Dependent VALUES (15, 'Dustin', 'son');
SELECT * FROM Dependent;
--
DELETE FROM Employee WHERE id = 10;
SELECT * From Employee;
SELECT * FROM Dependent;
--
SET ECHO OFF
SPOOL OFF

</code>```

edited: To show the working solution based on the correct answer selected below.

答:
Logical implication A->B is expressed as NOT A OR B. For example

```<code>/*
IC2: The salary of a 'DB guru' is above 200.
*/
CONSTRAINT IC2 CHECK (rank != 'DB guru' OR salary > 200),
</code>```

Body:
So it is showing me that the first insert is failing IC4, but it should be good to go as far as IC2 is concerned. IC2 states that 'DB guru' should be above 200--which the first entry is!

For example you'll see that the first entry on the insert list below is:

INSERT INTO Employee VALUES (10, 'Gray', 'DB guru', 240);

But this fails IC4... why?!

How do I specify that a CONSTRAINT has to apply to only a certain categorical value like I am attempting here? Am I missing an important notion with respect to the way that CHECK is implemented? I'm really new to SQL and trying to wrap my head around this:

SPOOL ddl.out
SET ECHO ON

--
-- IMPORTANT: use the names IC1, IC2, etc. as given below.
-- --------------------------------------------------------------------
/*The following DROP command is inserted for convenience so that if you need to recompile
your code, it will drop the table (if it already exists).
*/
DROP TABLE Employee CASCADE CONSTRAINTS;
DROP TABLE Dependent CASCADE CONSTRAINTS;
--
CREATE TABLE Employee
(
id INTEGER PRIMARY KEY,
name CHAR(10) NOT NULL,
rank CHAR(10) NOT NULL,
salary INTEGER NOT NULL,
/*
IC1: The rank is one of: 'DB guru', 'DB expert', or 'DB rookie'
*/
CONSTRAINT IC1 CHECK (rank IN ('DB guru', 'DB expert', 'DB rookie')),
/*
IC2: The salary of a 'DB guru' is above 200.
*/
CONSTRAINT IC2 CHECK (rank != 'DB guru' OR salary > 200),
/*
IC3: The salary of a 'DB expert' is between 80 and 220 (inclusive).
*/
CONSTRAINT IC3 CHECK (rank != 'DB expert' OR (salary >= 80 AND salary <= 220 )),
/*
IC4: The salary of a 'DB rookie' is less than 100.
*/
CONSTRAINT IC4 CHECK (rank != 'DB rookie' OR salary < 100)
);
--
--
CREATE TABLE Dependent
(
empID INTEGER,
dependentName CHAR(20) NOT NULL,
relationship CHAR(20) NOT NULL,
PRIMARY KEY (empID, dependentName),
/*
IC5: empID must refer to an employee in the company. Also:
if an employee is deleted then his/her dependents must be deleted.
IMPORTANT: DO NOT declare this IC as DEFERRABLE.
*/
CONSTRAINT IC5 FOREIGN KEY (empID) REFERENCES Employee(id)
          ON DELETE CASCADE
);
--
-- ----------------------------------------------------------------
-- TESTING THE SCHEMA
-- ----------------------------------------------------------------
INSERT INTO Employee VALUES (10, 'Gray', 'DB guru', 240);
INSERT INTO Employee VALUES (20, 'Garland', 'DB guru', 190);
INSERT INTO Employee VALUES (30, 'Edison', 'DB expert', 210);
INSERT INTO Employee VALUES (40, 'Eckerd', 'DB expert', 70);
INSERT INTO Employee VALUES (50, 'Roberts', 'DB rookie', 110);
INSERT INTO Employee VALUES (60, 'Rush', 'DB rookie', 90);
SELECT * from Employee;
-- ----------------------------------------------------------------
INSERT INTO Dependent VALUES (10, 'Grace', 'daughter');
INSERT INTO Dependent VALUES (10, 'George', 'son');
INSERT INTO Dependent VALUES (60, 'Reba', 'daughter');
INSERT INTO Dependent VALUES (15, 'Dustin', 'son');
SELECT * FROM Dependent;
--
DELETE FROM Employee WHERE id = 10;
SELECT * From Employee;
SELECT * FROM Dependent;
--
SET ECHO OFF
SPOOL OFF

edited: To show the working solution based on the correct answer selected below.

Body:
Logical implication A->B is expressed as NOT A OR B. For example

/*
IC2: The salary of a 'DB guru' is above 200.
*/
CONSTRAINT IC2 CHECK (rank != 'DB guru' OR salary > 200),


问:
How to close/hide the Android soft keyboard programmatically?
I have an EditText and a Button in my layout.

After writing in the edit field and clicking on the Button, I want to hide the virtual keyboard when touching outside the keyboard. I assume that this is a simple piece of code, but where can I find an example of it?

答:
When moving from fragment to fragment</p>

```<code>fun hideKeyboard(activity: Activity?): Boolean {
    val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
    if (inputManager != null) {
        val currentFocus = activity?.currentFocus
        if (currentFocus != null) {
            val windowToken = currentFocus.windowToken
            if (windowToken != null) {
                return inputManager.hideSoftInputFromWindow(windowToken, 0)
            }
        }
    }
    return false
}

fun showKeyboard(editText: EditText) {
    val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(editText.windowToken, 0)
    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0)
    editText.requestFocus()
}
</code>```

Body:
When moving from fragment to fragment

fun hideKeyboard(activity: Activity?): Boolean {
    val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
    if (inputManager != null) {
        val currentFocus = activity?.currentFocus
        if (currentFocus != null) {
            val windowToken = currentFocus.windowToken
            if (windowToken != null) {
                return inputManager.hideSoftInputFromWindow(windowToken, 0)
            }
        }
    }
    return false
}

fun showKeyboard(editText: EditText) {
    val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(editText.windowToken, 0)
    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0)
    editText.requestFocus()
}


问:
Laravel permission denied errors
I made a website and the website got error on the server . But there is no problem on my local.
When I send code to git , I got error file put content .
When I use php artisan view:cache problem solved but some hours later I got error file put content permission denied automatically.

I investigated for this problem and I found chmod -R 777 command but I got this error again .
I don't know how to solve this problem .

May you please help me ?

Thanks in advance.

答:
Try this..Whichever way you set it up, then you need to give read and write permissions to the webserver for storage, cache </p>

```<code>sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
</code>```

Title: Laravel permission denied errors

Body:
Try this..Whichever way you set it up, then you need to give read and write permissions to the webserver for storage, cache

sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache


问:
How to hidden field in contact form 7
sorry my english bad,i have a problem : i have a form, one field i store data and i want to hidden it, i used to tag hidden in contact form 7 but it is not working

my setting contact form 7  :
  Image setting form

Form after i set
  image form after set

答:
input:

```<code>[hidden form-name default:"popup contact form" ]
</code>```

output:

```<code><input type="hidden" name="form-name" value="popup contact form" class="wpcf7-form-control wpcf7-hidden">
</code>```

Title: How to hidden field in contact form 7

Body:
input:

[hidden form-name default:"popup contact form" ]

output:

<input type="hidden" name="form-name" value="popup contact form" class="wpcf7-form-control wpcf7-hidden">


问:
Check box checking issue
I have an issue in checkbox checking in my data table.

The paginated checkboxes are not checked. My code is:

```<code>// Handle click on "Select all" control
$('#example-select-all').on('click', function(){
    // Check/uncheck all checkboxes in the table
    var rows = candidateTable.rows({ 'search': 'applied' }).nodes();
    console.log(rows);
    $('input[type="checkbox"]', rows).prop('checked', this.checked);
});
</code>```

答:
html:

```<code><table id="candidates-table" class="display compact nowrap" style="width:100%">
                            <thead>
                                <tr>
                                    <th><input type="checkbox" name="select_all" value="1" id="example-select-all"></th>
                                    <th>Firstname</th>
                                    <th>Lastname</th>
                                    <th>Email</th>
                                    <th>Drive</th>
                                    <th>Department</th>
                                    <th>Experience</th>
                                    <th>Status</th>
                                    <th></th>
                                </tr>
                            </thead>
                        </table>
</code>```

js:

```<code> var candidateTable = $('#candidates-table').DataTable({
    columnDefs: [
       { width: '10%', targets: -1,  }
    ],
    "stateSave": true,
    "responsive" : true,
    "processing": false,
    "deferRender": true,
    "order": [[3,"disabled"]],
    "ajax": {
        "url": baseUrl + "admin/candidates",
        "dataSrc": ""
    },

    'fnCreatedRow': function (nRow, aData, iDataIndex) {
        $(nRow).attr('id', 'candidate-' + aData.id);
    },
    "columns": [
        {
            "render": function (data, type, content, meta) {
                return '<input type="checkbox" name="id[]" value="' + content.id + '">';

            }
    },
      {
            "render": function (data, type, content, meta) {
                return content.firstname;

            }
    },

    ]
});

 // Handle click on "Select all" control
$('#example-select-all').on('click', function(){
    // Get all rows with search applied
    var rows = candidateTable.rows({ 'search': 'applied' }).nodes();
    // Check/uncheck checkboxes for all rows in the table
    $('input[type="checkbox"]', rows).prop('checked', $(this).is(':checked'));
});
</code>```

Title: Check box checking issue

Body:
I have an issue in checkbox checking in my data table.

The paginated checkboxes are not checked. My code is:

// Handle click on "Select all" control
$('#example-select-all').on('click', function(){
    // Check/uncheck all checkboxes in the table
    var rows = candidateTable.rows({ 'search': 'applied' }).nodes();
    console.log(rows);
    $('input[type="checkbox"]', rows).prop('checked', this.checked);
});

Body:
html:

<table id="candidates-table" class="display compact nowrap" style="width:100%">
                            <thead>
                                <tr>
                                    <th><input type="checkbox" name="select_all" value="1" id="example-select-all"></th>
                                    <th>Firstname</th>
                                    <th>Lastname</th>
                                    <th>Email</th>
                                    <th>Drive</th>
                                    <th>Department</th>
                                    <th>Experience</th>
                                    <th>Status</th>
                                    <th></th>
                                </tr>
                            </thead>
                        </table>

js:

 var candidateTable = $('#candidates-table').DataTable({
    columnDefs: [
       { width: '10%', targets: -1,  }
    ],
    "stateSave": true,
    "responsive" : true,
    "processing": false,
    "deferRender": true,
    "order": [[3,"disabled"]],
    "ajax": {
        "url": baseUrl + "admin/candidates",
        "dataSrc": ""
    },

    'fnCreatedRow': function (nRow, aData, iDataIndex) {
        $(nRow).attr('id', 'candidate-' + aData.id);
    },
    "columns": [
        {
            "render": function (data, type, content, meta) {
                return '<input type="checkbox" name="id[]" value="' + content.id + '">';

            }
    },
      {
            "render": function (data, type, content, meta) {
                return content.firstname;

            }
    },

    ]
});

 // Handle click on "Select all" control
$('#example-select-all').on('click', function(){
    // Get all rows with search applied
    var rows = candidateTable.rows({ 'search': 'applied' }).nodes();
    // Check/uncheck checkboxes for all rows in the table
    $('input[type="checkbox"]', rows).prop('checked', $(this).is(':checked'));
});


问:
Ionic 5 gesture doesn't work with Angular bindings
I’ve got an Ionic page with a simple swipe gesture using the GestureController as described in the docs. On the swipe end event I increment a counter. There is a binding on the html of the page, which doesn’t get updated. Console.log() shows the updated counter, though.

Is there a known issue about that or am I doing something wrong?

Page Template

```<code><ion-content #contentElement>
    {{ counter }}
</ion-content>
</code>```

Typescript

```<code>export class TestPage {

  counter = 0;

  swipeGesture: Gesture;
  @ViewChild('contentElement', { static: true, read: ElementRef }) contentElement: ElementRef;

  constructor(private gestureController: GestureController) { }

  ionViewDidEnter() {
    this.swipeGesture = this.gestureController.create({
      el: this.contentElement.nativeElement,
      gestureName: 'swipe',
      onEnd: () => this.onSwipeEnd(),
    });
    this.swipeGesture.enable();
  }

  private onSwipeEnd() {
    this.counter++;
    console.log(this.counter);
  }

}
</code>```

答:
I had a similar issue and what I did was inject the ChangeDetectorRef into the constructor.

```<code>constructor(private ref: ChangeDetectorRef) {}
</code>```

Then in you can run the change detection manually.

```<code>private onSwipeEnd() {
   this.counter++;
   console.log(this.counter);
   this.ref.detectChanges(); // Runs the change detection
}
</code>```

Body:
I’ve got an Ionic page with a simple swipe gesture using the GestureController as described in the docs. On the swipe end event I increment a counter. There is a binding on the html of the page, which doesn’t get updated. Console.log() shows the updated counter, though.

Is there a known issue about that or am I doing something wrong?

Page Template

<ion-content #contentElement>
    {{ counter }}
</ion-content>

Typescript

export class TestPage {

  counter = 0;

  swipeGesture: Gesture;
  @ViewChild('contentElement', { static: true, read: ElementRef }) contentElement: ElementRef;

  constructor(private gestureController: GestureController) { }

  ionViewDidEnter() {
    this.swipeGesture = this.gestureController.create({
      el: this.contentElement.nativeElement,
      gestureName: 'swipe',
      onEnd: () => this.onSwipeEnd(),
    });
    this.swipeGesture.enable();
  }

  private onSwipeEnd() {
    this.counter++;
    console.log(this.counter);
  }

}

Body:
I had a similar issue and what I did was inject the ChangeDetectorRef into the constructor.

constructor(private ref: ChangeDetectorRef) {}

Then in you can run the change detection manually.

private onSwipeEnd() {
   this.counter++;
   console.log(this.counter);
   this.ref.detectChanges(); // Runs the change detection
}


问:
Can't locate element on Microsoft Sign In page
I'm currently trying to locate Microsoft Sign In page's email input box by using xpath (others as well) but after many tries I still can't locate the correct element for it.

After copying the element from the page, this is the element given:

```<code><input type="email" class="form-control" placeholder="Email, phone, or Skype" aria-required="true" spellcheck="false" autocomplete="off" data-bind="
                                    hasFocus: focus,
                                    textInput: email,
                                    attr: {'placeholder': config.text.emailPlaceHolder, 'aria-invalid': !error}">
</code>```

And this is currently my python code:

```<code>login = browser.find_element_by_xpath("//input[@class='form-control']")
login.send_keys(config.username)
login.send_keys(Keys.RETURN)
</code>```

I had tried multiple times but I still can't get the proper element to proceed. After entering https://forms.office.com/ I had successfully captured the sign in element but stuck at the next page.

答:
As the the desired element is within an  so to invoke click() on the element you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be clickable.

You can use either of the following  Locator Strategies:

Using XPATH:

```<code>WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[@class='landing-signin-hrd' and @id='hrdIframe']")))
login = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='form-control' and @placeholder='Email, phone, or Skype']")))
login.send_keys("StrangerSphinx")
login.send_keys(Keys.RETURN)
</code>```

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe.landing-signin-hrd#hrdIframe")))
login = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.form-control[placeholder='Email, phone, or Skype']")))
login.send_keys("StrangerSphinx")
login.send_keys(Keys.RETURN)
</code>```

Reference

You can find a relevant detailed discussion in Ways to deal with #document under iframe

Body:
I'm currently trying to locate Microsoft Sign In page's email input box by using xpath (others as well) but after many tries I still can't locate the correct element for it.

After copying the element from the page, this is the element given:

<input type="email" class="form-control" placeholder="Email, phone, or Skype" aria-required="true" spellcheck="false" autocomplete="off" data-bind="
                                    hasFocus: focus,
                                    textInput: email,
                                    attr: {'placeholder': config.text.emailPlaceHolder, 'aria-invalid': !error}">

And this is currently my python code:

login = browser.find_element_by_xpath("//input[@class='form-control']")
login.send_keys(config.username)
login.send_keys(Keys.RETURN)

I had tried multiple times but I still can't get the proper element to proceed. After entering https://forms.office.com/ I had successfully captured the sign in element but stuck at the next page.

Body:
As the the desired element is within an <iframe> so to invoke click() on the element you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be clickable.

You can use either of the following  Locator Strategies:

Using XPATH:

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[@class='landing-signin-hrd' and @id='hrdIframe']")))
login = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='form-control' and @placeholder='Email, phone, or Skype']")))
login.send_keys("StrangerSphinx")
login.send_keys(Keys.RETURN)

Using CSS_SELECTOR:

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe.landing-signin-hrd#hrdIframe")))
login = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.form-control[placeholder='Email, phone, or Skype']")))
login.send_keys("StrangerSphinx")
login.send_keys(Keys.RETURN)

Reference

You can find a relevant detailed discussion in Ways to deal with #document under iframe


问:
Custom dimension is not storing in Google Analytics
I have a 2 tracking ids. one for Development environment and another for Production environment.

Both are having same custom dimension property called 'dimension1'.

custom dimension values are storing in Development Environment but Production Environment is not storing in Google Analytics.

My code below,

```<code>import ReactGA from "react-ga";

export default {

initializeGA: (trackingId, profileId = null) => {

    ReactGA.initialize(trackingId, {
        debug: true
    });

    ReactGA.pageview("/SplashScreen", { dimension1: profileId });
    ReactGA.set({ dimension1: profileId });
},
pageView: (pageName, profileId) => {

    ReactGA.pageview(pageName, { dimension1: profileId });
},
modalView: (pageName, profileId) => {

    ReactGA.modalview(pageName, { dimension1: profileId });
},
pageEvent: (category, action, label, profileId) => {

    ReactGA.event({
        category: category,
        action: action,
        label: label
    }, { dimension1: profileId });
}
}
</code>```

My Custom Dimension

Please help me to resolve this issue.

答: did you set up the entry in GA of your production profile?</p>

Body:
I have a 2 tracking ids. one for Development environment and another for Production environment.

Both are having same custom dimension property called 'dimension1'.

custom dimension values are storing in Development Environment but Production Environment is not storing in Google Analytics.

My code below,

import ReactGA from "react-ga";

export default {

initializeGA: (trackingId, profileId = null) => {

    ReactGA.initialize(trackingId, {
        debug: true
    });

    ReactGA.pageview("/SplashScreen", { dimension1: profileId });
    ReactGA.set({ dimension1: profileId });
},
pageView: (pageName, profileId) => {

    ReactGA.pageview(pageName, { dimension1: profileId });
},
modalView: (pageName, profileId) => {

    ReactGA.modalview(pageName, { dimension1: profileId });
},
pageEvent: (category, action, label, profileId) => {

    ReactGA.event({
        category: category,
        action: action,
        label: label
    }, { dimension1: profileId });
}
}

My Custom Dimension

Please help me to resolve this issue.


问:
How do i reinterpter_cast vector to int?
I've got a vector of four bytes:
std::vector<int8_t> src = { 0x0, 0x0, 0x0, 0xa };, which in hexadecimal is. (0x0000000a)

How do i type-pun it into an int32_t so that i get 10 using reinterpret_cast?

This can be done easily using bitshifts like this:

(int32_t)((src[offset] << 24) | (src[offset+ 1] << 16) | (src[offset+ 2] << 8) | (src[offset+ 3]));

but as far as i'm aware of how reinterpret_cast work, it can be used here at its best, but i can't firgure out how exactly do that in code itself.

```<code>reinterpret_cast<int32_t*>(&0x0000000a);
</code>```

ps: This is not just for int32_t or so, this can be reinterpreted to anything i would wish. That's the point.

答:
This is not possible; an attempt would be undefined behaviour due to strict aliasing violation. An array of int8_t cannot be accessed as some other type (except for this specific cases listed in the rule, such as uint8_t).

Using bitshifts or memcpy are correct ways (as is the idea of S.M.'s answer)

Body:
I've got a vector of four bytes:
std::vector<int8_t> src = { 0x0, 0x0, 0x0, 0xa };, which in hexadecimal is. (0x0000000a)

How do i type-pun it into an int32_t so that i get 10 using reinterpret_cast?

This can be done easily using bitshifts like this:

(int32_t)((src[offset] << 24) | (src[offset+ 1] << 16) | (src[offset+ 2] << 8) | (src[offset+ 3]));

but as far as i'm aware of how reinterpret_cast work, it can be used here at its best, but i can't firgure out how exactly do that in code itself.

reinterpret_cast<int32_t*>(&0x0000000a);

ps: This is not just for int32_t or so, this can be reinterpreted to anything i would wish. That's the point.


问:
javascript can't reassignment data to array in map()
```<code>
let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array.map(obj=>{
  obj = obj.levle2.data
});
console.log(obj2Array)

</code>```

what I'm expecting is ["data","data","data"].But I still got the original data.
I know I can use forEach() to achieve this, but why I can't reassignment element in map()?

答:
map() returns a new array. Try this code:

```<code>let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array = obj2Array.map(obj=>
  obj.level2.data
);

console.log( obj2Array )
</code>```

output ["data", "data", "data"]

Body:
let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array.map(obj=>{
  obj = obj.levle2.data
});
console.log(obj2Array)

what I'm expecting is ["data","data","data"].But I still got the original data.
I know I can use forEach() to achieve this, but why I can't reassignment element in map()?

Body:
map() returns a new array. Try this code:

let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array = obj2Array.map(obj=>
  obj.level2.data
);

console.log( obj2Array )

output ["data", "data", "data"]


问:
How to add item to immutable array in React setState in Typescript?
I want to use an immutable array to handle the state. And add an item to this list.

interface MainState {
  list: readonly []; // define immutable array
}

const Component: React.FC = () => {
  // by default use the immutable array with type
  const [classes, setClasses] = useState({ list: [] } as MainState);

  useEffect(() => {
    if (data) {
      data.forEach((thing) => {
        setClasses(prevState => {
          //
          // Call signature return types '{ list: never[]; }' and 'MainState' are incompatible.
          // The types of 'list.length' are incompatible between these types.
          // Type 'number' is not assignable to type '0'.  TS2345
          //
          const list = prevState.list.concat(thing);
          return { list };
        });
      });
    }
  });
// ...

}
```

I though using concat would work, since it returns a new array.

答:
The easiest, most acceptable way of doing so:</p>

```<code>const list = [...prevState.list, thing];
</code>```

Body:
I want to use an immutable array to handle the state. And add an item to this list.

interface MainState {
  list: readonly []; // define immutable array
}

const Component: React.FC = () => {
  // by default use the immutable array with type
  const [classes, setClasses] = useState({ list: [] } as MainState);

  useEffect(() => {
    if (data) {
      data.forEach((thing) => {
        setClasses(prevState => {
          //
          // Call signature return types '{ list: never[]; }' and 'MainState' are incompatible.
          // The types of 'list.length' are incompatible between these types.
          // Type 'number' is not assignable to type '0'.  TS2345
          //
          const list = prevState.list.concat(thing);
          return { list };
        });
      });
    }
  });
// ...

}

I though using concat would work, since it returns a new array.

Body:
The easiest, most acceptable way of doing so:

const list = [...prevState.list, thing];


问:
How to install and run gym box2d environment in google colab?
I have followed this method to run a box2d enviroment without rendering it in google colab,

```<code>!apt-get install python-box2d
!pip install box2d-py
!pip install gym[Box_2D]
import gym
env = gym.make("BipedalWalker-v2")
</code>```

but its showing this

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
python-box2d is already the newest version (2.3.2~dfsg-2).
0 upgraded, 0 newly installed, 0 to remove and 28 not upgraded.
Requirement already satisfied: box2d-py in /usr/local/lib/python3.6/dist-packages (2.3.8)
Requirement already satisfied: gym[Box_2D] in /usr/local/lib/python3.6/dist-packages (0.15.3)
  WARNING: gym 0.15.3 does not provide the extra 'box_2d'
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from gym[Box_2D]) (1.12.0)
Requirement already satisfied: pyglet<=1.3.2,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym[Box_2D]) (1.3.2)
Requirement already satisfied: numpy>=1.10.4 in /usr/local/lib/python3.6/dist-packages (from gym[Box_2D]) (1.17.3)
Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from gym[Box_2D]) (1.3.1)
Requirement already satisfied: cloudpickle~=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym[Box_2D]) (1.2.2)
Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from pyglet<=1.3.2,>=1.2.0->gym[Box_2D]) (0.16.0)

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

AttributeError                            Traceback (most recent call last)

<ipython-input-10-62ca95674145> in <module>()
      3 get_ipython().system('pip install gym[Box_2D]')
      4 import gym
----> 5 env = gym.make("BipedalWalker-v2")

3 frames

/usr/local/lib/python3.6/dist-packages/gym/envs/registration.py in load(name)
     16     mod_name, attr_name = name.split(":")
     17     mod = importlib.import_module(mod_name)
---> 18     fn = getattr(mod, attr_name)
     19     return fn
     20

AttributeError: module 'gym.envs.box2d' has no attribute 'BipedalWalker'
</code>```

I also tried to install this box2d from pip pip install Box2D but its not installing in colab. How do we install and run a box2d gym enviroment in google colag?

答: I was able to get it working with !pip3 install box2d-py==2.3.8.

Body:
I have followed this method to run a box2d enviroment without rendering it in google colab,

!apt-get install python-box2d
!pip install box2d-py
!pip install gym[Box_2D]
import gym
env = gym.make("BipedalWalker-v2")

but its showing this

Reading package lists... Done
Building dependency tree
Reading state information... Done
python-box2d is already the newest version (2.3.2~dfsg-2).
0 upgraded, 0 newly installed, 0 to remove and 28 not upgraded.
Requirement already satisfied: box2d-py in /usr/local/lib/python3.6/dist-packages (2.3.8)
Requirement already satisfied: gym[Box_2D] in /usr/local/lib/python3.6/dist-packages (0.15.3)
  WARNING: gym 0.15.3 does not provide the extra 'box_2d'
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from gym[Box_2D]) (1.12.0)
Requirement already satisfied: pyglet<=1.3.2,>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym[Box_2D]) (1.3.2)
Requirement already satisfied: numpy>=1.10.4 in /usr/local/lib/python3.6/dist-packages (from gym[Box_2D]) (1.17.3)
Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from gym[Box_2D]) (1.3.1)
Requirement already satisfied: cloudpickle~=1.2.0 in /usr/local/lib/python3.6/dist-packages (from gym[Box_2D]) (1.2.2)
Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from pyglet<=1.3.2,>=1.2.0->gym[Box_2D]) (0.16.0)

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

AttributeError                            Traceback (most recent call last)

<ipython-input-10-62ca95674145> in <module>()
      3 get_ipython().system('pip install gym[Box_2D]')
      4 import gym
----> 5 env = gym.make("BipedalWalker-v2")

3 frames

/usr/local/lib/python3.6/dist-packages/gym/envs/registration.py in load(name)
     16     mod_name, attr_name = name.split(":")
     17     mod = importlib.import_module(mod_name)
---> 18     fn = getattr(mod, attr_name)
     19     return fn
     20

AttributeError: module 'gym.envs.box2d' has no attribute 'BipedalWalker'

I also tried to install this box2d from pip pip install Box2D but its not installing in colab. How do we install and run a box2d gym enviroment in google colag?


问:
Boost ASIO iostream random delays on reading
I have a client talking to server with TCP via localhost. The server uses Boost ASIO iostream in blocking mode. It accepts the incoming connections, reads the request, sends response and closes the socket. The problem is - sometimes server have a random delay for 10-200 milliseconds on the first read via getline. I've set TCP_NODELAY flag on both server's and client's socket. What can be the reason for this delays? I know, that i should use select before reading from socket, but i expected that there shouldn't be such a great delay via localhost.

Here is the relevant part of server's code:

```<code>
asio::io_service io_service;
ip::tcp::endpoint endpoint(bindAddress, 80);
ip::tcp::acceptor acceptor(io_service, endpoint);

for(;;)
{
    ip::tcp::iostream stream;
    acceptor.accept(*stream.rdbuf(), peer);
    ip::tcp::no_delay no_delay(true);
    stream.rdbuf()->set_option(no_delay);
    string str;
    getline(stream, str); // at this line i get random delays

    //the main part of code
}
</code>```

I have around 200 requests/second, delay happens several times per minute.
netstat -m shows, that there is enough buffers.

UPDATE:

It looks like the problem of client, not server: Apache HttpClient random delays under high requests/second

答:
Answering this question for the sake of closing it out.

Apache HttpClient random delays under high requests/second

Apache's ab(1) also has "saw tooth"-like performance because it dispatches -c connections that it monitors via select(2), then once all connections have returned, it will dispatch another -c connections. The alternate (and better) approach would be to establish a new connection and readd the file-descriptor to ab(1)'s select(2) array to make sure -c connections are always active processing.

I've seen ab(1) give some very misleading results because one connection out of a thousand hung (still not a good thing, but it skews results very negatively when using it through a load balancer).

Body:
I have a client talking to server with TCP via localhost. The server uses Boost ASIO iostream in blocking mode. It accepts the incoming connections, reads the request, sends response and closes the socket. The problem is - sometimes server have a random delay for 10-200 milliseconds on the first read via getline. I've set TCP_NODELAY flag on both server's and client's socket. What can be the reason for this delays? I know, that i should use select before reading from socket, but i expected that there shouldn't be such a great delay via localhost.

Here is the relevant part of server's code:

asio::io_service io_service;
ip::tcp::endpoint endpoint(bindAddress, 80);
ip::tcp::acceptor acceptor(io_service, endpoint);

for(;;)
{
    ip::tcp::iostream stream;
    acceptor.accept(*stream.rdbuf(), peer);
    ip::tcp::no_delay no_delay(true);
    stream.rdbuf()->set_option(no_delay);
    string str;
    getline(stream, str); // at this line i get random delays

    //the main part of code
}

I have around 200 requests/second, delay happens several times per minute.
netstat -m shows, that there is enough buffers.

UPDATE:

It looks like the problem of client, not server: Apache HttpClient random delays under high requests/second


问:
C# -> Android (Xamarin) -> start task every 5 minutes in Background
i want to run a task every 5 minutes. i've tried to solve it with an IntentService and AlarmManager, my code:

```<code>protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Main);

    var tkrServiceIntent = new Intent(this, typeof(GpsDataHandler));
    var tkrServicePendingIntent = PendingIntent.GetService(this, 0, tkrServiceIntent, 0);

    long interval = 5000;
    var firstStart = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + 1000;

    var am = (AlarmManager)GetSystemService(Context.AlarmService);

    am.SetInexactRepeating(AlarmType.RtcWakeup, firstStart, interval, tkrServicePendingIntent);

    Toast.MakeText(this, "Service started", ToastLength.Long).Show();
}
</code>```

i receive the toast, that the service is started, but if i look in running services, there is no service for my application. Can you tell me where the problem ist?

答:
Hope this code helps you:-

```<code>async void StartTimer()
{
   await Task.Delay(60000); //60 seconds
   // Do your code
   StartTimer(); // Again Call
}
</code>```

Call "StartTimer()" method where you want to. Call only once time then it calls automatically after 60 seconds.

Thanks !!!

Body:
i want to run a task every 5 minutes. i've tried to solve it with an IntentService and AlarmManager, my code:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Main);

    var tkrServiceIntent = new Intent(this, typeof(GpsDataHandler));
    var tkrServicePendingIntent = PendingIntent.GetService(this, 0, tkrServiceIntent, 0);

    long interval = 5000;
    var firstStart = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + 1000;

    var am = (AlarmManager)GetSystemService(Context.AlarmService);

    am.SetInexactRepeating(AlarmType.RtcWakeup, firstStart, interval, tkrServicePendingIntent);

    Toast.MakeText(this, "Service started", ToastLength.Long).Show();
}

i receive the toast, that the service is started, but if i look in running services, there is no service for my application. Can you tell me where the problem ist?

Body:
Hope this code helps you:-

async void StartTimer()
{
   await Task.Delay(60000); //60 seconds
   // Do your code
   StartTimer(); // Again Call
}

Call "StartTimer()" method where you want to. Call only once time then it calls automatically after 60 seconds.

Thanks !!!


问:
Nested JSON - Join sub-object
How can I remove sub-objects?   </p>

```<code>[{
    "id": "1",
    "desc": "SOME PRODUCT",
    "codigo": "CODE-28",
    "codigoBarras": "2000000001",
    "unidade": "PCT",
    "price": "24.15",
    "current_inventory": [{
        "2kg": "5",
        "5kg": "5",
        "10kg": "5",
        "20kg": "5",
        "productId": "1"
     }]
 }]

[{
    "id": "1",
    "desc": "SOME PRODUCT",
    "codigo": "CODE-28",
    "codigoBarras": "2000000001",
    "unidade": "PCT",
    "price": "24.15",
    "current_inventory_2kg": "5",
    "current_inventory_5kg": "5",
    "current_inventory_10kg": "5",
    "current_inventory_20kg": "5",
}]
</code>```

答:
THANK YOU VERY MUCH!!!

Solved using the code below:

data is de object

estoqueFracionado is the sub-object

```<code>              for (let [key, value] of Object.entries(data)) {
                    value.estoqueFracionado.forEach (e => {
                        Object.keys(e).forEach(j => {
                            value['estoqueFracionado_' + j] = e[j]
                        })
                        delete value.estoqueFracionado
                    })
                }
</code>```

Title: Nested JSON - Join sub-object

Body:
How can I remove sub-objects?

[{
    "id": "1",
    "desc": "SOME PRODUCT",
    "codigo": "CODE-28",
    "codigoBarras": "2000000001",
    "unidade": "PCT",
    "price": "24.15",
    "current_inventory": [{
        "2kg": "5",
        "5kg": "5",
        "10kg": "5",
        "20kg": "5",
        "productId": "1"
     }]
 }]

[{
    "id": "1",
    "desc": "SOME PRODUCT",
    "codigo": "CODE-28",
    "codigoBarras": "2000000001",
    "unidade": "PCT",
    "price": "24.15",
    "current_inventory_2kg": "5",
    "current_inventory_5kg": "5",
    "current_inventory_10kg": "5",
    "current_inventory_20kg": "5",
}]

Body:
THANK YOU VERY MUCH!!!

Solved using the code below:

data is de object

estoqueFracionado is the sub-object

              for (let [key, value] of Object.entries(data)) {
                    value.estoqueFracionado.forEach (e => {
                        Object.keys(e).forEach(j => {
                            value['estoqueFracionado_' + j] = e[j]
                        })
                        delete value.estoqueFracionado
                    })
                }


问:
How to fit a Rectangle inside a Circle?
So far I've tried creating another Rectangle to calculate the radius of an inner Circle with it's center and a point to the left side:

Rectangle rectangle = new Rectangle();
Vector2 center = new Vector2();
otherRectangle.getCenter(center);
Vector2 side = new Vector2(otherRectangle.x, otherRectangle.y + otherRectangle.height / 2f);
float size = center.dst(side);
rectangle.setSize(size);
rectangle.setCenter(center);
```

But this makes the rectangle be too small and I'd like the corners of the square to be touching the circle border:

答: As Nicolas commented, the answer so the corners of the square touch the circle is to set its size to Math.sqrt(2) * radius

Title: How to fit a Rectangle inside a Circle?

Body:
So far I've tried creating another Rectangle to calculate the radius of an inner Circle with it's center and a point to the left side:

Rectangle rectangle = new Rectangle();
Vector2 center = new Vector2();
otherRectangle.getCenter(center);
Vector2 side = new Vector2(otherRectangle.x, otherRectangle.y + otherRectangle.height / 2f);
float size = center.dst(side);
rectangle.setSize(size);
rectangle.setCenter(center);

But this makes the rectangle be too small and I'd like the corners of the square to be touching the circle border:


问:
Can org.springframework.data.repository be Hibernate managed?
I've been using Hibernate Search to query database entries. For the majority of my cases I use a cron job that builds my index, but for one specific case I need the index to update immediately on entity change.
I noticed that while the springframework.data.repository updates the data correctly in the database, Hibernate does not perform an update of the respective entity in the index.

When I change my implementation to use the entity manager for this transaction (using entitymanager.persist(x) etc...) it also updates the index correctly.

I like the simplicity of the crud repository and I would like to stay consistent, so is there a way to let hibernate know of this change using the crud repository?

答:
Spring Data offers a JPA-based CRUD repository, which will rely on JPA (Hibernate ORM) to perform CRUD operations and thus will allow Hibernate Search to update indexes automatically. You shouldn't need to implement calls to entityManager.persist(), etc. yourself.

If your CRUD repository does not use JPA (Hibernate ORM), then of course (as you noticed) Hibernate Search will not be aware of changes and will not update indexes.

You didn't specify how your CRUD repository was implemented exactly, so I suppose you're using the Spring Data JDBC implementation? That's the only way I know of that would allow you to update your database in Spring Data without relying on JPA (Hibernate ORM).

I would recommend switching to the Spring Data JPA implementation at least for the entity that requires automatic, on-the-fly indexing.

If that's really not an option, I suppose you may be able to plug into Spring Data JDBC somehow (overriding CRUD methods, or using event listeners maybe), so that, every time an entity is changed:

you load it using Hibernate ORM

you explicitly index it using fullTextSession.index() (in case of a create/update) or delete it from the index using fullTextSession.purge() (in case of delete).

I doubt performance will be very good, however. In particular, you'll be missing out on some optimizations in Hibernate Search that avoid reindexing when the change is only about properties that are not indexed.


问:
opening only part of large TDMS files in python, as Labview does
I have large (>20GB, larger than RAM) .tdms files created in Labview to open in python3.  I can use nptdms with the option memamp_dir to leave the RAM untouched. But this writes another large file on the disk, which is sometimes a problem and it's slow.

Labview has the possibility to read only part of the file, quite quickly.
Is that possible in python with nptdms or other?

(It seems discussed here, but I cannot find an easy solution. Also, nptdms.tdms_segment.py could be part of the solution but it's hard to understand how it works for me)

答:
Should be possible with iqtools library. I regularly use it to jump to a certain position of very large files (tested around 5GB) using seek and read a portion only, not the whole file. Generally you should consider the TDMS file containing a huge string of data points with a bit of complex data format inside, length of frames, number of frames are basically numbers for your analysis convenience. "Jumping" is done using the starting frame argument.

```<code>from iqtools import *
filename ='blah.tdms'
myiq=TDMSData(filename)
myiq.read(nframes=100, lframes=1024, sframes=400)
</code>```

Which means reading 100 frames each 1024 samples long starting from sample 400.

For very small files, there is also another read_complete_file function. In the library there are many other tools for spectral analysis such as 1D and 2D spectrograms, multi taper etc. There are some examples in the repository.

btw. iqtools library has also a GUI front end called IQGUI, which, although not as versatile as the library interface, can be used to "traverse" through the time file using a visual slider.

maybe this can help.

Body:
Should be possible with iqtools library. I regularly use it to jump to a certain position of very large files (tested around 5GB) using seek and read a portion only, not the whole file. Generally you should consider the TDMS file containing a huge string of data points with a bit of complex data format inside, length of frames, number of frames are basically numbers for your analysis convenience. "Jumping" is done using the starting frame argument.

from iqtools import *
filename ='blah.tdms'
myiq=TDMSData(filename)
myiq.read(nframes=100, lframes=1024, sframes=400)

Which means reading 100 frames each 1024 samples long starting from sample 400.

For very small files, there is also another read_complete_file function. In the library there are many other tools for spectral analysis such as 1D and 2D spectrograms, multi taper etc. There are some examples in the repository.

btw. iqtools library has also a GUI front end called IQGUI, which, although not as versatile as the library interface, can be used to "traverse" through the time file using a visual slider.

maybe this can help.


问:
How can I print or put to some HashMap or anything else my result of query?
I have an SQL query in the following Java Code:

```<code>try {
    Statement st = conn.createStatement();
    try {
        st.execute("SELECT * FROM students WHERE course_id =1");
    } finally {
        // st.close();
    }
} catch (SQLException ex) {
    throw new RuntimeException(ex);
}
</code>```

When I execute this code, I don't see anything in the console.

I want to put the results to a Hashmap or print them to see the values, at least.

How can I implement printing to the console or storing the results in a Map?

答:
Try this :-</p>

```<code>     try {
            Statement st = conn.createStatement();
            try {
                ResultSet rs=st.executeQuery("SELECT * FROM students WHERE course_id =1");
                while(rs.next()) {
                    //Your logic to put in map goes here
                }
            } finally {
               // st.close();
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
</code>```

Body:
I have an SQL query in the following Java Code:

try {
    Statement st = conn.createStatement();
    try {
        st.execute("SELECT * FROM students WHERE course_id =1");
    } finally {
        // st.close();
    }
} catch (SQLException ex) {
    throw new RuntimeException(ex);
}

When I execute this code, I don't see anything in the console.

I want to put the results to a Hashmap or print them to see the values, at least.

How can I implement printing to the console or storing the results in a Map?

Body:
Try this :-

     try {
            Statement st = conn.createStatement();
            try {
                ResultSet rs=st.executeQuery("SELECT * FROM students WHERE course_id =1");
                while(rs.next()) {
                    //Your logic to put in map goes here
                }
            } finally {
               // st.close();
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }


问:
React-Native: Convert local image to base64 string
Convert local image to base64 string in Javascript. I'm test in android device and my image path like:

../../Images/Stickers/Bigottario/14.png

How can I convert images from the project local folder to base64?
I have tried with react-native-fs as given below.

```<code>        RNFS.readFile(this.state.StateStrickersobject.imagePath, 'base64').then(image => {
            alert("22222222222222222"+image)
          });
</code>```

答:
Example image uploader component may be helpful for you.
Note: react-native-image-picker module is required. translation service is optional

```<code>import React from 'react';
import { View, TouchableOpacity, ScrollView, Alert } from 'react-native';
import {
    Item, Label, Thumbnail, Button, Icon, Text
} from 'native-base';
import ImagePicker from 'react-native-image-picker';
import { translate } from '../../Services/Translation/TranslationService';

selectPhotoTapped = ({ Image, onDataChanged }) => {
    const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, storageOptions: { skipBackup: true } };
    ImagePicker.showImagePicker(options, (response) => {
        if (response.didCancel) {         // console.log('User cancelled photo picker');
        }
        else if (response.error) {            // console.log('ImagePicker Error: ', response.error);
        }
        else if (response.customButton) {            // console.log('User tapped custom button: ', response.customButton);
        }
        else {
            Image = Image ? Image : {};
            Image.uri = response.uri;
            Image.ImageStream = response.data;
            onDataChanged(Image);
        }
    });
}

const ImageUploader = (props) => {
    return (
        <View>
            <Item fixedLabel style={{ paddingRight: 10 }} error={props.error}>
                <Label>
                    {props.children}
                </Label>
                <Button block onPress={() => selectPhotoTapped(props)} style={{ backgroundColor: "#8995A6" }}>
                    <Text uppercase={false}>{translate("choose_file")}</Text>
                    <Icon name='camera' />
                </Button>
            </Item>
        </View>
    );
}

export { ImageUploader };
</code>```

Example display method

```<code><ImageUploader
  error={checkError(`${prefix}DocumentImages`)}
  Image={this.state.image}
  onDataChanged={(image) => console.log(image)} >
  <Label> Select photo</Label>
</ImageUploader>
</code>```

Body:
Convert local image to base64 string in Javascript. I'm test in android device and my image path like:

../../Images/Stickers/Bigottario/14.png

How can I convert images from the project local folder to base64?
I have tried with react-native-fs as given below.

        RNFS.readFile(this.state.StateStrickersobject.imagePath, 'base64').then(image => {
            alert("22222222222222222"+image)
          });

Body:
Example image uploader component may be helpful for you.
Note: react-native-image-picker module is required. translation service is optional

import React from 'react';
import { View, TouchableOpacity, ScrollView, Alert } from 'react-native';
import {
    Item, Label, Thumbnail, Button, Icon, Text
} from 'native-base';
import ImagePicker from 'react-native-image-picker';
import { translate } from '../../Services/Translation/TranslationService';

selectPhotoTapped = ({ Image, onDataChanged }) => {
    const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, storageOptions: { skipBackup: true } };
    ImagePicker.showImagePicker(options, (response) => {
        if (response.didCancel) {         // console.log('User cancelled photo picker');
        }
        else if (response.error) {            // console.log('ImagePicker Error: ', response.error);
        }
        else if (response.customButton) {            // console.log('User tapped custom button: ', response.customButton);
        }
        else {
            Image = Image ? Image : {};
            Image.uri = response.uri;
            Image.ImageStream = response.data;
            onDataChanged(Image);
        }
    });
}

const ImageUploader = (props) => {
    return (
        <View>
            <Item fixedLabel style={{ paddingRight: 10 }} error={props.error}>
                <Label>
                    {props.children}
                </Label>
                <Button block onPress={() => selectPhotoTapped(props)} style={{ backgroundColor: "#8995A6" }}>
                    <Text uppercase={false}>{translate("choose_file")}</Text>
                    <Icon name='camera' />
                </Button>
            </Item>
        </View>
    );
}

export { ImageUploader };

Example display method

<ImageUploader
  error={checkError(`${prefix}DocumentImages`)}
  Image={this.state.image}
  onDataChanged={(image) => console.log(image)} >
  <Label> Select photo</Label>
</ImageUploader>


问:
Changing ng-model value in controller is not displayed in html input
I have an HTML input that is assigned to an ng-model value, before any manual change in input, all the changes of ng-model in the controller (pragmatically) are displayed in HTML input but if I write anything in input manually, no change in controller be effected on displayed input on-page.

I write $scope.$apply() but it is not worked. also changing vieweValue of input by calling $setVieweValue doesn't have any effect on input element value.
when I debug, I find out that the reason is that the DOM value of the element is unchangeable (changing ng-model value doesn't change input value) because when I change the value of the DOM element of input in chrome console, then the value becomes displayed in the page.

答:
Try putting your model inside an object.
eg- Suppose your scope variable is:

```<code>$scope.inputValue = "someValue";
</code>```

and you are binding it as:

```<code>ng-model="inputValue";
</code>```

Change it like this:

```<code>$scope.ob = {inputValue: "someValue"};
</code>```

and in html:

```<code>ng-model="ob.inputValue";
</code>```

Body:
Try putting your model inside an object.
eg- Suppose your scope variable is:

$scope.inputValue = "someValue";

and you are binding it as:

ng-model="inputValue";

Change it like this:

$scope.ob = {inputValue: "someValue"};

and in html:

ng-model="ob.inputValue";


问:
Changing language on iOS 8.1 simulator does not work
If I change the language on an iOS 8.1 simulator to anything and try to detect this from code with

```<code>NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
NSLog(@"Language: %@", language);
</code>```

I get "en" back. I've tried resetting the navigator, etc. I've tried this using the iOS 7.1 runtime (in Xcode 5.1.1), and it worked fine. Has anyone managed to find a workaround to this problem?

答:
In my case, editing schema works for region but not for language.
It looks overwrite by development language.
Changing developmentRegion works fine with project.pbxproj like this.

```<code>developmentRegion = ja;
</code>```

Xcode Version 11.3.1 (11C504)

iPhoneX iOS 13.3.1

Body:
If I change the language on an iOS 8.1 simulator to anything and try to detect this from code with

NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
NSLog(@"Language: %@", language);

I get "en" back. I've tried resetting the navigator, etc. I've tried this using the iOS 7.1 runtime (in Xcode 5.1.1), and it worked fine. Has anyone managed to find a workaround to this problem?

Body:
In my case, editing schema works for region but not for language.
It looks overwrite by development language.
Changing developmentRegion works fine with project.pbxproj like this.

developmentRegion = ja;

Xcode Version 11.3.1 (11C504)

iPhoneX iOS 13.3.1


问:
Custom alert rules with Application Insights
Need the help of the crowd.

I'm wondering if the below monitoring scenario is possible with Application Insights.

I want to have an alert if one event occurred (on a certain entity) but another event did not follow it.

We have a job scheduling machine, we want to monitor cases in which a job creation was requested but a job was not created.

So we log everything of course, we have an event that a job was requested, and we have an event when a job was created.

And we want to be alerted if jobs were requested but was not created.

What would be the best practice? Is it even possible to AI?

Thanx!

答:
Oh... I now found there is a way to define alerts on custom log searches.

We will give it a try and keep this post updated.

If anyone has other ideas - lets me know.