问:
React Navigation 5 header overlap
I am creating an application in React Native, I am using React Navigation 5.x and I have replaced the default header with one created by me, this is part of code:

App.js

```<code>    <NavigationContainer>
      <Drawer.Navigator initialRouteName="Home" drawerContent={SideMenu} drawerStyle={{
    backgroundColor: '#fff',
    width: Dimensions.get('window').width - 120,
  }}>
        <Drawer.Screen name="Home" component={StackNav} />
      </Drawer.Navigator>
    </NavigationContainer>
</code>```

StackNav.js

```<code>    <Stack.Navigator   headerMode="float" screenOptions={{
      cardShadowEnabled: false,
      cardOverlayEnabled:false,
      headerTransparent: true,
      headerBackTitleVisible: false,
      gestureEnabled: true,
      headerTintColor: currentTheme.colors.primary,
      headerTitleStyle: styles.headerTitle,
      gestureDirection:"horizontal",
      headerStyleInterpolator: HeaderStyleInterpolators.forStatic,
      cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        header: ({ scene, previous, navigation }) => {
        const { options } = scene.descriptor;
        const title =
          options.headerTitle !== undefined
            ? options.headerTitle
            : options.title !== undefined
            ? options.title
            : scene.route.name;

        return (
            <MyHeader click={() => addCart()} ref={myRef} scene={scene} onPress={navigation.goBack} navigation={navigation}/>
        );
      }
      }}>
        <Stack.Screen name="Home" component={Home} options={{title: 'Home'}}/>
        <Stack.Screen name="Menu" component={RestaurantMenu} options={({ route }) => ({ title: route.params.name })}/>
        <Stack.Screen name="Piatti" component={MenuItems} options={({ route }) => ({ title: route.params.name })}/>
        <Stack.Screen name="Carrello" component={Cart} options={({ route }) => ({ title: route.params.name })}/>
      </Stack.Navigator>
</code>```

MyHeader.js

```<code>import * as React from 'react';
import { StyleSheet, Button, SafeAreaView, TouchableOpacity, Image,View, Text } from 'react-native';

const styles = StyleSheet.create({
    containerSafe: {
        flex: 1,
        flexDirection:"row",
        justifyContent: "space-between"
      },
      containerLeft: {
        zIndex: 1,
        alignSelf: 'flex-start',
        left: 0,
        marginTop:25,
        marginLeft:10,
        width: 25,
        height: 25,
        justifyContent: 'center',
        alignContent: 'center'
      },
      containerCenter: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
      },
      containerRight: {
        zIndex: 1,
        alignSelf: 'flex-end',
        right: 0,
        marginTop:25,
        marginRight:10,
        width: 25,
        height: 25,
        justifyContent: 'center',
        alignContent: 'center'
      }
  });

class CartButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
        return (
            <TouchableOpacity onPress={() => this.props.onPress()}  style={styles.containerRight}>
            <Image style={{width:"100%", height:"100%"}}
                source={require('../assets/cart.png')}
            />
            <Text>{this.props.nCart}</Text>
        </TouchableOpacity>
        )
    }
}

class HomeButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
        return (
            <TouchableOpacity onPress={() => this.props.onPress()} style={styles.containerLeft}>
                <Image style={{width:"100%", height:"100%"}}
                    source={require('../assets/menu.png')}
                />
            </TouchableOpacity>
        )
    }
}

class BackButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
        return (
            <TouchableOpacity onPress={() => this.props.onPress()} style={styles.containerLeft}>
                <Image style={{width:"100%", height:"100%"}}
                    source={require('../assets/leftArrow.png')}
                />
            </TouchableOpacity>
        )
    }
}

  class MyHeader extends React.Component {
    constructor(props) {
        super(props);
        this.state= {
            nCart: 0
        }
        this.addCart = this.addCart.bind(this);
    }

    addCart(){
        var current = this.state.nCart;
        this.setState({
            nCart: current +1
        })
    }

    render(){
        return(
            <SafeAreaView style={styles.containerSafe}>
                {(this.props.scene.route.name === "Home")? <HomeButton onPress={() =>this.props.navigation.openDrawer()} /> : <BackButton onPress={() => this.props.navigation.goBack()} />}
                <Button title="click" onPress={(() => this.props.click())} />
                <CartButton nCart={this.state.nCart} onPress={() => this.props.navigation.navigate('Carrello', {name: 'Carrello'})} />
            </SafeAreaView>
        )
    }
}

export default MyHeader;
</code>```

but it gives me this problem

The Back button and the Cart button overlap when I change the screen, but the burger menu should disappear and become the arrow of the back button while the cart should simply update in the counter as it does in the home.

答:
https://reactnavigation.org/docs/en/stack-navigator.html#header

When using a custom header, it's recommended set the headerMode prop on the navigator to screen so that you don't have to implement animations.

If you want your custom header to animate with screen transitions and want to keep headerMode as float, you can interpolate on the scene.progress.current and scene.progress.next props.

Title: React Navigation 5 header overlap

Body:
I am creating an application in React Native, I am using React Navigation 5.x and I have replaced the default header with one created by me, this is part of code:

App.js

    <NavigationContainer>
      <Drawer.Navigator initialRouteName="Home" drawerContent={SideMenu} drawerStyle={{
    backgroundColor: '#fff',
    width: Dimensions.get('window').width - 120,
  }}>
        <Drawer.Screen name="Home" component={StackNav} />
      </Drawer.Navigator>
    </NavigationContainer>

StackNav.js

    <Stack.Navigator   headerMode="float" screenOptions={{
      cardShadowEnabled: false,
      cardOverlayEnabled:false,
      headerTransparent: true,
      headerBackTitleVisible: false,
      gestureEnabled: true,
      headerTintColor: currentTheme.colors.primary,
      headerTitleStyle: styles.headerTitle,
      gestureDirection:"horizontal",
      headerStyleInterpolator: HeaderStyleInterpolators.forStatic,
      cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        header: ({ scene, previous, navigation }) => {
        const { options } = scene.descriptor;
        const title =
          options.headerTitle !== undefined
            ? options.headerTitle
            : options.title !== undefined
            ? options.title
            : scene.route.name;

        return (
            <MyHeader click={() => addCart()} ref={myRef} scene={scene} onPress={navigation.goBack} navigation={navigation}/>
        );
      }
      }}>
        <Stack.Screen name="Home" component={Home} options={{title: 'Home'}}/>
        <Stack.Screen name="Menu" component={RestaurantMenu} options={({ route }) => ({ title: route.params.name })}/>
        <Stack.Screen name="Piatti" component={MenuItems} options={({ route }) => ({ title: route.params.name })}/>
        <Stack.Screen name="Carrello" component={Cart} options={({ route }) => ({ title: route.params.name })}/>
      </Stack.Navigator>

MyHeader.js

import * as React from 'react';
import { StyleSheet, Button, SafeAreaView, TouchableOpacity, Image,View, Text } from 'react-native';

const styles = StyleSheet.create({
    containerSafe: {
        flex: 1,
        flexDirection:"row",
        justifyContent: "space-between"
      },
      containerLeft: {
        zIndex: 1,
        alignSelf: 'flex-start',
        left: 0,
        marginTop:25,
        marginLeft:10,
        width: 25,
        height: 25,
        justifyContent: 'center',
        alignContent: 'center'
      },
      containerCenter: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
      },
      containerRight: {
        zIndex: 1,
        alignSelf: 'flex-end',
        right: 0,
        marginTop:25,
        marginRight:10,
        width: 25,
        height: 25,
        justifyContent: 'center',
        alignContent: 'center'
      }
  });

class CartButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
        return (
            <TouchableOpacity onPress={() => this.props.onPress()}  style={styles.containerRight}>
            <Image style={{width:"100%", height:"100%"}}
                source={require('../assets/cart.png')}
            />
            <Text>{this.props.nCart}</Text>
        </TouchableOpacity>
        )
    }
}

class HomeButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
        return (
            <TouchableOpacity onPress={() => this.props.onPress()} style={styles.containerLeft}>
                <Image style={{width:"100%", height:"100%"}}
                    source={require('../assets/menu.png')}
                />
            </TouchableOpacity>
        )
    }
}

class BackButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render(){
        return (
            <TouchableOpacity onPress={() => this.props.onPress()} style={styles.containerLeft}>
                <Image style={{width:"100%", height:"100%"}}
                    source={require('../assets/leftArrow.png')}
                />
            </TouchableOpacity>
        )
    }
}

  class MyHeader extends React.Component {
    constructor(props) {
        super(props);
        this.state= {
            nCart: 0
        }
        this.addCart = this.addCart.bind(this);
    }

    addCart(){
        var current = this.state.nCart;
        this.setState({
            nCart: current +1
        })
    }

    render(){
        return(
            <SafeAreaView style={styles.containerSafe}>
                {(this.props.scene.route.name === "Home")? <HomeButton onPress={() =>this.props.navigation.openDrawer()} /> : <BackButton onPress={() => this.props.navigation.goBack()} />}
                <Button title="click" onPress={(() => this.props.click())} />
                <CartButton nCart={this.state.nCart} onPress={() => this.props.navigation.navigate('Carrello', {name: 'Carrello'})} />
            </SafeAreaView>
        )
    }
}

export default MyHeader;

but it gives me this problem

The Back button and the Cart button overlap when I change the screen, but the burger menu should disappear and become the arrow of the back button while the cart should simply update in the counter as it does in the home.


来源: stackexchange

问:
Concatenation in Haskell and confusion with AList ([a] -> [a])
I have a project where we are improving the speed of concatenating a list in Haskell.
I'm new to Haskell and confused about  AList ([a] -> [a]) Specifically how to convert my AppendedList to a regular List. Any help would be appreciated.

```<code>newtype AppendedList a = AList ([a] -> [a])

-- List[5] is represented as AList (\x -> 5:x)
-- This function takes an argument and returns the AppendedList for that
single :: a -> AppendedList a
single m = AList (\x -> m : x)

-- converts AppendedList to regular List
toList :: AppendedList a -> [a]
toList = ???
</code>```

答:
The toughest part is to not give you the answer directly :)

If you remember how lists are constructed in Haskell: [1, 2, 3] = 1 : 2 : 3 : [], with [] being the empty list.

Now let's "follow the types" (we also call this thought process TDD for Type Driven Development) and see what you have at hand:

toList :: AppendedList a -> [a]
toList (AList listFunction) = ???
```

and listFunction has the type [a] -> [a]. So you need to provide it a polymorphic list (i.e. a list of any type) so that it gives you back a list.

What is the only list of any type you know of? Pass this list to listFunction and everything will compile, which is a good indicator that it's probably right :D

I hope that helps without providing the plain answer (the goal is for you to learn!).

ContentLicense: CC BY-SA 4.0

Body:
I have a project where we are improving the speed of concatenating a list in Haskell.
I'm new to Haskell and confused about  AList ([a] -> [a]) Specifically how to convert my AppendedList to a regular List. Any help would be appreciated.

newtype AppendedList a = AList ([a] -> [a])

-- List[5] is represented as AList (\x -> 5:x)
-- This function takes an argument and returns the AppendedList for that
single :: a -> AppendedList a
single m = AList (\x -> m : x)

-- converts AppendedList to regular List
toList :: AppendedList a -> [a]
toList = ???

Body:
The toughest part is to not give you the answer directly :)

If you remember how lists are constructed in Haskell: [1, 2, 3] = 1 : 2 : 3 : [], with [] being the empty list.

Now let's "follow the types" (we also call this thought process TDD for Type Driven Development) and see what you have at hand:

toList :: AppendedList a -> [a]
toList (AList listFunction) = ???

and listFunction has the type [a] -> [a]. So you need to provide it a polymorphic list (i.e. a list of any type) so that it gives you back a list.

What is the only list of any type you know of? Pass this list to listFunction and everything will compile, which is a good indicator that it's probably right :D

I hope that helps without providing the plain answer (the goal is for you to learn!).


问:
How to structure angular project with one level url?
Working on the website with several sections: post arranged by categories, video gallery, etc..
I need to have one level url (domain.com/page-address). I can get information of which view does this page-address has to load on the front side, However I could not organize angular project well.

I managed to make everything work but via components only, in single module and single router-outlet, by sending all routes to single component.
routes: Routes = [{apth:  '**', , component: MainComponent }]
and the component decides which component should be loaded.

```<code>/// viewType is retrieved from backend
<app-articles *ngIf="viewType == 'article_categories' || viewType == 'articles'" [viewType]='viewType'></app-articles>
<app-videos *ngIf="viewType == 'video_categories' || viewType == 'video_page'" [viewType]='viewType'></app-videos>
<app-page-not-found *ngIf="viewType == 'page-not-found'" ></app-page-not-found>
</code>```

It seems really bad solution to me, as I can't use RouterLink and each click reloads whole website.

Also tried to make nested RouterOutlets, but could not make it work.

Do you have a solution for it?

Thank you

答:
If I understand your problem correctly, I believe that one solution is to use Express Router on the the back-end to handle your routing. Explaining Express is out of the scope of a Stack Overflow answer but there is an abundance of tutorials on YouTube. I suggest the 'MEAN Stack Front-to-Back' series by Traversy Media. Its old, so parts of it require workarounds, but his workflow for setting up the router is the one I use with Angular to this day.

Your AppModule will contain:

```<code>routes: Routes = [
           {path:  '/pathA', , component: ComponentA },
           {path:  '/pathB', , component: ComponentB },
           {path:  '/pathC', , component: ComponentC, canActivate:[AuthGuard] },
]
</code>```

but the actual routing will be handled via Express Router the back-end.

There are a lot of router packages for Node; Express is just the one that I use.

Body:
Working on the website with several sections: post arranged by categories, video gallery, etc..
I need to have one level url (domain.com/page-address). I can get information of which view does this page-address has to load on the front side, However I could not organize angular project well.

I managed to make everything work but via components only, in single module and single router-outlet, by sending all routes to single component.
routes: Routes = [{apth:  '**', , component: MainComponent }]
and the component decides which component should be loaded.

/// viewType is retrieved from backend
<app-articles *ngIf="viewType == 'article_categories' || viewType == 'articles'" [viewType]='viewType'></app-articles>
<app-videos *ngIf="viewType == 'video_categories' || viewType == 'video_page'" [viewType]='viewType'></app-videos>
<app-page-not-found *ngIf="viewType == 'page-not-found'" ></app-page-not-found>

It seems really bad solution to me, as I can't use RouterLink and each click reloads whole website.

Also tried to make nested RouterOutlets, but could not make it work.

Do you have a solution for it?

Thank you

Body:
If I understand your problem correctly, I believe that one solution is to use Express Router on the the back-end to handle your routing. Explaining Express is out of the scope of a Stack Overflow answer but there is an abundance of tutorials on YouTube. I suggest the 'MEAN Stack Front-to-Back' series by Traversy Media. Its old, so parts of it require workarounds, but his workflow for setting up the router is the one I use with Angular to this day.

Your AppModule will contain:

routes: Routes = [
           {path:  '/pathA', , component: ComponentA },
           {path:  '/pathB', , component: ComponentB },
           {path:  '/pathC', , component: ComponentC, canActivate:[AuthGuard] },
]

but the actual routing will be handled via Express Router the back-end.

There are a lot of router packages for Node; Express is just the one that I use.


问:
php how to add php code in the twitter callback url?
I am trying to start a new app on dev.twitter.com, and in the callback URL I want to pass a link like: www.text.com?number=<?= $var?> but it won't let me.

Any ideas? Thanks.

Edit: my link will eventually look like this: www.text.com?number=123456

But it will depend on who is logged in, so the number could be any 6 numbers, so I'm thinking the callback URL has to have that var inside it.

答: You have to pass the complete URL in an oauth_callback parameter when you get a request_token from Twitter. The specifics are detailed in the authentication documentation. For example you would have something like oauth_callback=http://example.com/callback.php?number=123456 and with the request token will be an attribute of oauth_callback_confirmed set to a value of true so you know that Twitter will honor the custom callback URL.

ContentLicense: CC BY-SA 3.0


问:
Video recording with OpenVidu and electron
I have to be able to record an incoming video call into a file. The recording must be done on the desktop application, built with electron. I'm using OpenVidu as a streaming platform. Is there any way to do that?</p>

答:
@Vasniktel Technically it could be possible to record the video client side as there are a number of WebRTC examples that record locally on the client, however this is not natvie to openvidu. However recording on electronjs is...

github.com/hokein/electron-screen-recorder

tutorialspoint.com/electron/… You could integrate recording separately along side your openvidu app.

The main difference here is that you want to record an incoming call and while you likely won't be able to just write the incoming webrtc data you should be able to record the area of the app (canvas) where the video player is rendered.  You will be re-encoding the decoded rendered video stream, but it shouldn't be too much of a hit performance wise.


问:
XPath optimization to select a node if it does not have an ancestor
In very simple terms, I would like to write an XPath 1.0 query that selects 10 but not 15.  15 should not be selected since it has an ancestor ArgumentList.

Here is the XML.

```<code><IfStatement>
   <Expression>
      ...
         <PrimaryExpression>
            <PrimaryPrefix>
               <Literal Image="10"/>
            </PrimaryPrefix>
            <PrimarySuffix>
               <Arguments>
                  <ArgumentList>
                     <Expression>
                        ...
                           <PrimaryExpression>
                              <PrimaryPrefix>
                                 <Literal Image="15"/>
                              </PrimaryPrefix>
                           </PrimaryExpression>
                        ...
                     </Expression>
                  </ArgumentList>
               </Arguments>
            </PrimarySuffix>
         </PrimaryExpression>
      ...
   </Expression>
</IfStatement>
</code>```

Here is the XPath query I am using...

```<code>(//IfStatement | //ForStatement | //WhileStatement)
/Expression
//*
/PrimaryExpression
/PrimaryPrefix
/Literal[not(ancestor::ArgumentList)]
</code>```

The //* is required because of the unknown number of nodes in the hierarchy represented by the ... in the XML.

The problem is that ancestor::ArgumentList is a slow operation.  I would like to write the XPath query like the following.

```<code>(//IfStatement | //ForStatement | //WhileStatement)
/Expression
//*[not(self::ArgumentList)]
/PrimaryExpression
/PrimaryPrefix
/Literal
</code>```

The problem is that //*[not(self::ArgumentList)] does not prevent from selecting 15.

What do I put after //* to prevent from selecting 15 due to ArgumentList?

答:
This XPath,

```<code>//Literal[not(ancestor::ArgumentList)]
</code>```

will select Literal elements that do not have an ArgumentList ancestor,

```<code><Literal Image="10"/>
</code>```

but not

```<code><Literal Image="15"/>
</code>```

as requested.

Body:
In very simple terms, I would like to write an XPath 1.0 query that selects 10 but not 15.  15 should not be selected since it has an ancestor ArgumentList.

Here is the XML.

<IfStatement>
   <Expression>
      ...
         <PrimaryExpression>
            <PrimaryPrefix>
               <Literal Image="10"/>
            </PrimaryPrefix>
            <PrimarySuffix>
               <Arguments>
                  <ArgumentList>
                     <Expression>
                        ...
                           <PrimaryExpression>
                              <PrimaryPrefix>
                                 <Literal Image="15"/>
                              </PrimaryPrefix>
                           </PrimaryExpression>
                        ...
                     </Expression>
                  </ArgumentList>
               </Arguments>
            </PrimarySuffix>
         </PrimaryExpression>
      ...
   </Expression>
</IfStatement>

Here is the XPath query I am using...

(//IfStatement | //ForStatement | //WhileStatement)
/Expression
//*
/PrimaryExpression
/PrimaryPrefix
/Literal[not(ancestor::ArgumentList)]

The //* is required because of the unknown number of nodes in the hierarchy represented by the ... in the XML.

The problem is that ancestor::ArgumentList is a slow operation.  I would like to write the XPath query like the following.

(//IfStatement | //ForStatement | //WhileStatement)
/Expression
//*[not(self::ArgumentList)]
/PrimaryExpression
/PrimaryPrefix
/Literal

The problem is that //*[not(self::ArgumentList)] does not prevent from selecting 15.

What do I put after //* to prevent from selecting 15 due to ArgumentList?

Body:
This XPath,

//Literal[not(ancestor::ArgumentList)]

will select Literal elements that do not have an ArgumentList ancestor,

<Literal Image="10"/>

but not

<Literal Image="15"/>

as requested.


问:
Programmatically detect SQL Server Edition
I'm using C# with SMO and attempting to detect what edition of SQL Server (e.g., enterprise, standard) I'm connecting to.  I know how to get the version information, but that only tells me what version of SQL Server (e.g., SQL Server 2008 vs SQL Server 2005).

Does anyone know how to get the actual product edition (e.g., enterprise, standard)?

I need this information because some SQL Server features are only enterprise.  Thus, I could just try to call them and catch the exception, but I'd much prefer an upfront detection.

Thanks!

答:
```<code>SELECT  SERVERPROPERTY('productversion'),
        SERVERPROPERTY ('productlevel'),
        SERVERPROPERTY ('edition')
</code>```

on my system returns

```<code>9.00.1399.06, RTM, Express Edition
</code>```

It seems this technique only works on SQL Server 2000 or later, if any of your databases are 7.0 or less, you'll have to use @@Version and manipulate the results as others have posted

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

Body:
SELECT  SERVERPROPERTY('productversion'),
        SERVERPROPERTY ('productlevel'),
        SERVERPROPERTY ('edition')

on my system returns

9.00.1399.06, RTM, Express Edition

It seems this technique only works on SQL Server 2000 or later, if any of your databases are 7.0 or less, you'll have to use @@Version and manipulate the results as others have posted

OwnerDisplayName: Patrick McDonald


问:
Name a stage per build-arguments using a Dockerfile with multi-stage-builds
Is there a possibiliity to name a build-stage?
I am searching something like the following example:

```<code>ARG NAME

FROM python:3.7-alpine as modul-${NAME}
# ...
</code>```

If I try this example this error occurs:

```<code>Error response from daemon: Dockerfile parse error line 5: invalid name for build stage: "modul-${NAME}", name can't start with a number or contain symbols
</code>```

I also tryed to use the argument as tag (modul:${NAME}) with the same result.

答:
You can do this with BuildKit, which requires docker 18.09+. (https://docs.docker.com/develop/develop-images/build_enhancements/)

All you have to do is set an env variable before building:

DOCKER_BUILDKIT=1 docker build -t whatever .

I don't think it's possible without BuildKit.

Body:
Is there a possibiliity to name a build-stage?
I am searching something like the following example:

ARG NAME

FROM python:3.7-alpine as modul-${NAME}
# ...

If I try this example this error occurs:

Error response from daemon: Dockerfile parse error line 5: invalid name for build stage: "modul-${NAME}", name can't start with a number or contain symbols

I also tryed to use the argument as tag (modul:${NAME}) with the same result.


问:
No tests found for given includes Error, when running Parameterized Unit test in Android Studio
I have tried to run Parameterized Unit Tests in Android Studio, as shown below:

import android.test.suitebuilder.annotation.SmallTest;

import junit.framework.TestCase;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

import java.util.Arrays;
import java.util.Collection;

@RunWith(Parameterized.class)
@SmallTest
public class FibonacciTest extends TestCase {
    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
                {0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8}
        });
    }

    @Parameter // first data value (0) is default
    public /* NOT private */ int fInput;

    @Parameter(value = 1)
    public /* NOT private */ int fExpected;

    @Test
    public void test() {
        assertEquals(fExpected, Fibonacci.calculate(fInput));
    }
}
```
<p>The result is an error stating <code>No Test Run</code>. However, if I remove the Parameterized tests, and change them to individual tests, it works.</p>
<p>Can anyone shed some light on why this is not working? Ar Parameterized unit tests not supported in Android development yet?</p>
<p>Below is the error with stack trace:</p>
<pre class="lang-none prettyprint-override"><code>FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:testDebug'.
> No tests found for given includes: [com.example.......FibonacciTest]
* Try:
Run with --info or --debug option to get more log output.
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:testDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:310)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:54)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:49)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:66)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:71)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: org.gradle.api.GradleException: No tests found for given includes: [com.example........FibonacciTest]
    at org.gradle.api.internal.tasks.testing.NoMatchingTestsReporter.afterSuite(NoMatchingTestsReporter.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:87)
    at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:31)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy46.afterSuite(Unknown Source)
    at org.gradle.api.internal.tasks.testing.results.TestListenerAdapter.completed(TestListenerAdapter.java:48)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:87)
    at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:31)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy45.completed(Unknown Source)
    at org.gradle.api.internal.tasks.testing.results.StateTrackingTestResultProcessor.completed(StateTrackingTestResultProcessor.java:69)
    at org.gradle.api.internal.tasks.testing.results.AttachParentTestResultProcessor.completed(AttachParentTestResultProcessor.java:52)
    at org.gradle.api.internal.tasks.testing.processors.TestMainAction.run(TestMainAction.java:51)
    at org.gradle.api.internal.tasks.testing.detection.DefaultTestExecuter.execute(DefaultTestExecuter.java:75)
    at org.gradle.api.tasks.testing.Test.executeTests(Test.java:527)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:226)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:219)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:208)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:589)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:572)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    ... 57 more
BUILD FAILED
Total time: 4.153 secs
No tests found for given includes: [com.example......FibonacciTest]
</code>```

答:
I am using JUnit 4, and what worked for me is changing the IntelliJ settings for 'Gradle -> Run Tests Using' from 'Gradle (default)' to 'IntelliJ IDEA'.

Source of my fix: https://linked2ev.github.io/devsub/2019/09/30/Intellij-junit4-gradle-issue/

Body:
I have tried to run Parameterized Unit Tests in Android Studio, as shown below:

import android.test.suitebuilder.annotation.SmallTest;

import junit.framework.TestCase;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

import java.util.Arrays;
import java.util.Collection;

@RunWith(Parameterized.class)
@SmallTest
public class FibonacciTest extends TestCase {
    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
                {0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8}
        });
    }

    @Parameter // first data value (0) is default
    public /* NOT private */ int fInput;

    @Parameter(value = 1)
    public /* NOT private */ int fExpected;

    @Test
    public void test() {
        assertEquals(fExpected, Fibonacci.calculate(fInput));
    }
}

The result is an error stating No Test Run. However, if I remove the Parameterized tests, and change them to individual tests, it works.

Can anyone shed some light on why this is not working? Ar Parameterized unit tests not supported in Android development yet?

Below is the error with stack trace:

FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:testDebug'.
> No tests found for given includes: [com.example.......FibonacciTest]
* Try:
Run with --info or --debug option to get more log output.
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:testDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:310)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:54)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:49)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:66)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:71)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: org.gradle.api.GradleException: No tests found for given includes: [com.example........FibonacciTest]
    at org.gradle.api.internal.tasks.testing.NoMatchingTestsReporter.afterSuite(NoMatchingTestsReporter.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:87)
    at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:31)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy46.afterSuite(Unknown Source)
    at org.gradle.api.internal.tasks.testing.results.TestListenerAdapter.completed(TestListenerAdapter.java:48)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:87)
    at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:31)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy45.completed(Unknown Source)
    at org.gradle.api.internal.tasks.testing.results.StateTrackingTestResultProcessor.completed(StateTrackingTestResultProcessor.java:69)
    at org.gradle.api.internal.tasks.testing.results.AttachParentTestResultProcessor.completed(AttachParentTestResultProcessor.java:52)
    at org.gradle.api.internal.tasks.testing.processors.TestMainAction.run(TestMainAction.java:51)
    at org.gradle.api.internal.tasks.testing.detection.DefaultTestExecuter.execute(DefaultTestExecuter.java:75)
    at org.gradle.api.tasks.testing.Test.executeTests(Test.java:527)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:226)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:219)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:208)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:589)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:572)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    ... 57 more
BUILD FAILED
Total time: 4.153 secs
No tests found for given includes: [com.example......FibonacciTest]


问:
Kivy - TextInput on_focus behavior issue
I'm creating an app using kivy. So I don't think I'm understanding something correctly regarding the on_focus behavior of the FloatInput.

Let me first describe what I'm trying to do here. I'm trying to activate a pop-up numpad when the user clicks on a TextInput (this numpad just has buttons for numbers 0-9 and an "enter" button). Next, once the user provides a number in the pop-up numpad and hits an "enter" button, the pop-up should close and the text field of the TextInput should be updated to the user entered number.

However, I'm running into a problem. Essentially, I have a form with multiple TextInputs constructed as described above (I'll refer to them hereafter as "FloatInputs" b/c that's what I've named them). The first time I enter values into one of the FloatInputs, everything works as expected. But the problem occurs whenever I try to enter a number into a second FloatInput. Specifically, the on_focus function is called twice somehow and the user must enter the value into the pop-up twice as a result (this is obviously not ideal as it would serve to frustrate the user).

I apologize if this is a stupid question, but I've been puzzled by it for quite a while. I think the heart of the problem lies in the order of the focusing of the TextInput and the popup widgets, but I could be wrong here. If someone could please offer suggestions as to how I could fix this bug I'd greatly appreciate it.

Here is the relevant python code:

```<code>class FloatInput(TextInput):

    def on_focus(self, instance, value):

        print 'ON FOCUS CALLED - THIS SHOULD ONLY BE CALLED ONCE!'

        # Adding this helped part of the problem (however, on_focus is still being called twice???)
        self.unfocus_on_touch = False

        prompt_content = BoxLayout(orientation='vertical')      # Main layout

        num_pad = NumPadWidget()
        prompt_content.add_widget(num_pad)

        def my_callback(instance):

            self.text = num_pad.ids.num_label.text
            self.popup.dismiss()

        # Now define the popup, with the content being the layout:
        self.popup = Popup(id='num_pad_popup', title='Enter value', content=prompt_content, size_hint=(0.8,0.5), autodismiss=False)

        num_pad.ids.enter_btn.bind(on_press=my_callback)

        # Open the pop-up:
        self.popup.open()
</code>```

And here is the relevant kv code:

```<code><NumPadButton@Button>:
    font_size: '16dp'
    bold: True

<NumPadWidget>:
    BoxLayout:
        orientation: 'vertical'
        BoxLayout:
            size_hint_y: 1
            id: num_label
            Label:
                id: num_label
                text: ''
        BoxLayout:
            size_hint_y: 5
            orientation: 'vertical'
            BoxLayout:
                NumPadButton:
                    text: '7'
                    on_press:
                        num_label.text = num_label.text + '7'
                NumPadButton:
                    text: '8'
                    on_press:
                        num_label.text = num_label.text + '8'
                NumPadButton:
                    text: '9'
                    on_press:
                        num_label.text = num_label.text + '9'
            BoxLayout:
                NumPadButton:
                    text: '4'
                    on_press:
                        num_label.text = num_label.text + '4'
                NumPadButton:
                    text: '5'
                    on_press:
                        num_label.text = num_label.text + '5'
                NumPadButton:
                    text: '6'
                    on_press:
                        num_label.text = num_label.text + '6'
            BoxLayout:
                NumPadButton:
                    text: '1'
                    on_press:
                        num_label.text = num_label.text + '1'
                NumPadButton:
                    text: '2'
                    on_press:
                        num_label.text = num_label.text + '2'
                NumPadButton:
                    text: '3'
                    on_press:
                        num_label.text = num_label.text + '3'
            BoxLayout:
                NumPadButton:
                    text: '0'
                    on_press:
                        num_label.text = num_label.text + '0'
                NumPadButton:
                    text: '.'
                    on_press:
                        num_label.text = num_label.text + '.'
                NumPadButton:
                    text: 'del'
                    on_press:
                        num_label.text = num_label.text[:-1]
            BoxLayout:
                BoxLayout:
                    size_hint_x: 1
                    NumPadButton:
                        text: 'C'
                        on_press:
                            num_label.text = ''
                BoxLayout:
                    size_hint_x: 2
                    NumPadButton:
                        id: enter_btn
                        text: 'Enter'
</code>```

答:
For what it's worth, the on_focus() method of TextInput looks like this:

```<code>def on_focus(self, instance, value, *largs):
</code>```

If value is True, it's a focus event. If it's False, then it's a defocus/blur event. I really don't know why they used one handler for both events but they implemented it this way. I think anyone else would have implemented this as on_focus()/on_blur().

This could be the reason why a method might be firing off twice.

Body:
I'm creating an app using kivy. So I don't think I'm understanding something correctly regarding the on_focus behavior of the FloatInput.

Let me first describe what I'm trying to do here. I'm trying to activate a pop-up numpad when the user clicks on a TextInput (this numpad just has buttons for numbers 0-9 and an "enter" button). Next, once the user provides a number in the pop-up numpad and hits an "enter" button, the pop-up should close and the text field of the TextInput should be updated to the user entered number.

However, I'm running into a problem. Essentially, I have a form with multiple TextInputs constructed as described above (I'll refer to them hereafter as "FloatInputs" b/c that's what I've named them). The first time I enter values into one of the FloatInputs, everything works as expected. But the problem occurs whenever I try to enter a number into a second FloatInput. Specifically, the on_focus function is called twice somehow and the user must enter the value into the pop-up twice as a result (this is obviously not ideal as it would serve to frustrate the user).

I apologize if this is a stupid question, but I've been puzzled by it for quite a while. I think the heart of the problem lies in the order of the focusing of the TextInput and the popup widgets, but I could be wrong here. If someone could please offer suggestions as to how I could fix this bug I'd greatly appreciate it.

Here is the relevant python code:

class FloatInput(TextInput):

    def on_focus(self, instance, value):

        print 'ON FOCUS CALLED - THIS SHOULD ONLY BE CALLED ONCE!'

        # Adding this helped part of the problem (however, on_focus is still being called twice???)
        self.unfocus_on_touch = False

        prompt_content = BoxLayout(orientation='vertical')      # Main layout

        num_pad = NumPadWidget()
        prompt_content.add_widget(num_pad)

        def my_callback(instance):

            self.text = num_pad.ids.num_label.text
            self.popup.dismiss()

        # Now define the popup, with the content being the layout:
        self.popup = Popup(id='num_pad_popup', title='Enter value', content=prompt_content, size_hint=(0.8,0.5), autodismiss=False)

        num_pad.ids.enter_btn.bind(on_press=my_callback)

        # Open the pop-up:
        self.popup.open()

And here is the relevant kv code:

<NumPadButton@Button>:
    font_size: '16dp'
    bold: True

<NumPadWidget>:
    BoxLayout:
        orientation: 'vertical'
        BoxLayout:
            size_hint_y: 1
            id: num_label
            Label:
                id: num_label
                text: ''
        BoxLayout:
            size_hint_y: 5
            orientation: 'vertical'
            BoxLayout:
                NumPadButton:
                    text: '7'
                    on_press:
                        num_label.text = num_label.text + '7'
                NumPadButton:
                    text: '8'
                    on_press:
                        num_label.text = num_label.text + '8'
                NumPadButton:
                    text: '9'
                    on_press:
                        num_label.text = num_label.text + '9'
            BoxLayout:
                NumPadButton:
                    text: '4'
                    on_press:
                        num_label.text = num_label.text + '4'
                NumPadButton:
                    text: '5'
                    on_press:
                        num_label.text = num_label.text + '5'
                NumPadButton:
                    text: '6'
                    on_press:
                        num_label.text = num_label.text + '6'
            BoxLayout:
                NumPadButton:
                    text: '1'
                    on_press:
                        num_label.text = num_label.text + '1'
                NumPadButton:
                    text: '2'
                    on_press:
                        num_label.text = num_label.text + '2'
                NumPadButton:
                    text: '3'
                    on_press:
                        num_label.text = num_label.text + '3'
            BoxLayout:
                NumPadButton:
                    text: '0'
                    on_press:
                        num_label.text = num_label.text + '0'
                NumPadButton:
                    text: '.'
                    on_press:
                        num_label.text = num_label.text + '.'
                NumPadButton:
                    text: 'del'
                    on_press:
                        num_label.text = num_label.text[:-1]
            BoxLayout:
                BoxLayout:
                    size_hint_x: 1
                    NumPadButton:
                        text: 'C'
                        on_press:
                            num_label.text = ''
                BoxLayout:
                    size_hint_x: 2
                    NumPadButton:
                        id: enter_btn
                        text: 'Enter'

Body:
For what it's worth, the on_focus() method of TextInput looks like this:

def on_focus(self, instance, value, *largs):

If value is True, it's a focus event. If it's False, then it's a defocus/blur event. I really don't know why they used one handler for both events but they implemented it this way. I think anyone else would have implemented this as on_focus()/on_blur().

This could be the reason why a method might be firing off twice.


问:
Enforcing a delay on textbox_textchanged
I have a barcode scanner that emulates keyboard entry. I'm using it to enter ISBN numbers into a textbox, which then performs a search for that title. I need the textbox method to wait for wither a 10 or 13 character entry before doing anything, however I'm not sure how to go about doing it.

So far, I have the following:

```<code>private void scanBox_TextChanged(object sender, EventArgs e)
        {

            if (scanBox.Text.Length == 10)
            {
                getRecord10();
            }
            else if (scanBox.Text.Length == 13)
            {
                getRecord13();
            }
            else
            {
                MessageBox.Show("Not in directory", "Error");
            }
        }
</code>```

I'm considering some sort of timer implementation to hold off on that last condition, but what I really need is for the method to wait for either 10 or 13 digits. The barcode scanner emulates individual keys being pressed, which is why it is currently failing.

答:
I went for the timer solution and created a simple class to wrap it up a bit more neatly.
The TypingFinished event is then accessed from the Form if it is needed.

The TextChanged event is wrapped inside the HandleCreated event to prevent it from being invoked when Application Settings are being set to the textbox.

Settings.Default.Save is called because it is always true for me, but could just as well be put in the TypingFinished event.

```<code>using YourApp.Properties;
using System;
using System.Windows.Forms;

namespace YourApp.Controls
{
    public partial class TypeDelayTextBox : TextBox
    {
        public TypeDelayTextBox()
        {
            InitializeComponent();

            this.HandleCreated += (senderX, argsX) => { this.TextChanged += OnTextChanged; };
        }

        private void OnTextChanged(object sender, EventArgs args)
        {
            _timer.Enabled = true;
            _timer.Stop();
            _timer.Start();
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            _timer.Stop();
            Settings.Default.Save();
            OnTypingFinished();
        }

        public event EventHandler TypingFinished;

        protected virtual void OnTypingFinished()
        {
            TypingFinished?.Invoke(this, EventArgs.Empty);
        }
    }
}
</code>```

Designer code:

```<code>namespace YourApp.Controls
{
    partial class TypeDelayTextBox
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this._timer = new System.Windows.Forms.Timer(this.components);
            this.SuspendLayout();
            //
            // _timer
            //
            this._timer.Interval = 3000;
            this._timer.Tick += new System.EventHandler(this._timer_Tick);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Timer _timer;
    }
}
</code>```

Body:
I have a barcode scanner that emulates keyboard entry. I'm using it to enter ISBN numbers into a textbox, which then performs a search for that title. I need the textbox method to wait for wither a 10 or 13 character entry before doing anything, however I'm not sure how to go about doing it.

So far, I have the following:

private void scanBox_TextChanged(object sender, EventArgs e)
        {

            if (scanBox.Text.Length == 10)
            {
                getRecord10();
            }
            else if (scanBox.Text.Length == 13)
            {
                getRecord13();
            }
            else
            {
                MessageBox.Show("Not in directory", "Error");
            }
        }

I'm considering some sort of timer implementation to hold off on that last condition, but what I really need is for the method to wait for either 10 or 13 digits. The barcode scanner emulates individual keys being pressed, which is why it is currently failing.

Body:
I went for the timer solution and created a simple class to wrap it up a bit more neatly.
The TypingFinished event is then accessed from the Form if it is needed.

The TextChanged event is wrapped inside the HandleCreated event to prevent it from being invoked when Application Settings are being set to the textbox.

Settings.Default.Save is called because it is always true for me, but could just as well be put in the TypingFinished event.

using YourApp.Properties;
using System;
using System.Windows.Forms;

namespace YourApp.Controls
{
    public partial class TypeDelayTextBox : TextBox
    {
        public TypeDelayTextBox()
        {
            InitializeComponent();

            this.HandleCreated += (senderX, argsX) => { this.TextChanged += OnTextChanged; };
        }

        private void OnTextChanged(object sender, EventArgs args)
        {
            _timer.Enabled = true;
            _timer.Stop();
            _timer.Start();
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            _timer.Stop();
            Settings.Default.Save();
            OnTypingFinished();
        }

        public event EventHandler TypingFinished;

        protected virtual void OnTypingFinished()
        {
            TypingFinished?.Invoke(this, EventArgs.Empty);
        }
    }
}

Designer code:

namespace YourApp.Controls
{
    partial class TypeDelayTextBox
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this._timer = new System.Windows.Forms.Timer(this.components);
            this.SuspendLayout();
            //
            // _timer
            //
            this._timer.Interval = 3000;
            this._timer.Tick += new System.EventHandler(this._timer_Tick);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Timer _timer;
    }
}


问:
Just trying out to check whether the value is present in array or not
I am trying to write a function in jQuery.

var arr1 = ["Jcob", "Pete", "Fin", "John"];
var str = $("#fname").val();
if (jQuery.inArray(str, arr1))
  $("#lname").text("Bob");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname"></code>```

Please check my fiddle here

What it will do it the user will give the value in the first input box the jQuery function will check if the value is present in that array it will fill the second input box with the given text.

答:
Try this:</p>

```<code><body>

    <input type="text" id="fname" name="fname">
    <input type="text" id="lname" name="lname">
    <button onclick="checkValue()">Click</button>

    <script>
        var arr1 = ["Jcob", "Pete", "Fin", "John"];

        function checkValue() {
            var str = $("#fname").val();
            var val = jQuery.inArray(str, arr1);
            if (val === -1) {
                console.log("no value");
            }
            else {
                $("#lname").val("Bob");
            }

        }
    </script>
</body>
</code>```

Body:
I am trying to write a function in jQuery.

var arr1 = ["Jcob", "Pete", "Fin", "John"];
var str = $("#fname").val();
if (jQuery.inArray(str, arr1))
  $("#lname").text("Bob");

<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">

Please check my fiddle here

What it will do it the user will give the value in the first input box the jQuery function will check if the value is present in that array it will fill the second input box with the given text.

Body:
Try this:

<body>

    <input type="text" id="fname" name="fname">
    <input type="text" id="lname" name="lname">
    <button onclick="checkValue()">Click</button>

    <script>
        var arr1 = ["Jcob", "Pete", "Fin", "John"];

        function checkValue() {
            var str = $("#fname").val();
            var val = jQuery.inArray(str, arr1);
            if (val === -1) {
                console.log("no value");
            }
            else {
                $("#lname").val("Bob");
            }

        }
    </script>
</body>


问:
How to fit the map in a destination point with MapViewDirections on react native?
How to fit the map in a destination point?
I just need to fit the camera to the destination point, not to both coordinates (initial and destination like today). How do I do this? Another way to fit the coordinates to this?

{destination && (
  <Fragment>
    <Directions
      origin={region}
      destination={destination}
      onReady={result => {
        this.setState({ duration: Math.floor(result.duration) });
        this.mapView.fitToCoordinates(result.coordinates, {
          edgePadding: {
            right: getPixelSize(10),
            left: getPixelSize(10),
            top: getPixelSize(10),
            bottom: getPixelSize(50),
          },
          animated: true,
        });
      }}
    />
    <Marker
      onPress={this.pickLocationHandler}
      coordinate={destination}
      centerOffset={{ x: -18, y: -60 }}
      anchor={{ x: 0, y: 0 }}
    //opacity={0.6}
    >
      <LocationBox>
        <LocationText>{destination.title}</LocationText>
      </LocationBox>
    </Marker>
    <Marker
      coordinate={region}
      anchor={{ x: 0, y: 0 }}
      onPress={this.pickLocationHandler}>
      <LocationBox>
        <LocationTimeBox>
          <LocationTimeText>{duration}</LocationTimeText>
          <LocationTimeTextSmall>
            Tempo de Viagem
          </LocationTimeTextSmall>
        </LocationTimeBox>
        <LocationText>{location}</LocationText>
      </LocationBox>
    </Marker>
  </Fragment>
)}
```

It would be nice if anyone has some code that works together with GooglePlacesAutocomplete.

答:
Assuming that you're using react-native-maps, you can use these methods:

animateToRegion: takes two params:

region, an object with longitude, latitude, longitudeDelta, latitudeDelta (last two are how close/far away your camera will be from the coords)

duration, the animation duration in milliseconds

```<code>// focus on NYC

this.mapView.animateToRegion({
  latitude: 40.730610,
  longitude: -73.935242,
  latitudeDelta: 0.026,
  longitudeDelta: 0.027,
}, 2000)
</code>```

fitToCoordinates: takes two params:

coordinates, an array of coordinates to be fit in the camera view

options: edgePadding (how much padding should surround the view), animated (whether you want to animate to this view or not)

```<code>// focus on NYC

this.mapView.animateToRegion([{
  latitude: 40.730610,
  longitude: -73.935242,
}], {
  edgePadding: {
    top: 20,
    right: 20,
    bottom: 20,
    left: 20,
  },
  animated: true,
})
</code>```

These methods need to be called on the ref to the your map, like how you do in your code example: this.mapView.fitToCoordinates(...)

There are a bunch of methods that you can use to fit the camera to a destination point, potentially better suited to your use case than what I've described above. Check the RN Maps docs for more info.

Body:
How to fit the map in a destination point?
I just need to fit the camera to the destination point, not to both coordinates (initial and destination like today). How do I do this? Another way to fit the coordinates to this?

{destination && (
  <Fragment>
    <Directions
      origin={region}
      destination={destination}
      onReady={result => {
        this.setState({ duration: Math.floor(result.duration) });
        this.mapView.fitToCoordinates(result.coordinates, {
          edgePadding: {
            right: getPixelSize(10),
            left: getPixelSize(10),
            top: getPixelSize(10),
            bottom: getPixelSize(50),
          },
          animated: true,
        });
      }}
    />
    <Marker
      onPress={this.pickLocationHandler}
      coordinate={destination}
      centerOffset={{ x: -18, y: -60 }}
      anchor={{ x: 0, y: 0 }}
    //opacity={0.6}
    >
      <LocationBox>
        <LocationText>{destination.title}</LocationText>
      </LocationBox>
    </Marker>
    <Marker
      coordinate={region}
      anchor={{ x: 0, y: 0 }}
      onPress={this.pickLocationHandler}>
      <LocationBox>
        <LocationTimeBox>
          <LocationTimeText>{duration}</LocationTimeText>
          <LocationTimeTextSmall>
            Tempo de Viagem
          </LocationTimeTextSmall>
        </LocationTimeBox>
        <LocationText>{location}</LocationText>
      </LocationBox>
    </Marker>
  </Fragment>
)}

It would be nice if anyone has some code that works together with GooglePlacesAutocomplete.

Body:
Assuming that you're using react-native-maps, you can use these methods:

animateToRegion: takes two params:

region, an object with longitude, latitude, longitudeDelta, latitudeDelta (last two are how close/far away your camera will be from the coords)

duration, the animation duration in milliseconds

// focus on NYC

this.mapView.animateToRegion({
  latitude: 40.730610,
  longitude: -73.935242,
  latitudeDelta: 0.026,
  longitudeDelta: 0.027,
}, 2000)

fitToCoordinates: takes two params:

coordinates, an array of coordinates to be fit in the camera view

options: edgePadding (how much padding should surround the view), animated (whether you want to animate to this view or not)

// focus on NYC

this.mapView.animateToRegion([{
  latitude: 40.730610,
  longitude: -73.935242,
}], {
  edgePadding: {
    top: 20,
    right: 20,
    bottom: 20,
    left: 20,
  },
  animated: true,
})

These methods need to be called on the ref to the your map, like how you do in your code example: this.mapView.fitToCoordinates(...)

There are a bunch of methods that you can use to fit the camera to a destination point, potentially better suited to your use case than what I've described above. Check the RN Maps docs for more info.


问:
Static field initialization order (C#) - can someone explain this snippet?
I am a C++ programmer learning C#. I am currently reading C#4.0 in a Nutshell.

I have come accross this statement/snipet on page 74:

Static field initializers run in the
  order in which the fields are
  declared. The following example
  illustrates this: X is initialized to
  0 and Y is initialized to 3.

```<code>class Foo
{
    public static int X = Y; // 0
    public static int Y = 3; // 3
}
</code>```

I dont understand how X can be assigned the value in Y, without Y being first declared. Am I missing something here?

As an aside, coming from a C++ background, I tend to use the term ctor for constructor - however, I haven't yet come accross the term in C# - is the term ctor also used in the C# world?

[Edit]

A further example on the same page (in the book mentioned earlier) is this:

```<code>class Program
{
    static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
    public static Foo Instance = new Foo();
    public static int X = 3;
    Foo() { Console.WriteLine (X); } // 0
}
</code>```

The book states (for the example above):

The example prints 0 followed by 3
  because the field initializer that
  instantiates a Foo executes before X
  is initialized to 3:

I have some further questions w.r.t the examples.

Both examples appear under the section entitled Static constructors and field initialization order however, the code examples dont show a static ctor - atleast, not one that I can easily recognise. I was expecting a static ctor to have the same name as the class, be parameterless and be preceeded by the 'static' keyword. So I dont see how the examples relate to the section heading. What am I missing here?

In the second example, the (non static) ctor prints out the value of X - which had explicitly been assigned the value of 3 in the previous line - and yet, the output printed out is 0. Why?!

答:
Initialisers are actually run in the constructor of the class. When the class is created, all static members are set to zero, then the static constructor runs. That is why the initialiser code can use the Y field to initialise the X field.

Your code works basically the same as:

```<code>class Foo {

  public static int X; // 0
  public static int Y; // 0

  static Foo() {
    X = Y; // 0
    Y = 3; // 3
  }

}
</code>```

(There are however some differences between a class that has an explicit static constructor and one that doesn't, see Jon Skeet's article if you want to dig deeper.)

The term "ctor" is not widely used for "constructor" in C#, usually abbreviations like that are avoided in .NET. That is why identifiers tend to be lengthy and descriptive rather than short and cryptic, like StringComparison.CurrentCultureIgnoreCase rather than something like str_cmp.cc_is.

The abbreviation "ctor" is used in the templates in Visual Studio, by typing "ctor" and pressing tab, you get a template for a constructor.

Body:
I am a C++ programmer learning C#. I am currently reading C#4.0 in a Nutshell.

I have come accross this statement/snipet on page 74:

Static field initializers run in the
  order in which the fields are
  declared. The following example
  illustrates this: X is initialized to
  0 and Y is initialized to 3.

class Foo
{
    public static int X = Y; // 0
    public static int Y = 3; // 3
}

I dont understand how X can be assigned the value in Y, without Y being first declared. Am I missing something here?

As an aside, coming from a C++ background, I tend to use the term ctor for constructor - however, I haven't yet come accross the term in C# - is the term ctor also used in the C# world?

[Edit]

A further example on the same page (in the book mentioned earlier) is this:

class Program
{
    static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
    public static Foo Instance = new Foo();
    public static int X = 3;
    Foo() { Console.WriteLine (X); } // 0
}

The book states (for the example above):

The example prints 0 followed by 3
  because the field initializer that
  instantiates a Foo executes before X
  is initialized to 3:

I have some further questions w.r.t the examples.

Both examples appear under the section entitled Static constructors and field initialization order however, the code examples dont show a static ctor - atleast, not one that I can easily recognise. I was expecting a static ctor to have the same name as the class, be parameterless and be preceeded by the 'static' keyword. So I dont see how the examples relate to the section heading. What am I missing here?

In the second example, the (non static) ctor prints out the value of X - which had explicitly been assigned the value of 3 in the previous line - and yet, the output printed out is 0. Why?!

Body:
Initialisers are actually run in the constructor of the class. When the class is created, all static members are set to zero, then the static constructor runs. That is why the initialiser code can use the Y field to initialise the X field.

Your code works basically the same as:

class Foo {

  public static int X; // 0
  public static int Y; // 0

  static Foo() {
    X = Y; // 0
    Y = 3; // 3
  }

}

(There are however some differences between a class that has an explicit static constructor and one that doesn't, see Jon Skeet's article if you want to dig deeper.)

The term "ctor" is not widely used for "constructor" in C#, usually abbreviations like that are avoided in .NET. That is why identifiers tend to be lengthy and descriptive rather than short and cryptic, like StringComparison.CurrentCultureIgnoreCase rather than something like str_cmp.cc_is.

The abbreviation "ctor" is used in the templates in Visual Studio, by typing "ctor" and pressing tab, you get a template for a constructor.


问:
"A GameObject can only contain one 'Graphic' component." problem
I`m making the quiz game in Unity using C#. Each question consists two game objects: question text and question image. Here is the fragment of the script:

```<code>[SerializeField] Text QuestionTask;
[SerializeField] Text QuestionImage;
[SerializeField] GameObject temp;
[SerializeField] GameObject questionImagePrefab

public void LoadQuestion(Question question)
{
    CurrentQuestion = question;

    //delete possible old elements
    DeleteQuestion();
    //set question Text and Image
    QuestionTask.text = CurrentQuestion.QuestionTask;
    QuestionImage.text = CurrentQuestion.QuestionImage;
    questionImagePrefab.AddComponent(typeof(Image));
    temp = Instantiate(questionImagePrefab);
    temp.GetComponent<Image>().sprite= Resources.Load<Sprite>(QuestionImage.text);
    }
</code>```

In runtime text is showing but image isnt. In the Inspector window I see the name of the sprite but nothing is on the game screen. After load the question I have message in console:
       "Can't add 'Image' to QuestionImagePrefab because a 'Image' is already added to the game object!
        A GameObject can only contain one 'Graphic' component."
I`ve been trying call the method:

```<code>     Destroy(temp);
</code>```

but nothing. Have someone had similar issue? I have searched a lot but didn`t find any solutions. Thanks for help.

答:
It sounds like questionImagePrefab already has an Image component. If this is the case, you do not need to add an Image component to your game object (because it is already there).

I suggest you try removing the line:

```<code>questionImagePrefab.AddComponent(typeof(Image));
</code>```

and post the results here.

Body:
I`m making the quiz game in Unity using C#. Each question consists two game objects: question text and question image. Here is the fragment of the script:

[SerializeField] Text QuestionTask;
[SerializeField] Text QuestionImage;
[SerializeField] GameObject temp;
[SerializeField] GameObject questionImagePrefab

public void LoadQuestion(Question question)
{
    CurrentQuestion = question;

    //delete possible old elements
    DeleteQuestion();
    //set question Text and Image
    QuestionTask.text = CurrentQuestion.QuestionTask;
    QuestionImage.text = CurrentQuestion.QuestionImage;
    questionImagePrefab.AddComponent(typeof(Image));
    temp = Instantiate(questionImagePrefab);
    temp.GetComponent<Image>().sprite= Resources.Load<Sprite>(QuestionImage.text);
    }

In runtime text is showing but image isnt. In the Inspector window I see the name of the sprite but nothing is on the game screen. After load the question I have message in console:
       "Can't add 'Image' to QuestionImagePrefab because a 'Image' is already added to the game object!
        A GameObject can only contain one 'Graphic' component."
I`ve been trying call the method:

     Destroy(temp);

but nothing. Have someone had similar issue? I have searched a lot but didn`t find any solutions. Thanks for help.

Body:
It sounds like questionImagePrefab already has an Image component. If this is the case, you do not need to add an Image component to your game object (because it is already there).

I suggest you try removing the line:

questionImagePrefab.AddComponent(typeof(Image));

and post the results here.


问:
focus() not working in this getUi().showSidebar html in Chrome
I'm opening a sidebar containing a form in Google Sheets using a custom Menubar function.

I want the <textarea> to be focused whenever sidebar opens (so that cursor is in it, and any typing adds to it right away). But using focus() is not working. (Applying style to it is working, as per the next line.)

How can I accomplish that please? Thank you very much for your help.

NOTE: It is not working in Chrome (Win 10), but it does in Firefox.

```<code>function abc() {
    var html =
    '<form id="form">' +
    '<textarea id="title"> </textarea> '+
    '</form> <button>Submit</button> '+
    '<script>'+
    ' document.getElementById("title").focus(); '+ // << NOT WORKING
    ' document.getElementById("title").style.outline ="solid 2px red"' +  // << WORKING
    ' </script>'+
    '';

  var a = HtmlService.createHtmlOutput(html)
  .setSandboxMode(HtmlService.SandboxMode.IFRAME)
  .setTitle('MY-FORM')
  SpreadsheetApp.getUi().showSidebar(a);
}

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My Functions')
  .addItem('Start', 'abc')
  .addSeparator()
  .addToUi();
}

</code>```

答:
Try adding the Boolean attribute autofocus:</p>

```<code>'<textarea id="title" autofocus> </textarea> '
</code>```

Body:
I'm opening a sidebar containing a form in Google Sheets using a custom Menubar function.

I want the <textarea> to be focused whenever sidebar opens (so that cursor is in it, and any typing adds to it right away). But using focus() is not working. (Applying style to it is working, as per the next line.)

How can I accomplish that please? Thank you very much for your help.

NOTE: It is not working in Chrome (Win 10), but it does in Firefox.

function abc() {
    var html =
    '<form id="form">' +
    '<textarea id="title"> </textarea> '+
    '</form> <button>Submit</button> '+
    ''+
    '';

  var a = HtmlService.createHtmlOutput(html)
  .setSandboxMode(HtmlService.SandboxMode.IFRAME)
  .setTitle('MY-FORM')
  SpreadsheetApp.getUi().showSidebar(a);
}

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My Functions')
  .addItem('Start', 'abc')
  .addSeparator()
  .addToUi();
}

Body:
Try adding the Boolean attribute autofocus:

'<textarea id="title" autofocus> </textarea> '


问:
How do I import Three.js into my Nuxt project
I want to import modules in examples folder in THREE.js such as OBJLoader into my Nuxt Project.

I can import main folder of THREE, but error occurs when trying to import modules in examples folder.

Tried these steps in official docs.

https://threejs.org/docs/index.html#manual/en/introduction/Import-via-modules

I'm getting error below

SyntaxError
Unexpected token {

```<code><template>
</template>
<script>
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
export default{
}
</script>
</code>```

here are my github repository
https://github.com/ksuhara/threejs-test

答:
Finally I managed to do it like this!

```<code><template>
    <div>
        <client-only>
            <threejs-component />
        </client-only>
    </div>
</template>
<script>
export default {
    components: {
        ThreejsComponent: process.browser ? () => import('~/path/to/ThreejsComponent.vue') : null
    }
}
</script>
</code>```

inside ThreejsComponent.vue are all the threejs imports

Body:
I want to import modules in examples folder in THREE.js such as OBJLoader into my Nuxt Project.

I can import main folder of THREE, but error occurs when trying to import modules in examples folder.

Tried these steps in official docs.

https://threejs.org/docs/index.html#manual/en/introduction/Import-via-modules

I'm getting error below

SyntaxError
Unexpected token {

<template>
</template>

here are my github repository
https://github.com/ksuhara/threejs-test

Body:
Finally I managed to do it like this!

<template>
    <div>
        <client-only>
            <threejs-component />
        </client-only>
    </div>
</template>
<script>
export default {
    components: {
        ThreejsComponent: process.browser ? () => import('~/path/to/ThreejsComponent.vue') : null
    }
}
</script>

inside ThreejsComponent.vue are all the threejs imports


问:
How to plot multiple bars grouped
How to plot multiple bars in matplotlib, when I tried to call the bar function multiple times, they overlap and as seen the below figure the highest value red can be seen only.
How can I plot the multiple bars with dates on the x-axes?

So far, I tried this:

import matplotlib.pyplot as plt
import datetime

x = [
    datetime.datetime(2011, 1, 4, 0, 0),
    datetime.datetime(2011, 1, 5, 0, 0),
    datetime.datetime(2011, 1, 6, 0, 0)
]
y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]

ax = plt.subplot(111)
ax.bar(x, y, width=0.5, color='b', align='center')
ax.bar(x, z, width=0.5, color='g', align='center')
ax.bar(x, k, width=0.5, color='r', align='center')
ax.xaxis_date()

plt.show()
```

I got this:

The results should be something like, but with the dates are on the x-axes and bars are next to each other:

答:
after looking for a similar solution and not finding anything flexible enough, I decided to write my own function for it. It allows you to have as many bars per group as you wish and specify both the width of a group as well as the individual widths of the bars within the groups.

Enjoy:

```<code>from matplotlib import pyplot as plt

def bar_plot(ax, data, colors=None, total_width=0.8, single_width=1, legend=True):
    """Draws a bar plot with multiple bars per data point.

    Parameters
    ----------
    ax : matplotlib.pyplot.axis
        The axis we want to draw our plot on.

    data: dictionary
        A dictionary containing the data we want to plot. Keys are the names of the
        data, the items is a list of the values.

        Example:
        data = {
            "x":[1,2,3],
            "y":[1,2,3],
            "z":[1,2,3],
        }

    colors : array-like, optional
        A list of colors which are used for the bars. If None, the colors
        will be the standard matplotlib color cyle. (default: None)

    total_width : float, optional, default: 0.8
        The width of a bar group. 0.8 means that 80% of the x-axis is covered
        by bars and 20% will be spaces between the bars.

    single_width: float, optional, default: 1
        The relative width of a single bar within a group. 1 means the bars
        will touch eachother within a group, values less than 1 will make
        these bars thinner.

    legend: bool, optional, default: True
        If this is set to true, a legend will be added to the axis.
    """

    # Check if colors where provided, otherwhise use the default color cycle
    if colors is None:
        colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

    # Number of bars per group
    n_bars = len(data)

    # The width of a single bar
    bar_width = total_width / n_bars

    # List containing handles for the drawn bars, used for the legend
    bars = []

    # Iterate over all data
    for i, (name, values) in enumerate(data.items()):
        # The offset in x direction of that bar
        x_offset = (i - n_bars / 2) * bar_width + bar_width / 2

        # Draw a bar for every value of that type
        for x, y in enumerate(values):
            bar = ax.bar(x + x_offset, y, width=bar_width * single_width, color=colors[i % len(colors)])

        # Add a handle to the last drawn bar, which we'll need for the legend
        bars.append(bar[0])

    # Draw legend if we need
    if legend:
        ax.legend(bars, data.keys())

if __name__ == "__main__":
    # Usage example:
    data = {
        "a": [1, 2, 3, 2, 1],
        "b": [2, 3, 4, 3, 1],
        "c": [3, 2, 1, 4, 2],
        "d": [5, 9, 2, 1, 8],
        "e": [1, 3, 2, 2, 3],
        "f": [4, 3, 1, 1, 4],
    }

    fig, ax = plt.subplots()
    bar_plot(ax, data, total_width=.8, single_width=.9)
    plt.show()

</code>```

Output:

Title: How to plot multiple bars grouped

Body:
How to plot multiple bars in matplotlib, when I tried to call the bar function multiple times, they overlap and as seen the below figure the highest value red can be seen only.
How can I plot the multiple bars with dates on the x-axes?

So far, I tried this:

import matplotlib.pyplot as plt
import datetime

x = [
    datetime.datetime(2011, 1, 4, 0, 0),
    datetime.datetime(2011, 1, 5, 0, 0),
    datetime.datetime(2011, 1, 6, 0, 0)
]
y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]

ax = plt.subplot(111)
ax.bar(x, y, width=0.5, color='b', align='center')
ax.bar(x, z, width=0.5, color='g', align='center')
ax.bar(x, k, width=0.5, color='r', align='center')
ax.xaxis_date()

plt.show()

I got this:

The results should be something like, but with the dates are on the x-axes and bars are next to each other:

Body:
after looking for a similar solution and not finding anything flexible enough, I decided to write my own function for it. It allows you to have as many bars per group as you wish and specify both the width of a group as well as the individual widths of the bars within the groups.

Enjoy:

from matplotlib import pyplot as plt

def bar_plot(ax, data, colors=None, total_width=0.8, single_width=1, legend=True):
    """Draws a bar plot with multiple bars per data point.

    Parameters
    ----------
    ax : matplotlib.pyplot.axis
        The axis we want to draw our plot on.

    data: dictionary
        A dictionary containing the data we want to plot. Keys are the names of the
        data, the items is a list of the values.

        Example:
        data = {
            "x":[1,2,3],
            "y":[1,2,3],
            "z":[1,2,3],
        }

    colors : array-like, optional
        A list of colors which are used for the bars. If None, the colors
        will be the standard matplotlib color cyle. (default: None)

    total_width : float, optional, default: 0.8
        The width of a bar group. 0.8 means that 80% of the x-axis is covered
        by bars and 20% will be spaces between the bars.

    single_width: float, optional, default: 1
        The relative width of a single bar within a group. 1 means the bars
        will touch eachother within a group, values less than 1 will make
        these bars thinner.

    legend: bool, optional, default: True
        If this is set to true, a legend will be added to the axis.
    """

    # Check if colors where provided, otherwhise use the default color cycle
    if colors is None:
        colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

    # Number of bars per group
    n_bars = len(data)

    # The width of a single bar
    bar_width = total_width / n_bars

    # List containing handles for the drawn bars, used for the legend
    bars = []

    # Iterate over all data
    for i, (name, values) in enumerate(data.items()):
        # The offset in x direction of that bar
        x_offset = (i - n_bars / 2) * bar_width + bar_width / 2

        # Draw a bar for every value of that type
        for x, y in enumerate(values):
            bar = ax.bar(x + x_offset, y, width=bar_width * single_width, color=colors[i % len(colors)])

        # Add a handle to the last drawn bar, which we'll need for the legend
        bars.append(bar[0])

    # Draw legend if we need
    if legend:
        ax.legend(bars, data.keys())

if __name__ == "__main__":
    # Usage example:
    data = {
        "a": [1, 2, 3, 2, 1],
        "b": [2, 3, 4, 3, 1],
        "c": [3, 2, 1, 4, 2],
        "d": [5, 9, 2, 1, 8],
        "e": [1, 3, 2, 2, 3],
        "f": [4, 3, 1, 1, 4],
    }

    fig, ax = plt.subplots()
    bar_plot(ax, data, total_width=.8, single_width=.9)
    plt.show()

Output: