问:
Google Maps (ReferenceError: google is not defined)
I use google map's API in my website to show couple of locations.
Google Maps is working fine .
But when I want to calculate the distance between to latitude and longitude I got this error ( ReferenceError: google is not defined)

home.component.ts

```<code>import { Component, OnInit } from '@angular/core';
declare var google: any;
@Component({

selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {

location: Location
selectedMarker: Marker
origin: any;
destination: any;
distance: String;

ngOnInit(){

this.distance = this.calculateDistance(this.origin, this.destination);

this.origin = {
  lat: 32.6950,
  lng: 35.2820
};
this.destination = {
  lat: 32.6050,
  lng: 35.2020
};

this.location = {
  latitude: 32.6950,
  longitude: 35.2820,
  zoom: 15,
  markers: [
      {
          lat: 32.6950,
          lng: 35.2820
      }
  ]
  }

 this.loadScript('assets/js/jquery-3.3.1.min.js');
 this.loadScript('assets/vendors/appear/jquery.appear.min.js');
 this.loadScript('assets/vendors/jquery.easing/jquery.easing.min.js');
 this.loadScript('assets/js/popper.min.js');
 this.loadScript('assets/js/bootstrap.min.js');
 this.loadScript('assets/vendors/common/common.min.js');
 this.loadScript('assets/vendors/fancybox/jquery.fancybox.min.js');
 this.loadScript('assets/vendors/menu/src/main.menu.js');
 this.loadScript('assets/vendors/owl.carousel/owl.carousel.min.js');
 this.loadScript('assets/vendors/animated-headline/js/animated-headline.js');
 this.loadScript('assets/js/main.js');
 this.loadScript('assets/js/theme.init.js');
 this.loadScript('assets/js/custom.js');

 }

 public loadScript(url: string) {
 const body = <HTMLDivElement> document.body;
 const script = document.createElement('script');
 script.innerHTML = '';
 script.src = url;
 script.async = false;
 script.defer = true;
 body.appendChild(script);
 }

addMarker(lat: number, lng: number) {
this.location.markers.push({
    lat,
    lng
 })
 }

selectMarker(event) {
this.selectedMarker = {
    lat: event.latitude,
    lng: event.longitude
 }
 }

calculateDistance(point1, point2) {

const p1 = new google.maps.LatLng(
point1.lat,
point1.lng
);
const p2 = new google.maps.LatLng(
point2.lat,
point2.lng
);

return (
google.maps.geometry.spherical.computeDistanceBetween(p1, p2)/1000
).toFixed(2);
}

}

interface Marker {
lat: number;
lng: number;
}

interface Location {
latitude: number;
longitude: number;
zoom: number;
markers: Array<Marker>;
}
</code>```

home.component.html

```<code><agm-map [latitude]="location.latitude" [longitude]="location.longitude"
[zoom]="location.zoom" (mapClick)="addMarker($event.coords.lat, $event.coords.lng)">
<!-- ... -->
<agm-direction
    [origin]="origin"
    [destination]="destination"
></agm-direction>
</agm-map>
<div>
 Distance: {{distance}}
 </div>
 <!-- ... -->
</code>```

Only thing it says: ReferenceError: google is not defined

Does anyone familiar with such problem?

答:
this code worked for me

home.component.ts

```<code>import { Component, OnInit ,ViewChild} from '@angular/core';
import { MapsAPILoader, AgmMap } from '@agm/core';
declare var google: any;

@Component({

  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {

  location: Location
  selectedMarker: Marker
  origin: any;
  destination: any;
  distance: String;
  geocoder: any;

   ngOnInit(){

    this.origin = {
      lat: 32.6950,
      lng: 35.2820
    };
  this.destination = {
      lat: 32.6050,
      lng: 35.2020
   };

    this.location = {
      latitude: 32.6950,
      longitude: 35.2820,
      zoom: 15,
      markers: [
          {
              lat: 32.6950,
              lng: 35.2820
          }
      ]
  }

     this.loadScript('assets/js/jquery-3.3.1.min.js');
     this.loadScript('assets/vendors/appear/jquery.appear.min.js');
     this.loadScript('assets/vendors/jquery.easing/jquery.easing.min.js');
     this.loadScript('assets/js/popper.min.js');
     this.loadScript('assets/js/bootstrap.min.js');
     this.loadScript('assets/vendors/common/common.min.js');
     this.loadScript('assets/vendors/fancybox/jquery.fancybox.min.js');
     this.loadScript('assets/vendors/menu/src/main.menu.js');
     this.loadScript('assets/vendors/owl.carousel/owl.carousel.min.js');
     this.loadScript('assets/vendors/animated-headline/js/animated-headline.js');
     this.loadScript('assets/js/main.js');
     this.loadScript('assets/js/theme.init.js');
     this.loadScript('assets/js/custom.js');
  }

  @ViewChild(AgmMap, { static: true }) map: AgmMap;

  constructor(public mapsApiLoader: MapsAPILoader) {
    this.mapsApiLoader = mapsApiLoader;

    this.mapsApiLoader.load().then(() => {
      this.geocoder = new google.maps.Geocoder();
      this.distance = this.calculateDistance(this.origin, this.destination);
    });
  }

  public loadScript(url: string) {
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.innerHTML = '';
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }

  addMarker(lat: number, lng: number) {
    this.location.markers.push({
        lat,
        lng
    })
  }

  selectMarker(event) {
    this.selectedMarker = {
        lat: event.latitude,
        lng: event.longitude
    }
  }

  calculateDistance(point1, point2) {

    const p1 = new google.maps.LatLng(
    point1.lat,
    point1.lng
    );
    const p2 = new google.maps.LatLng(
    point2.lat,
    point2.lng
    );

    return (
    google.maps.geometry.spherical.computeDistanceBetween(p1, p2)/1000
    ).toFixed(2);
}

}

interface Marker {
lat: number;
lng: number;
}

interface Location {
latitude: number;
longitude: number;
zoom: number;
markers: Array<Marker>;
}
</code>```

Body:
I use google map's API in my website to show couple of locations.
Google Maps is working fine .
But when I want to calculate the distance between to latitude and longitude I got this error ( ReferenceError: google is not defined)

home.component.ts

import { Component, OnInit } from '@angular/core';
declare var google: any;
@Component({

selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {

location: Location
selectedMarker: Marker
origin: any;
destination: any;
distance: String;

ngOnInit(){

this.distance = this.calculateDistance(this.origin, this.destination);

this.origin = {
  lat: 32.6950,
  lng: 35.2820
};
this.destination = {
  lat: 32.6050,
  lng: 35.2020
};

this.location = {
  latitude: 32.6950,
  longitude: 35.2820,
  zoom: 15,
  markers: [
      {
          lat: 32.6950,
          lng: 35.2820
      }
  ]
  }

 this.loadScript('assets/js/jquery-3.3.1.min.js');
 this.loadScript('assets/vendors/appear/jquery.appear.min.js');
 this.loadScript('assets/vendors/jquery.easing/jquery.easing.min.js');
 this.loadScript('assets/js/popper.min.js');
 this.loadScript('assets/js/bootstrap.min.js');
 this.loadScript('assets/vendors/common/common.min.js');
 this.loadScript('assets/vendors/fancybox/jquery.fancybox.min.js');
 this.loadScript('assets/vendors/menu/src/main.menu.js');
 this.loadScript('assets/vendors/owl.carousel/owl.carousel.min.js');
 this.loadScript('assets/vendors/animated-headline/js/animated-headline.js');
 this.loadScript('assets/js/main.js');
 this.loadScript('assets/js/theme.init.js');
 this.loadScript('assets/js/custom.js');

 }

 public loadScript(url: string) {
 const body = <HTMLDivElement> document.body;
 const script = document.createElement('script');
 script.innerHTML = '';
 script.src = url;
 script.async = false;
 script.defer = true;
 body.appendChild(script);
 }

addMarker(lat: number, lng: number) {
this.location.markers.push({
    lat,
    lng
 })
 }

selectMarker(event) {
this.selectedMarker = {
    lat: event.latitude,
    lng: event.longitude
 }
 }

calculateDistance(point1, point2) {

const p1 = new google.maps.LatLng(
point1.lat,
point1.lng
);
const p2 = new google.maps.LatLng(
point2.lat,
point2.lng
);

return (
google.maps.geometry.spherical.computeDistanceBetween(p1, p2)/1000
).toFixed(2);
}

}

interface Marker {
lat: number;
lng: number;
}

interface Location {
latitude: number;
longitude: number;
zoom: number;
markers: Array<Marker>;
}

home.component.html

<agm-map [latitude]="location.latitude" [longitude]="location.longitude"
[zoom]="location.zoom" (mapClick)="addMarker($event.coords.lat, $event.coords.lng)">

<agm-direction
    [origin]="origin"
    [destination]="destination"
></agm-direction>
</agm-map>

 Distance: {{distance}}

Only thing it says: ReferenceError: google is not defined

Does anyone familiar with such problem?

Body:
this code worked for me

home.component.ts

import { Component, OnInit ,ViewChild} from '@angular/core';
import { MapsAPILoader, AgmMap } from '@agm/core';
declare var google: any;

@Component({

  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {

  location: Location
  selectedMarker: Marker
  origin: any;
  destination: any;
  distance: String;
  geocoder: any;

   ngOnInit(){

    this.origin = {
      lat: 32.6950,
      lng: 35.2820
    };
  this.destination = {
      lat: 32.6050,
      lng: 35.2020
   };

    this.location = {
      latitude: 32.6950,
      longitude: 35.2820,
      zoom: 15,
      markers: [
          {
              lat: 32.6950,
              lng: 35.2820
          }
      ]
  }

     this.loadScript('assets/js/jquery-3.3.1.min.js');
     this.loadScript('assets/vendors/appear/jquery.appear.min.js');
     this.loadScript('assets/vendors/jquery.easing/jquery.easing.min.js');
     this.loadScript('assets/js/popper.min.js');
     this.loadScript('assets/js/bootstrap.min.js');
     this.loadScript('assets/vendors/common/common.min.js');
     this.loadScript('assets/vendors/fancybox/jquery.fancybox.min.js');
     this.loadScript('assets/vendors/menu/src/main.menu.js');
     this.loadScript('assets/vendors/owl.carousel/owl.carousel.min.js');
     this.loadScript('assets/vendors/animated-headline/js/animated-headline.js');
     this.loadScript('assets/js/main.js');
     this.loadScript('assets/js/theme.init.js');
     this.loadScript('assets/js/custom.js');
  }

  @ViewChild(AgmMap, { static: true }) map: AgmMap;

  constructor(public mapsApiLoader: MapsAPILoader) {
    this.mapsApiLoader = mapsApiLoader;

    this.mapsApiLoader.load().then(() => {
      this.geocoder = new google.maps.Geocoder();
      this.distance = this.calculateDistance(this.origin, this.destination);
    });
  }

  public loadScript(url: string) {
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.innerHTML = '';
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }

  addMarker(lat: number, lng: number) {
    this.location.markers.push({
        lat,
        lng
    })
  }

  selectMarker(event) {
    this.selectedMarker = {
        lat: event.latitude,
        lng: event.longitude
    }
  }

  calculateDistance(point1, point2) {

    const p1 = new google.maps.LatLng(
    point1.lat,
    point1.lng
    );
    const p2 = new google.maps.LatLng(
    point2.lat,
    point2.lng
    );

    return (
    google.maps.geometry.spherical.computeDistanceBetween(p1, p2)/1000
    ).toFixed(2);
}

}

interface Marker {
lat: number;
lng: number;
}

interface Location {
latitude: number;
longitude: number;
zoom: number;
markers: Array<Marker>;
}


来源: stackexchange

问:
Google Places Autocomplete Force Selection
I am using the JavaScript Google places autocomplete API v3. It works fine but I was wondering if there was a way to force the selection from the autocomplete, that is input that will not accept any free form text. I looked at the docs and didn't see such an option but figured I would ask just to be safe. I'm sure I could work out a way to do it with some JavaScript but would prefer to use an already built method if it is available. Thanks!</p>

答:
Like they mentioned it's not supported in the Google Autocomplete API.
I found a way to make it work by creating a hidden element that stores the selected places than check if it's equal to the autocomplete input.

```<code>/*----------------------------------------------------*/
/*  check if it's valid address
/*----------------------------------------------------*/
function checkAddress(location, validLocation) {
if (location.val() == validLocation.val()) {
    return true;
}
return false;
}

/*----------------------------------------------------*/
/*  initialize auto complete address
/*----------------------------------------------------*/
function initialize() {
 let input = document.getElementById('autocomplete-input');
 let inputHidden = document.getElementById('autocomplete-input-hidden');
 let options = {
    types: ['(regions)'],
    componentRestrictions: {country: "tn"}
 };
 let autocomplete =new google.maps.places.Autocomplete(input, options);
 autocomplete.setFields(['formatted_address']);
 autocomplete.addListener('place_changed', function () {
    inputHidden.value= autocomplete.getPlace().formatted_address;
 });
}
</code>```

call the function in your main.

```<code> let location = $('#autocomplete-input');
 let validLocation = $('#autocomplete-input-hidden');
 checkAddress(location,validLocation);
</code>```

and in your html:

```<code> <input id="autocomplete-input" type="text">
 <input id="autocomplete-input-hidden" type="hidden" >
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Like they mentioned it's not supported in the Google Autocomplete API.
I found a way to make it work by creating a hidden element that stores the selected places than check if it's equal to the autocomplete input.

/*----------------------------------------------------*/
/*  check if it's valid address
/*----------------------------------------------------*/
function checkAddress(location, validLocation) {
if (location.val() == validLocation.val()) {
    return true;
}
return false;
}

/*----------------------------------------------------*/
/*  initialize auto complete address
/*----------------------------------------------------*/
function initialize() {
 let input = document.getElementById('autocomplete-input');
 let inputHidden = document.getElementById('autocomplete-input-hidden');
 let options = {
    types: ['(regions)'],
    componentRestrictions: {country: "tn"}
 };
 let autocomplete =new google.maps.places.Autocomplete(input, options);
 autocomplete.setFields(['formatted_address']);
 autocomplete.addListener('place_changed', function () {
    inputHidden.value= autocomplete.getPlace().formatted_address;
 });
}

call the function in your main.

 let location = $('#autocomplete-input');
 let validLocation = $('#autocomplete-input-hidden');
 checkAddress(location,validLocation);

and in your html:

 <input id="autocomplete-input" type="text">
 <input id="autocomplete-input-hidden" type="hidden" >

ContentLicense: CC BY-SA 4.0


问:
Trigger a jQuery Event Handler Assigned in a Different Code Block
I have a case where a click handler is defined/assigned in one jQuery code block (file) and I want to trigger it from another click event defined/assigned in a different jQuery code block.  How can I accomplish this?

The following code is a greatly simplified version of what I am trying to accomplish. The behavior I want to see is a JavaScript alert "Element One" when I click #Element2.

Example HTML:

```<code><p id="Element1">Element One</p>
<p id="Element2">Element Two</p>
</code>```

First jQuery code block:

```<code>$(document).ready(function() {
    $('#Element1').click(function() {
        alert('Element One');
    });
});
</code>```

Second jQuery code block:

```<code>$(document).ready(function() {
    $('#Element2').click(function() {
        $('#Element1').click();
    });
});
</code>```

UPDATE: My original example actually works. I was building upon my field hint jQuery UI Dialog solution, and didn't account for about the 'clickoutside' handler that I was using.  Adding a check to for the second element in my 'clickoutside' handler allows the dialog to display.

答:
You need to trigger a click when you click on the first element. You can use the trigger method for this.</p>

```<code>function element1Hanlder () {
    alert('Element One');
}

$(document).ready(function() {
    $('#Element1').click(function() {
        alert('Element One');
    });
});

$(document).ready(function() {
    $('#Element2').click(function() {
        $('#Element1').trigger('click');
    });
});
</code>```

Body:
I have a case where a click handler is defined/assigned in one jQuery code block (file) and I want to trigger it from another click event defined/assigned in a different jQuery code block.  How can I accomplish this?

The following code is a greatly simplified version of what I am trying to accomplish. The behavior I want to see is a JavaScript alert "Element One" when I click #Element2.

Example HTML:

Element One

Element Two

First jQuery code block:

$(document).ready(function() {
    $('#Element1').click(function() {
        alert('Element One');
    });
});

Second jQuery code block:

$(document).ready(function() {
    $('#Element2').click(function() {
        $('#Element1').click();
    });
});

UPDATE: My original example actually works. I was building upon my field hint jQuery UI Dialog solution, and didn't account for about the 'clickoutside' handler that I was using.  Adding a check to for the second element in my 'clickoutside' handler allows the dialog to display.

Body:
You need to trigger a click when you click on the first element. You can use the trigger method for this.

function element1Hanlder () {
    alert('Element One');
}

$(document).ready(function() {
    $('#Element1').click(function() {
        alert('Element One');
    });
});

$(document).ready(function() {
    $('#Element2').click(function() {
        $('#Element1').trigger('click');
    });
});


问:
Linq to SQL and Entity Framework in Same project
I have a project that is using l2s. We are going to expand with new modules. Now we are thinking of using entity framework for new modules as it is not possible for us to change our existing modules to EF. Can some one share experiences of using both l2s and EF in same mvc project

Regards

答:
As mentioned - no issues with having them both - but having two technologies is
1. More difficult to follow
2. You sometimes need to maintain separate pieces of connection info
3. You require multiple skillsets
4. If l2s is ever deprecated - then you really should switch to one. True - its not currently deprecated as some thought it would be but its a better practice to be consistent inside of any one project.


问:
Merge dataframe on python
I'm working with dataframes on Python, I'm having trouble joining two dataframes.
A dataframe is related to information from countries around the world.
Another dataframe is related to the detailed information of one of the countries of the world of the previous dataframe (i.e. I'm going to add information on the regions, provinces, municipalities).
I created a script that merged the headers of the two data frames, the problem now is how to make a very distant comparison between the information of the second dataframe only in the field of the country in question?

My idea of a pseudo code was to first add 'len (dataframe2)' lines equal to dataframe1 related to the country information of which I then have the second detailed dataframe.
How do I get that information right?
This is what I would like to do (see photos)

答:
Make sure you have one column that's identical in both CSV files. I would add a column to the CSV with data of one country and enter the name of that country in each cell. Let's call the header of that column "country_name". Then do this:</p>

```<code>countries = pd.read_csv(filepath)
one_country = pd.read_csv(filepath)

merged = pd.merge(countries, one_country, on=["country_name"], how="inner")
</code>```

Title: Merge dataframe on python

Body:
Make sure you have one column that's identical in both CSV files. I would add a column to the CSV with data of one country and enter the name of that country in each cell. Let's call the header of that column "country_name". Then do this:

countries = pd.read_csv(filepath)
one_country = pd.read_csv(filepath)

merged = pd.merge(countries, one_country, on=["country_name"], how="inner")


问:
How to get the return from Axios.get and Render components dynamically on a Functional Component
I have a Functional Component and I am trying to get data from an axios.get() and render some components dynamically based on the response of the request.

If I console.log the response is Ok, but my problem is how to use the return from axios.get() to create components on the screen.

I've tried with a simple array and using it I can create the components. What I want is to create the components on screen the same way I've done with the array.

I've read a lot of post before posting my own. I would really appreciate some help or guidance.

import React, { createElement, useState, useEffect } from 'react';
import { Text, StyleSheet, View, TouchableOpacity, Image } from 'react-native';
import axios from 'axios';

const HomeScreen = ({ navigation }) => {

  axios.get("http://100.103.16.113:8081/api/checklists", {
  }).then
    (function (response) {
      console.log(response.data);
    }).catch(error => {
      console.log(error);
    })
  const checklists = [{
    "id": 1,
    "checklisT_DESCRIPTION": "CHECKLIST 1"
  },
  {
    "id": 2,
    "checklisT_DESCRIPTION": "CHECKLIST 2"
  },
  {
    "id": 3,
    "checklisT_DESCRIPTION": "CHECKLIST 3"
  }
  ]
  return (
    <View >
      <Text style={styles.text}> Select an Audit</Text>

      <View style={styles.maincontainer}>
        <View style={styles.container}>

          {}
          {checklists.map(r => (

            <TouchableOpacity onPress={() => navigation.navigate('AuditS')} style={styles.button}
            >
              <Image source={require('../assets/icons8-audit-80.png')} style={styles.Image}></Image>
              <Text style={styles.ButtonText}>{r.checklisT_DESCRIPTION}</Text>

            </TouchableOpacity >
          ))}

        </View>
      </View>
      <View style={styles.bottomcontainer}>
        <TouchableOpacity onPress={() => navigation.navigate('Login')}
        >
          <Text style={styles.logout}>LOGOUT</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  text: {
    fontSize: 50,
    fontFamily: 'Comfortaa-Regular',
    alignItems: "center",
    textAlignVertical: "center",
    textAlign: "center",
    justifyContent: "center",
  },
  container: {
    marginTop: 50,
    flexDirection: "row",
    marginLeft: 50,
    width: '100%'
  },
  maincontainer: {
    flexDirection: "column",
    width: '80%',
    alignContent: "center",
    justifyContent: "center",
  },
  bottomcontainer: {
    marginTop: '70%',
    width: '100%',
    alignItems: "center",
    justifyContent: "flex-end",
    alignContent: "flex-end",
  },
  logout: {
    marginTop: 50,
    margin: 15,
    height: 60,
    width: 440,
    borderColor: '#000000',
    backgroundColor: '#000000',
    borderWidth: 2,
    borderRadius: 10,
    fontSize: 18,
    textAlign: "center",
    textAlignVertical: "center",
    color: "#FFFFFF",
    fontFamily: 'Comfortaa-Bold'
  },
  button: {
    backgroundColor: '#0f99f5',
    fontSize: 16,
    color: '#FFF',
    width: 150,
    height: 150,
    borderRadius: 10,
    textAlignVertical: "bottom",
    textAlign: "center",
    marginVertical: 20,
    marginHorizontal: 10,
    fontFamily: 'Comfortaa-Bold'
  },
  ButtonText: {
    textAlignVertical: "bottom",
    textAlign: "center",
    fontSize: 16,
    color: '#FFF',
    marginHorizontal: 10,
    fontFamily: 'Comfortaa-Bold'
  },
  Image: {
    width: "50%",
    height: "50%",
    alignContent: "center",
    alignSelf: "center",
    marginTop: 10,
    marginBottom: 10
  }
});

export default HomeScreen;
```

答:
You can create a state variable for checklists then populate it using axios.get inside an useEffect. Make sure you verify if the checklist is populated or not by checking checklists.length before mapping over the list and accessing the data to render items.

const HomeScreen = ({ navigation }) => {

  // initialize the state variable
  const [checklists, setChecklists] = useState([]);

  // populate the data
  useEffect(() => {
   axios.get("http://100.103.16.113:8081/api/checklists")
         .then(function (response) {
                 setChecklists(response.data)
              })
         .catch(error => {
                 console.log(error);
         })
  }, [])

  // when mapping over the checklists make sure you check for the checklists.length before mapping

  {checklists.length &&  checklists.map(r =>(

      <TouchableOpacity onPress = {() => navigation.navigate('AuditS')}
         style={styles.button}
      >
        <Image source={require('../assets/icons8-audit-80.png')}
          style={styles.Image}>
        </Image>
        <Text style={styles.ButtonText}>{r.checklisT_DESCRIPTION}</Text>

      </TouchableOpacity >
       ))}

}

```

Here is an example codesandbox

Body:
You can create a state variable for checklists then populate it using axios.get inside an useEffect. Make sure you verify if the checklist is populated or not by checking checklists.length before mapping over the list and accessing the data to render items.

const HomeScreen = ({ navigation }) => {

  // initialize the state variable
  const [checklists, setChecklists] = useState([]);

  // populate the data
  useEffect(() => {
   axios.get("http://100.103.16.113:8081/api/checklists")
         .then(function (response) {
                 setChecklists(response.data)
              })
         .catch(error => {
                 console.log(error);
         })
  }, [])

  // when mapping over the checklists make sure you check for the checklists.length before mapping

  {checklists.length &&  checklists.map(r =>(

      <TouchableOpacity onPress = {() => navigation.navigate('AuditS')}
         style={styles.button}
      >
        <Image source={require('../assets/icons8-audit-80.png')}
          style={styles.Image}>
        </Image>
        <Text style={styles.ButtonText}>{r.checklisT_DESCRIPTION}</Text>

      </TouchableOpacity >
       ))}

}

Here is an example codesandbox


问:
Insert and populate Global Array LLVM
I am trying to write an LLVM Pass that locates a global array, copies it and inserts a new modified global array. But I can't even insert elements into my new array. I tried many different things such as populating a Value * array, IRBuilder, pushing onto a vector, reading terminal output from clang emit-llvm etc. It appears that Getelementptr load and store should be the best way of doing this but I kept getting errors and the LLVM Documentation does not explain this very well. Your help would be greatly appreciated.</p>

```<code>#include "llvm/Pass.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;

namespace {

    struct CopyMod : public FunctionPass
    {
        static char ID;
        const ConstantDataArray *data;
        const GlobalVariable *GR;
        ConstantDataArray *Add;
        GlobalVariable *G;
        Module * Mod;

        CopyMod() : FunctionPass(ID) {}

        bool runOnFunction(Function &F) override
        {
          for (inst_iterator idx = inst_begin(F), E = inst_end(F); idx != E; idx++)
          {
             if(auto *GI = dyn_cast<GetElementPtrInst>(&*idx))
             {
                 for(const Value *Op : GI->operands())
                 {
                     if(GR = dyn_cast<GlobalVariable>(Op))
                     {
                         if(data = dyn_cast<ConstantDataArray>(GR->getInitializer()))
                         {
                             errs() << "Number of Elements we got: " << data->getNumElements() << "\n";

                             for(int k = 0, ed = data->getNumElements(); k < ed; ++k)
                                errs() << data->getElementAsInteger(k) << "\n";

                                Mod = F.getParent();
                                auto dude = Mod->getOrInsertGlobal("new_table", ArrayType::get(Type::getInt32Ty(F.getContext()),
                                                                                data->getNumElements()));
                                G = Mod->getNamedGlobal("new_table");
                                G->setLinkage(GlobalValue::LinkageTypes::CommonLinkage);

                                auto arrayType =
                                    llvm::ArrayType::get(llvm::IntegerType::get(idx->getContext(), 32), data->getNumElements());

                                auto arrayPtr = new llvm::AllocaInst(arrayType, "", idx->getContext());

                                for(auto id = 0; id < data->getNumElements(); ++id)
                                {

                                      auto myElt = llvm::ConstantInt::get(idx->getContext(), llvm::APInt(64, 0, true));
                                      auto myIndex = llvm::ConstantInt::get(idx->getContext(), llvm::APInt(32, id, true));

                                      auto ptr = llvm::GetElementPtrInst::Create(arrayPtr->getType(), arrayPtr, { myElt, myIndex }, "", idx->getParent());
                                      auto store = new llvm::StoreInst(myIndex, ptr, false, idx->getParent());
                                }
                                G->setInitializer((Constant *)arrayPtr);
                         }
                     }

                 }
             }
          }
            return false;
        }
    };
} //End of namespace

char CopyMod::ID = 0;
static RegisterPass<CopyMod> X("cpymd", "CopyMod", false, false);
</code>```

答:
The GetElementPtrInst doesn't perform memory operations. It only computes memory addresses. You've already constructed the new array dude, so to populate it with data's elements, we use the loop as you have done except on each iteration, we compute the address of the current element with the GEP instruction, create a load operation from that address, and store the value of that load op in the corresponding computed address of the dude array (what a cool name! maybe that's why it always has trouble getting pass code reviews :):) ).

I recommend you use a builder instance, as it's a lot easier. I've modified part your code

```<code>struct CopyMod : public FunctionPass
{
    static char ID;
    const ConstantDataArray *data;
    const GlobalVariable *GR;
    ConstantDataArray *Add;
    GlobalVariable *G;
    Module * Mod;

    CopyMod() : FunctionPass(ID) {}

    bool runOnFunction(Function &F) override
    {
    IRBuilder<> builder(F.getContext());
      for (inst_iterator idx = inst_begin(F), E = inst_end(F); idx != E; idx++)
      {
         if(auto *GI = dyn_cast<GetElementPtrInst>(&*idx))
         {
             for(const Value *Op : GI->operands())
             {
                 if(GR = dyn_cast<GlobalVariable>(Op))
                 {
                     if(data = dyn_cast<ConstantDataArray>(GR->getInitializer()))
                     {
                         errs() << "Number of Elements we got: " << data->getNumElements() << "\n";

                         for(int k = 0, ed = data->getNumElements(); k < ed; ++k)
                            errs() << data->getElementAsInteger(k) << "\n";

                            Mod = F.getParent();
                            auto dude = Mod->getOrInsertGlobal("new_table", data->getType()),
                                                                                data->getNumElements()));
                            G = Mod->getNamedGlobal("new_table");
                            G->setLinkage(GlobalValue::LinkageTypes::CommonLinkage);

                            for(auto id = 0; id < data->getNumElements(); ++id)
                            {
                              auto srcAddress = builder.CreateGEP(data, std::vector<Value*>{ConstantInt::get(Type::getInt32Ty(context), 0), id});
                              auto loadedElem = builder.CreateLoad(srcAddress);
                              auto destAddress = builder.CreateGEP(G, std::vector<Value*>{ConstantInt::get(Type::getInt32Ty(context), 0), id});
                              builder.CreateStore(loadedElem, destAddress);
                            }

                     }
                 }

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

Title: Insert and populate Global Array LLVM

Body:
I am trying to write an LLVM Pass that locates a global array, copies it and inserts a new modified global array. But I can't even insert elements into my new array. I tried many different things such as populating a Value * array, IRBuilder, pushing onto a vector, reading terminal output from clang emit-llvm etc. It appears that Getelementptr load and store should be the best way of doing this but I kept getting errors and the LLVM Documentation does not explain this very well. Your help would be greatly appreciated.

#include "llvm/Pass.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;

namespace {

    struct CopyMod : public FunctionPass
    {
        static char ID;
        const ConstantDataArray *data;
        const GlobalVariable *GR;
        ConstantDataArray *Add;
        GlobalVariable *G;
        Module * Mod;

        CopyMod() : FunctionPass(ID) {}

        bool runOnFunction(Function &F) override
        {
          for (inst_iterator idx = inst_begin(F), E = inst_end(F); idx != E; idx++)
          {
             if(auto *GI = dyn_cast<GetElementPtrInst>(&*idx))
             {
                 for(const Value *Op : GI->operands())
                 {
                     if(GR = dyn_cast<GlobalVariable>(Op))
                     {
                         if(data = dyn_cast<ConstantDataArray>(GR->getInitializer()))
                         {
                             errs() << "Number of Elements we got: " << data->getNumElements() << "\n";

                             for(int k = 0, ed = data->getNumElements(); k < ed; ++k)
                                errs() << data->getElementAsInteger(k) << "\n";

                                Mod = F.getParent();
                                auto dude = Mod->getOrInsertGlobal("new_table", ArrayType::get(Type::getInt32Ty(F.getContext()),
                                                                                data->getNumElements()));
                                G = Mod->getNamedGlobal("new_table");
                                G->setLinkage(GlobalValue::LinkageTypes::CommonLinkage);

                                auto arrayType =
                                    llvm::ArrayType::get(llvm::IntegerType::get(idx->getContext(), 32), data->getNumElements());

                                auto arrayPtr = new llvm::AllocaInst(arrayType, "", idx->getContext());

                                for(auto id = 0; id < data->getNumElements(); ++id)
                                {

                                      auto myElt = llvm::ConstantInt::get(idx->getContext(), llvm::APInt(64, 0, true));
                                      auto myIndex = llvm::ConstantInt::get(idx->getContext(), llvm::APInt(32, id, true));

                                      auto ptr = llvm::GetElementPtrInst::Create(arrayPtr->getType(), arrayPtr, { myElt, myIndex }, "", idx->getParent());
                                      auto store = new llvm::StoreInst(myIndex, ptr, false, idx->getParent());
                                }
                                G->setInitializer((Constant *)arrayPtr);
                         }
                     }

                 }
             }
          }
            return false;
        }
    };
} //End of namespace

char CopyMod::ID = 0;
static RegisterPass<CopyMod> X("cpymd", "CopyMod", false, false);

Body:
The GetElementPtrInst doesn't perform memory operations. It only computes memory addresses. You've already constructed the new array dude, so to populate it with data's elements, we use the loop as you have done except on each iteration, we compute the address of the current element with the GEP instruction, create a load operation from that address, and store the value of that load op in the corresponding computed address of the dude array (what a cool name! maybe that's why it always has trouble getting pass code reviews :):) ).

I recommend you use a builder instance, as it's a lot easier. I've modified part your code

struct CopyMod : public FunctionPass
{
    static char ID;
    const ConstantDataArray *data;
    const GlobalVariable *GR;
    ConstantDataArray *Add;
    GlobalVariable *G;
    Module * Mod;

    CopyMod() : FunctionPass(ID) {}

    bool runOnFunction(Function &F) override
    {
    IRBuilder<> builder(F.getContext());
      for (inst_iterator idx = inst_begin(F), E = inst_end(F); idx != E; idx++)
      {
         if(auto *GI = dyn_cast<GetElementPtrInst>(&*idx))
         {
             for(const Value *Op : GI->operands())
             {
                 if(GR = dyn_cast<GlobalVariable>(Op))
                 {
                     if(data = dyn_cast<ConstantDataArray>(GR->getInitializer()))
                     {
                         errs() << "Number of Elements we got: " << data->getNumElements() << "\n";

                         for(int k = 0, ed = data->getNumElements(); k < ed; ++k)
                            errs() << data->getElementAsInteger(k) << "\n";

                            Mod = F.getParent();
                            auto dude = Mod->getOrInsertGlobal("new_table", data->getType()),
                                                                                data->getNumElements()));
                            G = Mod->getNamedGlobal("new_table");
                            G->setLinkage(GlobalValue::LinkageTypes::CommonLinkage);

                            for(auto id = 0; id < data->getNumElements(); ++id)
                            {
                              auto srcAddress = builder.CreateGEP(data, std::vector<Value*>{ConstantInt::get(Type::getInt32Ty(context), 0), id});
                              auto loadedElem = builder.CreateLoad(srcAddress);
                              auto destAddress = builder.CreateGEP(G, std::vector<Value*>{ConstantInt::get(Type::getInt32Ty(context), 0), id});
                              builder.CreateStore(loadedElem, destAddress);
                            }

                     }
                 }

             }
         }
      }
        return false;
    }
};


问:
Assign_attributes only assigns child attr_accessor values if a table column is changed on updates
Here's the set up

```<code>class Order
  has_many :items
  accepts_nested_attributes_for :items
end

class Item
  belongs_to :order
  attr_accessor :discount # this is NOT a table column, just a virtual attribute I want to be able to assign
end
</code>```

Let's say I have an existing order @order. I noticed that if I were to try to assign discount on the child Item from the Order model, this only works if some other attribute on the child Item is changed.

```<code>@order.assign_attributes({"items_attributes"=>[{"id"=>40, "discount"=>"test"}]})
@order.items.first.discount
=> nil

@order.assign_attributes({"items_attributes"=>[{"id"=>40, "discount"=>"test", "admin_notes"=>"hello"}]})
# where admin_notes is a table column for Item
@order.items.first.discount
=> "test
@order.items.first.admin_notes
=> "hello"
</code>```

Is there a quick setting change or something to change this? I'd like attr_accessor attributes to always be assigned even if no attributes are changing?

答: FWIW if anyone stumbles upon this.... it appears to have resolved itself. Was working on something else today and noticed that I can't duplicate the original error anymore. A lot has changed in code, not going to go back and dig into this to figure out what happened. I do know that key configuration variables that could have affected this have not changed, e.g., inverse_of flag set on both models, Order model set to accepts_nested_attributes_for :items

Body:
Here's the set up

class Order
  has_many :items
  accepts_nested_attributes_for :items
end

class Item
  belongs_to :order
  attr_accessor :discount # this is NOT a table column, just a virtual attribute I want to be able to assign
end

Let's say I have an existing order @order. I noticed that if I were to try to assign discount on the child Item from the Order model, this only works if some other attribute on the child Item is changed.

@order.assign_attributes({"items_attributes"=>[{"id"=>40, "discount"=>"test"}]})
@order.items.first.discount
=> nil

@order.assign_attributes({"items_attributes"=>[{"id"=>40, "discount"=>"test", "admin_notes"=>"hello"}]})
# where admin_notes is a table column for Item
@order.items.first.discount
=> "test
@order.items.first.admin_notes
=> "hello"

Is there a quick setting change or something to change this? I'd like attr_accessor attributes to always be assigned even if no attributes are changing?


问:
Losing Data on Reload When Fetching Data from a Service in Angular 8
I am using a service to send two lists of objects between two Angular pages, which works correctly. The problem is, if I happen to reload the page that recieves the data, the lists will get deleted from memory.
Is there a way to avoid this problem?

The way I am sending the data is simply by having two lists in the service defined as global variables, and I assign them the values of the two lists in page 1 before navigating to page 2. Once I'm in page two, I simply fetch the service on the OnInit method and assign the lists to the ones on page 2. Is there a way to persist this data after a reload?

答:
Put this to the place where you get the data:

```<code>localStorage.setItem('theKeyYouWant', JSON.stringify(this.list));
</code>```

Put this to the ngOnInit:

```<code>const item = localStorage.getItem('theKeyYouWant');
if (item) {
    this.list = JSON.parse(item);
} else {
    this.list = [];
}
</code>```

See: MDN localStorage

localStorage exists in the browser, there is no need to import something.

I often use this code in my projects:

```<code>import { BehaviorSubject } from 'rxjs';

export class TypedDataService<T> {
  private readonly bhs: BehaviorSubject<T> = new BehaviorSubject<T>(null);
  valueChanges$ = this.bhs.asObservable();
  private value: T;

  constructor(
    private readonly key: string,
    private readonly defaultValue: T = null,
    private readonly equals: (x: T, y: T) => boolean = (x: T, y: T) =>
      JSON.stringify(x) === JSON.stringify(y),
    private readonly clone: (x: T) => T = (x: T) => JSON.parse(JSON.stringify(x)),
    private readonly parse: (s: string) => T = (s: string) => JSON.parse(s) as T,
    private readonly stringify: (x: T) => string = (x: T) => JSON.stringify(x)
  ) {
    this.init();
  }

  init() {
    const item = localStorage.getItem(this.key);
    if (item) {
      this.value = this.parse(item);
    } else {
      this.value = this.defaultValue;
    }
    if (this.value) {
      this.next();
    }
  }

  update(nvObj: T) {
    if (!this.equals(nvObj, this.value)) {
      if (nvObj === null) {
        localStorage.removeItem(this.key);

      } else {
        this.value = this.parse(this.stringify(nvObj));
        const nv = this.stringify(nvObj);
        localStorage.setItem(this.key, nv);
      }
      this.next();
    }
  }

  getValue(): T {
    return this.value;
  }

  private next() {
    this.bhs.next(this.clone(this.value));
  }
}
</code>```

Example usage:

```<code>import { Injectable } from '@angular/core';
import { SettingsData } from '../data/settings.data';
import { TypedDataService } from '../../common/typed-data-service';

@Injectable({
  providedIn: 'root'
})
export class SettingsService {
  private static readonly innerService = new TypedDataService<SettingsData>(
    'settings',
    new SettingsData()
  );

  get settings$() {
    return SettingsService.innerService.valueChanges$;
  }

  getSettingsFromStorage(): SettingsData {
    return SettingsService.innerService.getValue();
  }

  settings2storage(data: SettingsData): void {
    SettingsService.innerService.update(data);
  }

  private deleteSettingsFromStorage(): void {
    SettingsService.innerService.update(null);
  }
}
</code>```

Body:
Put this to the place where you get the data:

localStorage.setItem('theKeyYouWant', JSON.stringify(this.list));

Put this to the ngOnInit:

const item = localStorage.getItem('theKeyYouWant');
if (item) {
    this.list = JSON.parse(item);
} else {
    this.list = [];
}

See: MDN localStorage

localStorage exists in the browser, there is no need to import something.

I often use this code in my projects:

import { BehaviorSubject } from 'rxjs';

export class TypedDataService<T> {
  private readonly bhs: BehaviorSubject<T> = new BehaviorSubject<T>(null);
  valueChanges$ = this.bhs.asObservable();
  private value: T;

  constructor(
    private readonly key: string,
    private readonly defaultValue: T = null,
    private readonly equals: (x: T, y: T) => boolean = (x: T, y: T) =>
      JSON.stringify(x) === JSON.stringify(y),
    private readonly clone: (x: T) => T = (x: T) => JSON.parse(JSON.stringify(x)),
    private readonly parse: (s: string) => T = (s: string) => JSON.parse(s) as T,
    private readonly stringify: (x: T) => string = (x: T) => JSON.stringify(x)
  ) {
    this.init();
  }

  init() {
    const item = localStorage.getItem(this.key);
    if (item) {
      this.value = this.parse(item);
    } else {
      this.value = this.defaultValue;
    }
    if (this.value) {
      this.next();
    }
  }

  update(nvObj: T) {
    if (!this.equals(nvObj, this.value)) {
      if (nvObj === null) {
        localStorage.removeItem(this.key);

      } else {
        this.value = this.parse(this.stringify(nvObj));
        const nv = this.stringify(nvObj);
        localStorage.setItem(this.key, nv);
      }
      this.next();
    }
  }

  getValue(): T {
    return this.value;
  }

  private next() {
    this.bhs.next(this.clone(this.value));
  }
}

Example usage:

import { Injectable } from '@angular/core';
import { SettingsData } from '../data/settings.data';
import { TypedDataService } from '../../common/typed-data-service';

@Injectable({
  providedIn: 'root'
})
export class SettingsService {
  private static readonly innerService = new TypedDataService<SettingsData>(
    'settings',
    new SettingsData()
  );

  get settings$() {
    return SettingsService.innerService.valueChanges$;
  }

  getSettingsFromStorage(): SettingsData {
    return SettingsService.innerService.getValue();
  }

  settings2storage(data: SettingsData): void {
    SettingsService.innerService.update(data);
  }

  private deleteSettingsFromStorage(): void {
    SettingsService.innerService.update(null);
  }
}


问:
How to get string value from a enum in typescript?
I have an enum of string values. I want to pass a string value to enum and get the value from it.

```<code>export enum OperationType  {
    CREATE = "CREATE",
    UPDATE = "UPDATE"
}
</code>```

I have class as well

```<code>class Item {
type:string;
id:string
date:string
}
</code>```

Now i am calling below function

```<code>function sendData(type:OperationType) {
//Do some work
}
</code>```

Now i want to pass the value in enum like this but i am not able to do

```<code>//Here item.type = "CREATE"

sendData(OperationType[item.type])
</code>```

But this is now allowed i get compile time error of wrong type. Please tell me how can i achieve?

EDIT:
Error is

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof OperationType'.

答:
In your case I'd use unions:

```<code>type OperationType = "CREATE" | "UPDATE";

class Item {
  type: OperationType;
  id: string;
  date: string;
}

function sendData(type: OperationType) {
  //Do some work
}
</code>```

This approach provides same IDE intelligence and type checking. Otherwise, you can just change type: OperationType;.

Also you can use const enums. const modifier makes enum readonly and tells compiler not to generate reverse mapping;

```<code>export const enum OperationType  {
    CREATE = "CREATE",
    UPDATE = "UPDATE"
}
</code>```

Body:
I have an enum of string values. I want to pass a string value to enum and get the value from it.

export enum OperationType  {
    CREATE = "CREATE",
    UPDATE = "UPDATE"
}

I have class as well

class Item {
type:string;
id:string
date:string
}

Now i am calling below function

function sendData(type:OperationType) {
//Do some work
}

Now i want to pass the value in enum like this but i am not able to do

//Here item.type = "CREATE"

sendData(OperationType[item.type])

But this is now allowed i get compile time error of wrong type. Please tell me how can i achieve?

EDIT:
Error is

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof OperationType'.

Body:
In your case I'd use unions:

type OperationType = "CREATE" | "UPDATE";

class Item {
  type: OperationType;
  id: string;
  date: string;
}

function sendData(type: OperationType) {
  //Do some work
}

This approach provides same IDE intelligence and type checking. Otherwise, you can just change type: OperationType;.

Also you can use const enums. const modifier makes enum readonly and tells compiler not to generate reverse mapping;

export const enum OperationType  {
    CREATE = "CREATE",
    UPDATE = "UPDATE"
}


问:
TreeView style does not apply in tkinter
I designed a button with tkinter in root window, when i click on the button, a new window should appear with a treeView. I already defined a style for the treeView but it doesn't apply.
The full code is shown below

```<code>import tkinter as tk
from tkinter import ttk
import pandas as pd
root = tk.Tk()
style1 = ttk.Style()
style1.configure("mystyle1.Treeview", highlightthickness=0, bd=0, font=('Calibri', 11, 'bold')) # Modify the font of the body
style1.configure("mystyle1.Treeview.Heading", font=('Calibri', 10,'bold'),foreground="white", background="blue") # Modify the font of the headings
style1.layout("mystyle1.Treeview", [('mystyle1.Treeview.treearea', {'sticky': 'nswe'})]) # Remove the borders
def displaytree():
    app = tk.Tk()
    sample = {"File Name":[f"file_{i}" for i in range(5)],
              'Sheet Name': [f"sheet_{i}" for i in range(5)],
              'Number Of Rows': [f"row_{i}" for i in range(5)],
              'Number Of Columns': [f"col_{i}" for i in range(5)]
              }
    df = pd.DataFrame(sample)
    cols = list(df.columns)
    treeV = ttk.Treeview(app, style="mystyle1.Treeview")
    treeV.pack()
    treeV["columns"] = cols
    for i in cols:
        treeV.column(i, anchor="w")
        treeV.heading(i, text=i, anchor='w')
    for index, row in df.iterrows():
        treeV.insert("","end",text=index,values=list(row))
    app.mainloop()
bt1 = tk.Button(root, text="DISPLAY TREE VIEW", font="Times 12 bold", activebackground="white",
                activeforeground="green",width=16,height=1,bg="green",fg="white", command=displaytree)
bt1.pack()
root.mainloop()
</code>```

What did i miss?
Thank you in advance for your help

答:
Dont call tk.Tk() twice use Toplevel instead.</p>

```<code>import tkinter as tk
from tkinter import ttk
import pandas as pd
root = tk.Tk()
style1 = ttk.Style()
style1.configure("mystyle1.Treeview", highlightthickness=0, bd=0, font=('Calibri', 11, 'bold')) # Modify the font of the body
style1.configure("mystyle1.Treeview.Heading", font=('Calibri', 10,'bold'),foreground="white", background="blue") # Modify the font of the headings
style1.layout("mystyle1.Treeview", [('mystyle1.Treeview.treearea', {'sticky': 'nswe'})]) # Remove the borders
def displaytree():
    app = tk.Toplevel()
    sample = {"File Name":[f"file_{i}" for i in range(5)],
              'Sheet Name': [f"sheet_{i}" for i in range(5)],
              'Number Of Rows': [f"row_{i}" for i in range(5)],
              'Number Of Columns': [f"col_{i}" for i in range(5)]
              }
    df = pd.DataFrame(sample)
    cols = list(df.columns)
    treeV = ttk.Treeview(app, style="mystyle1.Treeview")
    treeV.pack()
    treeV["columns"] = cols
    for i in cols:
        treeV.column(i, anchor="w")
        treeV.heading(i, text=i, anchor='w')
    for index, row in df.iterrows():
        treeV.insert("","end",text=index,values=list(row))
    app.mainloop()
bt1 = tk.Button(root, text="DISPLAY TREE VIEW", font="Times 12 bold", activebackground="white",
                activeforeground="green",width=16,height=1,bg="green",fg="white", command=displaytree)
bt1.pack()
root.mainloop()
</code>```

Body:
I designed a button with tkinter in root window, when i click on the button, a new window should appear with a treeView. I already defined a style for the treeView but it doesn't apply.
The full code is shown below

import tkinter as tk
from tkinter import ttk
import pandas as pd
root = tk.Tk()
style1 = ttk.Style()
style1.configure("mystyle1.Treeview", highlightthickness=0, bd=0, font=('Calibri', 11, 'bold')) # Modify the font of the body
style1.configure("mystyle1.Treeview.Heading", font=('Calibri', 10,'bold'),foreground="white", background="blue") # Modify the font of the headings
style1.layout("mystyle1.Treeview", [('mystyle1.Treeview.treearea', {'sticky': 'nswe'})]) # Remove the borders
def displaytree():
    app = tk.Tk()
    sample = {"File Name":[f"file_{i}" for i in range(5)],
              'Sheet Name': [f"sheet_{i}" for i in range(5)],
              'Number Of Rows': [f"row_{i}" for i in range(5)],
              'Number Of Columns': [f"col_{i}" for i in range(5)]
              }
    df = pd.DataFrame(sample)
    cols = list(df.columns)
    treeV = ttk.Treeview(app, style="mystyle1.Treeview")
    treeV.pack()
    treeV["columns"] = cols
    for i in cols:
        treeV.column(i, anchor="w")
        treeV.heading(i, text=i, anchor='w')
    for index, row in df.iterrows():
        treeV.insert("","end",text=index,values=list(row))
    app.mainloop()
bt1 = tk.Button(root, text="DISPLAY TREE VIEW", font="Times 12 bold", activebackground="white",
                activeforeground="green",width=16,height=1,bg="green",fg="white", command=displaytree)
bt1.pack()
root.mainloop()

What did i miss?
Thank you in advance for your help

Body:
Dont call tk.Tk() twice use Toplevel instead.

import tkinter as tk
from tkinter import ttk
import pandas as pd
root = tk.Tk()
style1 = ttk.Style()
style1.configure("mystyle1.Treeview", highlightthickness=0, bd=0, font=('Calibri', 11, 'bold')) # Modify the font of the body
style1.configure("mystyle1.Treeview.Heading", font=('Calibri', 10,'bold'),foreground="white", background="blue") # Modify the font of the headings
style1.layout("mystyle1.Treeview", [('mystyle1.Treeview.treearea', {'sticky': 'nswe'})]) # Remove the borders
def displaytree():
    app = tk.Toplevel()
    sample = {"File Name":[f"file_{i}" for i in range(5)],
              'Sheet Name': [f"sheet_{i}" for i in range(5)],
              'Number Of Rows': [f"row_{i}" for i in range(5)],
              'Number Of Columns': [f"col_{i}" for i in range(5)]
              }
    df = pd.DataFrame(sample)
    cols = list(df.columns)
    treeV = ttk.Treeview(app, style="mystyle1.Treeview")
    treeV.pack()
    treeV["columns"] = cols
    for i in cols:
        treeV.column(i, anchor="w")
        treeV.heading(i, text=i, anchor='w')
    for index, row in df.iterrows():
        treeV.insert("","end",text=index,values=list(row))
    app.mainloop()
bt1 = tk.Button(root, text="DISPLAY TREE VIEW", font="Times 12 bold", activebackground="white",
                activeforeground="green",width=16,height=1,bg="green",fg="white", command=displaytree)
bt1.pack()
root.mainloop()


问:
How to create multiple images upload in Django CreateView?
I have a Django project and I created a post operation in this project, so the user will be able to share multiple picture posts. But I have a problem. I can't write multiple image upload function. I looked at a lot of content, but it doesn't work. Either it reports a problem or context is not sent to the HTML page I wanted. Please help me. The multi picture function I want should be under CreateView and should be placed in the same template as it. Also, there should be 4 Image upload buttons, and the last one should be assigned multiple features (to HTML tag).

models.py:

```<code>class Photo(models.Model):
    post= models.ForeignKey(Person, on_delete=models.CASCADE)

    image = models.ImageField(upload_to=get_image_filename)
    uploaded_at = models.DateTimeField(auto_now_add=True)
</code>```

views.py:

```<code>class PersonCreateView(CreateView):
    model = Person
    form_class = PersonForm
    success_url = reverse_lazy('person_changelist')
</code>```

forms.py:

```<code>class PhotoForm(forms.ModelForm):
    image = forms.ImageField(label='Image')
    class Meta:
        model = Photo
        fields = ('image', )

class PersonForm(forms.ModelForm):
    title = forms.CharField(max_length=128)
    body = forms.CharField(max_length=245, label="Item Description.")
    file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

    class Meta:
        model = Person
        widgets = {
            'valyuta': forms.RadioSelect,
            'barter': forms.CheckboxInput,

        }
        fields = ('country', 'city', 'ban', 'yurus', 'reng', 'qiymet', 'valyuta', 'yanacaqnovu', 'oturucu', 'squtu', 'buraxilisili', 'hecm', 'seher', 'barter', 'metin')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['city'].queryset = City.objects.none()

        if 'country' in self.data:
            try:
                country_id = int(self.data.get('country'))
                self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name')
            except (ValueError, TypeError):
                pass  # invalid input from the client; ignore and fallback to empty City queryset
        elif self.instance.pk:
            self.fields['city'].queryset = self.instance.country.city_set.order_by('name')
</code>```

答:
I was struggling with the same issue but eventually I succeeded. So i want to share my solution.
First of all we need to create 2 models, one of them to put ImageField and connect using ForeignKey with the first model.

models.py

```<code>class Item(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="items")
    name = models.CharField(max_length=100)

class ItemImage(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    img = models.ImageField(default="store/default_noitem.jpg", upload_to=get_image_dir)
</code>```

Then create form using inlineformset_factory. It helps especially in the case of working with related objects via a foreign key.

forms.py

```<code>from django import forms
from django.forms.models import inlineformset_factory

from .models import Item, ItemImage

class  ItemImageForm(forms.ModelForm):
    class Meta:
        model = ItemImage
        exclude = ()

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ["name",]

ItemImageFormSet = inlineformset_factory(
    Item, ItemImage, form=ItemImageForm,
    fields=['img'], extra=3, can_delete=True  # <- place where you can enter the nr of img
)
</code>```

And finally

views.py

```<code>class ItemCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    template_name = "items/add_item_form.html"
    success_message = 'Item successfully added!'
    form_class = ItemForm

    def get_context_data(self, **kwargs):
        data = super(ItemCreateView, self).get_context_data(**kwargs)
        data['form_images'] = ItemImageFormSet()
        if self.request.POST:
            data['form_images'] = ItemImageFormSet(self.request.POST, self.request.FILES)
        else:
            data['form_images'] = ItemImageFormSet()
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        form_img = context['form_images']
        with transaction.atomic():
            form.instance.user = self.request.user
            self.object = form.save()
            if form_img.is_valid():
                form_img.instance = self.object
                form_img.save()
        return super(ItemCreateView, self).form_valid(form)
</code>```

Remember to add (self.request.POST, self.request.FILES) inside formset and enctype="multipart/form-data" inside html where <form> tag is located.

Body:
I have a Django project and I created a post operation in this project, so the user will be able to share multiple picture posts. But I have a problem. I can't write multiple image upload function. I looked at a lot of content, but it doesn't work. Either it reports a problem or context is not sent to the HTML page I wanted. Please help me. The multi picture function I want should be under CreateView and should be placed in the same template as it. Also, there should be 4 Image upload buttons, and the last one should be assigned multiple features (to HTML tag).

models.py:

class Photo(models.Model):
    post= models.ForeignKey(Person, on_delete=models.CASCADE)

    image = models.ImageField(upload_to=get_image_filename)
    uploaded_at = models.DateTimeField(auto_now_add=True)

views.py:

class PersonCreateView(CreateView):
    model = Person
    form_class = PersonForm
    success_url = reverse_lazy('person_changelist')

forms.py:

class PhotoForm(forms.ModelForm):
    image = forms.ImageField(label='Image')
    class Meta:
        model = Photo
        fields = ('image', )

class PersonForm(forms.ModelForm):
    title = forms.CharField(max_length=128)
    body = forms.CharField(max_length=245, label="Item Description.")
    file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

    class Meta:
        model = Person
        widgets = {
            'valyuta': forms.RadioSelect,
            'barter': forms.CheckboxInput,

        }
        fields = ('country', 'city', 'ban', 'yurus', 'reng', 'qiymet', 'valyuta', 'yanacaqnovu', 'oturucu', 'squtu', 'buraxilisili', 'hecm', 'seher', 'barter', 'metin')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['city'].queryset = City.objects.none()

        if 'country' in self.data:
            try:
                country_id = int(self.data.get('country'))
                self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name')
            except (ValueError, TypeError):
                pass  # invalid input from the client; ignore and fallback to empty City queryset
        elif self.instance.pk:
            self.fields['city'].queryset = self.instance.country.city_set.order_by('name')

Body:
I was struggling with the same issue but eventually I succeeded. So i want to share my solution.
First of all we need to create 2 models, one of them to put ImageField and connect using ForeignKey with the first model.

models.py

class Item(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="items")
    name = models.CharField(max_length=100)

class ItemImage(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    img = models.ImageField(default="store/default_noitem.jpg", upload_to=get_image_dir)

Then create form using inlineformset_factory. It helps especially in the case of working with related objects via a foreign key.

forms.py

from django import forms
from django.forms.models import inlineformset_factory

from .models import Item, ItemImage

class  ItemImageForm(forms.ModelForm):
    class Meta:
        model = ItemImage
        exclude = ()

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ["name",]

ItemImageFormSet = inlineformset_factory(
    Item, ItemImage, form=ItemImageForm,
    fields=['img'], extra=3, can_delete=True  # <- place where you can enter the nr of img
)

And finally

views.py

class ItemCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    template_name = "items/add_item_form.html"
    success_message = 'Item successfully added!'
    form_class = ItemForm

    def get_context_data(self, **kwargs):
        data = super(ItemCreateView, self).get_context_data(**kwargs)
        data['form_images'] = ItemImageFormSet()
        if self.request.POST:
            data['form_images'] = ItemImageFormSet(self.request.POST, self.request.FILES)
        else:
            data['form_images'] = ItemImageFormSet()
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        form_img = context['form_images']
        with transaction.atomic():
            form.instance.user = self.request.user
            self.object = form.save()
            if form_img.is_valid():
                form_img.instance = self.object
                form_img.save()
        return super(ItemCreateView, self).form_valid(form)

Remember to add (self.request.POST, self.request.FILES) inside formset and enctype="multipart/form-data" inside html where <form> tag is located.


问:
Can i use UUID as datatype for id field in model/pojo class using hibernate search
I am trying to implement search functionality using hibernate search for my project which is in spring boot .

I used hibernate search annotations like @Indexed, @Field.

When i use datatype of id  Field as Long then search is performed and list of results is returned but in my project UUID is used as datatype for id field which is also primary key  .in the case of UUID the result is an empty list.

```<code>@Id
@GeneratedValue
private UUID id;
</code>```

How can i perform search operation using UUID as datatype for id field?

答:
Please use the following code

```<code>@Id
@Type(type = "uuid-char") // add column type
@GeneratedValue
@Column(name = "id")
</code>```

You need to add  @Type for the ID column if your using uuid as your data type

I hope it helps you
Thanks

Body:
I am trying to implement search functionality using hibernate search for my project which is in spring boot .

I used hibernate search annotations like @Indexed, @Field.

When i use datatype of id  Field as Long then search is performed and list of results is returned but in my project UUID is used as datatype for id field which is also primary key  .in the case of UUID the result is an empty list.

@Id
@GeneratedValue
private UUID id;

How can i perform search operation using UUID as datatype for id field?

Body:
Please use the following code

@Id
@Type(type = "uuid-char") // add column type
@GeneratedValue
@Column(name = "id")

You need to add  @Type for the ID column if your using uuid as your data type

I hope it helps you
Thanks


问:
How to extract the last digits of strings using regular expressions?
I have a bunch of colnames

```<code>L_1_3
L_2_23
L_3_91
L_3_16
</code>```

I want to replace these colnames with new names using the last digits following the _ like this:

```<code>3
23
91
16
</code>```

I've tried colnames(X) <- gsub("L_\\d\\d_", "", colnames(X)) which works for strings with double digits at the end. I want one that works for both single and double digits.

Thank you!

答:
Here is a regular expression that does it.

It gets anything until a non-digit followed by the capture group of one or more digits at the end. And replaces by the the capture group.

```<code>sub('.*[^[:digit:]]{1}([[:digit:]]+$)', '\\1', x)
#[1] "3"  "23" "91" "16"
</code>```

A regex that works for single and double digits but neither more nor less would be

```<code>sub('.*[^[:digit:]]{1}([[:digit:]]{1,2}$)', '\\1', x)
#[1] "3"  "23" "91" "16"
</code>```

Data

```<code>x <- scan(what = character(), text = '
L_1_3
L_2_23
L_3_91
L_3_16')
</code>```

Body:
I have a bunch of colnames

L_1_3
L_2_23
L_3_91
L_3_16

I want to replace these colnames with new names using the last digits following the _ like this:

3
23
91
16

I've tried colnames(X) <- gsub("L_\\d\\d_", "", colnames(X)) which works for strings with double digits at the end. I want one that works for both single and double digits.

Thank you!

Body:
Here is a regular expression that does it.

It gets anything until a non-digit followed by the capture group of one or more digits at the end. And replaces by the the capture group.

sub('.*[^[:digit:]]{1}([[:digit:]]+$)', '\\1', x)
#[1] "3"  "23" "91" "16"

A regex that works for single and double digits but neither more nor less would be

sub('.*[^[:digit:]]{1}([[:digit:]]{1,2}$)', '\\1', x)
#[1] "3"  "23" "91" "16"

Data

x <- scan(what = character(), text = '
L_1_3
L_2_23
L_3_91
L_3_16')


问:
Smooth animation in keyboardWillShow doesn't work with UITextView
Solution which worked for me

After struggling for days I finally manage to find the fix for view animation issue. For me keyboardWillChangeFrameNotification worked. The solution is discussed in the following thread:

Move textfield when keyboard appears swift

I've a bunch of views embedded inside stack view along with text view. I've given text view height of <= 120. In keyboardWillShow view doesn't animate despite adding code as required. I've played with duration value but it's all same result. I was wondering if it's due to text view? How to fix it?

```<code>@objc func keyboardWillShow(notification:NSNotification) {

    guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }

    let keyboardScreenEndFrame = keyboardValue.cgRectValue
    let keyboardFrame = view.convert(keyboardScreenEndFrame, from: view.window)

    if #available(iOS 11.0, *) {
        scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardFrame.height - view.safeAreaInsets.bottom, right: 0)
    } else {
        scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardFrame.height, right: 0)
    }

    scrollView.scrollIndicatorInsets = scrollView.contentInset

    let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height + keyboardFrame.height - scrollView.bounds.size.height)
    scrollView.setContentOffset(bottomOffset, animated: true)

    UIView.animate(withDuration: 0.5, animations: { () -> Void in
        self.view.layoutIfNeeded()
    })
}
</code>```

===

```<code>   extension FirstViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {

        let estimatedSize = textView.sizeThatFits(textView.frame.size)

        if estimatedSize.height > textViewMaxHeight {
            if estimatedSize.height - textViewMaxHeight < textView.font!.lineHeight && !didExpandTextView {

                didExpandTextView = true

                var contentInset:UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: self.savedKbHeight, right: 0.0)

                if let v = self.tabBarController?.tabBar {
                    contentInset.bottom -= v.frame.height
                }

                scrollView.contentInset = contentInset
                scrollView.scrollIndicatorInsets = contentInset

                if textView.isFirstResponder {
                    let fr = textView.frame
                    scrollView.scrollRectToVisible(fr, animated: false)
                }
            }

            textView.isScrollEnabled = true
            textView.showsVerticalScrollIndicator = true

        } else {
            if let lineHeight = textView.font?.lineHeight, Int(estimatedSize.height / lineHeight) != numberOfLines {
                numberOfLines = Int(estimatedSize.height / textView.font!.lineHeight)

                var contentInset:UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: self.savedKbHeight, right: 0.0)

                print("contentInset: \(contentInset)")
                scrollView.contentInset = contentInset
                scrollView.scrollIndicatorInsets = contentInset

                if textView.isFirstResponder {
                    let fr = textView.frame
                    scrollView.scrollRectToVisible(fr, animated: false)
                }

                didExpandTextView = false
            }

            textView.isScrollEnabled = false
        }
    }

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}
</code>```

答:
Try this approach:

    func textViewDidChange(_ textView: UITextView) {

        let estimatedSize = textView.sizeThatFits(textView.frame.size)

        textView.isScrollEnabled = estimatedSize.height > textViewMaxHeight

        if !textView.isScrollEnabled {
            let maxBottom = self.view.frame.height - self.savedKbHeight

            // Use following line if you have Extended Edges set
            // let maxBottom = self.view.frame.height - self.savedKbHeight - topLayoutGuide.length - bottomLayoutGuide.length

            var r = self.textView.frame
            r.size.height = estimatedSize.height
            let tvBottom = self.scrollView.convert(r, to: self.view).maxX
            if tvBottom > maxBottom {
                self.scrollView.scrollRectToVisible(r, animated: true)
            }
        }
    }
```

Edit Note: This is not intended to be Production Ready code. There are many things that affect layout / positioning, and there is no guarantee that just "dropping this in" will work in all situations.

Body:
Solution which worked for me

After struggling for days I finally manage to find the fix for view animation issue. For me keyboardWillChangeFrameNotification worked. The solution is discussed in the following thread:

Move textfield when keyboard appears swift

I've a bunch of views embedded inside stack view along with text view. I've given text view height of <= 120. In keyboardWillShow view doesn't animate despite adding code as required. I've played with duration value but it's all same result. I was wondering if it's due to text view? How to fix it?

@objc func keyboardWillShow(notification:NSNotification) {

    guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }

    let keyboardScreenEndFrame = keyboardValue.cgRectValue
    let keyboardFrame = view.convert(keyboardScreenEndFrame, from: view.window)

    if #available(iOS 11.0, *) {
        scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardFrame.height - view.safeAreaInsets.bottom, right: 0)
    } else {
        scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardFrame.height, right: 0)
    }

    scrollView.scrollIndicatorInsets = scrollView.contentInset

    let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height + keyboardFrame.height - scrollView.bounds.size.height)
    scrollView.setContentOffset(bottomOffset, animated: true)

    UIView.animate(withDuration: 0.5, animations: { () -> Void in
        self.view.layoutIfNeeded()
    })
}

===

   extension FirstViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {

        let estimatedSize = textView.sizeThatFits(textView.frame.size)

        if estimatedSize.height > textViewMaxHeight {
            if estimatedSize.height - textViewMaxHeight < textView.font!.lineHeight && !didExpandTextView {

                didExpandTextView = true

                var contentInset:UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: self.savedKbHeight, right: 0.0)

                if let v = self.tabBarController?.tabBar {
                    contentInset.bottom -= v.frame.height
                }

                scrollView.contentInset = contentInset
                scrollView.scrollIndicatorInsets = contentInset

                if textView.isFirstResponder {
                    let fr = textView.frame
                    scrollView.scrollRectToVisible(fr, animated: false)
                }
            }

            textView.isScrollEnabled = true
            textView.showsVerticalScrollIndicator = true

        } else {
            if let lineHeight = textView.font?.lineHeight, Int(estimatedSize.height / lineHeight) != numberOfLines {
                numberOfLines = Int(estimatedSize.height / textView.font!.lineHeight)

                var contentInset:UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: self.savedKbHeight, right: 0.0)

                print("contentInset: \(contentInset)")
                scrollView.contentInset = contentInset
                scrollView.scrollIndicatorInsets = contentInset

                if textView.isFirstResponder {
                    let fr = textView.frame
                    scrollView.scrollRectToVisible(fr, animated: false)
                }

                didExpandTextView = false
            }

            textView.isScrollEnabled = false
        }
    }

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

Body:
Try this approach:

    func textViewDidChange(_ textView: UITextView) {

        let estimatedSize = textView.sizeThatFits(textView.frame.size)

        textView.isScrollEnabled = estimatedSize.height > textViewMaxHeight

        if !textView.isScrollEnabled {
            let maxBottom = self.view.frame.height - self.savedKbHeight

            // Use following line if you have Extended Edges set
            // let maxBottom = self.view.frame.height - self.savedKbHeight - topLayoutGuide.length - bottomLayoutGuide.length

            var r = self.textView.frame
            r.size.height = estimatedSize.height
            let tvBottom = self.scrollView.convert(r, to: self.view).maxX
            if tvBottom > maxBottom {
                self.scrollView.scrollRectToVisible(r, animated: true)
            }
        }
    }

Edit Note: This is not intended to be Production Ready code. There are many things that affect layout / positioning, and there is no guarantee that just "dropping this in" will work in all situations.


问:
CASE statement with multiple THEN's
I am using the following SQL to try and accomodate multiple scenarios for an input parameter.

```<code>AND ec.eventId in (CASE WHEN @event = 'test_reeq' THEN 223
                        WHEN @event = 'test_NT' THEN 224
                        WHEN @event = 'Both' then '223,224'
                        WHEN @event = 'All' THEN ec.EventId
                        end
                        )
</code>```

My trouble appears to be with my attempt to use the 'both' input. SQL does not like the comma, and I've tried using parentheses instead of single quotes, as well as no quotes, but still no luck. Is it even possible to do what I'm trying to do?

For a bit more info: The EventId itself is an integer data type in the DB. For sake of convenience for user (this will ultimately be an SSRS report), I'd like to have the option for having these two ID's (223,224) grouped by using the keyword 'Both'. I am aware that in SSRS, I could just do a multi-select and even maybe have those two selected by default, but I'd prefer to have them grouped together as an option.

答:
One way is to use another CASE expression as

```<code>DECLARE @Var VARCHAR(45) = 'Both';
-- You can change the value of the varible @Var to test for other inputs
SELECT *
FROM
(
  VALUES
  (223),
  (224),
  (1)
) T(Col)
WHERE Col IN (
               CASE @Var
                 WHEN 'test_reeq' THEN 223
                 WHEN 'test_NT' THEN 224
                 WHEN 'Both' THEN 223
                 WHEN 'All Others' THEN Col
               END
             ) OR Col = CASE WHEN @Var = 'Both' THEN 224 END;
</code>```

You can get ride of IN() and use

```<code>WHERE Col = CASE @Var
                 WHEN 'test_reeq' THEN 223
                 WHEN 'test_NT' THEN 224
                 WHEN 'Both' THEN 223
                 WHEN 'All Others' THEN Col
               END
              OR Col = CASE WHEN @Var = 'Both' THEN 224 END;
</code>```

Online Demo

Title: CASE statement with multiple THEN's

Body:
I am using the following SQL to try and accomodate multiple scenarios for an input parameter.

AND ec.eventId in (CASE WHEN @event = 'test_reeq' THEN 223
                        WHEN @event = 'test_NT' THEN 224
                        WHEN @event = 'Both' then '223,224'
                        WHEN @event = 'All' THEN ec.EventId
                        end
                        )

My trouble appears to be with my attempt to use the 'both' input. SQL does not like the comma, and I've tried using parentheses instead of single quotes, as well as no quotes, but still no luck. Is it even possible to do what I'm trying to do?

For a bit more info: The EventId itself is an integer data type in the DB. For sake of convenience for user (this will ultimately be an SSRS report), I'd like to have the option for having these two ID's (223,224) grouped by using the keyword 'Both'. I am aware that in SSRS, I could just do a multi-select and even maybe have those two selected by default, but I'd prefer to have them grouped together as an option.

Body:
One way is to use another CASE expression as

DECLARE @Var VARCHAR(45) = 'Both';
-- You can change the value of the varible @Var to test for other inputs
SELECT *
FROM
(
  VALUES
  (223),
  (224),
  (1)
) T(Col)
WHERE Col IN (
               CASE @Var
                 WHEN 'test_reeq' THEN 223
                 WHEN 'test_NT' THEN 224
                 WHEN 'Both' THEN 223
                 WHEN 'All Others' THEN Col
               END
             ) OR Col = CASE WHEN @Var = 'Both' THEN 224 END;

You can get ride of IN() and use

WHERE Col = CASE @Var
                 WHEN 'test_reeq' THEN 223
                 WHEN 'test_NT' THEN 224
                 WHEN 'Both' THEN 223
                 WHEN 'All Others' THEN Col
               END
              OR Col = CASE WHEN @Var = 'Both' THEN 224 END;

Online Demo


问:
Docker php with apache on localhost: ERR_SSL_PROTOCOL_ERROR
I am trying to serve a hello_world.php file with apache and php in a docker container on Windows 10 with Docker Desktop.

Here's the Dockerfile:

```<code>FROM php:7.3-apache
# install git and zip, both needed for composer
RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y git && \
    apt-get install zip unzip
# install composer
RUN curl -sS https://getcomposer.org/installer | php -- \
--install-dir=/usr/bin --filename=composer && chmod +x /usr/bin/composer

RUN a2enmod headers
RUN echo 'ServerName localhost' >> /etc/apache2/apache2.conf
COPY . /var/www/html
WORKDIR /var/www/html

#RUN composer install
EXPOSE 80
</code>```

As you can see, some of the additional code for setting up composer etc. (so I can dockerize an existing PHP application) is even commented out but it does not work with even a basic hello world php file and no other files (no .htaccess for example).

Firstly, I build the image with docker build .. When I then execute docker run -it -p 8000:80 d7cd1255a20f, I get the console output

```<code>[Tue Jun 02 16:01:29.592455 2020] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.38 (Debian) PHP/7.3.18 configured -- resuming normal operations
[Tue Jun 02 16:01:29.592531 2020] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND'
</code>```

Looks fine to me.
I open http://localhost:8000in my browser and get "Can't establish a secure connection. ERR_SSL_PROTOCOL_ERROR". The server log shows (two lines each time I load the page in my browser):

```<code>172.17.0.1 - - [02/Jun/2020:16:02:55 +0000] "\x16\x03\x01\x02" 400 0 "-" "-"
172.17.0.1 - - [02/Jun/2020:16:02:55 +0000] "\x16\x03\x01\x02" 400 0 "-" "-"
</code>```

I have already researched this and it looks like it's the beginning of a TLS handshake.

How can I get this to work?

答:
okay Try this

Follow the folder structure

```<code>phpExample/
   php/
      index.php
   dockerfile
</code>```

dockerfile

```<code>FROM php:7.3-apache
COPY php/ /var/www/html
EXPOSE 80
</code>```

index.php

```<code><?php
echo "Hello World from Docker container using PHP<br>";
echo '<img src="https://www.docker.com/sites/default/files/d8/2019-07/Moby-logo.png">';
?>
</code>```

After this  run following command

```<code>docker build -t helloWorld-php-docker .
</code>```

When the build is completed.

```<code>docker run -p 80:80 helloWorld-php-docker
</code>```

Please make sure port 80 is not in use, or what you can do change the port number

PS: directory structure is not mandatory. I added just to structure the example

Body:
I am trying to serve a hello_world.php file with apache and php in a docker container on Windows 10 with Docker Desktop.

Here's the Dockerfile:

FROM php:7.3-apache
# install git and zip, both needed for composer
RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y git && \
    apt-get install zip unzip
# install composer
RUN curl -sS https://getcomposer.org/installer | php -- \
--install-dir=/usr/bin --filename=composer && chmod +x /usr/bin/composer

RUN a2enmod headers
RUN echo 'ServerName localhost' >> /etc/apache2/apache2.conf
COPY . /var/www/html
WORKDIR /var/www/html

#RUN composer install
EXPOSE 80

As you can see, some of the additional code for setting up composer etc. (so I can dockerize an existing PHP application) is even commented out but it does not work with even a basic hello world php file and no other files (no .htaccess for example).

Firstly, I build the image with docker build .. When I then execute docker run -it -p 8000:80 d7cd1255a20f, I get the console output

[Tue Jun 02 16:01:29.592455 2020] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.38 (Debian) PHP/7.3.18 configured -- resuming normal operations
[Tue Jun 02 16:01:29.592531 2020] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND'

Looks fine to me.
I open http://localhost:8000in my browser and get "Can't establish a secure connection. ERR_SSL_PROTOCOL_ERROR". The server log shows (two lines each time I load the page in my browser):

172.17.0.1 - - [02/Jun/2020:16:02:55 +0000] "\x16\x03\x01\x02" 400 0 "-" "-"
172.17.0.1 - - [02/Jun/2020:16:02:55 +0000] "\x16\x03\x01\x02" 400 0 "-" "-"

I have already researched this and it looks like it's the beginning of a TLS handshake.

How can I get this to work?

Body:
okay Try this

Follow the folder structure

phpExample/
   php/
      index.php
   dockerfile

dockerfile

FROM php:7.3-apache
COPY php/ /var/www/html
EXPOSE 80

index.php

<?php
echo "Hello World from Docker container using PHP<br>";
echo '<img src="https://www.docker.com/sites/default/files/d8/2019-07/Moby-logo.png">';
?>

After this  run following command

docker build -t helloWorld-php-docker .

When the build is completed.

docker run -p 80:80 helloWorld-php-docker

Please make sure port 80 is not in use, or what you can do change the port number

PS: directory structure is not mandatory. I added just to structure the example


问:
Apply the same random shuffle on multiple containers
I am writing a program where a Manager-class handles different containers.
Every container is the same size with the same contents and needs to be (randomly) shuffled the same way.
(FYI, The program will later apply different operations on each container)

What I want to achieve:
Randomly sort each container, but all containers has to be sorted the same way, without copying a container. I do not want to copy because the contents of each container is not just integers and would thus be very expensive.

Therefore, I do not seek a solution like the one that follows:

```<code>void ContainerMgr::Shuffle()
{
    std::random_shuffle(m_tmp.begin(), m_tmp.end());

    for (auto &subContainer : m_allContainers)
        subContainer = m_tmp;
}
</code>```

My question:
Does C++ (perhaps STL) provide a way to randomly shuffle, let's say 5, different (equally sized) containers in the same way?

Thanks in advance!

答:
range-v3 provides zip view that you can then shuffle.

```<code>auto zip_view = ranges::view::zip(v1, v2, v3);

std::mt19937 rnd(std::random_device{});
std::shuffle(zip_view.begin(), zip_view.end(), rnd);
</code>```

Else, without library, you might create an array of indexes, shuffle it, and access your array with that indirection:

```<code>std::vector<std::size_t> indexes(v1.size());
std::iota(indexes.begin(), indexes.end(), 0);

std::mt19937 rnd(std::random_device{});
std::shuffle(indexes.begin(), indexes.end(), rnd);

std::size_t i = 42;
f(v1[indexes[i]], v2[indexes[i]], v3[indexes[i]]);
</code>```

Body:
I am writing a program where a Manager-class handles different containers.
Every container is the same size with the same contents and needs to be (randomly) shuffled the same way.
(FYI, The program will later apply different operations on each container)

What I want to achieve:
Randomly sort each container, but all containers has to be sorted the same way, without copying a container. I do not want to copy because the contents of each container is not just integers and would thus be very expensive.

Therefore, I do not seek a solution like the one that follows:

void ContainerMgr::Shuffle()
{
    std::random_shuffle(m_tmp.begin(), m_tmp.end());

    for (auto &subContainer : m_allContainers)
        subContainer = m_tmp;
}

My question:
Does C++ (perhaps STL) provide a way to randomly shuffle, let's say 5, different (equally sized) containers in the same way?

Thanks in advance!

Body:
range-v3 provides zip view that you can then shuffle.

auto zip_view = ranges::view::zip(v1, v2, v3);

std::mt19937 rnd(std::random_device{});
std::shuffle(zip_view.begin(), zip_view.end(), rnd);

Else, without library, you might create an array of indexes, shuffle it, and access your array with that indirection:

std::vector<std::size_t> indexes(v1.size());
std::iota(indexes.begin(), indexes.end(), 0);

std::mt19937 rnd(std::random_device{});
std::shuffle(indexes.begin(), indexes.end(), rnd);

std::size_t i = 42;
f(v1[indexes[i]], v2[indexes[i]], v3[indexes[i]]);


问:
JQuery: Why Unobtrusive JavaScript / Document Ready function rather than OnClick event?
I've just started looking at JQuery. I don't have any AJAX in my web application at present.

My existing JavaScript in my HTML looks like:

```<code><form ...>
<p>Find what? <input ...></p>
<div class="ButtonArray">
  <a href="AddRecord.ASP&Action=ADD">ADD</a>
  <a href="#" onClick="return MyFormSubmit();">FIND</a>
</div>
</form>
</code>```

This displays Buttons for [Add] and [Find].  For Find it is necessary to Submit the form, and I use MyFormSubmit() which validates the data, adds a visual effect to the page, and then POSTs the data.

I could add a CLASS or ID to the  for the Find button and in JQuery I could write something like:

```<code>$(function() {
  $(".MySearchButtonClass").click(function() {
    // validate and process form here
  });
});
</code>```

At my "novice" stage of understanding with JQuery I don't get why I would do it this way

My old way identifies the Method near the object. There may be a risk that the JS has not loaded before the user presses the button (is there? The LOAD for the JS is right at the top of the page).

The JQuery Document Ready method won't be activated until the document is loaded (which I assume guarantees that the JS is all present and ready to be run?), but it moves the code to a separate part of my HTML file - so when I see the MyButtonArray DIV in the HTML source it isn't obvious to me which objects have methods, and which do not.

Can you please help me understand what my options are and the benefits / gotchas that I should look out for?

Edit: I'm comfortable that DOM manipulation - such as a LightBox that can appear when any thumbnail with class "LightBoxThumb" is clicked - would use Unobtrusive Javascript.

However I am struggling to persuade myself that a button that has a specific action should have its method applied in that way. (I certainly wouldn't put any code on the button other than a single function call to something "elsewhere", but to my mind that is my best clue as to what that button does, and layers of Unobtrusive Javascript may make that much harder to determine.)

Edit2 - Accepted Answer

I've taken Russ Cams answer. It describes Unobtrusive Javascript in a way that has been helpful to me in understanding more about how & when that should be used.

For the moment (may change when I have more experience!) I'll stick with an OnClick event for a single, non-changing, action on an object as I feel that will be easier for me to debug - and diagnose if problems arise. For ZebraStripes on a table that allows click on heading column to sort (and situations of that type) I can see the benefits of the Unobtrusive Javascript approach

Russ's final comment was particularly helpful, repeated here:

"@Kristen - You're right, like a lot
  of programming topics, there is more
  than one approach and people will
  vehemently stand by their beliefs! If
  we're talking about a single method
  for a single button, I totally
  understand where you're coming from...

If we're talking about lots of
  JavaScript, with same function calls
  for more than one element, different
  function calls for different methods,
  etc. I think that it would be more
  difficult for oneself to mix inline
  and unobtrusive approaches, and it
  would be better to adopt one or the
  other approach"

答:
Unobtrusive JavaScript is the main driver for separating JS code from markup

Separation of functionality (the    "behavior layer") from a Web page's

  structure/content and presentation

Best practices to avoid the problems    of traditional JavaScript
  programming    (such as browser
  inconsistencies and    lack of
  scalability)

Progressive enhancement to support    user agents that may not support

  advanced JavaScript functionality

With the code in document.ready, it will not execute until the DOM has loaded and before the page contents are loaded

From Learning jQuery

With $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads.

You may want to take a look at jQuery in Action, I'd highly recommend it. You can sample Chapter 1 and Chapter 5 on the book's homepage. I think doing so may provide further insight into why separation can work well.

Finally, have a look at this question which has answers that detail how you would find the event listeners on a DOM node.

EDIT:

Some thoughts which may persuade you why unobtrusive JavaScript can be a good idea.

Imagine that you have a function bound as an event handler for the same event raised on  each of a number of elements -

Would it be easier to find out which
elements call that function to handle
an event when the declaration is inline
in each element, or the declaration
is in one place, outside of the
markup?

What if you want to add to the
elements that call that function when
the event is raised on each of them?
Would it be easier/better to add the
event handler inline to each element
or to change the code in one place?

OwnerDisplayName: Kristen

ContentLicense: CC BY-SA 2.5

Body:
I've just started looking at JQuery. I don't have any AJAX in my web application at present.

My existing JavaScript in my HTML looks like:

<form ...>

Find what? <input ...>

  ADD
  FIND

</form>

This displays Buttons for [Add] and [Find].  For Find it is necessary to Submit the form, and I use MyFormSubmit() which validates the data, adds a visual effect to the page, and then POSTs the data.

I could add a CLASS or ID to the  for the Find button and in JQuery I could write something like:

$(function() {
  $(".MySearchButtonClass").click(function() {
    // validate and process form here
  });
});

At my "novice" stage of understanding with JQuery I don't get why I would do it this way

My old way identifies the Method near the object. There may be a risk that the JS has not loaded before the user presses the button (is there? The LOAD for the JS is right at the top of the page).

The JQuery Document Ready method won't be activated until the document is loaded (which I assume guarantees that the JS is all present and ready to be run?), but it moves the code to a separate part of my HTML file - so when I see the MyButtonArray DIV in the HTML source it isn't obvious to me which objects have methods, and which do not.

Can you please help me understand what my options are and the benefits / gotchas that I should look out for?

Edit: I'm comfortable that DOM manipulation - such as a LightBox that can appear when any thumbnail with class "LightBoxThumb" is clicked - would use Unobtrusive Javascript.

However I am struggling to persuade myself that a button that has a specific action should have its method applied in that way. (I certainly wouldn't put any code on the button other than a single function call to something "elsewhere", but to my mind that is my best clue as to what that button does, and layers of Unobtrusive Javascript may make that much harder to determine.)

Edit2 - Accepted Answer

I've taken Russ Cams answer. It describes Unobtrusive Javascript in a way that has been helpful to me in understanding more about how & when that should be used.

For the moment (may change when I have more experience!) I'll stick with an OnClick event for a single, non-changing, action on an object as I feel that will be easier for me to debug - and diagnose if problems arise. For ZebraStripes on a table that allows click on heading column to sort (and situations of that type) I can see the benefits of the Unobtrusive Javascript approach

Russ's final comment was particularly helpful, repeated here:

"@Kristen - You're right, like a lot
  of programming topics, there is more
  than one approach and people will
  vehemently stand by their beliefs! If
  we're talking about a single method
  for a single button, I totally
  understand where you're coming from...

If we're talking about lots of
  JavaScript, with same function calls
  for more than one element, different
  function calls for different methods,
  etc. I think that it would be more
  difficult for oneself to mix inline
  and unobtrusive approaches, and it
  would be better to adopt one or the
  other approach"

LastEditorDisplayName: Kristen

OwnerDisplayName: Russ Cam

LastEditorDisplayName: Russ Cam