问:
Target of URI doesn't exist: 'package:flutter_gen/gen_l10n/gallery_localizations.dart'
I am now using flutter gallary in my project, this is the package reference:

```<code>import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';
</code>```

but it shows:

```<code>Target of URI doesn't exist: 'package:flutter_gen/gen_l10n/gallery_localizations.dart'.
</code>```

I added lib in pubspec.yaml:

```<code>flutter_localizations:
    sdk: flutter
intl: ^0.16.1
flutter_localized_locales: ^1.1.1
</code>```

and added l10n.yaml:

```<code>template-arb-file: intl_en.arb
output-localization-file: gallery_localizations.dart
output-class: GalleryLocalizations
preferred-supported-locales:
  - en
use-deferred-loading: false
</code>```

Am I missing something? still not work, what should I do to make it work? This is the full code:

```<code>import 'package:flutter/material.dart';
import 'package:animations/animations.dart';
import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';

enum BottomNavigationDemoType {
  withLabels,
  withoutLabels,
}

class BottomNavigationDemo extends StatefulWidget {
  const BottomNavigationDemo({Key key, @required this.type}) : super(key: key);

  final BottomNavigationDemoType type;

  @override
  _BottomNavigationDemoState createState() => _BottomNavigationDemoState();
}

class _BottomNavigationDemoState extends State<BottomNavigationDemo> {
  int _currentIndex = 0;

  String _title(BuildContext context) {
    switch (widget.type) {
      case BottomNavigationDemoType.withLabels:
        return GalleryLocalizations.of(context)
            .demoBottomNavigationPersistentLabels;
      case BottomNavigationDemoType.withoutLabels:
        return GalleryLocalizations.of(context)
            .demoBottomNavigationSelectedLabel;
    }
    return '';
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final textTheme = Theme.of(context).textTheme;

    var bottomNavigationBarItems = <BottomNavigationBarItem>[
      BottomNavigationBarItem(
        icon: const Icon(Icons.add_comment),
        label: GalleryLocalizations.of(context).bottomNavigationCommentsTab,
      ),
      BottomNavigationBarItem(
        icon: const Icon(Icons.calendar_today),
        label: GalleryLocalizations.of(context).bottomNavigationCalendarTab,
      ),
      BottomNavigationBarItem(
        icon: const Icon(Icons.account_circle),
        label: GalleryLocalizations.of(context).bottomNavigationAccountTab,
      ),
      BottomNavigationBarItem(
        icon: const Icon(Icons.alarm_on),
        label: GalleryLocalizations.of(context).bottomNavigationAlarmTab,
      ),
      BottomNavigationBarItem(
        icon: const Icon(Icons.camera_enhance),
        label: GalleryLocalizations.of(context).bottomNavigationCameraTab,
      ),
    ];

    if (widget.type == BottomNavigationDemoType.withLabels) {
      bottomNavigationBarItems = bottomNavigationBarItems.sublist(
          0, bottomNavigationBarItems.length - 2);
      _currentIndex =
          _currentIndex.clamp(0, bottomNavigationBarItems.length - 1).toInt();
    }

    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text(_title(context)),
      ),
      body: Center(
        child: PageTransitionSwitcher(
          child: _NavigationDestinationView(
            // Adding [UniqueKey] to make sure the widget rebuilds when transitioning.
            key: UniqueKey(),
            item: bottomNavigationBarItems[_currentIndex],
          ),
          transitionBuilder: (child, animation, secondaryAnimation) {
            return FadeThroughTransition(
              child: child,
              animation: animation,
              secondaryAnimation: secondaryAnimation,
            );
          },
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        showUnselectedLabels:
        widget.type == BottomNavigationDemoType.withLabels,
        items: bottomNavigationBarItems,
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        selectedFontSize: textTheme.caption.fontSize,
        unselectedFontSize: textTheme.caption.fontSize,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        selectedItemColor: colorScheme.onPrimary,
        unselectedItemColor: colorScheme.onPrimary.withOpacity(0.38),
        backgroundColor: colorScheme.primary,
      ),
    );
  }
}

class _NavigationDestinationView extends StatelessWidget {
  _NavigationDestinationView({Key key, this.item}) : super(key: key);

  final BottomNavigationBarItem item;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        ExcludeSemantics(
          child: Center(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.asset(
                  'assets/demos/bottom_navigation_background.png',
                  package: 'flutter_gallery_assets',
                ),
              ),
            ),
          ),
        ),
        Center(
          child: IconTheme(
            data: const IconThemeData(
              color: Colors.white,
              size: 80,
            ),
            child: Semantics(
              label: GalleryLocalizations.of(context)
                  .bottomNavigationContentPlaceholder(
                item.label,
              ),
              child: item.icon,
            ),
          ),
        ),
      ],
    );
  }
}
</code>```

when I run the command flutter clean && flutter run , shows the result:

```<code>[dolphin@MiWiFi-R4CM-srv]~/AndroidStudioProjects/Cruise% flutter clean && flutter run
Attempted to generate localizations code without having the flutter: generate flag turned on.
Check pubspec.yaml and ensure that flutter: generate: true has been added and rebuild the project. Otherwise, the localizations source code will not be
importable.
Generating synthetic localizations package has failed.
</code>```

答:
I just solved it after adding l10n.yaml, then did this:

restart your project

Run:

flutter clean

flutter pub get

Body:
I am now using flutter gallary in my project, this is the package reference:

import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';

but it shows:

Target of URI doesn't exist: 'package:flutter_gen/gen_l10n/gallery_localizations.dart'.

I added lib in pubspec.yaml:

flutter_localizations:
    sdk: flutter
intl: ^0.16.1
flutter_localized_locales: ^1.1.1

and added l10n.yaml:

template-arb-file: intl_en.arb
output-localization-file: gallery_localizations.dart
output-class: GalleryLocalizations
preferred-supported-locales:
  - en
use-deferred-loading: false

Am I missing something? still not work, what should I do to make it work? This is the full code:

import 'package:flutter/material.dart';
import 'package:animations/animations.dart';
import 'package:flutter_gen/gen_l10n/gallery_localizations.dart';

enum BottomNavigationDemoType {
  withLabels,
  withoutLabels,
}

class BottomNavigationDemo extends StatefulWidget {
  const BottomNavigationDemo({Key key, @required this.type}) : super(key: key);

  final BottomNavigationDemoType type;

  @override
  _BottomNavigationDemoState createState() => _BottomNavigationDemoState();
}

class _BottomNavigationDemoState extends State<BottomNavigationDemo> {
  int _currentIndex = 0;

  String _title(BuildContext context) {
    switch (widget.type) {
      case BottomNavigationDemoType.withLabels:
        return GalleryLocalizations.of(context)
            .demoBottomNavigationPersistentLabels;
      case BottomNavigationDemoType.withoutLabels:
        return GalleryLocalizations.of(context)
            .demoBottomNavigationSelectedLabel;
    }
    return '';
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final textTheme = Theme.of(context).textTheme;

    var bottomNavigationBarItems = <BottomNavigationBarItem>[
      BottomNavigationBarItem(
        icon: const Icon(Icons.add_comment),
        label: GalleryLocalizations.of(context).bottomNavigationCommentsTab,
      ),
      BottomNavigationBarItem(
        icon: const Icon(Icons.calendar_today),
        label: GalleryLocalizations.of(context).bottomNavigationCalendarTab,
      ),
      BottomNavigationBarItem(
        icon: const Icon(Icons.account_circle),
        label: GalleryLocalizations.of(context).bottomNavigationAccountTab,
      ),
      BottomNavigationBarItem(
        icon: const Icon(Icons.alarm_on),
        label: GalleryLocalizations.of(context).bottomNavigationAlarmTab,
      ),
      BottomNavigationBarItem(
        icon: const Icon(Icons.camera_enhance),
        label: GalleryLocalizations.of(context).bottomNavigationCameraTab,
      ),
    ];

    if (widget.type == BottomNavigationDemoType.withLabels) {
      bottomNavigationBarItems = bottomNavigationBarItems.sublist(
          0, bottomNavigationBarItems.length - 2);
      _currentIndex =
          _currentIndex.clamp(0, bottomNavigationBarItems.length - 1).toInt();
    }

    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text(_title(context)),
      ),
      body: Center(
        child: PageTransitionSwitcher(
          child: _NavigationDestinationView(
            // Adding [UniqueKey] to make sure the widget rebuilds when transitioning.
            key: UniqueKey(),
            item: bottomNavigationBarItems[_currentIndex],
          ),
          transitionBuilder: (child, animation, secondaryAnimation) {
            return FadeThroughTransition(
              child: child,
              animation: animation,
              secondaryAnimation: secondaryAnimation,
            );
          },
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        showUnselectedLabels:
        widget.type == BottomNavigationDemoType.withLabels,
        items: bottomNavigationBarItems,
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        selectedFontSize: textTheme.caption.fontSize,
        unselectedFontSize: textTheme.caption.fontSize,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        selectedItemColor: colorScheme.onPrimary,
        unselectedItemColor: colorScheme.onPrimary.withOpacity(0.38),
        backgroundColor: colorScheme.primary,
      ),
    );
  }
}

class _NavigationDestinationView extends StatelessWidget {
  _NavigationDestinationView({Key key, this.item}) : super(key: key);

  final BottomNavigationBarItem item;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        ExcludeSemantics(
          child: Center(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.asset(
                  'assets/demos/bottom_navigation_background.png',
                  package: 'flutter_gallery_assets',
                ),
              ),
            ),
          ),
        ),
        Center(
          child: IconTheme(
            data: const IconThemeData(
              color: Colors.white,
              size: 80,
            ),
            child: Semantics(
              label: GalleryLocalizations.of(context)
                  .bottomNavigationContentPlaceholder(
                item.label,
              ),
              child: item.icon,
            ),
          ),
        ),
      ],
    );
  }
}

when I run the command flutter clean && flutter run , shows the result:

[dolphin@MiWiFi-R4CM-srv]~/AndroidStudioProjects/Cruise% flutter clean && flutter run
Attempted to generate localizations code without having the flutter: generate flag turned on.
Check pubspec.yaml and ensure that flutter: generate: true has been added and rebuild the project. Otherwise, the localizations source code will not be
importable.
Generating synthetic localizations package has failed.


来源: stackexchange

问:
Segmentation Fault in my Quick Sort Program in C?
I'm Getting Segmentation fault by debugger in partition() function at commented variable...following code is a complete implementation of Quick Sort algorithm.

// Sorting Algorithms

void quick_sort(int arr[],int length);
int partition(int a[],int low, int high);
void quick_sort_recursion(int arr[], int low, int high);
void swap(int *x, int *y);

void quick_sort(int arr[],int length){
    quick_sort_recursion(arr,0,length-1);

}

void quick_sort_recursion(int arr[],int low, int high){

    if(low<high){
        int pivot_value = partition(arr,low,high);
        quick_sort_recursion(arr,low,pivot_value - 1);
        quick_sort_recursion(arr,pivot_value+1,high);
    }
}

int partition(int arr[], int low, int high){

    int pivot_value = arr[high]; //getting 'segmentation fault' here
    int i = low;

    for (int j = low; j < high; j++)
    {
        if(arr[j] <= pivot_value){
            swap(&arr[i],&arr[j]);
            i++;
        }
    }
    swap(&arr[i],&arr[high]);
}

```

see image here...

答: In the image, the high value (6422295) is quite large as for the size of array. The large size array would lead to the segmentation fault.

ContentLicense: CC BY-SA 4.0

Body:
I'm Getting Segmentation fault by debugger in partition() function at commented variable...following code is a complete implementation of Quick Sort algorithm.

// Sorting Algorithms

void quick_sort(int arr[],int length);
int partition(int a[],int low, int high);
void quick_sort_recursion(int arr[], int low, int high);
void swap(int *x, int *y);

void quick_sort(int arr[],int length){
    quick_sort_recursion(arr,0,length-1);

}

void quick_sort_recursion(int arr[],int low, int high){

    if(low<high){
        int pivot_value = partition(arr,low,high);
        quick_sort_recursion(arr,low,pivot_value - 1);
        quick_sort_recursion(arr,pivot_value+1,high);
    }
}

int partition(int arr[], int low, int high){

    int pivot_value = arr[high]; //getting 'segmentation fault' here
    int i = low;

    for (int j = low; j < high; j++)
    {
        if(arr[j] <= pivot_value){
            swap(&arr[i],&arr[j]);
            i++;
        }
    }
    swap(&arr[i],&arr[high]);
}

see image here...


问:
Flutter - Disable navigation InAppWebView
I'm new to Flutter, and I want to put a web view between other widgets and I'm using the InAppWebView flutter in order to do it, but I want to prevent the user to navigate to other pages when he clicks on a button inside the web view. Do I have to write some native code for iOS and Android to prevent the navigation?

Thanks

答:
Disable navigation InAppWebView:-

we have onUpdateVisitedHistory property in Inappwebview widget.Using this onUpdateVisitedHistory property we can listen url changes in the Inappwebview widget.So disable navigation we can use webcontroller.goback() method.

widget code:

```<code>InAppWebView(
              key: webViewKey,
              onWebViewCreated: (controller) {
                webViewController = controller;
                _loadHtmlFromAssets();
              },
              onUpdateVisitedHistory: (controller, url, androidIsReload) {
                if (url!.host.contains("google.com")) {
                  webViewController?.goBack();
                  //You can do anything
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen1()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("yahoo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen3()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("duckduckgo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen2()),
                  );
                }
              })
</code>```

Here we skipping loading the search engine and jump to other widget

nb: if we did'nt add webcontroller.goback().it will load site and move to the widget .if we back pressed it will show webpage.

sampleCode:

```<code>class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  WebViewController? _controller;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;
  late PullToRefreshController pullToRefreshController;
  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
        useShouldOverrideUrlLoading: true,
        mediaPlaybackRequiresUserGesture: false,
      ),
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      ));

  @override
  void initState() {
    super.initState();

    pullToRefreshController = PullToRefreshController(
      options: PullToRefreshOptions(
        color: Colors.blue,
      ),
      onRefresh: () async {
        if (Platform.isAndroid) {
          webViewController?.reload();
        } else if (Platform.isIOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            webViewController?.goBack();
          },
          child: Icon(Icons.arrow_back),
        ),
        appBar: AppBar(
          backgroundColor: Colors.black87,
          title: Text(widget.title),
        ),
        body: Center(
          child: InAppWebView(
              key: webViewKey,
              onWebViewCreated: (controller) {
                webViewController = controller;
                _loadHtmlFromAssets();
              },
              onUpdateVisitedHistory: (controller, url, androidIsReload) {
                if (url!.host.contains("google.com")) {
                  webViewController?.goBack();
                  //You can do anything
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen1()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("yahoo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen3()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("duckduckgo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen2()),
                  );
                }
              }),
        ));
  }

  _loadHtmlFromAssets() {
    var fileText =
        "<!DOCTYPE html> <html> <head> <title>HTML, CSS and JavaScript demo</title> <style> .rotate { transform: rotate(1700deg) ; } .rotate2 { transform: rotate(90deg) ; } .bg { background: url(https://picsum.photos/2000/1000?image=1069) center/cover; height: 50vh; width: 50vh; } body { margin:0; overflow:hidden; } </style> </head> "
        "<!-- Start your code here --> <ul> <li> <a href ='http://duckduckgo.com/' /><p> duckduckgo.com</a> </li>  <li> <a href='http://www.google.com'>google.com </a> </li>    <li> <a href='http://www.yahoo.com/'> yahoo.com </a> </li></ul> </html>";
    // return Uri.dataFromString(fileText,
    //         mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
    //     .toString();
    webViewController!.loadUrl(
        urlRequest: URLRequest(
            url: new Uri.dataFromString(fileText, mimeType: 'text/html')));

    // _controller?.loadUrl(Uri.dataFromString(fileText,
    //         mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
    //     .toString());
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class Screen1 extends StatelessWidget {
  const Screen1({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Text("Screen 1 google.com"),
      ),
    );
  }
}

class Screen2 extends StatelessWidget {
  const Screen2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: MaterialApp(
        home: Container(
          child: Text("Screen 2 yahoo.com"),
        ),
      ),
    );
  }
}

class Screen3 extends StatelessWidget {
  const Screen3({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Text("Screen 3 duck.com"),
      ),
    );
  }
}
</code>```

Disable navigation in Webview Widget:

We can use navigationDelegate to monitor url changes in webview.NavigationDecision.prevent will block jump to website

```<code>WebView(
      // initialUrl: 'https://flutter.dev',
      onWebViewCreated: (WebViewController webViewController) {
        _controller = webViewController;
        _loadHtmlFromAssets();
      },
      navigationDelegate: (NavigationRequest request) {
        if (request.url.contains("google.com")) {
          //You can do anything
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const Screen1()),
          );
          //Prevent that url works
          return NavigationDecision.prevent;
        } else if (request.url.contains("yahoo.com")) {
          //You can do anything
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const Screen1()),
          );
          //Prevent that url works
          return NavigationDecision.prevent;
        } else if (request.url.contains("duckduckgo.com")) {
          //You can do anything
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const Screen3()),
          );
          //Prevent that url works
          return NavigationDecision.prevent;
        }
        //Any other url works
        return NavigationDecision.navigate;
      },
    );
</code>```

Body:
Disable navigation InAppWebView:-

we have onUpdateVisitedHistory property in Inappwebview widget.Using this onUpdateVisitedHistory property we can listen url changes in the Inappwebview widget.So disable navigation we can use webcontroller.goback() method.

widget code:

InAppWebView(
              key: webViewKey,
              onWebViewCreated: (controller) {
                webViewController = controller;
                _loadHtmlFromAssets();
              },
              onUpdateVisitedHistory: (controller, url, androidIsReload) {
                if (url!.host.contains("google.com")) {
                  webViewController?.goBack();
                  //You can do anything
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen1()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("yahoo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen3()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("duckduckgo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen2()),
                  );
                }
              })

Here we skipping loading the search engine and jump to other widget

nb: if we did'nt add webcontroller.goback().it will load site and move to the widget .if we back pressed it will show webpage.

sampleCode:

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  WebViewController? _controller;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;
  late PullToRefreshController pullToRefreshController;
  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
        useShouldOverrideUrlLoading: true,
        mediaPlaybackRequiresUserGesture: false,
      ),
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      ));

  @override
  void initState() {
    super.initState();

    pullToRefreshController = PullToRefreshController(
      options: PullToRefreshOptions(
        color: Colors.blue,
      ),
      onRefresh: () async {
        if (Platform.isAndroid) {
          webViewController?.reload();
        } else if (Platform.isIOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            webViewController?.goBack();
          },
          child: Icon(Icons.arrow_back),
        ),
        appBar: AppBar(
          backgroundColor: Colors.black87,
          title: Text(widget.title),
        ),
        body: Center(
          child: InAppWebView(
              key: webViewKey,
              onWebViewCreated: (controller) {
                webViewController = controller;
                _loadHtmlFromAssets();
              },
              onUpdateVisitedHistory: (controller, url, androidIsReload) {
                if (url!.host.contains("google.com")) {
                  webViewController?.goBack();
                  //You can do anything
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen1()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("yahoo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen3()),
                  );
                  //Prevent that url works
                  return;
                } else if (url.host.contains("duckduckgo.com")) {
                  //You can do anything
                  webViewController?.goBack();
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const Screen2()),
                  );
                }
              }),
        ));
  }

  _loadHtmlFromAssets() {
    var fileText =
        "<!DOCTYPE html> <html> <head> <title>HTML, CSS and JavaScript demo</title> <style> .rotate { transform: rotate(1700deg) ; } .rotate2 { transform: rotate(90deg) ; } .bg { background: url(https://picsum.photos/2000/1000?image=1069) center/cover; height: 50vh; width: 50vh; } body { margin:0; overflow:hidden; } </style> </head> "
        "<!-- Start your code here --> <ul> <li> <a href ='http://duckduckgo.com/' /><p> duckduckgo.com</a> </li>  <li> <a href='http://www.google.com'>google.com </a> </li>    <li> <a href='http://www.yahoo.com/'> yahoo.com </a> </li></ul> </html>";
    // return Uri.dataFromString(fileText,
    //         mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
    //     .toString();
    webViewController!.loadUrl(
        urlRequest: URLRequest(
            url: new Uri.dataFromString(fileText, mimeType: 'text/html')));

    // _controller?.loadUrl(Uri.dataFromString(fileText,
    //         mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
    //     .toString());
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class Screen1 extends StatelessWidget {
  const Screen1({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Text("Screen 1 google.com"),
      ),
    );
  }
}

class Screen2 extends StatelessWidget {
  const Screen2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: MaterialApp(
        home: Container(
          child: Text("Screen 2 yahoo.com"),
        ),
      ),
    );
  }
}

class Screen3 extends StatelessWidget {
  const Screen3({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: Text("Screen 3 duck.com"),
      ),
    );
  }
}

Disable navigation in Webview Widget:

We can use navigationDelegate to monitor url changes in webview.NavigationDecision.prevent will block jump to website

WebView(
      // initialUrl: 'https://flutter.dev',
      onWebViewCreated: (WebViewController webViewController) {
        _controller = webViewController;
        _loadHtmlFromAssets();
      },
      navigationDelegate: (NavigationRequest request) {
        if (request.url.contains("google.com")) {
          //You can do anything
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const Screen1()),
          );
          //Prevent that url works
          return NavigationDecision.prevent;
        } else if (request.url.contains("yahoo.com")) {
          //You can do anything
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const Screen1()),
          );
          //Prevent that url works
          return NavigationDecision.prevent;
        } else if (request.url.contains("duckduckgo.com")) {
          //You can do anything
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const Screen3()),
          );
          //Prevent that url works
          return NavigationDecision.prevent;
        }
        //Any other url works
        return NavigationDecision.navigate;
      },
    );


问:
Test if getJSONArray is null or not
My code extract results of JSONObject, but, sometimes, the i value don't begin to 1, and i have an error like that :

```<code>org.json.JSONException: No value for 1
</code>```

My code :

```<code>JSONObject obj = new JSONObject(result);
       for(int i=1;i<=14;i++) {

            JSONArray arr = obj.getJSONArray(""+i);
        extraction(arr, i);
       }
</code>```

I want to test before the extraction if the object code (i) exists or not. How i can do this ?

答:
use JSONObject.optJSONArray(key).

As indicated in the documentation, it returns null in case the key is not present.

Also, your JSON structure seems weird. Why do you have numeric ordered keys in an object? shouldn't that be an Array?

ContentLicense: CC BY-SA 3.0

Title: Test if getJSONArray is null or not

Body:
My code extract results of JSONObject, but, sometimes, the i value don't begin to 1, and i have an error like that :

org.json.JSONException: No value for 1

My code :

JSONObject obj = new JSONObject(result);
       for(int i=1;i<=14;i++) {

            JSONArray arr = obj.getJSONArray(""+i);
        extraction(arr, i);
       }

I want to test before the extraction if the object code (i) exists or not. How i can do this ?


问:
Embed html report in email body using Email-ext plugin on Jenkins pipeline?
How can I make the email body as the selenium html report. I have followed the methods give in the question Display HTML page inside mail body with Email-ext plugin in Jenkins, but I'm getting error

```<code>org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed: WorkflowScript: 6: unexpected token: FILE @ line 6,
column 17.
        body: ${FILE,path="enteryPath/template.html"},
                ^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(
ErrorCollector.java:310)
at org.codehaus.groovy.control.ErrorCollector.addFatalError(
ErrorCollector.java:150)
at org.codehaus.groovy.control.ErrorCollector.addError(
ErrorCollector.java:120)
at org.codehaus.groovy.control.ErrorCollector.addError(
ErrorCollector.java:132)
at org.codehaus.groovy.control.SourceUnit.addError(SourceUnit.java:350)
at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(
AntlrParserPlugin.java:144)
at org.codehaus.groovy.antlr.AntlrParserPlugin.parseCST(
AntlrParserPlugin.java:110)
at org.codehaus.groovy.control.SourceUnit.parse(SourceUnit.java:234)
at org.codehaus.groovy.control.CompilationUnit$1.call(
CompilationUnit.java:168)
at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(
CompilationUnit.java:943)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(
CompilationUnit.java:605)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(
CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(
CompilationUnit.java:558)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(
CpsGroovyShell.java:129)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(
CpsGroovyShell.java:123)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(
CpsFlowExecution.java:517)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(
CpsFlowExecution.java:480)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(
WorkflowRun.java:269)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:421) Finished: FAILURE
</code>```

The code I used is:

```<code>node {
    stage ('email')
    {
        emailext (
        subject: "some subject",
        body: ${FILE,path="enteryPath/template.html"},
        to: "email@example.com"
        )

    }
}
</code>```

Jenkins Version 2.85
Email extension plugin version 2.60
Thanks

答:
In order to use dynamic path or evaluated variable path, you can do the following:

```<code> " \ ${FILE,path= \ "${FILE_LOCATION} \ "}"
</code>```

Please note for the back slash, spaces need to be trimmed.

Body:
How can I make the email body as the selenium html report. I have followed the methods give in the question Display HTML page inside mail body with Email-ext plugin in Jenkins, but I'm getting error

org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed: WorkflowScript: 6: unexpected token: FILE @ line 6,
column 17.
        body: ${FILE,path="enteryPath/template.html"},
                ^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(
ErrorCollector.java:310)
at org.codehaus.groovy.control.ErrorCollector.addFatalError(
ErrorCollector.java:150)
at org.codehaus.groovy.control.ErrorCollector.addError(
ErrorCollector.java:120)
at org.codehaus.groovy.control.ErrorCollector.addError(
ErrorCollector.java:132)
at org.codehaus.groovy.control.SourceUnit.addError(SourceUnit.java:350)
at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(
AntlrParserPlugin.java:144)
at org.codehaus.groovy.antlr.AntlrParserPlugin.parseCST(
AntlrParserPlugin.java:110)
at org.codehaus.groovy.control.SourceUnit.parse(SourceUnit.java:234)
at org.codehaus.groovy.control.CompilationUnit$1.call(
CompilationUnit.java:168)
at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(
CompilationUnit.java:943)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(
CompilationUnit.java:605)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(
CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(
CompilationUnit.java:558)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(
CpsGroovyShell.java:129)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(
CpsGroovyShell.java:123)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(
CpsFlowExecution.java:517)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(
CpsFlowExecution.java:480)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(
WorkflowRun.java:269)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:421) Finished: FAILURE

The code I used is:

node {
    stage ('email')
    {
        emailext (
        subject: "some subject",
        body: ${FILE,path="enteryPath/template.html"},
        to: "email@example.com"
        )

    }
}

Jenkins Version 2.85
Email extension plugin version 2.60
Thanks

Body:
In order to use dynamic path or evaluated variable path, you can do the following:

 " \ ${FILE,path= \ "${FILE_LOCATION} \ "}"

Please note for the back slash, spaces need to be trimmed.


问:
How to import module from other directory in python
I have a file tree like this:

```<code>app
|---src
|    |---vlep/config.py
|
|---tests
     |---conftest.py
</code>```

from conftest.py I am trying to import vlep.confi as config and I am getting the ModulenotFoundError: No module named 'vlep'. I am using venv and I added absolute paths for app, src and vlep directories to venv/bin/activate, so when I activate the virtualenv I can have these directories in the PYTHONPATH env. I thought that this would do the job, but no...and have no idea why. What am I doing wrong?

答:
You need to set the file path manually to import the modules from another directory. You can assign a directory path to the PYTHONPATH variable and still get your program working.

In Linux, you can use the following command in the terminal to set the path:

```<code>export PYTHONPATH='path/to/directory'
</code>```

In Windows system :

```<code>SET PYTHONPATH='path/to/directory'
</code>```

To see if PYTHONPATH variable holds the path of the new folder, you can use the following command:

```<code>echo $PYTHONPATH
</code>```

Then you can do your imports:

```<code>from conftest import vlep.confi as config
</code>```

Body:
I have a file tree like this:

app
|---src
|    |---vlep/config.py
|
|---tests
     |---conftest.py

from conftest.py I am trying to import vlep.confi as config and I am getting the ModulenotFoundError: No module named 'vlep'. I am using venv and I added absolute paths for app, src and vlep directories to venv/bin/activate, so when I activate the virtualenv I can have these directories in the PYTHONPATH env. I thought that this would do the job, but no...and have no idea why. What am I doing wrong?

Body:
You need to set the file path manually to import the modules from another directory. You can assign a directory path to the PYTHONPATH variable and still get your program working.

In Linux, you can use the following command in the terminal to set the path:

export PYTHONPATH='path/to/directory'

In Windows system :

SET PYTHONPATH='path/to/directory'

To see if PYTHONPATH variable holds the path of the new folder, you can use the following command:

echo $PYTHONPATH

Then you can do your imports:

from conftest import vlep.confi as config


问:
How to correct the order of my attempted reverse array?
I was working on a project that would see an array of decimals be printed out in reverse and in a lateral printing. I have gotten the java code to be printed in lateral format, but when it comes to have my arrays variables printed, it is not in revers order, but in a random order.
I am not sure where I have gone wrong, looking for a second pare of eyes to catch where I went wrong, thanks.</p>
```<code>public static void main(String[] args) {
    // TODO Auto-generated method stub
    DecimalFormat decimalFormat = new DecimalFormat("#.##");
    double [] dArray = {3.1415, 17.4567, 8.3132};
    int i = 0;
    for (double d : dArray) {
        dArray [i] = Double.valueOf(decimalFormat.format(d));
        i++;
    }
    for (double d = dArray.length-1;d>=1;d--)
        //System.out.println(dArray[i]);
    Arrays.stream(dArray).forEach(System.out::println);
}

}
</code>```

答:
When you use stream in forEach(), the order is not strictly maintained. Instead forEachOrdered() should be used.
Like,

```<code>Arrays.stream(dArray).forEachOrdered(System.out::println);
</code>```

Body:
I was working on a project that would see an array of decimals be printed out in reverse and in a lateral printing. I have gotten the java code to be printed in lateral format, but when it comes to have my arrays variables printed, it is not in revers order, but in a random order.
I am not sure where I have gone wrong, looking for a second pare of eyes to catch where I went wrong, thanks.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    DecimalFormat decimalFormat = new DecimalFormat("#.##");
    double [] dArray = {3.1415, 17.4567, 8.3132};
    int i = 0;
    for (double d : dArray) {
        dArray [i] = Double.valueOf(decimalFormat.format(d));
        i++;
    }
    for (double d = dArray.length-1;d>=1;d--)
        //System.out.println(dArray[i]);
    Arrays.stream(dArray).forEach(System.out::println);
}

}

Body:
When you use stream in forEach(), the order is not strictly maintained. Instead forEachOrdered() should be used.
Like,

Arrays.stream(dArray).forEachOrdered(System.out::println);


问:
Python if statement to skip dictionary key when creating a dictionary
My code looks like this:

```<code>def createEventBody(name,description,attendees,location, eventColor = None):
    eventBody = {
              'Name': name, #EventName
              'Color': eventColor,
              'location': location,
              'description':description,
              'attendees': [],
              }
</code>```

The thing is, I want to add some logic so that the key 'Color' is not included if eventColor = None.
I was thinking something like this:

```<code>def createEventBody(name,description,attendees,location, eventColor = None):
    eventBody = {
              'Name': name, #EventName
              ('Color': eventColor) if eventColor != None else pass,
              'location': location,
              'description':description,
              'attendees': [],
              }
</code>```

However 'pass' doesn't allow me to "skip" that key.
How could I fix this?

答:
x if y else z is a conditional expression: it is a way of issuing a value that depends on a condition. It is not suitable for doing something or not doing it. That is what an if statement is for.

Set the Color entry in an if statement after the eventBody dict is created.

```<code>eventBody = {
          'Name': name,
          'location': location,
          'description':description,
          'attendees': [],
}
if eventColor is not None:
    eventBody['Color'] = eventColor
</code>```

is there a way to do this but for multiple variables without the use of multiple if statements? So instead of doing color is not None, description is not None doing it all with one single expression?

Yes. You could set all those entries in your dictionary, and then omit the ones that have the value None.

Something like this:

```<code>eventBody = {
          'Name': name,
          'Color': eventColor,
          'location': location,
          'description':description,
          'attendees': [],
}

eventBody = {k:v for (k,v) in eventBody.items() if v is not None}
</code>```

Or if you only want to filter some specific keys, like this:

```<code>for key in ('Color', 'location', 'description'):
    if eventBody[key] is None:
        del eventBody[key]
</code>```

Body:
My code looks like this:

def createEventBody(name,description,attendees,location, eventColor = None):
    eventBody = {
              'Name': name, #EventName
              'Color': eventColor,
              'location': location,
              'description':description,
              'attendees': [],
              }

The thing is, I want to add some logic so that the key 'Color' is not included if eventColor = None.
I was thinking something like this:

def createEventBody(name,description,attendees,location, eventColor = None):
    eventBody = {
              'Name': name, #EventName
              ('Color': eventColor) if eventColor != None else pass,
              'location': location,
              'description':description,
              'attendees': [],
              }

However 'pass' doesn't allow me to "skip" that key.
How could I fix this?

Body:
x if y else z is a conditional expression: it is a way of issuing a value that depends on a condition. It is not suitable for doing something or not doing it. That is what an if statement is for.

Set the Color entry in an if statement after the eventBody dict is created.

eventBody = {
          'Name': name,
          'location': location,
          'description':description,
          'attendees': [],
}
if eventColor is not None:
    eventBody['Color'] = eventColor

is there a way to do this but for multiple variables without the use of multiple if statements? So instead of doing color is not None, description is not None doing it all with one single expression?

Yes. You could set all those entries in your dictionary, and then omit the ones that have the value None.

Something like this:

eventBody = {
          'Name': name,
          'Color': eventColor,
          'location': location,
          'description':description,
          'attendees': [],
}

eventBody = {k:v for (k,v) in eventBody.items() if v is not None}

Or if you only want to filter some specific keys, like this:

for key in ('Color', 'location', 'description'):
    if eventBody[key] is None:
        del eventBody[key]


问:
Component's forwardRef children all point to the same ref in an array
I have a function component that takes a variable amount of child (forwardRef) function components. What I would like to achieve is having a ref to each of the child components for animations when a child component is clicked. I have a semi-working solution by creating an array of refs and then cloning all the children and passing an indexed ref to each of them. The only issue is that all of the refs in the index point to the same (last) child.

Here are my components:

```<code>const Navbar = ({children}) => {
    const [activeLink, setActiveLink] = useState(0);
    const linkRefs = Array(children.length).fill(React.createRef(null));

    const handleActiveLinkChange = (index) => {
        setActiveLink(index);
        console.log(linkRefs[index].current);
    }

    return (
        <nav>
            {React.Children.map(children, (child, index) => React.cloneElement(child, {index: index, active: index === activeLink, handleActiveLinkChange, key: "child" + index, ref: linkRefs[index]}))}
        </nav>
    )
}

const Link = React.forwardRef(({children, active, index, handleActiveLinkChange}, ref) => {
    return (
        <a href="#" style={linkStyle} onClick={() => handleActiveLinkChange(index)} ref={ref}>
            {active ? <b>{children}</b> : children}
        </a>
    )
});
</code>```

And assuming I use the components in the following way:

```<code><Navbar>
    <Link>One</Link>
    <Link>Two</Link>
    <Link>Three</Link>
    <Link>Four</Link>
    <Link>Five</Link>
</Navbar>
</code>```

I expect the refs to be:

Ref array index
Ref current

0
One

1
Two

2
Three

3
Four

4
Five

But the refs I get are:

Ref array index
Ref current

0
Five

1
Five

2
Five

3
Five

4
Five

I'm assuming it's something to do with variable scope but I just can't figure out the cause of the issue. I've tried many variations of loops and functions but I'd rather understand the cause than blindly try to find a solution.

答:
The issue is with the following line. It creates only one ref and all the array indices refer to that single ref.

```<code>const linkRefs = Array(children.length).fill(React.createRef(null));
</code>```

Instead of the above use the following line which creates new refs for each child as you expect.

```<code>const linkRefs = Array.from({ length: children.length }, () =>
    React.createRef(null)
);
</code>```

Body:
I have a function component that takes a variable amount of child (forwardRef) function components. What I would like to achieve is having a ref to each of the child components for animations when a child component is clicked. I have a semi-working solution by creating an array of refs and then cloning all the children and passing an indexed ref to each of them. The only issue is that all of the refs in the index point to the same (last) child.

Here are my components:

const Navbar = ({children}) => {
    const [activeLink, setActiveLink] = useState(0);
    const linkRefs = Array(children.length).fill(React.createRef(null));

    const handleActiveLinkChange = (index) => {
        setActiveLink(index);
        console.log(linkRefs[index].current);
    }

    return (

            {React.Children.map(children, (child, index) => React.cloneElement(child, {index: index, active: index === activeLink, handleActiveLinkChange, key: "child" + index, ref: linkRefs[index]}))}

    )
}

const Link = React.forwardRef(({children, active, index, handleActiveLinkChange}, ref) => {
    return (
         handleActiveLinkChange(index)} ref={ref}>
            {active ? {children} : children}

    )
});

And assuming I use the components in the following way:

<Navbar>
    <Link>One</Link>
    <Link>Two</Link>
    <Link>Three</Link>
    <Link>Four</Link>
    <Link>Five</Link>
</Navbar>

I expect the refs to be:

Ref array index
Ref current

0
One

1
Two

2
Three

3
Four

4
Five

But the refs I get are:

Ref array index
Ref current

0
Five

1
Five

2
Five

3
Five

4
Five

I'm assuming it's something to do with variable scope but I just can't figure out the cause of the issue. I've tried many variations of loops and functions but I'd rather understand the cause than blindly try to find a solution.

Body:
The issue is with the following line. It creates only one ref and all the array indices refer to that single ref.

const linkRefs = Array(children.length).fill(React.createRef(null));

Instead of the above use the following line which creates new refs for each child as you expect.

const linkRefs = Array.from({ length: children.length }, () =>
    React.createRef(null)
);


答: pass is not an expression, it does not have a value. I would stick with the original (i.e., set 'Color': None), but if you do not want None, you can just do a standard if statement.

Title: Python if statement to skip dictionary key when creating a dictionary


答:
You can use dict.update method

```<code>   eventBody = {
              'Name': name, #EventName
              'location': location,
              'description':description,
              'attendees': [],
              }
if eventColor:
    eventBody.update({"Color": eventColor})
</code>```

Body:
You can use dict.update method

   eventBody = {
              'Name': name, #EventName
              'location': location,
              'description':description,
              'attendees': [],
              }
if eventColor:
    eventBody.update({"Color": eventColor})


问:
I/UrlLauncher(17669): component name for (url) is null
Why does it throw an error and give me the link is empty even though the link exists?
And when I use launch (url) alone, the link opens without any problems.

```<code> String StateUrl = 'View App' ;
 var url = 'https://www.youtube.com/watch?v=-k0IXjCHObw' ;
body: Column(
        children: [
          Text(StateUrl),
          Center(
            child: ElevatedButton.icon(
                onPressed: () async{
                  try {
                    await canLaunch(url) ?
                    await launch(url):
                    throw 'Error';
                  } catch(e){
                    setState(() {
                      StateUrl = e.toString() ;
                    });
                  }
                },
                icon: const Icon(FontAwesomeIcons.link),
                label:  const Text('View Url')
            ),
          ),
        ],
      ),
</code>```

Performing hot reload:

D/EGL_emulation(17669): app_time_stats: avg=17852.65ms min=658.78ms
max=35046.52ms count=2 I/UrlLauncher(17669): component name for
https://www.youtube.com/watch?v=-k0IXjCHObw is null
D/EGL_emulation(17669): app_time_stats: avg=8279.72ms min=8279.72ms
max=8279.72ms count=1

答: Don't use canLaunch with videos URL, just use try/catch.

Body:
Why does it throw an error and give me the link is empty even though the link exists?
And when I use launch (url) alone, the link opens without any problems.

 String StateUrl = 'View App' ;
 var url = 'https://www.youtube.com/watch?v=-k0IXjCHObw' ;
body: Column(
        children: [
          Text(StateUrl),
          Center(
            child: ElevatedButton.icon(
                onPressed: () async{
                  try {
                    await canLaunch(url) ?
                    await launch(url):
                    throw 'Error';
                  } catch(e){
                    setState(() {
                      StateUrl = e.toString() ;
                    });
                  }
                },
                icon: const Icon(FontAwesomeIcons.link),
                label:  const Text('View Url')
            ),
          ),
        ],
      ),

Performing hot reload:

D/EGL_emulation(17669): app_time_stats: avg=17852.65ms min=658.78ms
max=35046.52ms count=2 I/UrlLauncher(17669): component name for
https://www.youtube.com/watch?v=-k0IXjCHObw is null
D/EGL_emulation(17669): app_time_stats: avg=8279.72ms min=8279.72ms
max=8279.72ms count=1


问:
react-native audio call app without webrtc
I want to add group audio chat facilities in a simple react-native game. Is there any third-party app or something that will handle this. I tried webrtc but I am new so it's become hard for me. So I want a simple solution for this. If there is any easier solution for this It will be helpful for me.

I am using :-

react-native

firebase

node js

答:
As for now, I am developing such an aplication, but I can find any alternantives to webrtc.
You can use some libraries, which are still built on to of webrtc, but they ease life a bit
These include

https://openbase.com/js/react-native-immediate-phone-call (for your
case)

https://openbase.com/js/react-native-webrtc

https://openbase.com/js/simple-peer

https://openbase.com/js/peerjs

https://openbase.com/js/react-native-twilio-video-webrtc

https://openbase.com/js/opentok-react

https://openbase.com/js/discord-rpc

and so on


问:
Is it advisable to write a test case for every class in your program?
Im am just getting introduced to unit testing and test driven development. Thus far, I have only used Junit as testing framework. A question which emerged and for which I have not yet found a definite answer is: how much test cases do I need to write? Do I have to write a test case for every single class in my program? Or is this a stupid question because unit testing implies testing at the lowest (i.e. class) level?

I think writing a test case for every class is probably the more safe way to go (after all the more you test the lower the number of unforeseen bugs). But I was wondering if there are any widely agreed upon strategies regarding the amount of test cases to write?

答: I wouldn't recommend a strict mapping of one test per class. Some classes may not have much worth testing on their own. Some classes may require multiple tests because you want to specify different setups for different cases. You should use a code coverage tool like Cobertura and try to cover as much code as possible. Also you should look at the code you're testing and see what kind of different data should break it, and try to test it with different combinations of sample data (so 100% code coverage is not the end of testing, of course).</p>


问:
Pivot the aggregate: getting wrong result
Table 1:

```<code>CREATE TABLE Main (patient VARCHAR(5), surgery_date date);
INSERT INTO Main VALUES
   ('P01','2018-01-01'),
   ('P02','2019-01-02'),
   ('P03','2019-01-03'),
   ('P04','2020-07-07');
</code>```

Table 2:

```<code>CREATE TABLE Additional (patient VARCHAR(5), record_date date, bpm integer);
INSERT INTO Additional VALUES
   ('P01','2018-01-01',60),
   ('P01','2018-02-01',49),
   ('P01','2018-02-10',52),
   ('P01','2018-03-10',57),
   ('P01','2018-04-10',57),
   ('P02','2019-01-02',46),
   ('P02','2019-02-02',55),
   ('P02','2019-03-02',55),
   ('P03','2019-01-03',60),
   ('P03','2019-02-03',49),
   ('P03','2019-03-03',49),
   ('P04','2021-07-07',71),
   ('P04','2021-08-07',49),
   ('P04','2021-09-07',49);
</code>```

First table has surgery date and second table has bpm readings post surgery......I want to have % of patient having avg bpm (averaged over calendar month) of > 50 in first and second calendar month post surgery. (need to ignore all data after second calendar month of surgery)

This is my attempt:

```<code>SELECT
   FORMAT(surgery_date,'yyyy-MM') as [Month],
   count(*) as [New_Surgery],
   (100*SUM(COALESCE(CASE WHEN b1.bpm>50 THEN 1 ELSE 0 END,0))) as [Month1_percentage],
   (100*SUM(COALESCE(CASE WHEN b2.bpm>50 THEN 1 ELSE 0 END,0))) as [Month2_percentage]
FROM Main a
LEFT JOIN Additional b1 On b1.patient=a.patient and b1.record_date=a.surgery_date
LEFT JOIN Additional b2 On b2.patient=a.patient and b2.record_date=DATEADD(M,1,a.surgery_date)
GROUP BY FORMAT(surgery_date,'yyyy-MM')
</code>```

But this is not giving me what it should.

My expectation is:

```<code>Month   New_Surgery Month1_percentage   Month2_percentage
2018-01 1   100 100
2019-01 2   50  50
2020-07 1   100 0
</code>```

答:
Your JOIN conditions are only returning record at exactly one month or exactly 2 months.I have changed this to include all tests during the first month and all tests during the second month. Also you had forgotten to divide the sum of cases by the number of cases. I have added /COUNT(*).
The small data set means that the results are very simple:0, 50 or 100%.

```<code>SELECT
   FORMAT(surgery_date,'yyyy-MM') as [Month],
   count(*) as [New_Surgery],
   (100*SUM(COALESCE(CASE WHEN b1.bpm>50 THEN 1 ELSE 0 END,0)))/COUNT(*) as [Month1_percentage],
   (100*SUM(COALESCE(CASE WHEN b2.bpm>50 THEN 1 ELSE 0 END,0)))/COUNT(*) as [Month2_percentage]
FROM Main a
LEFT JOIN Additional b1 On b1.patient=a.patient
   and b1.record_date <= DATEADD(month, 1 , surgery_date)
LEFT JOIN Additional b2 On b2.patient=a.patient
   and b2.record_date<=DATEADD(M,2,a.surgery_date)
      and b2.record_date>DATEADD(month, 1 , surgery_date)
GROUP BY FORMAT(surgery_date,'yyyy-MM')
</code>```

This gives:

```
Month   | New_Surgery | Month1_percentage | Month2_percentage
:------ | ----------: | ----------------: | ----------------:
2018-01 |           2 |                50 |               100
2019-01 |           4 |                50 |                50
2020-07 |           1 |                 0 |                 0
```

Body:
Table 1:

CREATE TABLE Main (patient VARCHAR(5), surgery_date date);
INSERT INTO Main VALUES
   ('P01','2018-01-01'),
   ('P02','2019-01-02'),
   ('P03','2019-01-03'),
   ('P04','2020-07-07');

Table 2:

CREATE TABLE Additional (patient VARCHAR(5), record_date date, bpm integer);
INSERT INTO Additional VALUES
   ('P01','2018-01-01',60),
   ('P01','2018-02-01',49),
   ('P01','2018-02-10',52),
   ('P01','2018-03-10',57),
   ('P01','2018-04-10',57),
   ('P02','2019-01-02',46),
   ('P02','2019-02-02',55),
   ('P02','2019-03-02',55),
   ('P03','2019-01-03',60),
   ('P03','2019-02-03',49),
   ('P03','2019-03-03',49),
   ('P04','2021-07-07',71),
   ('P04','2021-08-07',49),
   ('P04','2021-09-07',49);

First table has surgery date and second table has bpm readings post surgery......I want to have % of patient having avg bpm (averaged over calendar month) of > 50 in first and second calendar month post surgery. (need to ignore all data after second calendar month of surgery)

This is my attempt:

SELECT
   FORMAT(surgery_date,'yyyy-MM') as [Month],
   count(*) as [New_Surgery],
   (100*SUM(COALESCE(CASE WHEN b1.bpm>50 THEN 1 ELSE 0 END,0))) as [Month1_percentage],
   (100*SUM(COALESCE(CASE WHEN b2.bpm>50 THEN 1 ELSE 0 END,0))) as [Month2_percentage]
FROM Main a
LEFT JOIN Additional b1 On b1.patient=a.patient and b1.record_date=a.surgery_date
LEFT JOIN Additional b2 On b2.patient=a.patient and b2.record_date=DATEADD(M,1,a.surgery_date)
GROUP BY FORMAT(surgery_date,'yyyy-MM')

But this is not giving me what it should.

My expectation is:

Month   New_Surgery Month1_percentage   Month2_percentage
2018-01 1   100 100
2019-01 2   50  50
2020-07 1   100 0

Body:
Your JOIN conditions are only returning record at exactly one month or exactly 2 months.I have changed this to include all tests during the first month and all tests during the second month. Also you had forgotten to divide the sum of cases by the number of cases. I have added /COUNT(*).
The small data set means that the results are very simple:0, 50 or 100%.

SELECT
   FORMAT(surgery_date,'yyyy-MM') as [Month],
   count(*) as [New_Surgery],
   (100*SUM(COALESCE(CASE WHEN b1.bpm>50 THEN 1 ELSE 0 END,0)))/COUNT(*) as [Month1_percentage],
   (100*SUM(COALESCE(CASE WHEN b2.bpm>50 THEN 1 ELSE 0 END,0)))/COUNT(*) as [Month2_percentage]
FROM Main a
LEFT JOIN Additional b1 On b1.patient=a.patient
   and b1.record_date <= DATEADD(month, 1 , surgery_date)
LEFT JOIN Additional b2 On b2.patient=a.patient
   and b2.record_date<=DATEADD(M,2,a.surgery_date)
      and b2.record_date>DATEADD(month, 1 , surgery_date)
GROUP BY FORMAT(surgery_date,'yyyy-MM')

This gives:

Month   | New_Surgery | Month1_percentage | Month2_percentage
:------ | ----------: | ----------------: | ----------------:
2018-01 |           2 |                50 |               100
2019-01 |           4 |                50 |                50
2020-07 |           1 |                 0 |                 0


问:
Long press to select an option from a dropdown menu
I have to do a long press to select an option from a dropdown menu. I want the selection to be immediate.  How can I solve this problem.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = UITableViewCell()

        cell = countryTableView.dequeueReusableCell(withIdentifier: "countryCell", for: indexPath)
        cell.textLabel?.text = country[indexPath.row]

        return cell
}
</code>```

答:
I found the solution in this link:

didSelectRowAtIndexPath not being called

Is There a UITapestureRecognizer
Have you created a UITapGestureRecognizer on top of your table view?

It’s possible that the UITapGestureRecognizer is swallowing your click events before they reach your table view.

To resolve this, set the cancelsTouchesInView property of the UITapGestureRecognizer to false.

You can also set this in your storyboard by selecting the UITapGestureRecognizer, navigating to the property inspector and unchecking this box:

Body:
I have to do a long press to select an option from a dropdown menu. I want the selection to be immediate.  How can I solve this problem.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = UITableViewCell()

        cell = countryTableView.dequeueReusableCell(withIdentifier: "countryCell", for: indexPath)
        cell.textLabel?.text = country[indexPath.row]

        return cell
}


问:
Gorountines causing a deadlock
I am trying my hands on goroutines and came up this example - https://go.dev/play/p/mWHUmALk-1_K

But I am having this error - fatal error: all goroutines are asleep - deadlock!

I have tried to fix this but no luck. Please how do I fix this?

The error seem to be on lines 15, 23 and 32.

答:
The problem is that your program starts 3 separate goroutines that send to the same channel. And you have only the main goroutine receive from that channel only once. This causes the second channel send (ch <- fmt.Sprintf("...) to block indefinitely. With unbuffered channels you need to do as many receives as you do sends.

One approach to ensure all sends are received would be to use a range loop over the channel.

func getLength(dd []string, wg *sync.WaitGroup) {
    wg.Add(len(dd))
    c := make(chan string)
    for _, d := range dd {
        d1 := d
        go computeLength(d1, c, wg)
    }

    // close c once all goroutines are done to
    // ensure the for-range loop below exits.
    go func() { wg.Wait(); close(c) }()

    // Use for-range loop on the channel to receive all the sends.
    //
    // But note that a for-range loop over a channel exits only
    // when the channel is closed or the loop is exited from within.
    //
    // So to exit you can close c once wg.Wait() returns,
    // that's why there's that extra goroutine above.
    for v := range c {
        fmt.Println(v)
    }
}
```

https://go.dev/play/p/BUb7NHrq2B0

Title: Gorountines causing a deadlock

Body:
The problem is that your program starts 3 separate goroutines that send to the same channel. And you have only the main goroutine receive from that channel only once. This causes the second channel send (ch <- fmt.Sprintf("...) to block indefinitely. With unbuffered channels you need to do as many receives as you do sends.

One approach to ensure all sends are received would be to use a range loop over the channel.

func getLength(dd []string, wg *sync.WaitGroup) {
    wg.Add(len(dd))
    c := make(chan string)
    for _, d := range dd {
        d1 := d
        go computeLength(d1, c, wg)
    }

    // close c once all goroutines are done to
    // ensure the for-range loop below exits.
    go func() { wg.Wait(); close(c) }()

    // Use for-range loop on the channel to receive all the sends.
    //
    // But note that a for-range loop over a channel exits only
    // when the channel is closed or the loop is exited from within.
    //
    // So to exit you can close c once wg.Wait() returns,
    // that's why there's that extra goroutine above.
    for v := range c {
        fmt.Println(v)
    }
}

https://go.dev/play/p/BUb7NHrq2B0


问:
Java Inheritance: Child class not executing
I was practicing inheritance in Java, and faced the following issue:

Code for parent class:

public class FEB7 {
    String address,name;
    void get(String n, String a){
        name = n;
        address = a;
    }

    void show(){
        System.out.println("name is "+name);
        System.out.println("address is " + address);
    }

    public static void main(String args[]) {
        // compile time poly is method overloading, we will look at runtime poly
        FEB7 obj = new FEB7();
        obj.get("name1","address1");
        obj.show();
    }
}
```
<p>Code for child class:</p>
<pre class="lang-java prettyprint-override"><code>public class FEB8 extends FEB7 {
    String regno;

    void get(String r) {
        regno = r;
    }

    void showreg() {
        System.out.println("regno is " + regno);
    }

    public static void main(String args) {
        FEB8 obj1 = new FEB8();
        obj1.get("name2", "address2");
        obj1.get("regno1");
        obj1.show();
        obj1.showreg();
    }
}
</code>```

Both are separate .java files. When I try to execute the parent class file, it works, but for some reason I cannot even run the child class. The following message is there:

The file FEB8.java is not executable. please select a main class you
want to run

How do I solve this issue?

答: The main method in FEB8 has String args as the argument instead of String args[]. Change it to args[] and try again.

Body:
I was practicing inheritance in Java, and faced the following issue:

Code for parent class:

public class FEB7 {
    String address,name;
    void get(String n, String a){
        name = n;
        address = a;
    }

    void show(){
        System.out.println("name is "+name);
        System.out.println("address is " + address);
    }

    public static void main(String args[]) {
        // compile time poly is method overloading, we will look at runtime poly
        FEB7 obj = new FEB7();
        obj.get("name1","address1");
        obj.show();
    }
}

Code for child class:

public class FEB8 extends FEB7 {
    String regno;

    void get(String r) {
        regno = r;
    }

    void showreg() {
        System.out.println("regno is " + regno);
    }

    public static void main(String args) {
        FEB8 obj1 = new FEB8();
        obj1.get("name2", "address2");
        obj1.get("regno1");
        obj1.show();
        obj1.showreg();
    }
}

Both are separate .java files. When I try to execute the parent class file, it works, but for some reason I cannot even run the child class. The following message is there:

The file FEB8.java is not executable. please select a main class you
want to run

How do I solve this issue?


问:
How can I remove resources from a CfnInclude imported CloudFormation stack?
I'm importing an existing Cloudformation stack into CDK using the method described in the AWS documentation.

The imported stack contains resources which I want to remove from AWS, so I'm looking for some delete/remove method in the imported cfnInclude:

    const cfnInclude = new cfn_inc.CfnInclude(this, 'Template', {
      templateFile: 'ExistingTemplate.json'
    });
    // I'm looking for a method like this:
    // cfnInclude.remove('MyResourceName');
```

Is it possible to do this somehow?

答:
Call tryRemoveChild on the underlying Node to remove a child construct by name.

const success = cfnInclude.node.tryRemoveChild('MyFunctionToRemove');  // returns boolean
```

Note this is escape hatch functionality available to all Construct subclasses, not anything specific to CfnInclude.

Body:
I'm importing an existing Cloudformation stack into CDK using the method described in the AWS documentation.

The imported stack contains resources which I want to remove from AWS, so I'm looking for some delete/remove method in the imported cfnInclude:

    const cfnInclude = new cfn_inc.CfnInclude(this, 'Template', {
      templateFile: 'ExistingTemplate.json'
    });
    // I'm looking for a method like this:
    // cfnInclude.remove('MyResourceName');

Is it possible to do this somehow?

Body:
Call tryRemoveChild on the underlying Node to remove a child construct by name.

const success = cfnInclude.node.tryRemoveChild('MyFunctionToRemove');  // returns boolean

Note this is escape hatch functionality available to all Construct subclasses, not anything specific to CfnInclude.


问:
help with event click
I'm developing a html with this structure

```<code>div id="menuContainer">
    <div class = "menu ui-accordion-header ui-state-default ui-corner-all">
        <label class="formatText">Cliente</label><span class="ui-icon ui-icon-triangle-1-e menuIcon" style="float: right"></span>
            <div class = "subMenu ui-accordion-header ui-state-default ui-corner-all">
                <ul class="options">
                    <li>
                        <label class="formatText">Ver Cliente</label><span class="ui-icon ui-icon-triangle-1-e" style="float: right"></span>
                            <div class = "subMenuRight ui-accordion-header ui-state-default ui-corner-all">
                                <ul class="options">
                                    <li>
                                        <label class="formatText">Por Nombre</label><span class="ui-icon ui-icon-triangle-1-e" style="float: right"></span>
                                            <div class = "subMenuRight ui-accordion-header ui-state-default ui-corner-all">
                                                <ul class="options">
                                                    <li><label class="formatText">sub sub menu</label></li>
                                                    <li><label class="formatText">prueba</label></li>
                                                </ul>
                                            </div>
                                    </li>
                                    <li>
                                        <label class="formatText">Por Campana</label>
                                    </li>
                                </ul>
                            </div>
                    </li>
                    <li>
                        <label class="formatText">Reportes para Cliente</label>
                    </li>
                </ul>
            </div>
    </div>
</div>
</code>```

notice that the principal div have class called menu, in the inside there are a some divs that with a classes called subMenu and subMenuRight, my problem it's that i want associate a event click to the father and other behavior to the divs children i tried like this

```<code>$(".menu").click(function () {
    alert('click in the father');
});
$(".subMenu li").click(function () {
    alert('click in the first child');
});
$(".subMenuRight li").click(function () {
    alert('click in the second child');
});
</code>```

The problem with this code it's that div father contains the divs children all the event handler are triggered. So my question is How can I modify the selector or validate the in the event handler for to only fire the exactly element that is clicked??

答:
use event.stopPropagation() for all the click handlers e.g.

```<code>$(".menu").click(function (e) {
    e.stopPropagation()
    alert('click in the father');
});
</code>```

here is the fiddle http://jsfiddle.net/yFFGS/

Title: help with event click

Body:
I'm developing a html with this structure

div id="menuContainer">

        Cliente

                        Ver Cliente

                                        Por Nombre

sub sub menu

prueba

                                        Por Campana

                        Reportes para Cliente

notice that the principal div have class called menu, in the inside there are a some divs that with a classes called subMenu and subMenuRight, my problem it's that i want associate a event click to the father and other behavior to the divs children i tried like this

$(".menu").click(function () {
    alert('click in the father');
});
$(".subMenu li").click(function () {
    alert('click in the first child');
});
$(".subMenuRight li").click(function () {
    alert('click in the second child');
});

The problem with this code it's that div father contains the divs children all the event handler are triggered. So my question is How can I modify the selector or validate the in the event handler for to only fire the exactly element that is clicked??

Body:
use event.stopPropagation() for all the click handlers e.g.

$(".menu").click(function (e) {
    e.stopPropagation()
    alert('click in the father');
});

here is the fiddle http://jsfiddle.net/yFFGS/


问:
Why do I get this message (Set -DfailIfNoTests=false to ignore this error.) while running my test code?
I am using maven while building my java project, and I am using JUnit5 framework to test, when I tried to running the test code, I got this message:

```<code>Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test (default-cli) on project transaction-processor: No tests were executed!  (Set -DfailIfNoTests=false to ignore this error.) -> [Help 1]
</code>```

this is the POM.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.progressoft.induction</groupId>
    <artifactId>transaction-processor</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <testFailureIgnore>false</testFailureIgnore>
                    <source>1.8</source>
                    <target>1.8</target>

                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
       <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.6.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
        </dependency>
    </dependencies>

</project>
</code>```

How can I solve this, and what is the problem?

答:
I added the following plugin info in POM file that solved the problem.</p>
```<code>            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M5</version>
            </plugin>
</code>```

Body:
I am using maven while building my java project, and I am using JUnit5 framework to test, when I tried to running the test code, I got this message:

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test (default-cli) on project transaction-processor: No tests were executed!  (Set -DfailIfNoTests=false to ignore this error.) -> [Help 1]

this is the POM.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.progressoft.induction</groupId>
    <artifactId>transaction-processor</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <testFailureIgnore>false</testFailureIgnore>
                    <source>1.8</source>
                    <target>1.8</target>

                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
       <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.6.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
        </dependency>
    </dependencies>

</project>

How can I solve this, and what is the problem?

Body:
I added the following plugin info in POM file that solved the problem.

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M5</version>
            </plugin>


答:
You can't use if statement inside the dict.

But, this will get your work done.

```<code>eventBody = {
      'Name': name,
      'location': location,
      'description':description,
      }
if eventColor:
    eventBody.update(Color=eventColor)
</code>```

Body:
My code looks like this:

def createEventBody(name,description,attendees,location, eventColor = None):
    eventBody = {
              'Name': name, #EventName
              'Color': eventColor,
              'location': location,
              'description':description,
              'attendees': [],
              }

The thing is, I want to add some logic so that the key 'Color' is not included if eventColor = None.
I was thinking something like this:

def createEventBody(name,description,attendees,location, eventColor = None):
    eventBody = {
              'Name': name, #EventName
              ('Color': eventColor) if eventColor != None else pass,
              'location': location,
              'description':description,
              'attendees': [],
              }

However 'pass' doesn't allow me to "skip" that key.
How could I fix this?

Body:
You can't use if statement inside the dict.

But, this will get your work done.

eventBody = {
      'Name': name,
      'location': location,
      'description':description,
      }
if eventColor:
    eventBody.update(Color=eventColor)