问:
How do I use wildcard (*, aka asterisk) search with Solr and also include whitespace?
Struggling to get wildcard search to work when whitespace is present. I'd like to generally only match exact terms (including spaces) unless the user passes in a * on either end of the query, in which case just the last word should get wildcarded, but otherwise the exact phrase (including whitespace) needs to match. Here is my field type def:

```<code><fieldType name="myfieldtype" class="solr.TextField" sortMissingLast="true" multiValued="true">
  <analyzer type="index">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.ASCIIFoldingFilterFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.ReversedWildcardFilterFactory" maxPosAsterisk="1" maxPosQuestion="0" minTrailing="3"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.ASCIIFoldingFilterFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>
</code>```

And the field definition:

```<code><field name="myfield" type="myfieldtype" stored="true"/>
</code>```

If I push the following records into my Solr index:

```<code>{
  "id": "1",
  "myfield": ["dogbert"],
},
{
  "id": "2",
  "myfield": ["or around whatever aisle"],
}
</code>```

... I get the following example outcomes (using defType=edismax):

Search
Result

*tever
record 2

*"tever"
all records (see note(1) below)

*"tever aisle"
all records (see note(1) below)

*(tever aisle)
all records (see note(1) below)

*tever\ aisle
empty result (no records)

Note(1): I've also tried a similar query on a full index of 100k+ records and every record from the index is returned there.

Any advice for why Solr is acting as if I searched *:* when I put the asterisk outside the quotation marks?

In case it helps, here's an example debug from one of the queries that returns all records:

```<code>...
"rawquerystring":"*(tever aisle)",
"querystring":"*(tever aisle)",
"parsedquery":"+(MatchAllDocsQuery(*:*) (DisjunctionMaxQuery((myfield:tever)) DisjunctionMaxQuery((myfield:aisle))))",
"parsedquery_toString":"+(*:* ((myfield:tever) (myfield:aisle)))",
...
</code>```

The *:* in the parsedquery_toString of the debug looks sus, but I don't really understand why it's there.

EDIT: I think I can achieve what I want by using NGrams, ... however, the real data getting pushed into the search field is the user-generated long-form content from our app, so it becomes very resource intensive to use NGrams of pretty much any size, especially when indexing.

Body:
Struggling to get wildcard search to work when whitespace is present. I'd like to generally only match exact terms (including spaces) unless the user passes in a * on either end of the query, in which case just the last word should get wildcarded, but otherwise the exact phrase (including whitespace) needs to match. Here is my field type def:

<fieldType name="myfieldtype" class="solr.TextField" sortMissingLast="true" multiValued="true">
  <analyzer type="index">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.ASCIIFoldingFilterFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.ReversedWildcardFilterFactory" maxPosAsterisk="1" maxPosQuestion="0" minTrailing="3"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.ASCIIFoldingFilterFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>

And the field definition:

<field name="myfield" type="myfieldtype" stored="true"/>

If I push the following records into my Solr index:

{
  "id": "1",
  "myfield": ["dogbert"],
},
{
  "id": "2",
  "myfield": ["or around whatever aisle"],
}

... I get the following example outcomes (using defType=edismax):

Search
Result

*tever
record 2

*"tever"
all records (see note(1) below)

*"tever aisle"
all records (see note(1) below)

*(tever aisle)
all records (see note(1) below)

*tever\ aisle
empty result (no records)

Note(1): I've also tried a similar query on a full index of 100k+ records and every record from the index is returned there.

Any advice for why Solr is acting as if I searched *:* when I put the asterisk outside the quotation marks?

In case it helps, here's an example debug from one of the queries that returns all records:

...
"rawquerystring":"*(tever aisle)",
"querystring":"*(tever aisle)",
"parsedquery":"+(MatchAllDocsQuery(*:*) (DisjunctionMaxQuery((myfield:tever)) DisjunctionMaxQuery((myfield:aisle))))",
"parsedquery_toString":"+(*:* ((myfield:tever) (myfield:aisle)))",
...

The *:* in the parsedquery_toString of the debug looks sus, but I don't really understand why it's there.

EDIT: I think I can achieve what I want by using NGrams, ... however, the real data getting pushed into the search field is the user-generated long-form content from our app, so it becomes very resource intensive to use NGrams of pretty much any size, especially when indexing.


来源: stackexchange

问:
Mapbox How to conduct a if else statement expression
I am currently working on a function where the users can click anywhere within a polygon and a popup window shows up. However, I also wrote a function that once the users click on certain locations, a popup window displaying the information about those locations also shows up. So I ended up having two popup windows when I click on certain locations, how can I possibly change that?

JS Code for clicking anywhere within the polygon to show popup:

```<code>    map.on('click', 'CHOP Zone Transparent', (e) => {
        new mapboxgl.Popup().setLngLat(e.lngLat).setHTML(`
                                      <button class="open-button" onclick="openForm()">Comment</button>`).addTo(map);
    });
</code>```

JS code for clicking on certain locations' icons to show popup:

```<code>// Allow user to comment and comment once click on icons
for (const feature of stores.features) {
    // create a HTML element for each feature
    const el = document.createElement('div');
    el.className = 'store';
    // make a marker for each feature and add to the map
    new mapboxgl.Marker(el).setLngLat(feature.geometry.coordinates).setPopup(new mapboxgl.Popup({
        offset: 25
    }).setHTML(`
                                      <h2>${feature.properties.title}</h2>
                                      <p>${feature.properties.description}</p>
                                      <button class="open-button" onclick="openForm()">Comment</button>`)).addTo(map);
}
</code>```

Issue:

Two Popup Windows Show

How do I use some sort of if/else statement or other expressions to resolve this problem?

ContentLicense: CC BY-SA 4.0

Body:
I am currently working on a function where the users can click anywhere within a polygon and a popup window shows up. However, I also wrote a function that once the users click on certain locations, a popup window displaying the information about those locations also shows up. So I ended up having two popup windows when I click on certain locations, how can I possibly change that?

JS Code for clicking anywhere within the polygon to show popup:

    map.on('click', 'CHOP Zone Transparent', (e) => {
        new mapboxgl.Popup().setLngLat(e.lngLat).setHTML(`
                                      <button class="open-button" onclick="openForm()">Comment</button>`).addTo(map);
    });

JS code for clicking on certain locations' icons to show popup:

// Allow user to comment and comment once click on icons
for (const feature of stores.features) {
    // create a HTML element for each feature
    const el = document.createElement('div');
    el.className = 'store';
    // make a marker for each feature and add to the map
    new mapboxgl.Marker(el).setLngLat(feature.geometry.coordinates).setPopup(new mapboxgl.Popup({
        offset: 25
    }).setHTML(`

${feature.properties.title}

${feature.properties.description}

                                      <button class="open-button" onclick="openForm()">Comment</button>`)).addTo(map);
}

Issue:

Two Popup Windows Show

How do I use some sort of if/else statement or other expressions to resolve this problem?


问:
Sum by group in data.table
I have a data.table object as follows:

```<code>> ans
        race smoking_status    N
 1:    Asian          Never  255
 2:    Asian         Former  130
 3:    Asian        Current    9
 4:    Black          Never  421
 5:    Black         Former  257
 6:    Black        Current  215
 7: Hispanic        Current  184
 8: Hispanic          Never  910
 9: Hispanic         Former  525
10:    White          Never 2955
11:    White         Former 3109
12:    White        Current 1030

> class(ans)
[1] "data.table" "data.frame"
</code>```

I want to get the number of smokers by race, and the proportions of never, former and current smokers, also by race. How do I do that?

Title: Sum by group in data.table

Body:
I have a data.table object as follows:

> ans
        race smoking_status    N
 1:    Asian          Never  255
 2:    Asian         Former  130
 3:    Asian        Current    9
 4:    Black          Never  421
 5:    Black         Former  257
 6:    Black        Current  215
 7: Hispanic        Current  184
 8: Hispanic          Never  910
 9: Hispanic         Former  525
10:    White          Never 2955
11:    White         Former 3109
12:    White        Current 1030

> class(ans)
[1] "data.table" "data.frame"

I want to get the number of smokers by race, and the proportions of never, former and current smokers, also by race. How do I do that?


问:
Remove connecting lines from 3D Plotly Scatter Plot in R
I have data that looks like this:

After running the following code:

```<code>axx <- list(
  nticks = 3,
  tickvals = c(0,1,2),
  ticktext = c("AA", "Aa", "aa"),
  title = "SNP2 Genotype")

axy <- list(
  nticks = 3,
  tickvals = c(0,1,2),
  ticktext = c("AA", "Aa", "aa"),
  title = "SNP3 Genotype")

axz <- list(
  nticks = 7,
  tickvals = c(0,1,2,3,4,5,6),
  ticktext = c("1", "2", "3", "4", "5", "6"),
  title = "BMI with Tail")

plot_ly(Add3W_T, x = ~SNP2, y = ~SNP3, z = ~phenotype, type = 'scatter3d', mode = 'lines', opacity = 1, color = ~Geno_color,
        line = list(width = 14, color = ~Geno_color, showspikes=FALSE)) %>%
  layout(scene = list(xaxis = axx, yaxis = axy, zaxis = axz),
         title = list(text = "3D Reaction Norms - Additive"),
         legend = list(title = list(text = "SNP1 Genotype")))
</code>```

I get this:

I want to get rid of the connecting lines between the different colored lines (the ones that are a gradient from one color to another) As they are just distracting.

Body:
I have data that looks like this:

After running the following code:

axx <- list(
  nticks = 3,
  tickvals = c(0,1,2),
  ticktext = c("AA", "Aa", "aa"),
  title = "SNP2 Genotype")

axy <- list(
  nticks = 3,
  tickvals = c(0,1,2),
  ticktext = c("AA", "Aa", "aa"),
  title = "SNP3 Genotype")

axz <- list(
  nticks = 7,
  tickvals = c(0,1,2,3,4,5,6),
  ticktext = c("1", "2", "3", "4", "5", "6"),
  title = "BMI with Tail")

plot_ly(Add3W_T, x = ~SNP2, y = ~SNP3, z = ~phenotype, type = 'scatter3d', mode = 'lines', opacity = 1, color = ~Geno_color,
        line = list(width = 14, color = ~Geno_color, showspikes=FALSE)) %>%
  layout(scene = list(xaxis = axx, yaxis = axy, zaxis = axz),
         title = list(text = "3D Reaction Norms - Additive"),
         legend = list(title = list(text = "SNP1 Genotype")))

I get this:

I want to get rid of the connecting lines between the different colored lines (the ones that are a gradient from one color to another) As they are just distracting.


问:
My compiler is not showing any error on tsc but it's not running program
And this error is appearing on running

```<code>internal/modules/run_main.js:54
    internalBinding('errors').triggerUncaughtException(
                             ^
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'D:\node\node_modules\chalk\source\node_modules\' imported from D:\node\node_modules\chalk\source\index.js
←[90m    at packageMainResolve (internal/modules/esm/resolve.js:461:9)←[39m
←[90m    at packageResolve (internal/modules/esm/resolve.js:604:14)←[39m
←[90m    at moduleResolve (internal/modules/esm/resolve.js:649:14)←[39m
←[90m    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:695:13)←[39m
←[90m    at Loader.resolve (internal/modules/esm/loader.js:97:40)←[39m
←[90m    at Loader.getModuleJob (internal/modules/esm/loader.js:243:28)←[39m
←[90m    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)←[39m
←[90m    at link (internal/modules/esm/module_job.js:41:36)←[39m {
  code: ←[32m'ERR_MODULE_NOT_FOUND'←[39m
}
</code>```

Please tell me how should I run it and what changes or commands should I use.

Body:
And this error is appearing on running

internal/modules/run_main.js:54
    internalBinding('errors').triggerUncaughtException(
                             ^
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'D:\node\node_modules\chalk\source\node_modules\' imported from D:\node\node_modules\chalk\source\index.js
←[90m    at packageMainResolve (internal/modules/esm/resolve.js:461:9)←[39m
←[90m    at packageResolve (internal/modules/esm/resolve.js:604:14)←[39m
←[90m    at moduleResolve (internal/modules/esm/resolve.js:649:14)←[39m
←[90m    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:695:13)←[39m
←[90m    at Loader.resolve (internal/modules/esm/loader.js:97:40)←[39m
←[90m    at Loader.getModuleJob (internal/modules/esm/loader.js:243:28)←[39m
←[90m    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)←[39m
←[90m    at link (internal/modules/esm/module_job.js:41:36)←[39m {
  code: ←[32m'ERR_MODULE_NOT_FOUND'←[39m
}

Please tell me how should I run it and what changes or commands should I use.


问:
how to create a bar chart by counting values by date for a variable?
My data looks like this.

The following code  creates the bar chart (below).

```<code># counts per month

df %>%
  group_by(date) %>%
  summarize(dep_delay= mean(dep_delay)) %>%
  ggplot(aes(x = as.factor(month(date,label = TRUE)),
             y = dep_delay)) +
  geom_bar(stat = 'identity') +
  theme_bw()+
  scale_y_continuous(breaks = seq(0,1400,200))+
  labs(title="Departure delays in Newark airport per month in 2013",
       x="", y = "number of delays")

</code>```

However, the correct counts should be as follows

```<code>df_w_delays %>% group_by(month=month(date)) %>% count()

  month     n
   <dbl> <int>
 1     1  1035
 2     2   941
 3     3  1239
 4     4  1159
 5     5  1240
 6     6  1257
 7     7  1277
 8     8  1100
 9     9   702
10    10   880
11    11   861
12    12  1315

</code>```

So the bar chart counts do not look correct.

I have tried changing this line, summarize(dep_delay= mean(dep_delay)) to
summarize(dep_delay= n(dep_delay)) and summarize(dep_delay= count(dep_delay)) which gives errors in summarize().

```<code>Error in `summarize()`:
! Problem while computing `dep_delay = n(dep_delay)`.
ℹ The error occurred in group 1: date = 2013-01-01.
Caused by error in `n()`:
! unused argument (dep_delay)

Error in `summarize()`:
! Problem while computing `dep_delay = count(dep_delay)`.
ℹ The error occurred in group 1: date = 2013-01-01.
Caused by error in `UseMethod()`:
! no applicable method for 'count' applied to an object of class "c('double', 'numeric')"

</code>```

Can someone explain why mean() works in summarise but count() does not? how can I show row counts by month in the bar chart?

Body:
My data looks like this.

The following code  creates the bar chart (below).

# counts per month

df %>%
  group_by(date) %>%
  summarize(dep_delay= mean(dep_delay)) %>%
  ggplot(aes(x = as.factor(month(date,label = TRUE)),
             y = dep_delay)) +
  geom_bar(stat = 'identity') +
  theme_bw()+
  scale_y_continuous(breaks = seq(0,1400,200))+
  labs(title="Departure delays in Newark airport per month in 2013",
       x="", y = "number of delays")

However, the correct counts should be as follows

df_w_delays %>% group_by(month=month(date)) %>% count()

  month     n
   <dbl> <int>
 1     1  1035
 2     2   941
 3     3  1239
 4     4  1159
 5     5  1240
 6     6  1257
 7     7  1277
 8     8  1100
 9     9   702
10    10   880
11    11   861
12    12  1315

So the bar chart counts do not look correct.

I have tried changing this line, summarize(dep_delay= mean(dep_delay)) to
summarize(dep_delay= n(dep_delay)) and summarize(dep_delay= count(dep_delay)) which gives errors in summarize().

Error in `summarize()`:
! Problem while computing `dep_delay = n(dep_delay)`.
ℹ The error occurred in group 1: date = 2013-01-01.
Caused by error in `n()`:
! unused argument (dep_delay)

Error in `summarize()`:
! Problem while computing `dep_delay = count(dep_delay)`.
ℹ The error occurred in group 1: date = 2013-01-01.
Caused by error in `UseMethod()`:
! no applicable method for 'count' applied to an object of class "c('double', 'numeric')"

Can someone explain why mean() works in summarise but count() does not? how can I show row counts by month in the bar chart?


问:
White screen on publishing app on Apple store when revienwing

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of  from render. Or maybe you meant to call this function rather than return it.
in RCTText (created by Text)
in Text
in Text (created by BottomNavigation)
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper (created by BottomNavigation)
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper (created by BottomNavigation)
in RCTView (created by View)
in View (created by BottomNavigation)
in RCTView (created by View)
in View (created by Touchable)
in TouchableWithoutFeedback (created by Touchable)
in Touchable (created by BottomNavigation)
in RCTView (created by View)
in View (created by BottomNavigation)
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper (created by BottomNavigation)
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper
in Unknown (created by BottomNavigation)
in RCTView (created by View)
in View (created by BottomNavigation)
in BottomNavigation
in ThemedComponent (created by withTheme(BottomNavigation))
in withTheme(BottomNavigation) (created by MaterialBottomTabViewInner)
in MaterialBottomTabViewInner (created by MaterialBottomTabView)
in RNCSafeAreaProvider (created by SafeAreaProvider)
in SafeAreaProvider (created by SafeAreaInsetsContext)
in SafeAreaProviderCompat (created by MaterialBottomTabView)
in MaterialBottomTabView (created by MaterialBottomTabNavigator)
in PreventRemoveProvider (created by NavigationContent)
in NavigationContent
in Unknown (created by MaterialBottomTabNavigator)
in MaterialBottomTabNavigator (created by App)
in EnsureSingleNavigator
in BaseNavigationContainer
in ThemeProvider
in NavigationContainerInner (created by App)
in App (created by withDevTools(App))
in withDevTools(App)
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in main(RootComponent)

I tried to publish my app on Apple Store and they told me after splashscreen, a white screen appears and on my phone everything is getting fine.
bellow my code :

```<code>import React,{useEffect} from 'react';
import { ImageBackground,Text,StyleSheet,View,TouchableOpacity,Image,FlatList} from 'react-native';
import * as Animatable from 'react-native-animatable';
import Include_entete from '../includes/Include_entete';
import Couleurs from '../composants/Couleurs';
import { LinearGradient } from 'expo-linear-gradient';
import {expo} from '../app.json';
import { Ionicons } from '@expo/vector-icons';
import { MaterialCommunityIcons } from '@expo/vector-icons';
//import * as Device from 'expo-device';

export default function Fenetre_accueil({navigation})
{
    const [isLoading,setIsLoading] = React.useState(true);
    const [data, setData] = React.useState({hits:[]});

    useEffect(() =>
    {
        setIsLoading(true);
        setTimeout(async() => {
            fetch("https://www.xxxxxx.com/application/app-recueil-sct/last_four_song.php", {method: "GET"})
            .then((response) => response.json())
            .then((responseJson) =>
            {
                setData({hits:responseJson});
            })
            setIsLoading(false);
        },1000);
    }, []);

    if(isLoading)
    {
        return(
        <Animatable.View style={{flex:1,justifyContent:'center',alignItems:'center'}} animation="bounceIn">
            <RemotImage
                uri={"https://fxxxxxxx.com/ressources/images/logo.png"}
                desireWidth={200}
            />
        </Animatable.View>
        );
    }

    return(
        <Animatable.View animation="bounceInDown" style={{flex:1}}>
            <Include_entete />
            <ImageBackground imageStyle={{opacity: 0.2}} style={{flex:1,justifyContent:'center',alignSelf:'stretch'}} source={require('./../images/eagle1.jpeg')} resizeMode='cover'>
                    <View style={styles.container}>
                        <FlatList
                            ListHeaderComponent={
                                <View>
                                    <Text style={{color:Couleurs.text_info,fontSize:20,marginBottom:5,marginLeft:5}}>Bienvenue</Text>

                                    <TouchableOpacity onPress={() => {navigation.navigate('Search',{search:' '})}} style={[styles.boxshadow,styles.card]}>
                                        <ImageBackground source={{uri:'https://xxxxxxxx.com/ressources/images/bible.jpg'}} resizeMode='cover' style={{minHeight:200}}>
                                            <LinearGradient colors={['rgba(0,0,0,0.2)','rgba(0,0,0,0.8)']} style={{minHeight:200,padding:5}}>
                                                <View style={{flexDirection:'row'}}>
                                                    <MaterialCommunityIcons name="book-open-page-variant" size={45} color="#fff" style={{marginRight:5}}/>
                                                    <Text style={{fontSize:35,color:"#FDF2E9"}}>Recueil SCT</Text>
                                                </View>
                                                <Text style={{color:'#FDF2E9',fontSize:16,marginTop:10,paddingHorizontal:2}}>Cette application vous donne accès à tout le guide de cantiques de l'Eglise Soleil Couchant Tabernacle.</Text>
                                                <View style={{flexDirection:'row-reverse',borderTopColor:'#FDF2E9',borderTopWidth:1,marginTop:20}}>
                                                    <Ionicons name="arrow-forward-circle-sharp" size={40} color="#FDF2E9" />
                                                    <Text style={{fontSize:16,color:"#FDF2E9",marginRight:5,marginTop:7}}>Accéder à tous nos Cantiques</Text>
                                                </View>
                                            </LinearGradient>
                                        </ImageBackground>
                                    </TouchableOpacity>

                                    <Text style={{color:Couleurs.text_info,fontSize:20,marginBottom:5,marginLeft:5}}>Dernières mise à jour</Text>
                                </View>
                            }
                            data={data.hits} showsVerticalScrollIndicator={false} nestedScrollEnabled={true}
                            renderItem={({item,index}) =>
                            (
                                <TouchableOpacity onPress={() => {navigation.navigate('Chant',{Id:item.id})}} style={[styles.boxshadow,styles.card]}>
                                <ImageBackground source={{uri:'https://xxxxxxxx.com/ressources/images/jesus.jpg'}} resizeMode='cover' style={{minHeight:200}}>
                                    <LinearGradient colors={['rgba(0,0,0,0.2)','rgba(0,0,0,0.8)']} style={{minHeight:200,padding:5}}>
                                        <View style={{flexDirection:'row'}}>
                                            <MaterialCommunityIcons name="microphone-variant" size={45} color="#fff" />
                                            <Text style={{fontSize:35,color:"#FDF2E9"}}>Chant : #{item.num}</Text>
                                        </View>
                                        <Text style={{color:'#FDF2E9',fontSize:16,marginTop:10,paddingHorizontal:2}}>{item.chant.substring(0,100).replace(/\n|\r/g,' ')}...</Text>
                                        <View style={{flexDirection:'row-reverse',borderTopColor:'#FDF2E9',borderTopWidth:1,marginTop:20}}>
                                            <Ionicons name="arrow-forward-circle-sharp" size={40} color="#FDF2E9" />
                                            <Text style={{fontSize:16,color:"#FDF2E9",marginRight:5,marginTop:7}}>Consulter</Text>
                                        </View>
                                    </LinearGradient>
                                </ImageBackground>
                            </TouchableOpacity>
                            )}
                            keyExtractor = {( item, index ) => index.toString() }

                            ListFooterComponent={
                                <View>
                                    <Text style={styles.text_footer}>version {expo.version}</Text>
                                    <Text style={{fontSize:9,color:Couleurs.text_muted,textAlign:'center'}}>Développé par <Text style={{fontWeight:'bold'}}>ifluxe</Text></Text>
                                    <Text style={{fontSize:9,textAlign:'center'}}><Text style={{fontWeight:'700'}}>Fruxgroupe</Text> en parténariat avec <Text style={{fontWeight:'700'}}>Soleil Couchant Tabernacle</Text></Text>
                                </View>
                            }
                        />
                    </View>
            </ImageBackground>
        </Animatable.View>
    );
}

const styles = StyleSheet.create({
    text_footer:{textAlign:'center',marginTop:5,borderTopWidth:1,borderTopColor:"#7F8C8D",fontSize:10,paddingTop:1},
    container:{padding:10},
    card:{marginBottom:20},
    boxshadow:{shadowColor:Couleurs.text_muted,elevation:7},
});

const RemotImage = ({uri,desireWidth}) => {
    const [desiredHeight, setdesiredHeight] = React.useState(0)
    Image.getSize(uri, (width,height) =>
    {
        setdesiredHeight(desireWidth/width*height)
    })
    return (
        <Image source={{uri}} style={{width:desireWidth,height:desiredHeight}}/>
    )
};
</code>```

Body:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of  from render. Or maybe you meant to call this function rather than return it.
in RCTText (created by Text)
in Text
in Text (created by BottomNavigation)
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper (created by BottomNavigation)
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper (created by BottomNavigation)
in RCTView (created by View)
in View (created by BottomNavigation)
in RCTView (created by View)
in View (created by Touchable)
in TouchableWithoutFeedback (created by Touchable)
in Touchable (created by BottomNavigation)
in RCTView (created by View)
in View (created by BottomNavigation)
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper (created by BottomNavigation)
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper
in RCTView (created by View)
in View (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper
in Unknown (created by BottomNavigation)
in RCTView (created by View)
in View (created by BottomNavigation)
in BottomNavigation
in ThemedComponent (created by withTheme(BottomNavigation))
in withTheme(BottomNavigation) (created by MaterialBottomTabViewInner)
in MaterialBottomTabViewInner (created by MaterialBottomTabView)
in RNCSafeAreaProvider (created by SafeAreaProvider)
in SafeAreaProvider (created by SafeAreaInsetsContext)
in SafeAreaProviderCompat (created by MaterialBottomTabView)
in MaterialBottomTabView (created by MaterialBottomTabNavigator)
in PreventRemoveProvider (created by NavigationContent)
in NavigationContent
in Unknown (created by MaterialBottomTabNavigator)
in MaterialBottomTabNavigator (created by App)
in EnsureSingleNavigator
in BaseNavigationContainer
in ThemeProvider
in NavigationContainerInner (created by App)
in App (created by withDevTools(App))
in withDevTools(App)
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in main(RootComponent)

I tried to publish my app on Apple Store and they told me after splashscreen, a white screen appears and on my phone everything is getting fine.
bellow my code :

import React,{useEffect} from 'react';
import { ImageBackground,Text,StyleSheet,View,TouchableOpacity,Image,FlatList} from 'react-native';
import * as Animatable from 'react-native-animatable';
import Include_entete from '../includes/Include_entete';
import Couleurs from '../composants/Couleurs';
import { LinearGradient } from 'expo-linear-gradient';
import {expo} from '../app.json';
import { Ionicons } from '@expo/vector-icons';
import { MaterialCommunityIcons } from '@expo/vector-icons';
//import * as Device from 'expo-device';

export default function Fenetre_accueil({navigation})
{
    const [isLoading,setIsLoading] = React.useState(true);
    const [data, setData] = React.useState({hits:[]});

    useEffect(() =>
    {
        setIsLoading(true);
        setTimeout(async() => {
            fetch("https://www.xxxxxx.com/application/app-recueil-sct/last_four_song.php", {method: "GET"})
            .then((response) => response.json())
            .then((responseJson) =>
            {
                setData({hits:responseJson});
            })
            setIsLoading(false);
        },1000);
    }, []);

    if(isLoading)
    {
        return(
        <Animatable.View style={{flex:1,justifyContent:'center',alignItems:'center'}} animation="bounceIn">
            <RemotImage
                uri={"https://fxxxxxxx.com/ressources/images/logo.png"}
                desireWidth={200}
            />
        </Animatable.View>
        );
    }

    return(
        <Animatable.View animation="bounceInDown" style={{flex:1}}>
            <Include_entete />
            <ImageBackground imageStyle={{opacity: 0.2}} style={{flex:1,justifyContent:'center',alignSelf:'stretch'}} source={require('./../images/eagle1.jpeg')} resizeMode='cover'>
                    <View style={styles.container}>
                        <FlatList
                            ListHeaderComponent={
                                <View>
                                    <Text style={{color:Couleurs.text_info,fontSize:20,marginBottom:5,marginLeft:5}}>Bienvenue</Text>

                                    <TouchableOpacity onPress={() => {navigation.navigate('Search',{search:' '})}} style={[styles.boxshadow,styles.card]}>
                                        <ImageBackground source={{uri:'https://xxxxxxxx.com/ressources/images/bible.jpg'}} resizeMode='cover' style={{minHeight:200}}>
                                            <LinearGradient colors={['rgba(0,0,0,0.2)','rgba(0,0,0,0.8)']} style={{minHeight:200,padding:5}}>
                                                <View style={{flexDirection:'row'}}>
                                                    <MaterialCommunityIcons name="book-open-page-variant" size={45} color="#fff" style={{marginRight:5}}/>
                                                    <Text style={{fontSize:35,color:"#FDF2E9"}}>Recueil SCT</Text>
                                                </View>
                                                <Text style={{color:'#FDF2E9',fontSize:16,marginTop:10,paddingHorizontal:2}}>Cette application vous donne accès à tout le guide de cantiques de l'Eglise Soleil Couchant Tabernacle.</Text>
                                                <View style={{flexDirection:'row-reverse',borderTopColor:'#FDF2E9',borderTopWidth:1,marginTop:20}}>
                                                    <Ionicons name="arrow-forward-circle-sharp" size={40} color="#FDF2E9" />
                                                    <Text style={{fontSize:16,color:"#FDF2E9",marginRight:5,marginTop:7}}>Accéder à tous nos Cantiques</Text>
                                                </View>
                                            </LinearGradient>
                                        </ImageBackground>
                                    </TouchableOpacity>

                                    <Text style={{color:Couleurs.text_info,fontSize:20,marginBottom:5,marginLeft:5}}>Dernières mise à jour</Text>
                                </View>
                            }
                            data={data.hits} showsVerticalScrollIndicator={false} nestedScrollEnabled={true}
                            renderItem={({item,index}) =>
                            (
                                <TouchableOpacity onPress={() => {navigation.navigate('Chant',{Id:item.id})}} style={[styles.boxshadow,styles.card]}>
                                <ImageBackground source={{uri:'https://xxxxxxxx.com/ressources/images/jesus.jpg'}} resizeMode='cover' style={{minHeight:200}}>
                                    <LinearGradient colors={['rgba(0,0,0,0.2)','rgba(0,0,0,0.8)']} style={{minHeight:200,padding:5}}>
                                        <View style={{flexDirection:'row'}}>
                                            <MaterialCommunityIcons name="microphone-variant" size={45} color="#fff" />
                                            <Text style={{fontSize:35,color:"#FDF2E9"}}>Chant : #{item.num}</Text>
                                        </View>
                                        <Text style={{color:'#FDF2E9',fontSize:16,marginTop:10,paddingHorizontal:2}}>{item.chant.substring(0,100).replace(/\n|\r/g,' ')}...</Text>
                                        <View style={{flexDirection:'row-reverse',borderTopColor:'#FDF2E9',borderTopWidth:1,marginTop:20}}>
                                            <Ionicons name="arrow-forward-circle-sharp" size={40} color="#FDF2E9" />
                                            <Text style={{fontSize:16,color:"#FDF2E9",marginRight:5,marginTop:7}}>Consulter</Text>
                                        </View>
                                    </LinearGradient>
                                </ImageBackground>
                            </TouchableOpacity>
                            )}
                            keyExtractor = {( item, index ) => index.toString() }

                            ListFooterComponent={
                                <View>
                                    <Text style={styles.text_footer}>version {expo.version}</Text>
                                    <Text style={{fontSize:9,color:Couleurs.text_muted,textAlign:'center'}}>Développé par <Text style={{fontWeight:'bold'}}>ifluxe</Text></Text>
                                    <Text style={{fontSize:9,textAlign:'center'}}><Text style={{fontWeight:'700'}}>Fruxgroupe</Text> en parténariat avec <Text style={{fontWeight:'700'}}>Soleil Couchant Tabernacle</Text></Text>
                                </View>
                            }
                        />
                    </View>
            </ImageBackground>
        </Animatable.View>
    );
}

const styles = StyleSheet.create({
    text_footer:{textAlign:'center',marginTop:5,borderTopWidth:1,borderTopColor:"#7F8C8D",fontSize:10,paddingTop:1},
    container:{padding:10},
    card:{marginBottom:20},
    boxshadow:{shadowColor:Couleurs.text_muted,elevation:7},
});

const RemotImage = ({uri,desireWidth}) => {
    const [desiredHeight, setdesiredHeight] = React.useState(0)
    Image.getSize(uri, (width,height) =>
    {
        setdesiredHeight(desireWidth/width*height)
    })
    return (
        <Image source={{uri}} style={{width:desireWidth,height:desiredHeight}}/>
    )
};


问:
pipe still not found in component using shared module
I have a pipe I want to use in a component in a module.

At the module page level. I am able to use it.

But at the component level that us under this module, I cannot.

```<code>//shared module for the pipe
@NgModule({
  declarations: [DefaultPipe],
  exports: [DefaultPipe]
})
export class DefaultPipeModule{}

//shared module with the component and pipe
@NgModule({
  imports: [DefaultPipeModule],
  declarations: [LoginComponent],
  exports: [LoginComponent]
})
export class FooModule {}

//main page module
@NgModule({
  imports: [FooModule],
  declarations: []
})
export class MainModule{}
</code>```

At the main module, I am able to use the pipe in the template.

But not at the LoginComponent.

```<code>The pipe 'defaulttestpipe' could not be found in the 'LoginComponent' component
</code>```

I have basically tried everything.

First I tried to import the pipe directly.

Then as a shared module.

Now as a shared module with the pipe module and component.

And several other methods including directly using providers on the component.

Any help appreciated.

Body:
I have a pipe I want to use in a component in a module.

At the module page level. I am able to use it.

But at the component level that us under this module, I cannot.

//shared module for the pipe
@NgModule({
  declarations: [DefaultPipe],
  exports: [DefaultPipe]
})
export class DefaultPipeModule{}

//shared module with the component and pipe
@NgModule({
  imports: [DefaultPipeModule],
  declarations: [LoginComponent],
  exports: [LoginComponent]
})
export class FooModule {}

//main page module
@NgModule({
  imports: [FooModule],
  declarations: []
})
export class MainModule{}

At the main module, I am able to use the pipe in the template.

But not at the LoginComponent.

The pipe 'defaulttestpipe' could not be found in the 'LoginComponent' component

I have basically tried everything.

First I tried to import the pipe directly.

Then as a shared module.

Now as a shared module with the pipe module and component.

And several other methods including directly using providers on the component.

Any help appreciated.


问:
Modify Plotly legend to match color of lines but have text matching another column's contents in R dataframe
I have data that looks like this:

After running the following code:

```<code>axx <- list(
  nticks = 3,
  tickvals = c(0,1,2),
  ticktext = c("AA", "Aa", "aa"),
  title = "SNP2 Genotype")

axy <- list(
  nticks = 3,
  tickvals = c(0,1,2),
  ticktext = c("AA", "Aa", "aa"),
  title = "SNP3 Genotype")

axz <- list(
  nticks = 7,
  tickvals = c(0,1,2,3,4,5,6),
  ticktext = c("1", "2", "3", "4", "5", "6"),
  title = "BMI with Tail")

plot_ly(Add3W_T, x = ~SNP2, y = ~SNP3, z = ~phenotype, type = 'scatter3d', mode = 'lines', opacity = 1, color = ~Geno_color,
        line = list(width = 14, color = ~Geno_color, showspikes=FALSE)) %>%
  layout(scene = list(xaxis = axx, yaxis = axy, zaxis = axz),
         title = list(text = "3D Reaction Norms - Additive"),
         legend = list(title = list(text = "SNP1 Genotype")))
</code>```

I get this resulting image:

I want the legend in the top right to match the colors of the lines set by the first column of my dataframe (Geno_color) but have the text from the last column (SNP1_Geno)

Body:
I have data that looks like this:

After running the following code:

axx <- list(
  nticks = 3,
  tickvals = c(0,1,2),
  ticktext = c("AA", "Aa", "aa"),
  title = "SNP2 Genotype")

axy <- list(
  nticks = 3,
  tickvals = c(0,1,2),
  ticktext = c("AA", "Aa", "aa"),
  title = "SNP3 Genotype")

axz <- list(
  nticks = 7,
  tickvals = c(0,1,2,3,4,5,6),
  ticktext = c("1", "2", "3", "4", "5", "6"),
  title = "BMI with Tail")

plot_ly(Add3W_T, x = ~SNP2, y = ~SNP3, z = ~phenotype, type = 'scatter3d', mode = 'lines', opacity = 1, color = ~Geno_color,
        line = list(width = 14, color = ~Geno_color, showspikes=FALSE)) %>%
  layout(scene = list(xaxis = axx, yaxis = axy, zaxis = axz),
         title = list(text = "3D Reaction Norms - Additive"),
         legend = list(title = list(text = "SNP1 Genotype")))

I get this resulting image:

I want the legend in the top right to match the colors of the lines set by the first column of my dataframe (Geno_color) but have the text from the last column (SNP1_Geno)


问:
Code given by professor contains nonexistent commands
The main() below was given to my class by the professor with the objective of making the program into a sentinel loop but he claims that the program will run as a one off with copy paste but "getRootCount" and "solveEquation" are flagging and it won't work. I haven't been able to find anything on how to fix this problem. I am using Visual Studio which he also supposedly uses as well.

```<code>int const SIZE = 3;
double coefficients[SIZE];
double discriminant;

cout << "This program solves quadratic formulas\n";
cout << "Enter 3 coefficients separate by spaces: ";
cin >> coefficients[0] >> coefficients[1] >> coefficients[2];

if (coefficients[0] == 0)
    cout << "First coefficient cannot be 0.";
else
{
    // Get number of roots
    int rootCount = getRootCount(discriminant, coefficients);
    if (rootCount == 0)     // No root
        cout << "There is no root" << endl;
    else                            // 1 or 2 roots
    {
        double roots[2];
        solveEquation(discriminant, coefficients, roots);
        if (rootCount == 1)
            cout << "There is one root: " << roots[0] << endl;
        else
            cout << "There are 2 roots: " << roots[0] << "   " << roots[1] << endl;
    }
}
</code>```

I've googled it and as far as I can tell "getRootCount" and "solveEquation" aren't actually commands. If that's true I'm not sure what to use instead.

Body:
The main() below was given to my class by the professor with the objective of making the program into a sentinel loop but he claims that the program will run as a one off with copy paste but "getRootCount" and "solveEquation" are flagging and it won't work. I haven't been able to find anything on how to fix this problem. I am using Visual Studio which he also supposedly uses as well.

int const SIZE = 3;
double coefficients[SIZE];
double discriminant;

cout << "This program solves quadratic formulas\n";
cout << "Enter 3 coefficients separate by spaces: ";
cin >> coefficients[0] >> coefficients[1] >> coefficients[2];

if (coefficients[0] == 0)
    cout << "First coefficient cannot be 0.";
else
{
    // Get number of roots
    int rootCount = getRootCount(discriminant, coefficients);
    if (rootCount == 0)     // No root
        cout << "There is no root" << endl;
    else                            // 1 or 2 roots
    {
        double roots[2];
        solveEquation(discriminant, coefficients, roots);
        if (rootCount == 1)
            cout << "There is one root: " << roots[0] << endl;
        else
            cout << "There are 2 roots: " << roots[0] << "   " << roots[1] << endl;
    }
}

I've googled it and as far as I can tell "getRootCount" and "solveEquation" aren't actually commands. If that's true I'm not sure what to use instead.


问:
Intersection between each pair of bags

For 700 randomly selected sentences in the Brown news corpus (the
"anchor sentences"), and their immediately succeeding sentences, form
bags of the significant words for each pair of sentences and then
compute the intersection between each pair of bags.  Tabulate these and
compare the results to another randomly drawn 700 sentences,
ensuring that there are no duplicates between the anchor sentences and
this new set.  Permute all sentences in the corpus, then draw the same
700 and their new successors and repeat the computations

This is what I have so far

```<code>#+begin_src python :results output
random.sample(sorted(nltk.corpus.brown.tagged_sents(categories='news', tagset='universal')), 700)
#+end_sr
</code>```

Any suggestions?

Title: Intersection between each pair of bags

Body:
For 700 randomly selected sentences in the Brown news corpus (the
"anchor sentences"), and their immediately succeeding sentences, form
bags of the significant words for each pair of sentences and then
compute the intersection between each pair of bags.  Tabulate these and
compare the results to another randomly drawn 700 sentences,
ensuring that there are no duplicates between the anchor sentences and
this new set.  Permute all sentences in the corpus, then draw the same
700 and their new successors and repeat the computations

This is what I have so far

#+begin_src python :results output
random.sample(sorted(nltk.corpus.brown.tagged_sents(categories='news', tagset='universal')), 700)
#+end_sr

Any suggestions?


问:
How to target Dom elements in react native
Good day to anyone reading this, I wanted to ask if there was any way to target a specific dom element in react native such as this.

Tried to research but there was no clear answer.

This code was done in React.

```<code>  document.querySelector(
        `.node-${row}-${col}`
      ).className = `eachCell node-${row}-${col} wall`;
</code>```

Body:
Good day to anyone reading this, I wanted to ask if there was any way to target a specific dom element in react native such as this.

Tried to research but there was no clear answer.

This code was done in React.

  document.querySelector(
        `.node-${row}-${col}`
      ).className = `eachCell node-${row}-${col} wall`;


问:
Accessing an Alpine JS store for PDO query
I am working on a menu system for a LMS which has tabs across the top for each class and then the module menu opens down the side based on the class which is selected. I am very close to making it dynamic from the DB but have one glitch that I have spent a couple days on. I have read everything I can find but I am stuck so hoping someone here has the answer.
It seems to me that the most efficient way would be to store the active tab in the Alpine.store and then retrieve it within the class which queries the DB. I can retieve the data from the store in the form of x-text but and it echos out fine but I can't get the PDO query to recognise it. After all the searching and testing I have come to the conclusion that it must have to do with the order that the content is processed in the DOM so that the x-text is happening after the PDO query but I have not found a way to force it to run first or a different way to retrieve the store data in a variable that PHP will use.
Any help is greatly appreciated!

```<code>

$parent='\<container x-text="$store.nav.activeTab"\>\</container\>';

$parent=array($parent);

print_r($parent);

$sql = "SELECT * FROM nav WHERE parent LIKE ? && type = 'ClassMod'";
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute($parent);
</code>```

I have tried using jquery/AJAX, plain JS, and every related tutorial I can find on Alpine. I just want a way to retrieve Alpine.store data and use at as a PHP variable which I can use in a query. I can easily get the Alpine.store data printed to the screen, it just won't work in a query.

Body:
I am working on a menu system for a LMS which has tabs across the top for each class and then the module menu opens down the side based on the class which is selected. I am very close to making it dynamic from the DB but have one glitch that I have spent a couple days on. I have read everything I can find but I am stuck so hoping someone here has the answer.
It seems to me that the most efficient way would be to store the active tab in the Alpine.store and then retrieve it within the class which queries the DB. I can retieve the data from the store in the form of x-text but and it echos out fine but I can't get the PDO query to recognise it. After all the searching and testing I have come to the conclusion that it must have to do with the order that the content is processed in the DOM so that the x-text is happening after the PDO query but I have not found a way to force it to run first or a different way to retrieve the store data in a variable that PHP will use.
Any help is greatly appreciated!

$parent='\<container x-text="$store.nav.activeTab"\>\</container\>';

$parent=array($parent);

print_r($parent);

$sql = "SELECT * FROM nav WHERE parent LIKE ? && type = 'ClassMod'";
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute($parent);

I have tried using jquery/AJAX, plain JS, and every related tutorial I can find on Alpine. I just want a way to retrieve Alpine.store data and use at as a PHP variable which I can use in a query. I can easily get the Alpine.store data printed to the screen, it just won't work in a query.


问:
wp: footer text in different languages
i have wp website that translated to two languages .. i want to change footer copy right using php but below code is not working .. any help?

add_filter('botiga-credits','socket_per_language');
function socket_per_language(){
$currentlang = get_bloginfo('language');

if($currentlang=="en-US") {
$output = "your custom text in English";
}
elseif($currentlang=="de-DE") {
$output = "your custom text in German";
}
else{
$output = "your custom text in Dutch";
}
return $output;
}```

Title: wp: footer text in different languages


问:
Made this model network for a class I'm taking, but I can't get anything to ping anything. Can someone fix it for me? Thanks
https://github.com/LilPest0/projects/blob/main/hospitalnetwork.pkt

Spent about 6 hours on this today. Got pretty far, configured the ospf but i cant get anything to ping


问:
Will a feign-client method return before the entire response is downloaded from the Rest endpoint?
I am using feign to call an endpoint that returns a large binary file, and then I'm using this to get the InputStream:
Response.Body.asInputStream();

Will feign return the Response before the entire file has downloaded, so that I can stream it as it comes in? Or does it wait to return until the entire file is downloaded from the Rest endpoint?

The fact that it provides an InputStream implies to me that it will return before the whole file has downloaded, but I can't find documentation on that.


问:
MSBuild.exe does not result in failed build for editorconfig violations
I am creating a Visual Studio extension that attempts to rebuild a solution following a button click. I am using Process.Start() to perform a Rebuild the project using MSBuild. MSBuild displays all of the build errors/warnings but if I introduce an .editorconfig file with some code formatting guidelines for instance csharp_prefer_braces = true : error, MSBuild does not result in a failed build. Would anyone know what I could be doing wrong?

I am attempting to build a .NET framework 4.6 Console application and my MSBuild version is 4.8.4084.0

Thank you


问:
Correctly return pointer to key/value pair from bespoke associative container & iterator
I have an associative container that is implemented internally as two linear arrays, one of keys, and one of values. Both arrays are kept sorted so a binary search of keys yields the index of the value. This is done to improve the performance of searches when the size relationship between keys and values is grossly asymmetric. The container use case is modified rarely but searched often, which is why we have designed it this way.

```<code>template<typename Key, typename Value>
struct Container
{
  // allocated on create
  Key* mKeys;
  Value* mValues;
  unsigned mCount;

  class iterator
  {
       Container* mContainer;
       unsigned mIndex;

       // return a pair that can support mutating the value but not the key
       std::pair<const Key &,Value &> MakePair() {
           return std::make_pair( mContainer->mKeys[mIndex],
                                  mContainer->mValues[mIndex] );
           };

       // I don't have a std::pair to return here; and I can't return a temporary.
       std::pair<const Key,Value> & operator*();
       std::pair<const Key,Value> * operator->();
  }

}
</code>```

I am trying to implement an iterator over the container that returns a key/value pair similar to std::map.

My concern is around reference operator*() and pointer operator->(), where I don't actually have a std::pair to return a reference to. However, I would still like to use the syntax of container.begin()->first, or (*container.begin()).second.

Does anyone have any insights on how I can return a reference or pointer to a std::pair<const key, value> here? Or, can I simply return something by value which holds references to the key and value, named first and second, respectively, to get compliance?

Body:
I have an associative container that is implemented internally as two linear arrays, one of keys, and one of values. Both arrays are kept sorted so a binary search of keys yields the index of the value. This is done to improve the performance of searches when the size relationship between keys and values is grossly asymmetric. The container use case is modified rarely but searched often, which is why we have designed it this way.

template<typename Key, typename Value>
struct Container
{
  // allocated on create
  Key* mKeys;
  Value* mValues;
  unsigned mCount;

  class iterator
  {
       Container* mContainer;
       unsigned mIndex;

       // return a pair that can support mutating the value but not the key
       std::pair<const Key &,Value &> MakePair() {
           return std::make_pair( mContainer->mKeys[mIndex],
                                  mContainer->mValues[mIndex] );
           };

       // I don't have a std::pair to return here; and I can't return a temporary.
       std::pair<const Key,Value> & operator*();
       std::pair<const Key,Value> * operator->();
  }

}

I am trying to implement an iterator over the container that returns a key/value pair similar to std::map.

My concern is around reference operator*() and pointer operator->(), where I don't actually have a std::pair to return a reference to. However, I would still like to use the syntax of container.begin()->first, or (*container.begin()).second.

Does anyone have any insights on how I can return a reference or pointer to a std::pair<const key, value> here? Or, can I simply return something by value which holds references to the key and value, named first and second, respectively, to get compliance?


问:
REST API Authentication with C# WPF Client
I'm using API-Platform 3.0 on Symfony 6.1 to build an API-REST. Then I build a REST client with WPF (C#) on .Net 6.0, my problem: I can't authenticate my client to the API. Here is my source code:

```<code>using ApiClient.DAO.Account;
using System.Net.Http;
using System.Windows;
using Newtonsoft.Json;

namespace ApiClient.Controller.Account
{
    /// <summary>
    /// Logique d'interaction pour LoginWindow.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        public LoginWindow()
        {
            InitializeComponent();
        }

        private async void __submit_Click(object sender, RoutedEventArgs e)
        {
            Login login = new Login();
            login.username = "SID-000001";
            login.password = "test";

            var json = JsonConvert.SerializeObject(login);
            var data = new StringContent(json);

            using var client = new HttpClient();
            var response = await client.PostAsync("http://127.0.0.1:8000/api/login", data);

            MessageBox.Show(response.Content.ReadAsStringAsync().Result);
        }
    }
}
</code>```

Can anyone help me?

I tried to authenticate on a REST API via a WPF client (C#) but it doesn't work.

Body:
I'm using API-Platform 3.0 on Symfony 6.1 to build an API-REST. Then I build a REST client with WPF (C#) on .Net 6.0, my problem: I can't authenticate my client to the API. Here is my source code:

using ApiClient.DAO.Account;
using System.Net.Http;
using System.Windows;
using Newtonsoft.Json;

namespace ApiClient.Controller.Account
{
    ///
    /// Logique d'interaction pour LoginWindow.xaml
    ///
    public partial class LoginWindow : Window
    {
        public LoginWindow()
        {
            InitializeComponent();
        }

        private async void __submit_Click(object sender, RoutedEventArgs e)
        {
            Login login = new Login();
            login.username = "SID-000001";
            login.password = "test";

            var json = JsonConvert.SerializeObject(login);
            var data = new StringContent(json);

            using var client = new HttpClient();
            var response = await client.PostAsync("http://127.0.0.1:8000/api/login", data);

            MessageBox.Show(response.Content.ReadAsStringAsync().Result);
        }
    }
}

Can anyone help me?

I tried to authenticate on a REST API via a WPF client (C#) but it doesn't work.


问:
I want to make a "simple" division
I'm trying to do a "simple" division in c and the result is going wrong, I have a float variable that receives the value of a division, in this case the division is a number contained in a long int, but the decimal part is cut when I try to print the variable

#include <stdio.h>

int main() {
    long int a = 120510380;
    float b;
    b = a / 7;
    printf("%f", b);
    return 0;
}
```

Expected decimal number with numbers cut off after comma

Title: I want to make a "simple" division

Body:
I'm trying to do a "simple" division in c and the result is going wrong, I have a float variable that receives the value of a division, in this case the division is a number contained in a long int, but the decimal part is cut when I try to print the variable

#include <stdio.h>

int main() {
    long int a = 120510380;
    float b;
    b = a / 7;
    printf("%f", b);
    return 0;
}

Expected decimal number with numbers cut off after comma


问:
Want to add "add to cart" on a widget ... please advice
This is the widget code:

```<code><div class="fast-simon-upsell" data-title="You Might Also Like..." data-layout="horizontal" data-max-suggest="5" data-img-ratio="1:1" data-sources="related_views,similar_products,related_recently_viewed,related_cart,related_purchase" style="height: 100%;"></div>
<script src="https://widgetcode-upsell-and-cross-sell.net/abc123" async></script>

</code>```

This is the script for add to cart. I tried to add the script separately or tried to add to cart.liquid but that didn't work as well.

```<code><script>

/* CalllBacks START */

var isp_related_options = {
isp_related_callback: function (data) {
for (const key in ISP_RELATED_PRODUCTS) {
const product = ISP_RELATED_PRODUCTS[key];
const $divItem = $jquery_isp(
`.isp_related_product[isp_product_id="${key}"]`
);

/* +QuickAdd btn */
AddToCart.create(product, $divItem);
}
}, // Recommendations rendered
};

/* CalllBacks END */
const ButtonType = {
Single: "single",
Options: "options",
SelectColor: "select color",
SelectSize: "select size",
SoldOut: "sold out",
};

function getFirstVariantID(product) {
return product.vra && product.vra.length > 0 ? product.vra[0][0] : product.id;
}

function isSoldOut (product) {
return ("iso" in product && product.iso);
}
function findVariantOption(variant, optionName) {
const data = variant[1].find((option) => option[0] === optionName);
return data ? data[1][0] : null;
}

const AddToCart = {

create: (product, $gridItem) => {
const type = AddToCart.getButtonType(product);
const isFrom = AddToCart.checkFrom($gridItem);

AddToCart.removePrice($gridItem);

switch (type) {
case ButtonType.Single: {
AddToCart.setAddToCart(product, $gridItem, "ADD TO CART", isFrom);
break;
}
case ButtonType.SoldOut: {
AddToCart.setSoldOut($gridItem);
break;
}
case ButtonType.SelectColor: {
AddToCart.setRedirectToProduct(
product,
$gridItem,
"SELECT COLOR",
isFrom
);
break;
}
case ButtonType.SelectSize: {
AddToCart.setRedirectToProduct(
product,
$gridItem,
"SELECT SIZE",
isFrom
);
break;
}
case ButtonType.Options: {
AddToCart.setRedirectToProduct(
product,
$gridItem,
"SELECT OPTIONS",
isFrom
);
}
}
},

getButtonType: (product) => {
if (isSoldOut(product)) {
return ButtonType.SoldOut;
}

if (!product.vra || product.vra.length < 2) {
return ButtonType.Single;
}

const options = AddToCart.getOptions(product);
if (options.sizes.size > 1 && options.colors.size === 1) {
return ButtonType.SelectSize;
} else if (options.sizes.size === 1 && options.colors.size > 1) {
return ButtonType.SelectColor;
} else {
return ButtonType.Options;
}
},

getOptions: (product) => {
const colors = new Set();
const sizes = new Set();

for (const variant of product.vra) {
const color = findVariantOption(variant, COLOR_FACET_NAME);
const size = findVariantOption(variant, SIZE_FACET_NAME);

if (color) colors.add(color);
if (size) sizes.add(size);
}

return {
colors: colors,
sizes: sizes,
};
},

checkFrom: ($gridItem) => {
return $gridItem
.find(".isp_product_price_wrapper")
.text()
?.includes("from");
},

removePrice: ($gridItem) => {
$gridItem.find(".isp_product_price_wrapper").remove();
},

setSoldOut: ($gridItem) => {
const HTML = `
<div class="isp-product-add-to-cart sold-out">
<div class="add-to-cart-text">SOLD OUT</div>
</div>
`;

if ($gridItem.find(".isp_add_to_cart_form").length === 0) {
$gridItem.find(".isp_product_info").after(HTML);
} else {
$gridItem.find(".isp_add_to_cart_form").replaceWith(HTML);
}
},

setAddToCart: (product, $gridItem, text, useFrom) => {
const price = parseFloat(product.p);
const comparePrice = parseFloat(product.p_c);

const fromClass = useFrom ? "from-included" : "";
const compareClass = comparePrice ? "compare-included" : "";

const HTML = `
<div class="isp-product-add-to-cart">
<div class="isp-product-price-wrapper">
<span class="price-container actual ${fromClass} ${compareClass}">$${price.toFixed(2)}</span>
<span class="price-container compare">${comparePrice ? "$" + comparePrice.toFixed(2) : "" }</span>
</div>
<span class="atc-break"/>
<div class="add-to-cart-text">${text}</div>
</div>`;

if ($gridItem.find(".isp_add_to_cart_form").length === 0) {
$gridItem.find(".isp_product_info").after(HTML);
} else {
$gridItem.find(".isp_add_to_cart_form").replaceWith(HTML);
}

$gridItem.find(".isp-product-add-to-cart").click(function () {
AddToCart.addToCartAjax(product, $gridItem.attr("position"));
});
},

setRedirectToProduct: (product, $gridItem, text, useFrom) => {
const price = parseFloat(product.p);
const comparePrice = parseFloat(product.p_c);

const fromClass = useFrom ? "from-included" : "";
const compareClass = comparePrice ? "compare-included" : "";

const HTML = `<a class="isp-product-add-to-cart" href="${product.u}">
<div class="isp-product-price-wrapper">
<span class="price-container actual ${fromClass} ${compareClass}">$${price.toFixed(2)}</span>
<span class="price-container compare">${comparePrice ? "$" + comparePrice.toFixed(2) : ""}</span></div>
<span class="atc-break"/>
<div class="add-to-cart-text">${text}</div>
</a>`;

if ($gridItem.find(".isp_add_to_cart_form").length === 0) {
$gridItem.find(".isp_product_info").after(HTML);
} else {
$gridItem.find(".isp_add_to_cart_form").replaceWith(HTML);
}
},

addToCartAjax: (product, product_position) => {
if (product.vra.length > 2) {
QuickView.create(product);
return;
}

document.body.style.cursor = "wait";

const data = {
id: getFirstVariantID(product),
};

try {
localStorage.setItem("isp_add_to_cart_serp_product_id", product.id);
ispStoreProductPosition(product.id);
} catch (e) {}
$.ajax({
type: "POST",
url: "/cart/add.js",
data,
dataType: "json",
cache: false,
product_id: product.id,
form_id: `form_${product.id}`,
is_quick_view: false,
})
.done(function (data) {
onAddToCartFinish(this.product_id, false);
})
.fail(function (jqXHR, textStatus) {
console.log("error jqXHR: " + jqXHR + " | textStatus: " + textStatus);
})
.always(function () {
$jquery_isp("#" + this.form_id).removeClass("isp_add_to_cart_disable");
});
},

};

</script>
</code>```

I just tried to merge the two at the script but ofcourse it didn't work...
I tried to remove the script from the original widget and then added the src as css format but that didn't work as well.
I am a total beginner at this so I am guessing I am missing to add the url somewhere else as well but not sure where...
What would be the best way to do this?

```<code><div class="fast-simon-upsell" data-title="You Might Also Like..." data-layout="horizontal" data-max-suggest="5" data-img-ratio="1:1" data-sources="related_views,similar_products,related_recently_viewed,related_cart,related_purchase" style="height: 100%;"></div>

<script>

async src: url(https://widgetcode-upsell-and-cross-sell.net/abc123);

/* CalllBacks START */

var isp_related_options = {
isp_related_callback: function (data) {
for (const key in ISP_RELATED_PRODUCTS) {
const product = ISP_RELATED_PRODUCTS[key];
const $divItem = $jquery_isp(
`.isp_related_product[isp_product_id="${key}"]`
);

/* +QuickAdd btn */
AddToCart.create(product, $divItem);
}
}, // Recommendations rendered
};

/* CalllBacks END */
const ButtonType = {
Single: "single",
Options: "options",
SelectColor: "select color",
SelectSize: "select size",
SoldOut: "sold out",
};

function getFirstVariantID(product) {
return product.vra && product.vra.length > 0 ? product.vra[0][0] : product.id;
}

function isSoldOut (product) {
return ("iso" in product && product.iso);
}
function findVariantOption(variant, optionName) {
const data = variant[1].find((option) => option[0] === optionName);
return data ? data[1][0] : null;
}

const AddToCart = {

create: (product, $gridItem) => {
const type = AddToCart.getButtonType(product);
const isFrom = AddToCart.checkFrom($gridItem);

AddToCart.removePrice($gridItem);

switch (type) {
case ButtonType.Single: {
AddToCart.setAddToCart(product, $gridItem, "ADD TO CART", isFrom);
break;
}
case ButtonType.SoldOut: {
AddToCart.setSoldOut($gridItem);
break;
}
case ButtonType.SelectColor: {
AddToCart.setRedirectToProduct(
product,
$gridItem,
"SELECT COLOR",
isFrom
);
break;
}
case ButtonType.SelectSize: {
AddToCart.setRedirectToProduct(
product,
$gridItem,
"SELECT SIZE",
isFrom
);
break;
}
case ButtonType.Options: {
AddToCart.setRedirectToProduct(
product,
$gridItem,
"SELECT OPTIONS",
isFrom
);
}
}
},

getButtonType: (product) => {
if (isSoldOut(product)) {
return ButtonType.SoldOut;
}

if (!product.vra || product.vra.length < 2) {
return ButtonType.Single;
}

const options = AddToCart.getOptions(product);
if (options.sizes.size > 1 && options.colors.size === 1) {
return ButtonType.SelectSize;
} else if (options.sizes.size === 1 && options.colors.size > 1) {
return ButtonType.SelectColor;
} else {
return ButtonType.Options;
}
},

getOptions: (product) => {
const colors = new Set();
const sizes = new Set();

for (const variant of product.vra) {
const color = findVariantOption(variant, COLOR_FACET_NAME);
const size = findVariantOption(variant, SIZE_FACET_NAME);

if (color) colors.add(color);
if (size) sizes.add(size);
}

return {
colors: colors,
sizes: sizes,
};
},

checkFrom: ($gridItem) => {
return $gridItem
.find(".isp_product_price_wrapper")
.text()
?.includes("from");
},

removePrice: ($gridItem) => {
$gridItem.find(".isp_product_price_wrapper").remove();
},

setSoldOut: ($gridItem) => {
const HTML = `
<div class="isp-product-add-to-cart sold-out">
<div class="add-to-cart-text">SOLD OUT</div>
</div>
`;

if ($gridItem.find(".isp_add_to_cart_form").length === 0) {
$gridItem.find(".isp_product_info").after(HTML);
} else {
$gridItem.find(".isp_add_to_cart_form").replaceWith(HTML);
}
},

setAddToCart: (product, $gridItem, text, useFrom) => {
const price = parseFloat(product.p);
const comparePrice = parseFloat(product.p_c);

const fromClass = useFrom ? "from-included" : "";
const compareClass = comparePrice ? "compare-included" : "";

const HTML = `
<div class="isp-product-add-to-cart">
<div class="isp-product-price-wrapper">
<span class="price-container actual ${fromClass} ${compareClass}">$${price.toFixed(2)}</span>
<span class="price-container compare">${comparePrice ? "$" + comparePrice.toFixed(2) : "" }</span>
</div>
<span class="atc-break"/>
<div class="add-to-cart-text">${text}</div>
</div>`;

if ($gridItem.find(".isp_add_to_cart_form").length === 0) {
$gridItem.find(".isp_product_info").after(HTML);
} else {
$gridItem.find(".isp_add_to_cart_form").replaceWith(HTML);
}

$gridItem.find(".isp-product-add-to-cart").click(function () {
AddToCart.addToCartAjax(product, $gridItem.attr("position"));
});
},

setRedirectToProduct: (product, $gridItem, text, useFrom) => {
const price = parseFloat(product.p);
const comparePrice = parseFloat(product.p_c);

const fromClass = useFrom ? "from-included" : "";
const compareClass = comparePrice ? "compare-included" : "";

const HTML = `<a class="isp-product-add-to-cart" href="${product.u}">
<div class="isp-product-price-wrapper">
<span class="price-container actual ${fromClass} ${compareClass}">$${price.toFixed(2)}</span>
<span class="price-container compare">${comparePrice ? "$" + comparePrice.toFixed(2) : ""}</span></div>
<span class="atc-break"/>
<div class="add-to-cart-text">${text}</div>
</a>`;

if ($gridItem.find(".isp_add_to_cart_form").length === 0) {
$gridItem.find(".isp_product_info").after(HTML);
} else {
$gridItem.find(".isp_add_to_cart_form").replaceWith(HTML);
}
},

addToCartAjax: (product, product_position) => {
if (product.vra.length > 2) {
QuickView.create(product);
return;
}

document.body.style.cursor = "wait";

const data = {
id: getFirstVariantID(product),
};

try {
localStorage.setItem("isp_add_to_cart_serp_product_id", product.id);
ispStoreProductPosition(product.id);
} catch (e) {}
$.ajax({
type: "POST",
url: "/cart/add.js",
data,
dataType: "json",
cache: false,
product_id: product.id,
form_id: `form_${product.id}`,
is_quick_view: false,
})
.done(function (data) {
onAddToCartFinish(this.product_id, false);
})
.fail(function (jqXHR, textStatus) {
console.log("error jqXHR: " + jqXHR + " | textStatus: " + textStatus);
})
.always(function () {
$jquery_isp("#" + this.form_id).removeClass("isp_add_to_cart_disable");
});
},

};

</script>
</code>```

Body:
This is the widget code:

This is the script for add to cart. I tried to add the script separately or tried to add to cart.liquid but that didn't work as well.

I just tried to merge the two at the script but ofcourse it didn't work...
I tried to remove the script from the original widget and then added the src as css format but that didn't work as well.
I am a total beginner at this so I am guessing I am missing to add the url somewhere else as well but not sure where...
What would be the best way to do this?


问:
How do you use a class that was generated by an annotation processor? It says package does not exist
I have the world's simplest annotation processor:

@SupportedAnnotationTypes("deoplice.processor.MyAnnotation")
public class MySimpleProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        String src = "package foo.bar;\n\n" +
                "public class MyPojo {\n" +
                "\tpublic MyPojo() {}\n" +
                "}";

        HashSet<? extends Element> annotatedHandlers = HashSet.ofAll(roundEnv.getElementsAnnotatedWith(MyAnnotation.class));
        try {
            FileObject fileObj = processingEnv.getFiler().getResource(StandardLocation.SOURCE_OUTPUT, "", "MyPojo.java");
            File extensionsFile = new File(fileObj.toUri());
            FileOutputStream s = new FileOutputStream(extensionsFile);
            BufferedOutputStream ss = new BufferedOutputStream(s);
            ss.write(src.getBytes(StandardCharsets.UTF_8));
            ss.close();
            s.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;
    }
}
```
<p>When run, it spits out a class called <code>MyPojo.java</code> into the build directory. It's as plain as can be:</p>
<pre class="lang-java prettyprint-override"><code>package foo.bar;
public class MyPojo {
    public MyPojo() {}
}
</code>```

I have a simple main method:

package example;

public class Main {
    public static void main(String... args) {
        System.out.println("Hello world!");
    }
}
```
<p>When I run <code>main</code>, the annotation processor, <code>MySimpleProcessor</code>, does its work and generates the file. It gets stored in the default Gradle build directory. Here's what everything looks like:</p>
```├── lib
│   ...
|   └── build/generated/sources/annotationProcessor/java/main
|        └── MyPojo.java  <- generated File
│   └── src/main/java/example
│         └── Main.java
│   └── build.gradle.kts
├── processor
│   ...
│   └── src/main/java/
|   └── MySimpleProcessor.java
│   └── build.gradle.kts
└── settings.gradle.kts
```
<h3>If I try to use the generated file, I get a compile error: package not found</h3>
<pre class="lang-java prettyprint-override"><code>package example;

public class Main {
    public static void main(String... args) {
        new foo.bar.MyPojo(); // Trying to instantiate the object
        System.out.println("Hello world!");
    }
}
</code>```

Error:

```<code>error: package foo.bar does not exist
        new foo.bar.MyPojo();
                   ^
</code>```

How do you use a class generated by an annotation processor?

I've tried adding my build dir to the source sets, but it has no effect.

sourceSets {
    main {
        java {
            srcDir("path\\to\\my\\build\\generated\\sources\\annotationProcessor\\java\\main")

        }
    }
}
```

What in the world am I missing here?

Body:
I have the world's simplest annotation processor:

@SupportedAnnotationTypes("deoplice.processor.MyAnnotation")
public class MySimpleProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        String src = "package foo.bar;\n\n" +
                "public class MyPojo {\n" +
                "\tpublic MyPojo() {}\n" +
                "}";

        HashSet<? extends Element> annotatedHandlers = HashSet.ofAll(roundEnv.getElementsAnnotatedWith(MyAnnotation.class));
        try {
            FileObject fileObj = processingEnv.getFiler().getResource(StandardLocation.SOURCE_OUTPUT, "", "MyPojo.java");
            File extensionsFile = new File(fileObj.toUri());
            FileOutputStream s = new FileOutputStream(extensionsFile);
            BufferedOutputStream ss = new BufferedOutputStream(s);
            ss.write(src.getBytes(StandardCharsets.UTF_8));
            ss.close();
            s.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;
    }
}

When run, it spits out a class called MyPojo.java into the build directory. It's as plain as can be:

package foo.bar;
public class MyPojo {
    public MyPojo() {}
}

I have a simple main method:

package example;

public class Main {
    public static void main(String... args) {
        System.out.println("Hello world!");
    }
}

When I run main, the annotation processor, MySimpleProcessor, does its work and generates the file. It gets stored in the default Gradle build directory. Here's what everything looks like:

├── lib
│   ...
|   └── build/generated/sources/annotationProcessor/java/main
|        └── MyPojo.java  <- generated File
│   └── src/main/java/example
│         └── Main.java
│   └── build.gradle.kts
├── processor
│   ...
│   └── src/main/java/
|   └── MySimpleProcessor.java
│   └── build.gradle.kts
└── settings.gradle.kts

If I try to use the generated file, I get a compile error: package not found

package example;

public class Main {
    public static void main(String... args) {
        new foo.bar.MyPojo(); // Trying to instantiate the object
        System.out.println("Hello world!");
    }
}

Error:

error: package foo.bar does not exist
        new foo.bar.MyPojo();
                   ^

How do you use a class generated by an annotation processor?

I've tried adding my build dir to the source sets, but it has no effect.

sourceSets {
    main {
        java {
            srcDir("path\\to\\my\\build\\generated\\sources\\annotationProcessor\\java\\main")

        }
    }
}

What in the world am I missing here?


问:
Output tiered pricing model dynamically
I have created a tiered per-seat pricing model in Stripe and I'm wanting to dynamically populate this. For example if we have 45 seats the output should look like this according to the model:

20 seats * £25 = 500

20 seats * £20 = 400

5 seats * £10 = 50

Tiered pricing model:

This is the current code

tier.UpTo represents the last unit in the current iteration i.e.

at idx 0: 20

at idx 1: 40

at idx 2: 50

```<code>var seats = 45;
var tieredPricing = new List<TierPricingViewModel>();
var idx = 0;
foreach (var tier in tieredPricingModel)
{
    int qty;

    if (idx == 0)
    {
        qty = (int) (seats <= (tier.UpTo ?? 0) ? seats : tier.UpTo ?? 0);
    }
    else if (idx == tieredPricingModel.Count - 1)
    {
        qty = (int) (tieredPricingModel[idx - 1].UpTo ?? 0 - seats);
    }
    else
    {
        var prevStartingTier = tieredPricingModel[idx - 1].UpTo + 1;
        qty = (int) (seats- prevStartingTier ?? 0);
    }

    if (qty > seats)
        break;

    if (qty > 0 && tier.UnitAmount.HasValue)
    {
        total += (tier.UnitAmount.Value / 100) * qty;
    }

    var unitAmount = tier.UnitAmount / 100 ?? 0;
    var totalAmount = tier.UnitAmount.HasValue ? tier.UnitAmount.Value / 100 * qty : 0;

    tieredPricing.Add(new TierPricingViewModel
    {
        Quantity = qty,
        UnitAmount = $"{unitAmount:C}",
        TotalAmount = $"{totalAmount:C}",
    });

    idx++;
}
</code>```

Model

```<code>public class TierPricingViewModel
{
    public int Quantity { get; set; }
    public string UnitAmount { get; set; }
    public string TotalAmount { get; set; }
}
</code>```

The code is giving the wrong quantity (aka seat) output:

20

24

4

It should be outputting

20

20

5

Thanks anyone!

Title: Output tiered pricing model dynamically

Body:
I have created a tiered per-seat pricing model in Stripe and I'm wanting to dynamically populate this. For example if we have 45 seats the output should look like this according to the model:

20 seats * £25 = 500

20 seats * £20 = 400

5 seats * £10 = 50

Tiered pricing model:

This is the current code

tier.UpTo represents the last unit in the current iteration i.e.

at idx 0: 20

at idx 1: 40

at idx 2: 50

var seats = 45;
var tieredPricing = new List<TierPricingViewModel>();
var idx = 0;
foreach (var tier in tieredPricingModel)
{
    int qty;

    if (idx == 0)
    {
        qty = (int) (seats <= (tier.UpTo ?? 0) ? seats : tier.UpTo ?? 0);
    }
    else if (idx == tieredPricingModel.Count - 1)
    {
        qty = (int) (tieredPricingModel[idx - 1].UpTo ?? 0 - seats);
    }
    else
    {
        var prevStartingTier = tieredPricingModel[idx - 1].UpTo + 1;
        qty = (int) (seats- prevStartingTier ?? 0);
    }

    if (qty > seats)
        break;

    if (qty > 0 && tier.UnitAmount.HasValue)
    {
        total += (tier.UnitAmount.Value / 100) * qty;
    }

    var unitAmount = tier.UnitAmount / 100 ?? 0;
    var totalAmount = tier.UnitAmount.HasValue ? tier.UnitAmount.Value / 100 * qty : 0;

    tieredPricing.Add(new TierPricingViewModel
    {
        Quantity = qty,
        UnitAmount = $"{unitAmount:C}",
        TotalAmount = $"{totalAmount:C}",
    });

    idx++;
}

Model

public class TierPricingViewModel
{
    public int Quantity { get; set; }
    public string UnitAmount { get; set; }
    public string TotalAmount { get; set; }
}

The code is giving the wrong quantity (aka seat) output:

20

24

4

It should be outputting

20

20

5

Thanks anyone!


问:
Apply template string dynamically in JavaScript
I would like to apply a string as a template but dynamically.

I have a string, coming from a config file, with the same "format" as a template string.  For instance 'Hello, ${name}!'  And I'd like to evaluate it as a template string, but dynamically, controlling the values in scope.  Something like:

const input  = 'Hello, ${name}!';
const result = applyTemplate(input, {name: 'world'});
// result is 'Hello, world!'
```

Surprisingly, I have not found any way to achieve this.  Any idea?

Body:
I would like to apply a string as a template but dynamically.

I have a string, coming from a config file, with the same "format" as a template string.  For instance 'Hello, ${name}!'  And I'd like to evaluate it as a template string, but dynamically, controlling the values in scope.  Something like:

const input  = 'Hello, ${name}!';
const result = applyTemplate(input, {name: 'world'});
// result is 'Hello, world!'

Surprisingly, I have not found any way to achieve this.  Any idea?


问:
I need to show the order ID and the order total for largest order (order ID-dollar amount)?
The Database. I need to find the order ID and the largest order in terms of dollars using SQL. I attached the OM database. Using SQL I think I would need to use group by or order by but I just need to find the largest order.

select order_id from orders
Union
sum(unit_price) from items;

It resulted in an error. I wanted it to show the order id and the sum of the unit_price and get the largest unit price to get the largest order. I’m getting an error message saying query without GROUP BY and nonaggregated column.


问:
python install setup.py FileNotFoundError: No such file or directory: __init__.py
in my project, I downloaded the lib named m2crypto,

I want to install it by python ./libs/m2crypto/setup.py install

but I get error:

```<code>Traceback (most recent call last):
  File "/Users/markleo/Desktop/projects/test-proj/libs/m2crypto/setup.py", line 338, in <module>
    version=__get_version(),
  File "/Users/markleo/Desktop/projects/test-proj/libs/m2crypto/setup.py", line 319, in __get_version
    with open('src/M2Crypto/__init__.py') as init_file:
FileNotFoundError: [Errno 2] No such file or directory: 'src/M2Crypto/__init__.py'

</code>```

but i do have the __init__.py.

I also tried to add below content to libs/m2crypto/MANIFEST.in

```<code>recursive-include src/M2Crypto/__init__.py
</code>```

but still get this error when install setup.py.

Body:
in my project, I downloaded the lib named m2crypto,

I want to install it by python ./libs/m2crypto/setup.py install

but I get error:

Traceback (most recent call last):
  File "/Users/markleo/Desktop/projects/test-proj/libs/m2crypto/setup.py", line 338, in <module>
    version=__get_version(),
  File "/Users/markleo/Desktop/projects/test-proj/libs/m2crypto/setup.py", line 319, in __get_version
    with open('src/M2Crypto/__init__.py') as init_file:
FileNotFoundError: [Errno 2] No such file or directory: 'src/M2Crypto/__init__.py'

but i do have the __init__.py.

I also tried to add below content to libs/m2crypto/MANIFEST.in

recursive-include src/M2Crypto/__init__.py

but still get this error when install setup.py.


问:
Apache2 logs throwing server ip

LogFormat "%v:%p %a %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%a %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%a %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent

Do my server apache access logs show the request client IP as my server's IP? no proxy is included in my server I see same problem with mine but no clear answer found

Why apache access logs show request client IP as my server's IP?

I'm expecting to see the client IP , that's supposed to be, the mod_remoteip already enabled maybe wrong config

Title: Apache2 logs throwing server ip


问:
TypeError: parameter 'url' is missing a type annotation in callback 'play' + ffmpeg
I can't understand why Python interpreter doesn't like the fact that I use the url in the last line

```<code>@client.tree.command()
async def play(interaction: Interaction, url = str):
    global voice
    channel = interaction.user.voice.channel
    voice = get(client.voice_clients, Guild=interaction.guild)
    if voice and voice.is_connected():
        await voice.move_to(channel)
        await interaction.response.send_message(f"*1*")
    else:
        voice = await channel.connect()
        await interaction.response.send_message(f"*2*")
    voice.play(discord.FFmpegPCMAudio(executable="C:/ffmpeg/bin/ffmpeg.exe", source = url))

</code>```

By the way, ffmpeg also does not work.

Body:
I can't understand why Python interpreter doesn't like the fact that I use the url in the last line

@client.tree.command()
async def play(interaction: Interaction, url = str):
    global voice
    channel = interaction.user.voice.channel
    voice = get(client.voice_clients, Guild=interaction.guild)
    if voice and voice.is_connected():
        await voice.move_to(channel)
        await interaction.response.send_message(f"*1*")
    else:
        voice = await channel.connect()
        await interaction.response.send_message(f"*2*")
    voice.play(discord.FFmpegPCMAudio(executable="C:/ffmpeg/bin/ffmpeg.exe", source = url))

By the way, ffmpeg also does not work.


问:
Converting Aster L1T data radiance to surface reflectance in Google Earth Engine
I am working with ASTER images and I am trying to convert radiance values to reflectance. Currently, I converted DN values to radiance and I don't know what else to do. Also, I found a Landsat function, but I don't know if it works for this case. This is my code:

```<code>
var AOI = ee.Geometry.Polygon([
  [-75.01530862531565,9.762481145514606],[-74.58134866437815,9.762481145514606],
  [-74.58134866437815,10.27637106477599],[-75.01530862531565,10.27637106477599]]);

var dataset = ee.ImageCollection('ASTER/AST_L1T_003')
  .filter(ee.Filter.date('2000-01-01', '2020-10-30'))
  .filterBounds(AOI)
  .filterMetadata('CLOUDCOVER', 'less_than', 1)
  .filter(ee.Filter.and(
    ee.Filter.notNull(['GAIN_COEFFICIENT_B01']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B02']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B3N']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B04']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B05']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B06']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B07']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B08']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B09'])));

print(dataset)

    // red and NIR channel digital numbers to at sensor radiance
 function bands (img) {
        var gainB1 = 0.676;
        var gainB2= 0.708;
        var gainB3N = 0.862;
        var gainB4= 0.2174;
        var gainB5 = 0.0696;
        var gainB6= 0.0625;
        var gainB7 = 0.0597;
        var gainB8= 0.0417;
        var gainB9 = 0.0318;

        var rad_b1 = (img.select('B01').subtract(1)).multiply(gainB1);
        var rad_b2 = (img.select('B02').subtract(1)).multiply(gainB2);
        var rad_b3 = (img.select('B3N') .subtract(1)).multiply(gainB3N);
        var rad_b4 = (img.select('B04').subtract(1)).multiply(gainB4);
        var rad_b5 = (img.select('B05') .subtract(1)).multiply(gainB5);
        var rad_b6 = (img.select('B06').subtract(1)).multiply(gainB6);
        var rad_b7 = (img.select('B07').subtract(1)).multiply(gainB7);
        var rad_b8 = (img.select('B08').subtract(1)).multiply(gainB8);
        var rad_b9 = (img.select('B09').subtract(1)).multiply(gainB9);

        return (rad_b1).addBands(rad_b2).addBands(rad_b3).addBands(rad_b4)
                       .addBands(rad_b5).addBands(rad_b6).addBands(rad_b7)
                       .addBands(rad_b8).addBands(rad_b9);
    }

    // add all selected bands with radiance values

  var rad_bands =dataset.map(bands)
  print(rad_bands)

   function copyProps(index){
    var source = ee.Image(dataset.toList(dataset.size()).get(index))
    var dest = ee.Image(rad_bands.toList(rad_bands.size()).get(index))
    var image = ee.Image(dest.copyProperties(source))
    return image
}
var seq = ee.List.sequence(0, rad_bands.size().subtract(1))
print(seq)

var final_col = ee.ImageCollection(seq.map(copyProps))

</code>```

https://code.earthengine.google.com/5b2dfc9b609ba5738be49ae2915d3980

Body:
I am working with ASTER images and I am trying to convert radiance values to reflectance. Currently, I converted DN values to radiance and I don't know what else to do. Also, I found a Landsat function, but I don't know if it works for this case. This is my code:

var AOI = ee.Geometry.Polygon([
  [-75.01530862531565,9.762481145514606],[-74.58134866437815,9.762481145514606],
  [-74.58134866437815,10.27637106477599],[-75.01530862531565,10.27637106477599]]);

var dataset = ee.ImageCollection('ASTER/AST_L1T_003')
  .filter(ee.Filter.date('2000-01-01', '2020-10-30'))
  .filterBounds(AOI)
  .filterMetadata('CLOUDCOVER', 'less_than', 1)
  .filter(ee.Filter.and(
    ee.Filter.notNull(['GAIN_COEFFICIENT_B01']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B02']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B3N']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B04']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B05']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B06']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B07']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B08']),
    ee.Filter.notNull(['GAIN_COEFFICIENT_B09'])));

print(dataset)

    // red and NIR channel digital numbers to at sensor radiance
 function bands (img) {
        var gainB1 = 0.676;
        var gainB2= 0.708;
        var gainB3N = 0.862;
        var gainB4= 0.2174;
        var gainB5 = 0.0696;
        var gainB6= 0.0625;
        var gainB7 = 0.0597;
        var gainB8= 0.0417;
        var gainB9 = 0.0318;

        var rad_b1 = (img.select('B01').subtract(1)).multiply(gainB1);
        var rad_b2 = (img.select('B02').subtract(1)).multiply(gainB2);
        var rad_b3 = (img.select('B3N') .subtract(1)).multiply(gainB3N);
        var rad_b4 = (img.select('B04').subtract(1)).multiply(gainB4);
        var rad_b5 = (img.select('B05') .subtract(1)).multiply(gainB5);
        var rad_b6 = (img.select('B06').subtract(1)).multiply(gainB6);
        var rad_b7 = (img.select('B07').subtract(1)).multiply(gainB7);
        var rad_b8 = (img.select('B08').subtract(1)).multiply(gainB8);
        var rad_b9 = (img.select('B09').subtract(1)).multiply(gainB9);

        return (rad_b1).addBands(rad_b2).addBands(rad_b3).addBands(rad_b4)
                       .addBands(rad_b5).addBands(rad_b6).addBands(rad_b7)
                       .addBands(rad_b8).addBands(rad_b9);
    }

    // add all selected bands with radiance values

  var rad_bands =dataset.map(bands)
  print(rad_bands)

   function copyProps(index){
    var source = ee.Image(dataset.toList(dataset.size()).get(index))
    var dest = ee.Image(rad_bands.toList(rad_bands.size()).get(index))
    var image = ee.Image(dest.copyProperties(source))
    return image
}
var seq = ee.List.sequence(0, rad_bands.size().subtract(1))
print(seq)

var final_col = ee.ImageCollection(seq.map(copyProps))

https://code.earthengine.google.com/5b2dfc9b609ba5738be49ae2915d3980


问:
Failed to integrate the form into the code
I can't get it to work I'm new to this :(
Failed to integrate the form into the code

I don't understand where is my mistake

```<code>Fecha1: <input id="minutos" type="time" value="00:00" onchange="minsToAdd()"><br>
</code>```

`

```<code>Date.prototype.addMins = function(minsToAdd) {
  this.setTime(this.getTime() + (minsToAdd * 60 * 1000));
  return this;
}

Date.prototype.getHHMMFormat = function() {
  const formatter = new Intl.DateTimeFormat('es-ES', {
   hour: 'numeric',
    minute: 'numeric',
    second: 'numeric',
     timeZoneName: 'long'
  });
  return formatter.format(this.getTime());
}

let d = new Date();
let minutos = 1;
d.addMins(minutos);
console.log('El bloque finaliza a las: ', d.getHHMMFormat());
//w
document.getElementById("result").innerHTML = d.getHHMMFormat()
</code>```

`

Body:
I can't get it to work I'm new to this :(
Failed to integrate the form into the code

I don't understand where is my mistake

Fecha1: <input id="minutos" type="time" value="00:00" onchange="minsToAdd()">

`

Date.prototype.addMins = function(minsToAdd) {
  this.setTime(this.getTime() + (minsToAdd * 60 * 1000));
  return this;
}

Date.prototype.getHHMMFormat = function() {
  const formatter = new Intl.DateTimeFormat('es-ES', {
   hour: 'numeric',
    minute: 'numeric',
    second: 'numeric',
     timeZoneName: 'long'
  });
  return formatter.format(this.getTime());
}

let d = new Date();
let minutos = 1;
d.addMins(minutos);
console.log('El bloque finaliza a las: ', d.getHHMMFormat());
//w
document.getElementById("result").innerHTML = d.getHHMMFormat()

`


问:
typescript await in getter
I have html file where im calling get method getDate. Im trying to retrive data from database and add value to return statment. I having issue that im retriving return 'date' without start value. I added logs and it will print first 'outside' and then 'inside' thats the reason why its only returning 'date' without start. Is there any way how can I retrive full return statment after data are retrived from database?

Html code:

```<code><template v-slot:no-data>
 <div v-on="scope.on"  style="cursor: pointer;text-decoration:underline>{{getDate}}</div>
</template>
</code>```

Typescript code:

```<code>public get getDate()
{
  Service.getData(id)
    .then((response) => {
      console.log('inside');
    start = response[0].start;
    end = response[0].end;
  });
  console.log('outside');
  return 'date ' + start;
}
</code>```

Title: typescript await in getter

Body:
I have html file where im calling get method getDate. Im trying to retrive data from database and add value to return statment. I having issue that im retriving return 'date' without start value. I added logs and it will print first 'outside' and then 'inside' thats the reason why its only returning 'date' without start. Is there any way how can I retrive full return statment after data are retrived from database?

Html code:

<template v-slot:no-data>

{{getDate}}

</template>

Typescript code:

public get getDate()
{
  Service.getData(id)
    .then((response) => {
      console.log('inside');
    start = response[0].start;
    end = response[0].end;
  });
  console.log('outside');
  return 'date ' + start;
}


问:
How to target a cell and follow it using css, like google maps recenter
I'm attempting to track a specific cell, such as the one now selected, as seen in this video, which has a background color of red that moves.

https://drive.google.com/file/d/1pbaUMSE6RmPUTHDiflpMVQEg7HBmZ3ce/view?usp=drivesdk

My goal is to show something similar to this, where it zooms in on the presently selected cell and shrinks the window, similar to the Google Maps recenter button.

I'm using React BTW.