问:
asking permission on flutter creates new instance of page after accepting
For my flutter app, I have to request permission for the camera feed.
For this, I use the permission_handler module for this.

after calling the code below and accepting the permission a new instance of the same page is created and the old page still exists.
how can I stop the system from creating the new page?

```<code> Future<void> askPermissionBeforeHand() async{
    final PermissionHandler _permissionHandler = PermissionHandler();
    final permissionStatus = await _permissionHandler.checkPermissionStatus(PermissionGroup.camera);
    if (permissionStatus != PermissionStatus.granted) {
      var result = await _permissionHandler.requestPermissions([PermissionGroup.camera]);
    }
  }
</code>```

```<code>    import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:zorg_nl/core/utils/ui_utils.dart';
import 'package:zorg_nl/l10n/ionicons.dart';
import 'package:zorg_nl/locator.dart';
import 'package:zorg_share/colors.dart';
import 'package:zorg_share/components/molecules/header_icon_molecule.dart';
import 'package:zorg_nl/ui/widgets/wp_rounded_button.dart';

class RegistrationValidationInfo extends StatelessWidget {
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();

  void onFindHealthCareProviders(BuildContext context) {
    Locator.analytics().logSelectContent(contentType: 'button', itemId: 'registration_search_providers');
    UiUtils.navigateByTag(context: context,pushPath: '/providers');
  }

  Future<void> onHelp() async {
    await UiUtils.sendHelpAnalytics('registration_provider');
    await UiUtils.openWebsite('http://www.zorg.nl');
  }

  Future<void> askPermissionBeforeHand() async{
    final PermissionHandler _permissionHandler = PermissionHandler();
    final permissionStatus = await _permissionHandler.checkPermissionStatus(PermissionGroup.camera);
    if (permissionStatus != PermissionStatus.granted) {
      var result = await _permissionHandler.requestPermissions([PermissionGroup.camera]);
    }
  }

  @override
  Widget build(BuildContext context) {
    Locator.analytics().setCurrentScreen(screenName: 'VerifyHealthCareProvider');
    askPermissionBeforeHand();
    return Scaffold(
      backgroundColor: colorWhite,
      key: scaffoldKey,
      resizeToAvoidBottomInset: false,
      body: SafeArea(minimum: EdgeInsets.symmetric(horizontal: 16),
          child: Stack(children: <Widget>[
            Positioned(bottom: 10,
                left: 0, right: 0,child: Column(children: <Widget>[
              materialCareButton(context,
                  text: 'register_provider_care_provider',
                  iconData: IonIcons.ios_navigate,
                  color: colorPrimaryColor,
                  onPressed:() => onFindHealthCareProviders(context)),
              Container(height: 5),
              materialCareButton(context,
                  text: 'generic_need_help',
                  textColor: colorPrimaryColor,
                  onPressed: onHelp),
            ])),
            const Padding(
              padding: EdgeInsets.fromLTRB(16, 40, 16, 0),
              child: HeaderIcon(
                title: 'register_provider_title',
                subHeader: 'register_provider_sub_header',
                icon: IconData(0xe801, fontFamily: 'material'), // policy
              ),
            ),
          ],)
      ),
    );
  }
}
</code>```

答:
I solved the problem a few weeks ago but forgot to post the answer.
The problem wasn't what you would expect and was the continuation of a problem from another page.
On this page, I used the WidgetsBindingObserver to listen for changes in the lifecycle of the app and moved on to the next page with a Push if the validation was correct on the app's resume lifecycle. As you know previous pages in flutter are not directly cleaned or put on the stack like in Android. They are still alive and just below the currently visible page. So when I asked flutter to show a Dialog the OnResume function was called on my previous page and pushed a new Page to the screen and after this pushed the Dialog.

The solution for this was to Pop my last page and Push the new page afterward. In my case, I didn't need the page anymore. If you still need the page you can remove the listener on the WidgetsBindingObserver and reattach it when you Pop back to the page.

Body:
For my flutter app, I have to request permission for the camera feed.
For this, I use the permission_handler module for this.

after calling the code below and accepting the permission a new instance of the same page is created and the old page still exists.
how can I stop the system from creating the new page?

 Future<void> askPermissionBeforeHand() async{
    final PermissionHandler _permissionHandler = PermissionHandler();
    final permissionStatus = await _permissionHandler.checkPermissionStatus(PermissionGroup.camera);
    if (permissionStatus != PermissionStatus.granted) {
      var result = await _permissionHandler.requestPermissions([PermissionGroup.camera]);
    }
  }

    import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:zorg_nl/core/utils/ui_utils.dart';
import 'package:zorg_nl/l10n/ionicons.dart';
import 'package:zorg_nl/locator.dart';
import 'package:zorg_share/colors.dart';
import 'package:zorg_share/components/molecules/header_icon_molecule.dart';
import 'package:zorg_nl/ui/widgets/wp_rounded_button.dart';

class RegistrationValidationInfo extends StatelessWidget {
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();

  void onFindHealthCareProviders(BuildContext context) {
    Locator.analytics().logSelectContent(contentType: 'button', itemId: 'registration_search_providers');
    UiUtils.navigateByTag(context: context,pushPath: '/providers');
  }

  Future<void> onHelp() async {
    await UiUtils.sendHelpAnalytics('registration_provider');
    await UiUtils.openWebsite('http://www.zorg.nl');
  }

  Future<void> askPermissionBeforeHand() async{
    final PermissionHandler _permissionHandler = PermissionHandler();
    final permissionStatus = await _permissionHandler.checkPermissionStatus(PermissionGroup.camera);
    if (permissionStatus != PermissionStatus.granted) {
      var result = await _permissionHandler.requestPermissions([PermissionGroup.camera]);
    }
  }

  @override
  Widget build(BuildContext context) {
    Locator.analytics().setCurrentScreen(screenName: 'VerifyHealthCareProvider');
    askPermissionBeforeHand();
    return Scaffold(
      backgroundColor: colorWhite,
      key: scaffoldKey,
      resizeToAvoidBottomInset: false,
      body: SafeArea(minimum: EdgeInsets.symmetric(horizontal: 16),
          child: Stack(children: <Widget>[
            Positioned(bottom: 10,
                left: 0, right: 0,child: Column(children: <Widget>[
              materialCareButton(context,
                  text: 'register_provider_care_provider',
                  iconData: IonIcons.ios_navigate,
                  color: colorPrimaryColor,
                  onPressed:() => onFindHealthCareProviders(context)),
              Container(height: 5),
              materialCareButton(context,
                  text: 'generic_need_help',
                  textColor: colorPrimaryColor,
                  onPressed: onHelp),
            ])),
            const Padding(
              padding: EdgeInsets.fromLTRB(16, 40, 16, 0),
              child: HeaderIcon(
                title: 'register_provider_title',
                subHeader: 'register_provider_sub_header',
                icon: IconData(0xe801, fontFamily: 'material'), // policy
              ),
            ),
          ],)
      ),
    );
  }
}


来源: stackexchange

问:
React & Typescript, styled components & children
I've tried so many different combinations to get this to work, but it's not applying the styles I've written for the StyledLines component, by them selves they work fine! Using the StyledLines component as a child, it doesn't work. The Target component styles work as expected.

```<code>import React, { Fragment, FunctionComponent } from 'react';
import styled from '@emotion/styled';

interface Crosshair {
  size: number;
  thickness: number;
}

const Target = styled.div<Crosshair>`
  position:absolute;
  &:before {
    content: '';
    display:block;
    position:absolute;
    top:50%;
    left:50%;
    background-color:transparent;
    border-color:#2fd5d5;
    margin-left:-${({size}) => size / 4}px;
    margin-top:-${({thickness}) => thickness / 4}px;
    width:${({size}) => size / 2}px;
    height:${({thickness}) => thickness / 2}px;
  }
`;

const Lines: FunctionComponent = ({children}) => <div className="line">{children}</div>;

const StyledLines = styled(Lines)<Crosshair>`
  position:absolute;
  &:nth-of-type(1) {
    top:0;
    left:0;
  }
  &:nth-of-type(2) {
    top:0;
    right:0;
  }
  &:nth-of-type(3) {
    bottom:0;
    right:0;
  }
  &:nth-of-type(4) {
    bottom:0;
    left:0;
  }
  &:after, &:before {
    content: '';
    display:block;
    position:absolute;
    top:50%;
    left:50%;
    background:#2fd5d5;
    margin-left:-${({size = 2}) => size / 2}px;
    margin-top:-${({thickness = 24}) => thickness / 2}px;
    width:${({size = 2}) => size}px;
    height:${({thickness = 24}) => thickness}px;
  }
  &:before {
    transform: rotateZ(90deg);
  }
`;

export default function Crosshairs() {
  return <Fragment>
    <div>
      {[0,1,2,3].map(i => <StyledLines key={i} size={24} thickness={2}>
        <Target size={24} thickness={2} />
      </StyledLines>)}
    </div>
  </Fragment>;
}
</code>```

答:
Lines is a plain React component, not a styled component, so you have to pass the className prop to the DOM part you want to style:

```<code>const Lines: FunctionComponent = ({children, className}) => <div className={`line ${className}`}>{children}</div>;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've tried so many different combinations to get this to work, but it's not applying the styles I've written for the StyledLines component, by them selves they work fine! Using the StyledLines component as a child, it doesn't work. The Target component styles work as expected.

import React, { Fragment, FunctionComponent } from 'react';
import styled from '@emotion/styled';

interface Crosshair {
  size: number;
  thickness: number;
}

const Target = styled.div<Crosshair>`
  position:absolute;
  &:before {
    content: '';
    display:block;
    position:absolute;
    top:50%;
    left:50%;
    background-color:transparent;
    border-color:#2fd5d5;
    margin-left:-${({size}) => size / 4}px;
    margin-top:-${({thickness}) => thickness / 4}px;
    width:${({size}) => size / 2}px;
    height:${({thickness}) => thickness / 2}px;
  }
`;

const Lines: FunctionComponent = ({children}) =>
{children}
;

const StyledLines = styled(Lines)<Crosshair>`
  position:absolute;
  &:nth-of-type(1) {
    top:0;
    left:0;
  }
  &:nth-of-type(2) {
    top:0;
    right:0;
  }
  &:nth-of-type(3) {
    bottom:0;
    right:0;
  }
  &:nth-of-type(4) {
    bottom:0;
    left:0;
  }
  &:after, &:before {
    content: '';
    display:block;
    position:absolute;
    top:50%;
    left:50%;
    background:#2fd5d5;
    margin-left:-${({size = 2}) => size / 2}px;
    margin-top:-${({thickness = 24}) => thickness / 2}px;
    width:${({size = 2}) => size}px;
    height:${({thickness = 24}) => thickness}px;
  }
  &:before {
    transform: rotateZ(90deg);
  }
`;

export default function Crosshairs() {
  return <Fragment>

      {[0,1,2,3].map(i => )}

  </Fragment>;
}

Body:
Lines is a plain React component, not a styled component, so you have to pass the className prop to the DOM part you want to style:

const Lines: FunctionComponent = ({children, className}) => <div className={`line ${className}`}>{children}</div>;


问:
What project would you recommend me to get up to speed with C++
I know that C++ is a very complex language that takes many years of practice to master.

Taking that into account do you know of a small project (around a 1k of loc) that tests all of C++ major features (inheritance, pointers, memory management, etc).

The thing is I'm a Java/Python programmer and I really want to learn C++ so I've been studying C++ for a while but haven't tested anything of what I've learned beyond small exercises.

I want to take all of that knowledge and put into practice.

答:
Effective C++ and More Effective C++

Other than that, pick a (small?) personal project you want to write and do it in C++.  You are not going to learn C++ by reading a 1000 line project.

OwnerDisplayName: climatewarrior

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Tim

ContentLicense: CC BY-SA 2.5


问:
In RxJava, what is difference between RxJavaPlugins.setErrorHandler and Subscribe onError?
It seems that there are two kinds of error in RxJava:

Errors caught by a subscriber in onError

And errors caught globally by the handler set by RxJavaPlugins.setErrorHandler

I am having some trouble understanding why this is. Questions:

What was the rationale behind having two handlers for errors?

What causes an error to be sent to one handler vs the other?

How can I ensure that errors are only sent to onError?

答:
Subscribe onError() handles the errors that are emitted before the stream reaches its terminal state. For errors emitted after the stream terminates or after it gets cancelled rxjava defaults to printing the stacktrace to the console and calling the uncaught exception handler i.e crashing. RxJavaPlugins.setErrorHandler(...) therefore is necessary to handle these undeliverable exceptions on a global scope.

Reference:
https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling

https://github.com/ReactiveX/RxJava/issues/5425


问:
use loop to check the files in directory and add the files that have the same date on the filename to a zip folder
I need to check the files in the directory which all the files have the format like filename_20200219 and zip all the files which have the same date based on the date from the filename. How can this be done?

For example, a_20200219, b_20200219, c_20200220, d_20200220

The output after zipping should be:

a_20200219 and b_20200219 in a zip folder

c_20200220 and d_20200220 in another zip folder.

Thanks in advance.

答:
Use Directory.EnumerateFiles(path) to retrieve all the files in a directory.
Than Path.GetFileNameWithoutExtension(filePath) to get its name.
Than split it on the '_' with var elements = fileName.Split('_');.
At position 1 there will be the date var date = elements[1];.
So now you can group files having the same date.

To be able to create a zip file you need to create a new directory and copy there your files having the same date.

I hope I was helpful


问:
Getting 'str.indexOf is not a function' error when trying to S3.getSignedUrl()
While trying to get a signed URL for a getObject I am getting the following error from the aws-sdk library:

```<code><proj-dir>\node_modules\aws-sdk\lib\util.js:983
      return str && str.indexOf('arn:') === 0 && str.split(':').length >= 6;
                        ^

TypeError: str.indexOf is not a function
    at Object.validateARN [as validate] (<proj-dir>\node_modules\aws-sdk\lib\util.js:983:25)
    at features.constructor.hasBucketInParams [as isAccessPointApplicable] (<proj-dir>\node_modules\aws-sdk\lib\services\s3.js:180:2
3)
    at features.constructor.setupRequestListeners (<proj-dir>\node_modules\aws-sdk\lib\services\s3.js:126:14)
    at features.constructor.addAllRequestListeners (<proj-dir>\node_modules\aws-sdk\lib\service.js:276:10)
    at features.constructor.makeRequest (<proj-dir>\node_modules\aws-sdk\lib\service.js:203:10)
    at features.constructor.getSignedUrl (<proj-dir>\node_modules\aws-sdk\lib\services\s3.js:1026:24)
    at Object.<anonymous> (<proj-dir>\s3-test.js:101:8)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
</code>```

Other S3 calls (like listBuckets) are working fine. Here's my test file:

```<code>const S3 = require('./utils/s3Util');
const C = require('./utils/constants');
const _ = require('lodash');

// other code...

S3.svc.getSignedUrl('getObject', { Bucket: C.S3_BUCKET, Key: 'TestFrequencyCount.java', Expires: 60 }).promise()
    .then(retVal => {
        console.log("Return value:", retVal);
    }).catch(err => {
        console.log("Error::", err);
    });
</code>```

The s3Util.js file:

```<code>const C = require('./constants');
const AWS = require('aws-sdk');
const keys = require("../config/aws-config.json");

// AWS.config.update(keys);

const s3 = new AWS.S3({...keys, apiVersion: C.S3_API_VER, signatureVersion: 'v4' });

module.exports = Object.freeze({
    svc: s3,
});
</code>```

I was using aws-sdk version 2.610.0, then updated that to 2.621.0, but the problem remains.

Even tried by changing the way I was loading the AWS account credentials (will use an IAM user once I have things figured out) based on a combination of this note from AWS SDK documentation:

Note: You must ensure that you have static or previously resolved
credentials if you call this method synchronously (with no callback),
otherwise it may not properly sign the request. If you cannot
guarantee this (you are using an asynchronous credential provider,
i.e., EC2 IAM roles), you should always call this method with an
asynchronous callback.

and the solution given at Node.js and aws credentials error - json (which suggested not using AWS.config.loadFromPath(path) but instead loading the parameters directly through AWS.config.update(...)), but to no avail.

In deseparation I tried the callback version as well, but as expected it gave the same result:

```<code>S3.svc.getSignedUrl('getObject', { Bucket: C.S3_BUCKET, Key: 'TestFrequencyCount.java', Expires: 60 }, (err, retVal) => {
    if (err) {
        console.log("Error::", err);
    } else {
        console.log("Return value:", retVal);
    }
});
</code>```

答: str variable is probably an object, not a string or array, so indexOf method cannot be applied to it. Use console.log(str) to confirm this.

Body:
While trying to get a signed URL for a getObject I am getting the following error from the aws-sdk library:

<proj-dir>\node_modules\aws-sdk\lib\util.js:983
      return str && str.indexOf('arn:') === 0 && str.split(':').length >= 6;
                        ^

TypeError: str.indexOf is not a function
    at Object.validateARN [as validate] (<proj-dir>\node_modules\aws-sdk\lib\util.js:983:25)
    at features.constructor.hasBucketInParams [as isAccessPointApplicable] (<proj-dir>\node_modules\aws-sdk\lib\services\s3.js:180:2
3)
    at features.constructor.setupRequestListeners (<proj-dir>\node_modules\aws-sdk\lib\services\s3.js:126:14)
    at features.constructor.addAllRequestListeners (<proj-dir>\node_modules\aws-sdk\lib\service.js:276:10)
    at features.constructor.makeRequest (<proj-dir>\node_modules\aws-sdk\lib\service.js:203:10)
    at features.constructor.getSignedUrl (<proj-dir>\node_modules\aws-sdk\lib\services\s3.js:1026:24)
    at Object.<anonymous> (<proj-dir>\s3-test.js:101:8)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)

Other S3 calls (like listBuckets) are working fine. Here's my test file:

const S3 = require('./utils/s3Util');
const C = require('./utils/constants');
const _ = require('lodash');

// other code...

S3.svc.getSignedUrl('getObject', { Bucket: C.S3_BUCKET, Key: 'TestFrequencyCount.java', Expires: 60 }).promise()
    .then(retVal => {
        console.log("Return value:", retVal);
    }).catch(err => {
        console.log("Error::", err);
    });

The s3Util.js file:

const C = require('./constants');
const AWS = require('aws-sdk');
const keys = require("../config/aws-config.json");

// AWS.config.update(keys);

const s3 = new AWS.S3({...keys, apiVersion: C.S3_API_VER, signatureVersion: 'v4' });

module.exports = Object.freeze({
    svc: s3,
});

I was using aws-sdk version 2.610.0, then updated that to 2.621.0, but the problem remains.

Even tried by changing the way I was loading the AWS account credentials (will use an IAM user once I have things figured out) based on a combination of this note from AWS SDK documentation:

Note: You must ensure that you have static or previously resolved
credentials if you call this method synchronously (with no callback),
otherwise it may not properly sign the request. If you cannot
guarantee this (you are using an asynchronous credential provider,
i.e., EC2 IAM roles), you should always call this method with an
asynchronous callback.

and the solution given at Node.js and aws credentials error - json (which suggested not using AWS.config.loadFromPath(path) but instead loading the parameters directly through AWS.config.update(...)), but to no avail.

In deseparation I tried the callback version as well, but as expected it gave the same result:

S3.svc.getSignedUrl('getObject', { Bucket: C.S3_BUCKET, Key: 'TestFrequencyCount.java', Expires: 60 }, (err, retVal) => {
    if (err) {
        console.log("Error::", err);
    } else {
        console.log("Return value:", retVal);
    }
});


问:
Creating Laravel repositories and binding as service providers
I have a Symfony and Spring background, this is my first project with Laravel and as far as I understood Laravel doesn't have a build-in support for repositories. I found several tutorials; some of them try to offer architecture like Spring or Symfony.

As an example this blog suggests an folder structure like this:

```<code>---- Repository
------ Eloquent
-------- UserRepository.php // extends BaseRepository
-------- BaseRepository.php // implements EloquentRepositoryInterface
------ UserRepositoryInterface.php
------ EloquentRepositoryInterface.php
</code>```

which is not bad. The point I'm confused is, the author suggests to bind these repositories as service providers and access them in controller as providers.

```<code>class RepositoryServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(EloquentRepositoryInterface::class, BaseRepository::class);
        $this->app->bind(UserRepositoryInterface::class, UserRepository::class);
    }
}
</code>```

Than I decided to find a library in Github which focuses on creating an Eloquent Repository, which directly consumes User repository in controller:

```<code>class HomeController extends Controller
{
    public function index(UserRepository $userRepository)
    {
        return $userRepository->get();
        ...
</code>```

From architectural perspective, do we need to bind repositories as providers? (Let's think the fact that AWS or Elastic Search may join the project and repositories may vary for a single model)

And most importantly why doesn't Laravel have a built-in repository pattern support?
Thank you

答:
From Laravel Repository Pattern – How to use & why it matters

The last step is to register this service provider in our config/app.php. Open this file and add to providers our provider App\Providers\RepositoryServiceProvider::class

Now our application knows what class it should use when we type an
  objects by its interfaces.

This is why you need to bind your interfaces like that:

```<code>/**
* Register services.
*
* @return void
*/
public function register()
{
   $this->app->bind(EloquentRepositoryInterface::class, BaseRepository::class);
   $this->app->bind(UserRepositoryInterface::class, UserRepository::class);
}
</code>```

In order to let Laravel knows about what to instantiate when you do in your controller:

```<code>private $userRepository;

public function __construct(UserRepositoryInterface $userRepository)
{
   $this->userRepository = $userRepository;
}
</code>```

[EDIT 1]

Also there is a great article from the Laravel documentation for Dependency Injection: laravel.com/docs/master/controllers#dependency-injection-and-controllers

Body:
I have a Symfony and Spring background, this is my first project with Laravel and as far as I understood Laravel doesn't have a build-in support for repositories. I found several tutorials; some of them try to offer architecture like Spring or Symfony.

As an example this blog suggests an folder structure like this:

---- Repository
------ Eloquent
-------- UserRepository.php // extends BaseRepository
-------- BaseRepository.php // implements EloquentRepositoryInterface
------ UserRepositoryInterface.php
------ EloquentRepositoryInterface.php

which is not bad. The point I'm confused is, the author suggests to bind these repositories as service providers and access them in controller as providers.

class RepositoryServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(EloquentRepositoryInterface::class, BaseRepository::class);
        $this->app->bind(UserRepositoryInterface::class, UserRepository::class);
    }
}

Than I decided to find a library in Github which focuses on creating an Eloquent Repository, which directly consumes User repository in controller:

class HomeController extends Controller
{
    public function index(UserRepository $userRepository)
    {
        return $userRepository->get();
        ...

From architectural perspective, do we need to bind repositories as providers? (Let's think the fact that AWS or Elastic Search may join the project and repositories may vary for a single model)

And most importantly why doesn't Laravel have a built-in repository pattern support?
Thank you

Body:
From Laravel Repository Pattern – How to use & why it matters

The last step is to register this service provider in our config/app.php. Open this file and add to providers our provider App\Providers\RepositoryServiceProvider::class

Now our application knows what class it should use when we type an
  objects by its interfaces.

This is why you need to bind your interfaces like that:

/**
* Register services.
*
* @return void
*/
public function register()
{
   $this->app->bind(EloquentRepositoryInterface::class, BaseRepository::class);
   $this->app->bind(UserRepositoryInterface::class, UserRepository::class);
}

In order to let Laravel knows about what to instantiate when you do in your controller:

private $userRepository;

public function __construct(UserRepositoryInterface $userRepository)
{
   $this->userRepository = $userRepository;
}

[EDIT 1]

Also there is a great article from the Laravel documentation for Dependency Injection: laravel.com/docs/master/controllers#dependency-injection-and-controllers


问:
STM8A CAN Filtering in Standard Peripheral Library
I am working with the STM8AF5286UDY and am trying to set up a CAN interface.
For programming, I use the standard peripheral library. At the moment, my CAN interface works fine. The only thing, which does not work, is filtering.

I use extended IDs and want to get all IDs from 0x18FEC100 to 0x18FEC999.
My code looks as follows:

```<code>/* CAN filter init */

 CAN_FilterNumber = CAN_FilterNumber_0;

 CAN_FilterActivation = ENABLE;

 CAN_FilterMode = CAN_FilterMode_IdMask;

 CAN_FilterScale = CAN_FilterScale_32Bit;

 CAN_FilterID1=0x18FEC101;

 CAN_FilterID2=0;

 CAN_FilterID3=0;

 CAN_FilterID4=0;

 CAN_FilterIDMask1=0x1FFFF000;

 CAN_FilterIDMask2=0;

 CAN_FilterIDMask3=0;

 CAN_FilterIDMask4=0;

 CAN_FilterInit(CAN_FilterNumber, CAN_FilterActivation, CAN_FilterMode,
         CAN_FilterScale,CAN_FilterID1, CAN_FilterID2, CAN_FilterID3,
         CAN_FilterID4,CAN_FilterIDMask1, CAN_FilterIDMask2,
         CAN_FilterIDMask3, CAN_FilterIDMask4);
</code>```

I would appreciate any help! Thank you!

EDIT: In my initial code, I forgot to include IDE and RTR at addressing. Also, in the library, each address and mask is an 8-bit value. Therefore, I have changed my code to the following:

```<code>/* CAN filter init */
  CAN_FilterNumber = CAN_FilterNumber_2;
  CAN_FilterActivation = ENABLE;
  CAN_FilterMode = CAN_FilterMode_IdMask;
  CAN_FilterScale = CAN_FilterScale_32Bit;
  CAN_FilterID1=0xc7;
  CAN_FilterID2=0xed;
  CAN_FilterID3=0x02;
  CAN_FilterID4=0x02;
  CAN_FilterIDMask1=0xFF;
  CAN_FilterIDMask2=0xE7;
  CAN_FilterIDMask3=0xE0;
  CAN_FilterIDMask4=0x00;
  CAN_FilterInit(CAN_FilterNumber, CAN_FilterActivation, CAN_FilterMode,
                 CAN_FilterScale,CAN_FilterID1, CAN_FilterID2, CAN_FilterID3,
                 CAN_FilterID4,CAN_FilterIDMask1, CAN_FilterIDMask2,
                 CAN_FilterIDMask3, CAN_FilterIDMask4);
</code>```

This filter works for the first 16-bit, so at using 0x18FEC101 it filters the 0x18FE. Somehow, it does not work for the other 16-bit.

In the library, the following code is used for writing the addresses and masks in the filter bank at 32-bit:

```<code>else if (CAN_FilterScale == CAN_FilterScale_32Bit)
    {
      CAN->Page.Filter.FR01 = CAN_FilterID1;
      CAN->Page.Filter.FR02 = CAN_FilterID2;
      CAN->Page.Filter.FR03 = CAN_FilterID3;
      CAN->Page.Filter.FR04 = CAN_FilterID4;
      CAN->Page.Filter.FR05 = CAN_FilterIDMask1;
      CAN->Page.Filter.FR06 = CAN_FilterIDMask2;
      CAN->Page.Filter.FR07 = CAN_FilterIDMask3;
      CAN->Page.Filter.FR08 = CAN_FilterIDMask4;
    }
</code>```

Are there any ideas, what my mistake might be?
Thanks!

答:
Mask filtering works bitwise. So you can't create a filter to accept values between 0x18FEC100 - 0x18FEC999. You need to think binary.

In the filter mask registers, 1 means "must match" and 0 means "don't care".

ID = 0x18FEC101 and Mask = 0x1FFFF000 means that it will accept values between 0x18FEC000 - 0x18FECFFF as the filter won't care the least significant 12 bits.

However, the process is further complicated by the bit arrangement of the hardware registers. Be aware that RTR & IDE bits are also included in the filter registers. I don't know if the standard peripheral library handles this but probably not. You probably need to manually arrange the bits to determine the correct register values. In the reference manual (RM0016), refer to Figure 148.

Body:
I am working with the STM8AF5286UDY and am trying to set up a CAN interface.
For programming, I use the standard peripheral library. At the moment, my CAN interface works fine. The only thing, which does not work, is filtering.

I use extended IDs and want to get all IDs from 0x18FEC100 to 0x18FEC999.
My code looks as follows:

/* CAN filter init */

 CAN_FilterNumber = CAN_FilterNumber_0;

 CAN_FilterActivation = ENABLE;

 CAN_FilterMode = CAN_FilterMode_IdMask;

 CAN_FilterScale = CAN_FilterScale_32Bit;

 CAN_FilterID1=0x18FEC101;

 CAN_FilterID2=0;

 CAN_FilterID3=0;

 CAN_FilterID4=0;

 CAN_FilterIDMask1=0x1FFFF000;

 CAN_FilterIDMask2=0;

 CAN_FilterIDMask3=0;

 CAN_FilterIDMask4=0;

 CAN_FilterInit(CAN_FilterNumber, CAN_FilterActivation, CAN_FilterMode,
         CAN_FilterScale,CAN_FilterID1, CAN_FilterID2, CAN_FilterID3,
         CAN_FilterID4,CAN_FilterIDMask1, CAN_FilterIDMask2,
         CAN_FilterIDMask3, CAN_FilterIDMask4);

I would appreciate any help! Thank you!

EDIT: In my initial code, I forgot to include IDE and RTR at addressing. Also, in the library, each address and mask is an 8-bit value. Therefore, I have changed my code to the following:

/* CAN filter init */
  CAN_FilterNumber = CAN_FilterNumber_2;
  CAN_FilterActivation = ENABLE;
  CAN_FilterMode = CAN_FilterMode_IdMask;
  CAN_FilterScale = CAN_FilterScale_32Bit;
  CAN_FilterID1=0xc7;
  CAN_FilterID2=0xed;
  CAN_FilterID3=0x02;
  CAN_FilterID4=0x02;
  CAN_FilterIDMask1=0xFF;
  CAN_FilterIDMask2=0xE7;
  CAN_FilterIDMask3=0xE0;
  CAN_FilterIDMask4=0x00;
  CAN_FilterInit(CAN_FilterNumber, CAN_FilterActivation, CAN_FilterMode,
                 CAN_FilterScale,CAN_FilterID1, CAN_FilterID2, CAN_FilterID3,
                 CAN_FilterID4,CAN_FilterIDMask1, CAN_FilterIDMask2,
                 CAN_FilterIDMask3, CAN_FilterIDMask4);

This filter works for the first 16-bit, so at using 0x18FEC101 it filters the 0x18FE. Somehow, it does not work for the other 16-bit.

In the library, the following code is used for writing the addresses and masks in the filter bank at 32-bit:

else if (CAN_FilterScale == CAN_FilterScale_32Bit)
    {
      CAN->Page.Filter.FR01 = CAN_FilterID1;
      CAN->Page.Filter.FR02 = CAN_FilterID2;
      CAN->Page.Filter.FR03 = CAN_FilterID3;
      CAN->Page.Filter.FR04 = CAN_FilterID4;
      CAN->Page.Filter.FR05 = CAN_FilterIDMask1;
      CAN->Page.Filter.FR06 = CAN_FilterIDMask2;
      CAN->Page.Filter.FR07 = CAN_FilterIDMask3;
      CAN->Page.Filter.FR08 = CAN_FilterIDMask4;
    }

Are there any ideas, what my mistake might be?
Thanks!


问:
SwiftUI - How do I change the background color of a View?
I'm beginning to try out SwiftUI and I'm surprised that it doesn't seem to be straightforward to change the background color of a View. How do you do this using SwiftUI?

答:
The code on Scene delegate in Swift UI

Content view background-color

window.rootViewController?.view.backgroundColor = .lightGray


问:
Regex Excel Remove Middle Part of String
I have some address data that needs to be corrected. It is intending to show a range of addresses, but this will not work for geocoding. What is an effective way to to remove everything between the hyphen and the first space using regex in excel? Example:

```<code>    29-45  SICKLES ST
    31-39  SHERMAN AV
    36-44  ARDEN ST
   118-22  NAGLE AV
</code>```

Becomes

```<code>    29 SICKLES ST
    31 SHERMAN AV
    36 ARDEN ST
   118 NAGLE AV
</code>```

答:
Since you have tagged RegEx you could use it like so within Excel's VBA:

```<code>Sub Test()

Dim arr As Variant: arr = Array("29-45  SICKLES ST", "31-39  SHERMAN AV", "36-44  ARDEN ST", "118-22  NAGLE AV")

With CreateObject("VBScript.RegExp")
    .Pattern = "-\d*\s*"
    For x = LBound(arr) To UBound(arr)
        arr(x) = .Replace(arr(x), " ")
    Next
End With

End Sub
</code>```

Body:
I have some address data that needs to be corrected. It is intending to show a range of addresses, but this will not work for geocoding. What is an effective way to to remove everything between the hyphen and the first space using regex in excel? Example:

    29-45  SICKLES ST
    31-39  SHERMAN AV
    36-44  ARDEN ST
   118-22  NAGLE AV

Becomes

    29 SICKLES ST
    31 SHERMAN AV
    36 ARDEN ST
   118 NAGLE AV

Body:
Since you have tagged RegEx you could use it like so within Excel's VBA:

Sub Test()

Dim arr As Variant: arr = Array("29-45  SICKLES ST", "31-39  SHERMAN AV", "36-44  ARDEN ST", "118-22  NAGLE AV")

With CreateObject("VBScript.RegExp")
    .Pattern = "-\d*\s*"
    For x = LBound(arr) To UBound(arr)
        arr(x) = .Replace(arr(x), " ")
    Next
End With

End Sub


问:
Schedule ignors kwargs in django-q
I am using Django-q (https://django-q.readthedocs.io) for queuing in the Django framework. I have an async function when I use async_task:

```<code>async_task('sms.tasks.send',
                       username=username,
                       password=password,
                       text=text,
                       to=to,
                       path=path,
)
</code>```

everything is ok and works fine. but when I use it with schedule:

```<code>schedule('sms.tasks.send',
                       username=username,
                       password=password,
                       text=text,
                       to=to,
                       path=path,
next_run=scheduled_time)
</code>```

Although nothing has changed and even in Scheduled task all Kwargs exist, in execution, no Kwargs passes. Does anybody has faced this problem with Django-q?

答: It's solved. Remember do not pass a model instance as a Kwarg argument. That was the problem.</p>

Title: Schedule ignors kwargs in django-q

Body:
I am using Django-q (https://django-q.readthedocs.io) for queuing in the Django framework. I have an async function when I use async_task:

async_task('sms.tasks.send',
                       username=username,
                       password=password,
                       text=text,
                       to=to,
                       path=path,
)

everything is ok and works fine. but when I use it with schedule:

schedule('sms.tasks.send',
                       username=username,
                       password=password,
                       text=text,
                       to=to,
                       path=path,
next_run=scheduled_time)

Although nothing has changed and even in Scheduled task all Kwargs exist, in execution, no Kwargs passes. Does anybody has faced this problem with Django-q?


问:
Datagridview is completely hidden for bindingsource the second time
```<code>private void populateListingGrid(){

try{

Dictionary<string, Object> responseMap = new Dictionary<string, object>();
PaginationList newContractDetailsListingMsDTO = getNewContractDetailsListingMsDTO();
ContractService createContractService = ContractServiceFactory.getInstance();
responseMap = createContractService.getContractListing();
contractList = responseMap["contractListingMsDTOs"] as List<NewContractListingMsDTO>;
this.newContractListingMsDTOBindingSource.Clear();
             if (contractList != null && contractList.Count > 0)
             {
                 newContractListingMsDTOBindingSource.DataSource = contractList;
                 newContractListDataGridView.Refresh();
             }
}
catch (Exception e)
{
   logger.Info("populateListingGrid");
}
}
</code>```

I am using the newContractListingMsDTOBindingSource as a bindingsource, which works perfectly fine when i open the datagrid for first time, when i try to reopen the datagridview in winforms, entire datagridview seems crashed nothing is visible not even the column header of the bindingsource.

Am i using all the binding source or binding data source code correctly?

答:
After a lot of trial and error, i found the solution to the problem, it worked when i set the below property of the DataGridView

ColoumnHeadersHieghtSizeMode => AutoSize

If i change this property to DisableResizing/EnableResizing the Datagridview gets hidden the 2nd time. The probelem is not with the BindingSource or Datasource directly.

Body:
private void populateListingGrid(){

try{

Dictionary<string, Object> responseMap = new Dictionary<string, object>();
PaginationList newContractDetailsListingMsDTO = getNewContractDetailsListingMsDTO();
ContractService createContractService = ContractServiceFactory.getInstance();
responseMap = createContractService.getContractListing();
contractList = responseMap["contractListingMsDTOs"] as List<NewContractListingMsDTO>;
this.newContractListingMsDTOBindingSource.Clear();
             if (contractList != null && contractList.Count > 0)
             {
                 newContractListingMsDTOBindingSource.DataSource = contractList;
                 newContractListDataGridView.Refresh();
             }
}
catch (Exception e)
{
   logger.Info("populateListingGrid");
}
}

I am using the newContractListingMsDTOBindingSource as a bindingsource, which works perfectly fine when i open the datagrid for first time, when i try to reopen the datagridview in winforms, entire datagridview seems crashed nothing is visible not even the column header of the bindingsource.

Am i using all the binding source or binding data source code correctly?


问:
Key error in dictionary while deleting the key
I am trying to count the string and I want to delete the key with value 1 and 2. I am successfully able to count the strings with below script. If I am adding if loop to the dictionary its throwing Key error 'd' when I try to print it.

```<code>s = "aaabbbd"
def check_freq(s):
     freq = {}
     for c in s:
        freq[c] = s.count(c)
     for w in sorted(freq, key=freq.get, reverse=True):
         if freq[w] == 1:
             del freq[w]
             print (w, freq[w])

check_freq(s)
</code>```

Error is below

```<code>File "<ipython-input-60-a79c71ac1b31>", line 10, in check_freq
    print (w, freq[w])

KeyError: 'd'
</code>```

Expected output

{'a': 3, 'b': 3}

答:
Keep delete in try block and that worked for me.</p>

```<code>try:
   del freq[w]
except Exception as e:
   print(e)
</code>```

Body:
I am trying to count the string and I want to delete the key with value 1 and 2. I am successfully able to count the strings with below script. If I am adding if loop to the dictionary its throwing Key error 'd' when I try to print it.

s = "aaabbbd"
def check_freq(s):
     freq = {}
     for c in s:
        freq[c] = s.count(c)
     for w in sorted(freq, key=freq.get, reverse=True):
         if freq[w] == 1:
             del freq[w]
             print (w, freq[w])

check_freq(s)

Error is below

File "<ipython-input-60-a79c71ac1b31>", line 10, in check_freq
    print (w, freq[w])

KeyError: 'd'

Expected output

{'a': 3, 'b': 3}

Body:
Keep delete in try block and that worked for me.

try:
   del freq[w]
except Exception as e:
   print(e)


答:
why doesn't Laravel have a built-in repository pattern

Because there is no consensus on how they should be used if used at all.

For example, I use Repositories as an intermediary between laravel models and laravel controllers that needs the model instance to be instantiated and I never inject them into controllers but instantiate them manually when needed.

do we need to bind repositories as providers ?

As said above, there is no consensus so NO.

Depends on how you design your repositories, you can instantiate them manually, inject them into controller's instantiation (in the __contruct(UserRepository $userRepository)) as you can see in laravel from scratch tutorial from laracast or use them as service providers.

Title: Creating Laravel repositories and binding as service providers


问:
How can I safely resolve homebrew and zsh's conflicting needs for /usr/local/share/zsh ownership?
After switching my shell from bash to zsh with the macOS Catalina update, Homebrew and zsh are fighting over how they need /usr/local/share/zsh/site-functions and /usr/local/share/zsh to be owned.

zsh prefers that /usr/local/share/zsh/**/* be owned by root, and otherwise raises the annoying error

```<code>zsh compinit: insecure directories and files, run compaudit for list.
Ignore insecure directories and files and continue [y] or abort compinit [n]?
</code>```

every time I log in as root, for example via sudo -s.

I ran compaudit as root then chown root'd and chmod g-w'd all the directories that it listed. That satisfied zsh but now homebrew isn't happy.

Any brew install or upgrade fails with

```<code>Error: The following directories are not writable by your user:
/usr/local/share/zsh
/usr/local/share/zsh/site-functions

You should change the ownership of these directories to your user.
  sudo chown -R $(whoami) /usr/local/share/zsh /usr/local/share/zsh/site-functions

And make sure that your user has write permission.
  chmod u+w /usr/local/share/zsh /usr/local/share/zsh/site-functions
</code>```

brew doctor gives the same message as a warning.

Is there a compromise between the two? Or one of these warnings I can safely suppress? If so, how?

答:
There is compinit call somewhere like in your .zshrc. Change it to compinit -u which will silence the warning.

/usr/share/zsh/5.7.1/functions/compinit is responsible for that warning (change 5.7.1 to match your zsh version)

Body:
After switching my shell from bash to zsh with the macOS Catalina update, Homebrew and zsh are fighting over how they need /usr/local/share/zsh/site-functions and /usr/local/share/zsh to be owned.

zsh prefers that /usr/local/share/zsh/**/* be owned by root, and otherwise raises the annoying error

zsh compinit: insecure directories and files, run compaudit for list.
Ignore insecure directories and files and continue [y] or abort compinit [n]?

every time I log in as root, for example via sudo -s.

I ran compaudit as root then chown root'd and chmod g-w'd all the directories that it listed. That satisfied zsh but now homebrew isn't happy.

Any brew install or upgrade fails with

Error: The following directories are not writable by your user:
/usr/local/share/zsh
/usr/local/share/zsh/site-functions

You should change the ownership of these directories to your user.
  sudo chown -R $(whoami) /usr/local/share/zsh /usr/local/share/zsh/site-functions

And make sure that your user has write permission.
  chmod u+w /usr/local/share/zsh /usr/local/share/zsh/site-functions

brew doctor gives the same message as a warning.

Is there a compromise between the two? Or one of these warnings I can safely suppress? If so, how?


问:
Azure pipeline doesn't allow to enable pull request validation
While trying to enable Azure pull request validation it throws following error.

```<code>Unable to configure a service on the selected GitHub repository. This is likely caused by not having the necessary permission to manage hooks for the selected repository.
</code>```

I have created a github connection with access token. And enabled all the scopes as follows, What exact scope do I need to enable?

答:
I think the scopes are not the main cause of your issue. I generated different github PATs and found the pipeline with Azure pull request validation enabled can work well even when I only defined part of what you've defined above.

Please check this similar issue, check if you can directly create a webhooks in Github web UI. (Github=>Settings=>Webhooks). And according to reply from Eddie:

If it is a personal repository, only the repository owner can create hooks. If it is an organization repository, you need at least "Admin permissions" which can "Change a repository's settings" with "Adding, removing, and editing webhooks and service hooks permission included.

Hope it helps.

Body:
While trying to enable Azure pull request validation it throws following error.

Unable to configure a service on the selected GitHub repository. This is likely caused by not having the necessary permission to manage hooks for the selected repository.

I have created a github connection with access token. And enabled all the scopes as follows, What exact scope do I need to enable?


问:
select common values of multiple tables in mysql
I'm writing a php code to calculate a value. I have 4 tables with 2 column each. their headers are same. I want to fetch second column of tables that have, say 'MAN', value on their first column:
here are my tables and their dummy values:

I joined tables on 'dst' with a where clause but the problem arises when a table has does not have a common value and we have not full outer join in mysql. I know we can simulate this with union all operation but I want a efficient way to do this.
here is my try:

```<code>select t1.dst, t1.pay as pay, t2.pay as pay2, t3.pay as pay3, t4.pay as pay4 from t1 left outer join t2 on t1.dst = t2.dst left outer join t3 on t3.dst=t2.dst left outer join t4 on t1.dst=t4.dst where t1.dst='man';
</code>```

it's dummy because left outer join is not true for this purpose except special cases.

actually I want this:

答:
First union then pivot</p>

```<code>drop table if exists t,t1,t2,t3;
create table t  (dst varchar(3),value int);
create table t1 (dst varchar(3),value int);
create table t2 (dst varchar(3),value int);
create table t3 (dst varchar(3),value int);

insert into t values ('abc',10),('man',10);
insert into t1 values ('abc',10),('man',5);
insert into t2 values ('abc',10),('man',10);
insert into t3 values ('abc',10);

select  dst,
          MAX(CASE WHEN tbl = 't' then value end) as t1,
          MAX(CASE WHEN tbl = 't1' then value end) as t1,
          MAX(CASE WHEN tbl = 't2' then value end) as t2,
          MAX(CASE WHEN tbl = 't3' then value end) as t3
from
(
select 't' as tbl,dst,value from t where dst = 'man'
union
select 't1' as tbl,dst,value from t1 where dst = 'man'
union
select 't2' as tbl,dst,value from t2 where dst = 'man'
union
select 't3' as tbl,dst,value from t3 where dst = 'man'
) s
group by s.dst;

+------+------+------+------+------+
| dst  | t1   | t1   | t2   | t3   |
+------+------+------+------+------+
| man  |   10 |    5 |   10 | NULL |
+------+------+------+------+------+
1 row in set (0.00 sec)
</code>```

Body:
I'm writing a php code to calculate a value. I have 4 tables with 2 column each. their headers are same. I want to fetch second column of tables that have, say 'MAN', value on their first column:
here are my tables and their dummy values:

I joined tables on 'dst' with a where clause but the problem arises when a table has does not have a common value and we have not full outer join in mysql. I know we can simulate this with union all operation but I want a efficient way to do this.
here is my try:

select t1.dst, t1.pay as pay, t2.pay as pay2, t3.pay as pay3, t4.pay as pay4 from t1 left outer join t2 on t1.dst = t2.dst left outer join t3 on t3.dst=t2.dst left outer join t4 on t1.dst=t4.dst where t1.dst='man';

it's dummy because left outer join is not true for this purpose except special cases.

actually I want this:

Body:
First union then pivot

drop table if exists t,t1,t2,t3;
create table t  (dst varchar(3),value int);
create table t1 (dst varchar(3),value int);
create table t2 (dst varchar(3),value int);
create table t3 (dst varchar(3),value int);

insert into t values ('abc',10),('man',10);
insert into t1 values ('abc',10),('man',5);
insert into t2 values ('abc',10),('man',10);
insert into t3 values ('abc',10);

select  dst,
          MAX(CASE WHEN tbl = 't' then value end) as t1,
          MAX(CASE WHEN tbl = 't1' then value end) as t1,
          MAX(CASE WHEN tbl = 't2' then value end) as t2,
          MAX(CASE WHEN tbl = 't3' then value end) as t3
from
(
select 't' as tbl,dst,value from t where dst = 'man'
union
select 't1' as tbl,dst,value from t1 where dst = 'man'
union
select 't2' as tbl,dst,value from t2 where dst = 'man'
union
select 't3' as tbl,dst,value from t3 where dst = 'man'
) s
group by s.dst;

+------+------+------+------+------+
| dst  | t1   | t1   | t2   | t3   |
+------+------+------+------+------+
| man  |   10 |    5 |   10 | NULL |
+------+------+------+------+------+
1 row in set (0.00 sec)


问:
Pandas combine Hour and Minute column to time
I'm trying to combine Hour column and Minute column into HH:MM format

I tried the following

```<code>time = pd.to_timedelta(df['HOUR'],unit='h') + pd.to_timedelta(df['MINUTE'],unit ='m')
time = pd.to_datetime(report_time).dt.time
</code>```

This is working, however it shows

```<code>FutureWarning: Passing timedelta64-dtype data is deprecated, will raise a TypeError in a future version   return func(*args, **kwargs)
</code>```

and it's not efficient, since I tried the code for a large dataset, and it drained my memory.

I'm wondering if there's another method to convert Hour column and Minute column into HH:MM format

My data is like

```<code>Hour   Minute
 8       12
 9       30
 3       15
</code>```

And my target is like

```<code>08:12
09:30
03:15
</code>```

答:
Convert both columns to strings, add separator and use to_datetime with format parameter:

```<code>time = (pd.to_datetime(df['Hour'].astype(str) + ':' + df['Minute'].astype(str), format='%H:%M')
          .dt.time)
print (time)
0    08:12:00
1    09:30:00
2    03:15:00
dtype: object
</code>```

Another idea is multiple Hour by 100, add minutes and convert also with %H%M format:

```<code>time = pd.to_datetime(df['Hour']*100 + df['Minute'], format='%H%M').dt.time
print (time)
0    08:12:00
1    09:30:00
2    03:15:00
dtype: object
</code>```

Body:
I'm trying to combine Hour column and Minute column into HH:MM format

I tried the following

time = pd.to_timedelta(df['HOUR'],unit='h') + pd.to_timedelta(df['MINUTE'],unit ='m')
time = pd.to_datetime(report_time).dt.time

This is working, however it shows

FutureWarning: Passing timedelta64-dtype data is deprecated, will raise a TypeError in a future version   return func(*args, **kwargs)

and it's not efficient, since I tried the code for a large dataset, and it drained my memory.

I'm wondering if there's another method to convert Hour column and Minute column into HH:MM format

My data is like

Hour   Minute
 8       12
 9       30
 3       15

And my target is like

08:12
09:30
03:15

Body:
Convert both columns to strings, add separator and use to_datetime with format parameter:

time = (pd.to_datetime(df['Hour'].astype(str) + ':' + df['Minute'].astype(str), format='%H:%M')
          .dt.time)
print (time)
0    08:12:00
1    09:30:00
2    03:15:00
dtype: object

Another idea is multiple Hour by 100, add minutes and convert also with %H%M format:

time = pd.to_datetime(df['Hour']*100 + df['Minute'], format='%H%M').dt.time
print (time)
0    08:12:00
1    09:30:00
2    03:15:00
dtype: object


问:
How to replace question mark from a String so that same letter does not occur next to each other?
I wrote the code below to replace each question mark from a String so that same letter does not occur next to each other. For example:

Input

```<code>ab?ac?
</code>```

Output

```<code>abcaca
</code>```

Please note that ? should be replaced by any lowercase letter: [a-z]

Below is my solution. But my question: is there any more optimized way to solve this?

```<code>public String solution(String riddle) {
    char alpha[] = "abcdefghijklmnopqrstuvwxyz".toCharArray();
    if (riddle == null || riddle.indexOf('?') == -1) {
        return riddle;
    }
    StringBuilder sb = new StringBuilder("");
    int cnt = 0;
    for (int i = 0; i < riddle.length(); i++) {
        char current = riddle.charAt(i);
        char prev = '\0';
        char next = '\0';
        if (current == '?') {
            current = alpha[cnt];
            if (i != 0) {
                prev = sb.toString().charAt(i - 1);
            }
            if (i != riddle.length() - 1) {
                next = riddle.charAt(i + 1);
            }
            while (current == prev || current == next) {
                current = alpha[++cnt];
                if (cnt % 25 == 0) {
                    cnt = 0;
                }
            }
            sb.append(current);
        } else {
            sb.append(current);
        }
    }
    return sb.toString();
}
</code>```

答:
The time complexity of your algorithm degrades to O(n²) because of this conversion to string:

```<code>prev = sb.toString().charAt(i - 1);
</code>```

This .toString call needs time linear to the current length of sb. And this is really unnecessary, as .charAt is also available on a StringBuilder instance. So the quick fix is to do:

```<code>prev = sb.charAt(i - 1);
</code>```

Now the code will run with O(n) time complexity, and that cannot be improved further.

However, you can still gain some time using the following observations:

There is no need to pick up prev with charAt, since you could just do a prev = current assignment at the end of each iteration (and change its scope accordingly).

There is no need to look into 26 alternative letters for a ?. Every question mark can become either a, b or c. No other letters are needed -- you just need three (any three distinct letters would work). So there is no need to have alpha, no need to have cnt, and no need to apply a remainder operator to it. A simple ternary expression can do the job.

You can avoid code repetition and move the append call out of the if...else blocks.

So here is how the code could look:

```<code>public String solution(String riddle) {
    if (riddle == null || riddle.indexOf('?') == -1) {
        return riddle;
    }
    StringBuilder sb = new StringBuilder("");
    char prev = '\0';
    for (int i = 0; i < riddle.length(); i++) {
        char current = riddle.charAt(i);
        if (current == '?') {
            char next = '\0';
            if (i != riddle.length() - 1) {
                next = riddle.charAt(i + 1);
            }
            current = prev != 'a' && next != 'a' ? 'a'
                    : prev != 'b' && next != 'b' ? 'b'
                    : 'c';
        }
        sb.append(current);
        prev = current;
    }
    return sb.toString();
}
</code>```

Body:
I wrote the code below to replace each question mark from a String so that same letter does not occur next to each other. For example:

Input

ab?ac?

Output

abcaca

Please note that ? should be replaced by any lowercase letter: [a-z]

Below is my solution. But my question: is there any more optimized way to solve this?

public String solution(String riddle) {
    char alpha[] = "abcdefghijklmnopqrstuvwxyz".toCharArray();
    if (riddle == null || riddle.indexOf('?') == -1) {
        return riddle;
    }
    StringBuilder sb = new StringBuilder("");
    int cnt = 0;
    for (int i = 0; i < riddle.length(); i++) {
        char current = riddle.charAt(i);
        char prev = '\0';
        char next = '\0';
        if (current == '?') {
            current = alpha[cnt];
            if (i != 0) {
                prev = sb.toString().charAt(i - 1);
            }
            if (i != riddle.length() - 1) {
                next = riddle.charAt(i + 1);
            }
            while (current == prev || current == next) {
                current = alpha[++cnt];
                if (cnt % 25 == 0) {
                    cnt = 0;
                }
            }
            sb.append(current);
        } else {
            sb.append(current);
        }
    }
    return sb.toString();
}

Body:
The time complexity of your algorithm degrades to O(n²) because of this conversion to string:

prev = sb.toString().charAt(i - 1);

This .toString call needs time linear to the current length of sb. And this is really unnecessary, as .charAt is also available on a StringBuilder instance. So the quick fix is to do:

prev = sb.charAt(i - 1);

Now the code will run with O(n) time complexity, and that cannot be improved further.

However, you can still gain some time using the following observations:

There is no need to pick up prev with charAt, since you could just do a prev = current assignment at the end of each iteration (and change its scope accordingly).

There is no need to look into 26 alternative letters for a ?. Every question mark can become either a, b or c. No other letters are needed -- you just need three (any three distinct letters would work). So there is no need to have alpha, no need to have cnt, and no need to apply a remainder operator to it. A simple ternary expression can do the job.

You can avoid code repetition and move the append call out of the if...else blocks.

So here is how the code could look:

public String solution(String riddle) {
    if (riddle == null || riddle.indexOf('?') == -1) {
        return riddle;
    }
    StringBuilder sb = new StringBuilder("");
    char prev = '\0';
    for (int i = 0; i < riddle.length(); i++) {
        char current = riddle.charAt(i);
        if (current == '?') {
            char next = '\0';
            if (i != riddle.length() - 1) {
                next = riddle.charAt(i + 1);
            }
            current = prev != 'a' && next != 'a' ? 'a'
                    : prev != 'b' && next != 'b' ? 'b'
                    : 'c';
        }
        sb.append(current);
        prev = current;
    }
    return sb.toString();
}


问:
Mapstruct map a property for a null object
I have a particular problem to generate the map implementation, I need to map a property of a null object. The code is like this in ObjectRequestMapper:

```<code>    @Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED, nullValueCheckStrategy =
           NullValueCheckStrategy.ALWAYS, nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL, uses = {
           WrapperGrpcMapper.class, AddressRequestMapper.class })
    public interface ObjectRequestGrpcMapper {

      @Mapping(target = "wcsStoreId", source = "storeId")
      @Mapping(target = "linesList", source = "lines")
      ObjectRequest map(Long storeId, @Context String countryCode, List<ObjectLines> lines, Address address);

      ObjectRequestLine lineToProto (ObjectLine line);

    }
</code>```

and the AddressRequestMapper:

```<code>    public interface AddressRequestMapper {

      default Address toProto(Address address, @Context String countryCode){
          return this.map(address, countryCode);
      }

      Address map(Address address, String countryCode);
    }
</code>```

When I call the map of ObjectRequest passing all parameters with countryCode = "EN" and object address is null, the mapper of AddresRequestMapper doesn't applies because ObjectRequestMapper checks the Address == null, and then doesn't map ObjectRequest.Address to address

It is possible to get a solution for this case?

Thanks

答:
If you need to get instead of "Address == null" -> "new Address()" just do change:

nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT

Body:
I have a particular problem to generate the map implementation, I need to map a property of a null object. The code is like this in ObjectRequestMapper:

    @Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED, nullValueCheckStrategy =
           NullValueCheckStrategy.ALWAYS, nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL, uses = {
           WrapperGrpcMapper.class, AddressRequestMapper.class })
    public interface ObjectRequestGrpcMapper {

      @Mapping(target = "wcsStoreId", source = "storeId")
      @Mapping(target = "linesList", source = "lines")
      ObjectRequest map(Long storeId, @Context String countryCode, List<ObjectLines> lines, Address address);

      ObjectRequestLine lineToProto (ObjectLine line);

    }

and the AddressRequestMapper:

    public interface AddressRequestMapper {

      default Address toProto(Address address, @Context String countryCode){
          return this.map(address, countryCode);
      }

      Address map(Address address, String countryCode);
    }

When I call the map of ObjectRequest passing all parameters with countryCode = "EN" and object address is null, the mapper of AddresRequestMapper doesn't applies because ObjectRequestMapper checks the Address == null, and then doesn't map ObjectRequest.Address to address

It is possible to get a solution for this case?

Thanks


问:
Getting error when deploying a Google Cloud Function after Node upgrade
I updated Brew then updated Node from 10.12.0 -> 13.8.0

Now, I get the following error when trying to deploy a Google Cloud Function

```<code>firebase deploy --only functions:createJWT
</code>```

i  functions: preparing functions directory for
  uploading...

Error: Error parsing triggers: Failed to load gRPC binary module
  because it was not installed for the current system Expected
  directory: node-v79-darwin-x64-unknown Found:
  [node-v64-darwin-x64-unknown] This problem can often be fixed by
  running "npm rebuild" on the current system Original error: Cannot
  find module
  '/Users/.../cloud-functions/functions/node_modules/grpc/src/node/extension_binary/node-v79-darwin-x64-unknown/grpc_node.node'
  Require stack:
  - /Users/.../cloud-functions/functions/node_modules/grpc/src/grpc_extension.js
  - /Users/.../cloud-functions/functions/node_modules/grpc/src/client_interceptors.js
  - /Users/.../cloud-functions/functions/node_modules/grpc/src/client.js
  - /Users/.../cloud-functions/functions/node_modules/grpc/index.js
  - /Users/.../cloud-functions/functions/node_modules/@google-cloud/common-grpc/src/service.js
  - /Users/.../cloud-functions/functions/node_modules/@google-cloud/common-grpc/src/operation.js
  - /Users/.../cloud-functions/functions/node_modules/@google-cloud/common-grpc/src/index.js
  - /Users/.../cloud-functions/functions/node_modules/@google-cloud/logging/src/index.js
  - /Users/.../cloud-functions/functions/index.js
  - /usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js

Try running "npm install" in your functions directory before
  deploying.

Tried npm rebuild and npm install in my functions directory and nothing works

Furthermore...could this issue be due to the fact that GCF Node runtime enviroment is Node10 and I have installed Node13 on my machine? - according to these docs:

https://cloud.google.com/functions/docs/concepts/nodejs-10-runtime

I am struggling to revert back to Node10, have tried by running brew install node@10 and get this:

Then tried running the following command as per output above to symlink it to /usr/local but still no luck

```<code>echo 'export PATH="/usr/local/opt/node@10/bin:$PATH"' >> ~/.bash_profile
</code>```

答:
Searching around about this error, indeed, this seems that the problem is related to your system waiting for a version and founding another one - as per this part of the error.

Error: Error parsing triggers: Failed to load gRPC binary module because it was not installed for the current system Expected directory: node-v79-darwin-x64-unknown Found: [node-v64-darwin-x64-unknown]

There are some options that you can give it a try, besides trying the npm rebuild. Another option might be updating the package.json - as per this case solved here - that would return your npm version to an old one.

Besides that, on this question in the Community, there are a few solutions that helped other users, that I would recommend you to take a look at it: NodeJs Error - Failed to load gRPC binary module because it was not installed for the current system Expected directory?

Let me know if the information helped you!

Body:
I updated Brew then updated Node from 10.12.0 -> 13.8.0

Now, I get the following error when trying to deploy a Google Cloud Function

firebase deploy --only functions:createJWT

i  functions: preparing functions directory for
  uploading...

Error: Error parsing triggers: Failed to load gRPC binary module
  because it was not installed for the current system Expected
  directory: node-v79-darwin-x64-unknown Found:
  [node-v64-darwin-x64-unknown] This problem can often be fixed by
  running "npm rebuild" on the current system Original error: Cannot
  find module
  '/Users/.../cloud-functions/functions/node_modules/grpc/src/node/extension_binary/node-v79-darwin-x64-unknown/grpc_node.node'
  Require stack:
  - /Users/.../cloud-functions/functions/node_modules/grpc/src/grpc_extension.js
  - /Users/.../cloud-functions/functions/node_modules/grpc/src/client_interceptors.js
  - /Users/.../cloud-functions/functions/node_modules/grpc/src/client.js
  - /Users/.../cloud-functions/functions/node_modules/grpc/index.js
  - /Users/.../cloud-functions/functions/node_modules/@google-cloud/common-grpc/src/service.js
  - /Users/.../cloud-functions/functions/node_modules/@google-cloud/common-grpc/src/operation.js
  - /Users/.../cloud-functions/functions/node_modules/@google-cloud/common-grpc/src/index.js
  - /Users/.../cloud-functions/functions/node_modules/@google-cloud/logging/src/index.js
  - /Users/.../cloud-functions/functions/index.js
  - /usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js

Try running "npm install" in your functions directory before
  deploying.

Tried npm rebuild and npm install in my functions directory and nothing works

Furthermore...could this issue be due to the fact that GCF Node runtime enviroment is Node10 and I have installed Node13 on my machine? - according to these docs:

https://cloud.google.com/functions/docs/concepts/nodejs-10-runtime

I am struggling to revert back to Node10, have tried by running brew install node@10 and get this:

Then tried running the following command as per output above to symlink it to /usr/local but still no luck

echo 'export PATH="/usr/local/opt/node@10/bin:$PATH"' >> ~/.bash_profile


问:
Is it possible to make a hardcoding with the help of the command objcopy
I'm working on Linux and I've just heard that there was a command objcopy, I've found the relative command on my x86_64 PC: x86_64-linux-gnu-objcopy.

With its help, I can convert a file into an obj file: x86_64-linux-gnu-objcopy -I binary -O elf64-x86-64 custom.config custom.config.o

The file custom.config is a human-readable file. It contains two lines:

```<code>name titi
password 123
</code>```

Now I can execute objdump -x -s custom.config.o to check its information.

```<code>custom.config.o:     file format elf64-little
custom.config.o
architecture: UNKNOWN!, flags 0x00000010:
HAS_SYMS
start address 0x0000000000000000

Sections:
Idx Name          Size      VMA               LMA               File off  Algn
  0 .data         00000017  0000000000000000  0000000000000000  00000040  2**0
                  CONTENTS, ALLOC, LOAD, DATA
SYMBOL TABLE:
0000000000000000 l    d  .data  0000000000000000 .data
0000000000000000 g       .data  0000000000000000 _binary_custom_config_start
0000000000000017 g       .data  0000000000000000 _binary_custom_config_end
0000000000000017 g       *ABS*  0000000000000000 _binary_custom_config_size

Contents of section .data:
 0000 6e616d65 20746974 690a7061 7373776f  name titi.passwo
 0010 72642031 32330a                      rd 123.
</code>```

As all we know, we can open, read or write a file, such as custom.config in any C/C++ project. Now, I'm thinking if it's possible to use this obj file custom.config.o immediately in a C/C++ project. For example, is it possible to read the content of the file custom.config.o immediately without calling the I/O functions, such as open, read or write. If possible, I think this might become some kind of hardcoding style and avoid calling the I/O functions?

答:
Even if I tried this on Win10 with MinGW (MinGW-W64 project, GCC 8.1.0), this should work for you with only minor adaptions.

As you see from the info objdump gave you, the file's contents is placed in the .data section that is the common section for non-constant variables.

And some symbols were defined for it. You can declare these symbols in your C source.

The absolute value _binary_custom_config_size is special, because it is marked *ABS*. Currently I know no other way to obtain its value than to declare a variable of any type and take its address.

This is my show_config.c:

```<code>#include <stdio.h>
#include <string.h>

extern const char _binary_custom_config_start[];
extern const char _binary_custom_config_size;

int main(void) {
  size_t size = (size_t)&_binary_custom_config_size;
  char config[size + 1];
  strncpy(config, _binary_custom_config_start, size);
  config[size] = '\0';
  printf("config = \"%s\"\n", config);
  return 0;
}
</code>```

Because the "binary" file (actually a text) has no final '\0' character, you need to append one to get a correctly terminated C string.

You could as well declare _binary_custom_config_end and use it to calculate the size, or as a limit.

Building everything goes like this (I used the -g option to debug):

```<code>$ objcopy -I binary -O elf64-x86-64 -B i386 custom.config custom.config.o
$ gcc -Wall -Wextra -pedantic -g show_config.c custom.config.o -o show_config
</code>```

And the output shows the success:

```<code>$ show_config.exe
config = "name titi
password 123"
</code>```

If you need the file's contents in another section, you will add the option to rename the section to objcopy's call. Add any flag you need, the example shows .rodata that is used for read-only data:

--rename-section .data=.rodata,alloc,load,readonly,data,contents

Body:
I'm working on Linux and I've just heard that there was a command objcopy, I've found the relative command on my x86_64 PC: x86_64-linux-gnu-objcopy.

With its help, I can convert a file into an obj file: x86_64-linux-gnu-objcopy -I binary -O elf64-x86-64 custom.config custom.config.o

The file custom.config is a human-readable file. It contains two lines:

name titi
password 123

Now I can execute objdump -x -s custom.config.o to check its information.

custom.config.o:     file format elf64-little
custom.config.o
architecture: UNKNOWN!, flags 0x00000010:
HAS_SYMS
start address 0x0000000000000000

Sections:
Idx Name          Size      VMA               LMA               File off  Algn
  0 .data         00000017  0000000000000000  0000000000000000  00000040  2**0
                  CONTENTS, ALLOC, LOAD, DATA
SYMBOL TABLE:
0000000000000000 l    d  .data  0000000000000000 .data
0000000000000000 g       .data  0000000000000000 _binary_custom_config_start
0000000000000017 g       .data  0000000000000000 _binary_custom_config_end
0000000000000017 g       *ABS*  0000000000000000 _binary_custom_config_size

Contents of section .data:
 0000 6e616d65 20746974 690a7061 7373776f  name titi.passwo
 0010 72642031 32330a                      rd 123.

As all we know, we can open, read or write a file, such as custom.config in any C/C++ project. Now, I'm thinking if it's possible to use this obj file custom.config.o immediately in a C/C++ project. For example, is it possible to read the content of the file custom.config.o immediately without calling the I/O functions, such as open, read or write. If possible, I think this might become some kind of hardcoding style and avoid calling the I/O functions?

Body:
Even if I tried this on Win10 with MinGW (MinGW-W64 project, GCC 8.1.0), this should work for you with only minor adaptions.

As you see from the info objdump gave you, the file's contents is placed in the .data section that is the common section for non-constant variables.

And some symbols were defined for it. You can declare these symbols in your C source.

The absolute value _binary_custom_config_size is special, because it is marked *ABS*. Currently I know no other way to obtain its value than to declare a variable of any type and take its address.

This is my show_config.c:

#include <stdio.h>
#include <string.h>

extern const char _binary_custom_config_start[];
extern const char _binary_custom_config_size;

int main(void) {
  size_t size = (size_t)&_binary_custom_config_size;
  char config[size + 1];
  strncpy(config, _binary_custom_config_start, size);
  config[size] = '\0';
  printf("config = \"%s\"\n", config);
  return 0;
}

Because the "binary" file (actually a text) has no final '\0' character, you need to append one to get a correctly terminated C string.

You could as well declare _binary_custom_config_end and use it to calculate the size, or as a limit.

Building everything goes like this (I used the -g option to debug):

$ objcopy -I binary -O elf64-x86-64 -B i386 custom.config custom.config.o
$ gcc -Wall -Wextra -pedantic -g show_config.c custom.config.o -o show_config

And the output shows the success:

$ show_config.exe
config = "name titi
password 123"

If you need the file's contents in another section, you will add the option to rename the section to objcopy's call. Add any flag you need, the example shows .rodata that is used for read-only data:

--rename-section .data=.rodata,alloc,load,readonly,data,contents


问:
Duplicate Function Implementation
I have one file, app.ts under my scripts folder, that gets copied to wwwroot/scripts by a gulp task. After the gulp task runs, I now also have a wwwroot/scripts/app.ts file, in which the sole function is red-underlined as duplicate. Is this normal, or is my gulp task, below, declared incorrectly?

```<code>var paths = {
    scripts: ["scripts/**/*.js", "scripts/**/*.ts", "scripts/**/*.map"]
};

gulp.task("default", function() {
    gulp.src(paths.scripts).pipe(gulp.dest("wwwroot/scripts"));
});
</code>```

I see the raw app.ts file, from the root scripts folder also gets built into *.js and *.js.map files. Could this have something to do with the 'false positive' duplicate function?

答:
//VSCODE
This is an issue from VSCode. To fix it execute the following command </p>

```<code>tsc --init
//to initialize the tsconfig.json in the folder.
</code>```

<p>//VISUAL STUDIO
In order to prevent functions to be in global scope, you can add export {}; on top (or just export this function):</p>

```<code>// 1.ts
export {};

function test(){
    console log("File 1 Error");
}
// 2.ts
export {};

function test(){
    console.log("File 2 Error");
}
</code>```

Title: Duplicate Function Implementation

Body:
I have one file, app.ts under my scripts folder, that gets copied to wwwroot/scripts by a gulp task. After the gulp task runs, I now also have a wwwroot/scripts/app.ts file, in which the sole function is red-underlined as duplicate. Is this normal, or is my gulp task, below, declared incorrectly?

var paths = {
    scripts: ["scripts/**/*.js", "scripts/**/*.ts", "scripts/**/*.map"]
};

gulp.task("default", function() {
    gulp.src(paths.scripts).pipe(gulp.dest("wwwroot/scripts"));
});

I see the raw app.ts file, from the root scripts folder also gets built into *.js and *.js.map files. Could this have something to do with the 'false positive' duplicate function?

Body:
//VSCODE
This is an issue from VSCode. To fix it execute the following command

tsc --init
//to initialize the tsconfig.json in the folder.

//VISUAL STUDIO
In order to prevent functions to be in global scope, you can add export {}; on top (or just export this function):

// 1.ts
export {};

function test(){
    console log("File 1 Error");
}
// 2.ts
export {};

function test(){
    console.log("File 2 Error");
}


问:
R help - why can't I download the nortest package on my work computer?
I need to use R to do some stats at work. The problem is, when I try and download the nortest package, using the following function:

```<code>install.packages("nortest")
</code>```

Or by selecting 'install packages' from the R menu (NB.: I am using a UK CRAN mirror), I get the following error message:

```<code>Error in read.dcf(file = tmpf) :
  Line starting '<head><title> ...' is malformed!
</code>```

I spoke to the IT dept at work and they mentioned that because R is open source, there are blocks on downloading certain things - and we ran a check and the system was blocking my download of nortest, for security reasons. The IT guy did say he wouldn't mind lowering the block just once, if I could then save the (zip?) file so I didn't need to access the internet every time I loaded up the package.

The problem is, I have no idea how to get a copy of 'nortest' as a zip file. And then once I have it, I don't know how to save it so that it loads from a saved file rather than selecting 'install package' from the R menu.

Any help would be very much appreciated.

Thanks,

Kate

答:
Ask your site IT to add an exception to their firewall/content blocking for this CRAN mirror, or download it elsewhere and transfer the file to where you need it:

http://www.stats.bris.ac.uk/R/web/packages/nortest/index.html

Body:
I need to use R to do some stats at work. The problem is, when I try and download the nortest package, using the following function:

install.packages("nortest")

Or by selecting 'install packages' from the R menu (NB.: I am using a UK CRAN mirror), I get the following error message:

Error in read.dcf(file = tmpf) :
  Line starting '<title> ...' is malformed!

I spoke to the IT dept at work and they mentioned that because R is open source, there are blocks on downloading certain things - and we ran a check and the system was blocking my download of nortest, for security reasons. The IT guy did say he wouldn't mind lowering the block just once, if I could then save the (zip?) file so I didn't need to access the internet every time I loaded up the package.

The problem is, I have no idea how to get a copy of 'nortest' as a zip file. And then once I have it, I don't know how to save it so that it loads from a saved file rather than selecting 'install package' from the R menu.

Any help would be very much appreciated.

Thanks,

Kate


问:
From Text file to a pandas dataframe
I have a file which contains list of lists, its a text file, and it looks like that:

```<code>    [[ שומר
 ,קולורבי
 ,קיווי
 ,"תפו""ע פינק ליידי"
 ,גזר
 ,עגבניה
 ,Unknown
 ] ,
[ מארז נייצ'ר ואלי שיבולת שועל עם שבבי שוקולד
 ,פיטנס חטיפי פריכיות דקות קינמון 60 גרם
 ,פריכיות משולשות פלפל
 ,מארז נייצ'ר ואלי שיבולת שועל עם שבבי שוקולד
 ,Unknown
 ,בננה
 ,"תפו""ע פינק ליידי"
 ,"תפו""ע גרנד"
 ,מארז 5 חטיפי פרי דגנים תמר תפוח ללא סוכר
 ,Unknown
 ] ,
[ "תפו""א לבן ארוז דוד משה"
 ,כרוב לבן
 ,קישוא
 ,גזר
 ,בטטה
 ] ,
[ Unknown..........
</code>```

I need to convert it to pandas DataFrame, like wide columnstore, just one list = one row.
Any help would be amazing! I am working with Jupyter Notebook - Python 3.

答:
Read the file text and try below code -

```<code>import json
import pandas as pd

data = open('data.txt', 'r', encoding = 'windows-1255', errors='ignore').read().replace("\r","").replace("\n","")

remove_doulequotes = data.replace('""', '').replace('"', '')
list_of_str = list(map(lambda x: '"{x}"'.format(x=x), remove_doulequotes.split(",")))
final_data = ", ".join(list_of_str).replace('"[[', '[["').replace(']"','"]').replace(']]"', '"]]').replace('"[', '["').replace(']"]', '"]]')

data_in_list = json.loads(final_data)

df = pd.DataFrame(data_in_list)
</code>```

Or You can use ast.literal_eval function also -

```<code>import ast

data = open('data.txt', 'r', encoding = 'windows-1255', errors='ignore').read().replace("\r","").replace("\n","")

remove_doulequotes = data.replace('""', '').replace('"', '')
list_of_str = list(map(lambda x: '"{x}"'.format(x=x), remove_doulequotes.split(",")))
final_data = ", ".join(list_of_str).replace('"[[', '[["').replace(']"','"]').replace(']]"', '"]]').replace('"[', '["').replace(']"]', '"]]')

data_in_list = ast.literal_eval(final_data)

df = pd.DataFrame(data_in_list)
</code>```

Additional codes added for string manipulation to format string properly.

Title: From Text file to a pandas dataframe

Body:
I have a file which contains list of lists, its a text file, and it looks like that:

    [[ שומר
 ,קולורבי
 ,קיווי
 ,"תפו""ע פינק ליידי"
 ,גזר
 ,עגבניה
 ,Unknown
 ] ,
[ מארז נייצ'ר ואלי שיבולת שועל עם שבבי שוקולד
 ,פיטנס חטיפי פריכיות דקות קינמון 60 גרם
 ,פריכיות משולשות פלפל
 ,מארז נייצ'ר ואלי שיבולת שועל עם שבבי שוקולד
 ,Unknown
 ,בננה
 ,"תפו""ע פינק ליידי"
 ,"תפו""ע גרנד"
 ,מארז 5 חטיפי פרי דגנים תמר תפוח ללא סוכר
 ,Unknown
 ] ,
[ "תפו""א לבן ארוז דוד משה"
 ,כרוב לבן
 ,קישוא
 ,גזר
 ,בטטה
 ] ,
[ Unknown..........

I need to convert it to pandas DataFrame, like wide columnstore, just one list = one row.
Any help would be amazing! I am working with Jupyter Notebook - Python 3.

Body:
Read the file text and try below code -

import json
import pandas as pd

data = open('data.txt', 'r', encoding = 'windows-1255', errors='ignore').read().replace("\r","").replace("\n","")

remove_doulequotes = data.replace('""', '').replace('"', '')
list_of_str = list(map(lambda x: '"{x}"'.format(x=x), remove_doulequotes.split(",")))
final_data = ", ".join(list_of_str).replace('"[[', '[["').replace(']"','"]').replace(']]"', '"]]').replace('"[', '["').replace(']"]', '"]]')

data_in_list = json.loads(final_data)

df = pd.DataFrame(data_in_list)

Or You can use ast.literal_eval function also -

import ast

data = open('data.txt', 'r', encoding = 'windows-1255', errors='ignore').read().replace("\r","").replace("\n","")

remove_doulequotes = data.replace('""', '').replace('"', '')
list_of_str = list(map(lambda x: '"{x}"'.format(x=x), remove_doulequotes.split(",")))
final_data = ", ".join(list_of_str).replace('"[[', '[["').replace(']"','"]').replace(']]"', '"]]').replace('"[', '["').replace(']"]', '"]]')

data_in_list = ast.literal_eval(final_data)

df = pd.DataFrame(data_in_list)

Additional codes added for string manipulation to format string properly.


问:
Change the output of the Knex rawquery
I am forced to use raw query with the Knex, since there is an issue with the union

One query, is not that bad. But now I have other type of issue.

All other Knex queries (non raw ones), they simply return an array with the results

For example:

```<code>knex('user_subscription_plan')
        .select('*')
        .where('paused_days', '>', 91)
        .where('status', 'N_PAUSED')
</code>```

will return an array, empty of there is no results.

However, if I run raw query, for example:

```<code>mySqlClient.raw('select * from user')
</code>```

it will return an array, with two arrays inside it.
First one is the normal result, while other one contains some catalogue definitions.

That interferes with my logic. At the end of each call to knex, I have:

```<code>if (result.length > 0) {
   // send email
}
</code>```

Now, when I run the raw Query, the result is always greater then zero.
How can I tell Knex not to send the catalogue definitions, in other words, just send results back, exactly like it does on non raw queries?

答:
You should do it like @horatiu-jeflea answered.

Though we could add some way to knex to tell that also result of raw query should be parsed with default result parser. To make that way to appear in knex you could open feature request to its github issues.

Also there is https://knexjs.org/#Installation-post-process-response which you should be able to override to handle your raw query results are post processed.

Title: Change the output of the Knex rawquery

Body:
I am forced to use raw query with the Knex, since there is an issue with the union

One query, is not that bad. But now I have other type of issue.

All other Knex queries (non raw ones), they simply return an array with the results

For example:

knex('user_subscription_plan')
        .select('*')
        .where('paused_days', '>', 91)
        .where('status', 'N_PAUSED')

will return an array, empty of there is no results.

However, if I run raw query, for example:

mySqlClient.raw('select * from user')

it will return an array, with two arrays inside it.
First one is the normal result, while other one contains some catalogue definitions.

That interferes with my logic. At the end of each call to knex, I have:

if (result.length > 0) {
   // send email
}

Now, when I run the raw Query, the result is always greater then zero.
How can I tell Knex not to send the catalogue definitions, in other words, just send results back, exactly like it does on non raw queries?


问:
Assign (Set) an Application Security Group to Scale Set in Azure
I provisioned a Virtual Machine ScaleSet in Azure. Now, i want to assign an Application Security Group to the Scaleset:

This is the Scaleset

```<code>$vmssWeb = get-azvmss -ResourceGroupName webRG -VMScaleSetName webVMSS
This is the Application Security Group
$asgWeb = Get-AzApplicationSecurityGroup -ResourceGroupName webRG -Name webASG
</code>```

This is the nic associated to the Scaleset

```<code>$nic = $vmss1.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0]
</code>```

This line generates the error when i want to associate the ASG to VMSS

```<code>$nic.IpConfigurations[0].ApplicationSecurityGroups = $asgWeb

</code>```

Usually this works when we work with NICs. Not in this case :-(

```<code>-----------------

Error:
Exception setting "ApplicationSecurityGroups": "Cannot convert the "Microsoft.Azure.Commands.Network.Models.PSApplicationSecurityGroup" value of type
"Microsoft.Azure.Commands.Network.Models.PSApplicationSecurityGroup" to type "System.Collections.Generic.IList`1[Microsoft.Azure.Management.Compute.Models.SubResource]"."
At line:1 char:1
+ $nic.IpConfigurations[0].ApplicationSecurityGroups = $asgWeb
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], SetValueInvocationException
    + FullyQualifiedErrorId : ExceptionWhenSetting
</code>```

Any advice?

答:
With the test, I do not find the PowerShell command which can achieve your purpose. Now the PowerShell command does not have the parameter for the Application Security Group.

But instead, you can use the Azure CLI to achieve it. Use the CLI command like this:

```<code>az vmss update -g group_name -n vmss_name --add virtualMachineProfile.networkProfile.networkInterfaceConfigurations[0].ipConfigurations[0].applicationSecurityGroups id="asg_id"
az vmss update-instance -g group_name -n vmss_name --instance-ids id_number
</code>```

Also, you can associate the ASG to the VMSS through the Azure Template in the creation time.

Body:
I provisioned a Virtual Machine ScaleSet in Azure. Now, i want to assign an Application Security Group to the Scaleset:

This is the Scaleset

$vmssWeb = get-azvmss -ResourceGroupName webRG -VMScaleSetName webVMSS
This is the Application Security Group
$asgWeb = Get-AzApplicationSecurityGroup -ResourceGroupName webRG -Name webASG

This is the nic associated to the Scaleset

$nic = $vmss1.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations[0]

This line generates the error when i want to associate the ASG to VMSS

$nic.IpConfigurations[0].ApplicationSecurityGroups = $asgWeb

Usually this works when we work with NICs. Not in this case :-(

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

Error:
Exception setting "ApplicationSecurityGroups": "Cannot convert the "Microsoft.Azure.Commands.Network.Models.PSApplicationSecurityGroup" value of type
"Microsoft.Azure.Commands.Network.Models.PSApplicationSecurityGroup" to type "System.Collections.Generic.IList`1[Microsoft.Azure.Management.Compute.Models.SubResource]"."
At line:1 char:1
+ $nic.IpConfigurations[0].ApplicationSecurityGroups = $asgWeb
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], SetValueInvocationException
    + FullyQualifiedErrorId : ExceptionWhenSetting

Any advice?

Body:
With the test, I do not find the PowerShell command which can achieve your purpose. Now the PowerShell command does not have the parameter for the Application Security Group.

But instead, you can use the Azure CLI to achieve it. Use the CLI command like this:

az vmss update -g group_name -n vmss_name --add virtualMachineProfile.networkProfile.networkInterfaceConfigurations[0].ipConfigurations[0].applicationSecurityGroups id="asg_id"
az vmss update-instance -g group_name -n vmss_name --instance-ids id_number

Also, you can associate the ASG to the VMSS through the Azure Template in the creation time.


问:
Callkit loudspeaker bug / how WhatsApp fixed it?
I have an app with Callkit functionality. When I press the loudspeaker button, it will flash and animate to the OFF state (sometimes the speaker is set to LOUD but the icon is still OFF). When I tap on it multiple times... it can be clearly seen that this functionality is not behaving correctly.

However, WhatsApp has at the beginning the loudspeaker turned OFF and after 3+ seconds it activates it and its working. Has anyone encountered anything similar and can give me a solution?

Youtube video link to demonstrate my problem

答:
I've fixed the issue by doing following steps.

In CXAnswerCallAction, use below code to set audiosession config.

```<code>RTCDispatcher.dispatchAsync(on: RTCDispatcherQueueType.typeAudioSession) {
let audioSession = RTCAudioSession.sharedInstance()
audioSession.lockForConfiguration()
let configuration = RTCAudioSessionConfiguration.webRTC()
configuration.categoryOptions = [AVAudioSessionCategoryOptions.allowBluetoothA2DP,AVAudioSessionCategoryOptions.duckOthers,
                                 AVAudioSessionCategoryOptions.allowBluetooth]
try? audioSession.setConfiguration(configuration)
audioSession.unlockForConfiguration()}
</code>```

After call connected, I'm resetting AudioSession category to default.

```<code>func configureAudioSession() {
let session = RTCAudioSession.sharedInstance()
session.lockForConfiguration()
do {
    try session.setCategory(AVAudioSession.Category.playAndRecord.rawValue, with: .allowBluetooth)
    try session.setMode(AVAudioSession.Mode.default.rawValue)
    try session.setPreferredSampleRate(44100.0)
    try session.setPreferredIOBufferDuration(0.005)
}
catch let error {
    debugPrint("Error changeing AVAudioSession category: \(error)")
}
session.unlockForConfiguration()}
</code>```

Thanks to SO @Алексей Смольский for the help.

Body:
I've fixed the issue by doing following steps.

In CXAnswerCallAction, use below code to set audiosession config.

RTCDispatcher.dispatchAsync(on: RTCDispatcherQueueType.typeAudioSession) {
let audioSession = RTCAudioSession.sharedInstance()
audioSession.lockForConfiguration()
let configuration = RTCAudioSessionConfiguration.webRTC()
configuration.categoryOptions = [AVAudioSessionCategoryOptions.allowBluetoothA2DP,AVAudioSessionCategoryOptions.duckOthers,
                                 AVAudioSessionCategoryOptions.allowBluetooth]
try? audioSession.setConfiguration(configuration)
audioSession.unlockForConfiguration()}

After call connected, I'm resetting AudioSession category to default.

func configureAudioSession() {
let session = RTCAudioSession.sharedInstance()
session.lockForConfiguration()
do {
    try session.setCategory(AVAudioSession.Category.playAndRecord.rawValue, with: .allowBluetooth)
    try session.setMode(AVAudioSession.Mode.default.rawValue)
    try session.setPreferredSampleRate(44100.0)
    try session.setPreferredIOBufferDuration(0.005)
}
catch let error {
    debugPrint("Error changeing AVAudioSession category: \(error)")
}
session.unlockForConfiguration()}

Thanks to SO @Алексей Смольский for the help.


问:
How to disable html button using JSTL tags
I want disable HTML button depending on value present in Spring bean.I am using JSTL empty property but no luck.

Here is my code

```<code>   <input type="submit" value="SendEmail" disabled="${empty reportNotificationFbo.providersList}" >
</code>```

Here reportNotificationFbo is spring bean and providersList is a list.

I want to disable Submit button if providersList is empty.

-Thanks.

答:
State of the button is controlled by the presence of disabled attribute, not by its value. Try the following:

```<code><input type="submit" value="SendEmail"
    "${(empty reportNotificationFbo.providersList) ? 'disabled' : ''}" >
</code>```

Body:
I want disable HTML button depending on value present in Spring bean.I am using JSTL empty property but no luck.

Here is my code

   <input type="submit" value="SendEmail" disabled="${empty reportNotificationFbo.providersList}" >

Here reportNotificationFbo is spring bean and providersList is a list.

I want to disable Submit button if providersList is empty.

-Thanks.

Body:
State of the button is controlled by the presence of disabled attribute, not by its value. Try the following:

<input type="submit" value="SendEmail"
    "${(empty reportNotificationFbo.providersList) ? 'disabled' : ''}" >