问:
How to dynamically update my gallery data
Hello Respected Comrades,

I made a gallery app. initially I get a data of media from phone.
but when i add some new photos to device. i cant see them until :

re install app

fetching in view will appear (this is just a temperory fix)

I want to update my data dynamically with respect to phone data

code:
import UIKit
import Foundation
import Photos
import CoreData

enum MediaType{
case video, photo
}

View model

```<code>class GalleryPageViewModel : BaseViewModel{
    var mediaArray = Spectator<MediaArray?>(value:
    [])
    var title = "Gallery"
    var appDelegate:AppDelegate?
    var context : NSManagedObjectContext?
    let responder : AppResponder
    var tempMedia = [MediaModel]()

    init(with responder:AppResponder){
        self.responder = responder
        super.init()
    }
}

extension GalleryPageViewModel{
    func populatePhotos(){
        mediaArray.value = []
        tempMedia = []
        PHPhotoLibrary.requestAuthorization{ [weak self] status in
            if status == .authorized{
                let assets = PHAsset.fetchAssets(with: nil)
                assets.enumerateObjects{ (object,_,_) in
                    var image = UIImage()
                    image = self!.conversionPhotoToImage(asset: object)
                    var mediaType : MediaType = .photo
                    if object.mediaType == .video{
                        mediaType = .video
                    }
                    let media = MediaModel(img: image, asset: object, mediaType: mediaType)
                    self?.tempMedia.append(media)
                }
            }
            else{
                print("auth failed")
            }
            self?.setUpData()

        }
    }

    func conversionPhotoToImage(asset : PHAsset) -> UIImage{
        let manager = PHImageManager.default()
        var media = UIImage()
        let requestOptions=PHImageRequestOptions()
        requestOptions.isSynchronous=true
        requestOptions.deliveryMode = .highQualityFormat

        manager.requestImage(for: asset, targetSize: CGSize(width: 1000, height: 1000), contentMode:.aspectFill, options: requestOptions) { image,_ in
            media = image!
        }
        return media
    }

    func setUpData(){
        self.mediaArray.value = tempMedia
    }

}

extension GalleryPageViewModel{
    func numberOfItemsInSection() -> Int{
        return mediaArray.value?.count ?? 0
    }

    func didSelectAtRow(index:IndexPath){
        self.responder.pushToDetailVc(data: mediaArray.value![index.row])
    }
}

extension GalleryPageViewModel{
    func setUpCoreData(){
        appDelegate = UIApplication.shared.delegate as! AppDelegate
        context = appDelegate?.persistentContainer.viewContext
    }

    func storeInCoreData(){
        let entity = NSEntityDescription.entity(forEntityName: "MediaData", in: context!)
        let newUser = NSManagedObject(entity: entity!, insertInto: context)
        var i = 1
        for data in mediaArray.value!{
            newUser.setValue(data.img, forKey: "image")
            newUser.setValue(data.duration, forKey: "duration")
            newUser.setValue("data", forKey: "mediaType")
            newUser.setValue(data.location, forKey: "location")
            newUser.setValue(data.creationDate, forKey: "creationDate")
            var id = String()
            if data.mediaType == .photo{
                id = "imgEn\(i)"
            }
            else{
                id = "vidEn\(i)"
            }
            i+=1
            newUser.setValue(id, forKey: "id")
        }

    }
}
</code>```

View controller

```<code>
import UIKit
import Photos

class GalleryPageViewController: BaseViewController {

    var galleryCollectionView : UICollectionView?

    var galleryCollectionViewFlowLayout : UICollectionViewFlowLayout? = nil

    var viewModel: GalleryPageViewModel? {
        didSet {
            self.bindViewModel()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = viewModel?.title

        view.backgroundColor = .systemBackground
        setUpFlowLayout()
        galleryCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: galleryCollectionViewFlowLayout!)
        galleryCollectionView?.register(MediaCollectionViewCell.self, forCellWithReuseIdentifier: "cell")

        setUpCollectionView()
        viewConstraintsForGalleryPage()
        viewModel?.populatePhotos()

    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

}

// MARK: - UI WORKS

extension GalleryPageViewController{
    func setUpFlowLayout(){
        galleryCollectionViewFlowLayout = UICollectionViewFlowLayout()
        galleryCollectionViewFlowLayout?.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        galleryCollectionViewFlowLayout?.itemSize = CGSize(width: (view.frame.width/2) - 20, height: (self.view.frame.width/2)-10)
    }
    func setUpCollectionView(){

        galleryCollectionView?.dataSource = self
        galleryCollectionView?.delegate = self
    }

    func viewConstraintsForGalleryPage(){
        // adding sub view to maintain heirarchy.
        view.addSubview(galleryCollectionView!)

        // constraints for views in this page

        // collection view
        galleryCollectionView?.translatesAutoresizingMaskIntoConstraints = false
//        galleryCollectionView?.backgroundColor = .blue
        galleryCollectionView?.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,constant: 10).isActive = true
        galleryCollectionView?.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
        galleryCollectionView?.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,constant: 10).isActive = true
        galleryCollectionView?.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true

    }
}

//MARK: - COLLECTION VIEW DELEGATE AND DATA SOURCE

extension GalleryPageViewController : UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        vc.data = viewModel?.mediaArray.value?[indexPath.row]
        viewModel?.didSelectAtRow(index: indexPath)
    }
}

extension GalleryPageViewController : UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.numberOfItemsInSection() ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MediaCollectionViewCell
        let cellData = viewModel?.mediaArray.value?[indexPath.row]
        cell.imageView.image = cellData?.img
        if cellData?.mediaType == .video{
            cell.playBtn.isHidden = false
            cell.durationLabel.isHidden = false
            let manager = PHImageManager.default()
            manager.requestAVAsset(forVideo: (cellData?.asset)!, options: nil){asset,_,_ in
                let duration = asset?.duration
                let durationTime = CMTimeGetSeconds(duration!)
                let finalTime = durationTime/60

                DispatchQueue.main.async {
                    cell.durationLabel.text = "\(Int(finalTime)) : \(Int(durationTime) % 60)"
                }

            }
        }
        else{
            cell.playBtn.isHidden = true
            cell.durationLabel.isHidden = true
        }
        return cell
    }
}

//MARK: - BINDING VARIABLES

extension GalleryPageViewController{
    private func bindViewModel(){
        viewModel?.mediaArray.bind { [weak self] _ in
            print("i am gonna reload")
            print(self?.viewModel?.mediaArray.value?.isEmpty)
            DispatchQueue.main.async {
                self?.galleryCollectionView?.reloadData()
            }
        }
    }
}

</code>```

Body:
Hello Respected Comrades,

I made a gallery app. initially I get a data of media from phone.
but when i add some new photos to device. i cant see them until :

re install app

fetching in view will appear (this is just a temperory fix)

I want to update my data dynamically with respect to phone data

code:
import UIKit
import Foundation
import Photos
import CoreData

enum MediaType{
case video, photo
}

View model

class GalleryPageViewModel : BaseViewModel{
    var mediaArray = Spectator<MediaArray?>(value:
    [])
    var title = "Gallery"
    var appDelegate:AppDelegate?
    var context : NSManagedObjectContext?
    let responder : AppResponder
    var tempMedia = [MediaModel]()

    init(with responder:AppResponder){
        self.responder = responder
        super.init()
    }
}

extension GalleryPageViewModel{
    func populatePhotos(){
        mediaArray.value = []
        tempMedia = []
        PHPhotoLibrary.requestAuthorization{ [weak self] status in
            if status == .authorized{
                let assets = PHAsset.fetchAssets(with: nil)
                assets.enumerateObjects{ (object,_,_) in
                    var image = UIImage()
                    image = self!.conversionPhotoToImage(asset: object)
                    var mediaType : MediaType = .photo
                    if object.mediaType == .video{
                        mediaType = .video
                    }
                    let media = MediaModel(img: image, asset: object, mediaType: mediaType)
                    self?.tempMedia.append(media)
                }
            }
            else{
                print("auth failed")
            }
            self?.setUpData()

        }
    }

    func conversionPhotoToImage(asset : PHAsset) -> UIImage{
        let manager = PHImageManager.default()
        var media = UIImage()
        let requestOptions=PHImageRequestOptions()
        requestOptions.isSynchronous=true
        requestOptions.deliveryMode = .highQualityFormat

        manager.requestImage(for: asset, targetSize: CGSize(width: 1000, height: 1000), contentMode:.aspectFill, options: requestOptions) { image,_ in
            media = image!
        }
        return media
    }

    func setUpData(){
        self.mediaArray.value = tempMedia
    }

}

extension GalleryPageViewModel{
    func numberOfItemsInSection() -> Int{
        return mediaArray.value?.count ?? 0
    }

    func didSelectAtRow(index:IndexPath){
        self.responder.pushToDetailVc(data: mediaArray.value![index.row])
    }
}

extension GalleryPageViewModel{
    func setUpCoreData(){
        appDelegate = UIApplication.shared.delegate as! AppDelegate
        context = appDelegate?.persistentContainer.viewContext
    }

    func storeInCoreData(){
        let entity = NSEntityDescription.entity(forEntityName: "MediaData", in: context!)
        let newUser = NSManagedObject(entity: entity!, insertInto: context)
        var i = 1
        for data in mediaArray.value!{
            newUser.setValue(data.img, forKey: "image")
            newUser.setValue(data.duration, forKey: "duration")
            newUser.setValue("data", forKey: "mediaType")
            newUser.setValue(data.location, forKey: "location")
            newUser.setValue(data.creationDate, forKey: "creationDate")
            var id = String()
            if data.mediaType == .photo{
                id = "imgEn\(i)"
            }
            else{
                id = "vidEn\(i)"
            }
            i+=1
            newUser.setValue(id, forKey: "id")
        }

    }
}

View controller

import UIKit
import Photos

class GalleryPageViewController: BaseViewController {

    var galleryCollectionView : UICollectionView?

    var galleryCollectionViewFlowLayout : UICollectionViewFlowLayout? = nil

    var viewModel: GalleryPageViewModel? {
        didSet {
            self.bindViewModel()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = viewModel?.title

        view.backgroundColor = .systemBackground
        setUpFlowLayout()
        galleryCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: galleryCollectionViewFlowLayout!)
        galleryCollectionView?.register(MediaCollectionViewCell.self, forCellWithReuseIdentifier: "cell")

        setUpCollectionView()
        viewConstraintsForGalleryPage()
        viewModel?.populatePhotos()

    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

}

// MARK: - UI WORKS

extension GalleryPageViewController{
    func setUpFlowLayout(){
        galleryCollectionViewFlowLayout = UICollectionViewFlowLayout()
        galleryCollectionViewFlowLayout?.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        galleryCollectionViewFlowLayout?.itemSize = CGSize(width: (view.frame.width/2) - 20, height: (self.view.frame.width/2)-10)
    }
    func setUpCollectionView(){

        galleryCollectionView?.dataSource = self
        galleryCollectionView?.delegate = self
    }

    func viewConstraintsForGalleryPage(){
        // adding sub view to maintain heirarchy.
        view.addSubview(galleryCollectionView!)

        // constraints for views in this page

        // collection view
        galleryCollectionView?.translatesAutoresizingMaskIntoConstraints = false
//        galleryCollectionView?.backgroundColor = .blue
        galleryCollectionView?.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,constant: 10).isActive = true
        galleryCollectionView?.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
        galleryCollectionView?.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,constant: 10).isActive = true
        galleryCollectionView?.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true

    }
}

//MARK: - COLLECTION VIEW DELEGATE AND DATA SOURCE

extension GalleryPageViewController : UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        vc.data = viewModel?.mediaArray.value?[indexPath.row]
        viewModel?.didSelectAtRow(index: indexPath)
    }
}

extension GalleryPageViewController : UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.numberOfItemsInSection() ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MediaCollectionViewCell
        let cellData = viewModel?.mediaArray.value?[indexPath.row]
        cell.imageView.image = cellData?.img
        if cellData?.mediaType == .video{
            cell.playBtn.isHidden = false
            cell.durationLabel.isHidden = false
            let manager = PHImageManager.default()
            manager.requestAVAsset(forVideo: (cellData?.asset)!, options: nil){asset,_,_ in
                let duration = asset?.duration
                let durationTime = CMTimeGetSeconds(duration!)
                let finalTime = durationTime/60

                DispatchQueue.main.async {
                    cell.durationLabel.text = "\(Int(finalTime)) : \(Int(durationTime) % 60)"
                }

            }
        }
        else{
            cell.playBtn.isHidden = true
            cell.durationLabel.isHidden = true
        }
        return cell
    }
}

//MARK: - BINDING VARIABLES

extension GalleryPageViewController{
    private func bindViewModel(){
        viewModel?.mediaArray.bind { [weak self] _ in
            print("i am gonna reload")
            print(self?.viewModel?.mediaArray.value?.isEmpty)
            DispatchQueue.main.async {
                self?.galleryCollectionView?.reloadData()
            }
        }
    }
}


来源: stackexchange

问:
Factor with 2 levels yet still the " Error in `contrasts<-`" Bug
My problem sounds basic enough, yet i can't figure it out.
I try to fit a simple model with one outcome and a factor with two levels as the predictor.

```<code>model <- lm(outcome~Factor, data = df)
</code>```

But I get following error:

```<code>Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
  contrasts can be applied only to factors with 2 or more levels
</code>```

But when I check the number of levels of my factor it tells me there are 2 levels

```<code>nlevels(data$Factor)
[1] 2
</code>```

As well as the number of unique values also being > 1

```<code>length(unique(data$Factor))
[1] 2
</code>```

Any help to solve this issue would be highly appreciated.

ContentLicense: CC BY-SA 4.0

Body:
My problem sounds basic enough, yet i can't figure it out.
I try to fit a simple model with one outcome and a factor with two levels as the predictor.

model <- lm(outcome~Factor, data = df)

But I get following error:

Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
  contrasts can be applied only to factors with 2 or more levels

But when I check the number of levels of my factor it tells me there are 2 levels

nlevels(data$Factor)
[1] 2

As well as the number of unique values also being > 1

length(unique(data$Factor))
[1] 2

Any help to solve this issue would be highly appreciated.


问:
push data of an API to local data.js file
Hello Everyone Help me with the issue which I am facing i have a file called data.js it contains some obj locally and I made a request to an API and got some obj back I want to save that obj in my data.js file

wanted to add the data in the data.js file


问:
Angular Storybook cypress tests failing on Azure pipelines during build
I have a libs component project. Recently we updated to Angular 14 to Angular 15

Locally when i run npm run storybook:cypress - all works fine and tests have passed.

But when the tests are run on Azure on pull request - they fail with next error:

The injectable 'PlatformLocation' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.

And i totally have no idea what is wrong, all similar information in the Web is related to updating Angurlar to 13 version.

What i'm trying to say, if the configs were wrong, then it would fail already on Angular 14. Where i should start digging?

I have tried:

removing angularCompilerOptions from TSconfig.lib.json ( prod also )

adding compilationMode = full instead of current partial from TSconfig.lib.json ( prod also )

checked that test-setup.ts imports 'jset-preset-angular/setup-jest' instead of simple setip-jest

I have checked that PlatformLocation is not used somewhere incorrectly, e.g. imports component instead of module ( but my code doesn't use that at all )

Project structure is next:

```<code>apps
--myproject-e2e
----src
----cypress.json
----tsconfig.json
libs
--myproject
----src
----package.json
----tsconfig.json
----tsconfig.lib.json
----tsconfig.lib.prod.json
package.json
angular.json
jest.config.json
jest.preset.json
tsconfig.json
tsconfig.base.json
</code>```

Body:
I have a libs component project. Recently we updated to Angular 14 to Angular 15

Locally when i run npm run storybook:cypress - all works fine and tests have passed.

But when the tests are run on Azure on pull request - they fail with next error:

The injectable 'PlatformLocation' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.

And i totally have no idea what is wrong, all similar information in the Web is related to updating Angurlar to 13 version.

What i'm trying to say, if the configs were wrong, then it would fail already on Angular 14. Where i should start digging?

I have tried:

removing angularCompilerOptions from TSconfig.lib.json ( prod also )

adding compilationMode = full instead of current partial from TSconfig.lib.json ( prod also )

checked that test-setup.ts imports 'jset-preset-angular/setup-jest' instead of simple setip-jest

I have checked that PlatformLocation is not used somewhere incorrectly, e.g. imports component instead of module ( but my code doesn't use that at all )

Project structure is next:

apps
--myproject-e2e
----src
----cypress.json
----tsconfig.json
libs
--myproject
----src
----package.json
----tsconfig.json
----tsconfig.lib.json
----tsconfig.lib.prod.json
package.json
angular.json
jest.config.json
jest.preset.json
tsconfig.json
tsconfig.base.json


问:
React Calculator (using reducer hook), issue with .match() and operation
I have made a basic calculator in React using the reducer hook, however, there are two issues arising:
I have the state as {prevOperand,currentOperand,operation}

In the case where two operators are clicked consecutively, I want to check if the last character in the string in the currentOperand contains any of the arithematic operators so that I can return the same state back (preventing the second selected operator from entering). However, the .match method doesn't seem to be working, and the return statement in the 'if' loop isn't getting executed. What might be the problem here?

I have used a function for evaluating the numbers entered in currentOperand, which returns the value of the varible "result", which is equated to the currentOperand.Afterwards, when I press any operation (or) the DEL (DELETE) button , I am getting an error. How to resolve this????

```<code>import { ACTIONS } from "./Actions";

var symbol ;

function reducer (state, action) {
  symbol = ['*','.','+','-','/']
  console.log(state)
  console.log(action)
  switch(action.type){
    case ACTIONS.ADD_DIGIT: //add digit
      return {...state, currentOperand: `${state.currentOperand || ""}${action.payload}`}
    case ACTIONS.DELETE_DIGIT: //single digit
      return {...state, currentOperand: state.currentOperand.substring(0,state.currentOperand.length-1)}
    case ACTIONS.CLEAR:  //clear output
      return { prevOperand: null, currentOperand: 0 ,operation: null}
    case ACTIONS.CHOOSE_OPERATION:
     if(action.payload && state.currentOperand == null) { // operation and evaluation shouldn't be the first button pressed
        return state
      } else if(state.currentOperand.includes('/') || state.currentOperand.includes('*') ||
      state.currentOperand.includes('+')|| state.currentOperand.includes('-')) {
        // CHECK FOR THE ERROR FROM HERE ON --------------------------------------
          let string = state.currentOperand
          let variable = '/^[*+-/]*$/'
          console.log(string)
          if(string.charAt([string.length - 1]).match(variable)) {
            console.log("operator present")
             return state  // FIRST RETURN STATEMENT -------------------
          }
              const numbers = state.currentOperand.split(/([-+*/])/g) // the number is evaluated
              const result = evaluateNum(numbers[0], numbers[1],numbers[2])
              return {currentOperand : result} //SECOND RETURN STATEMENT -------------------

      } else if(action.payload ==='.' && state.currentOperand.includes('.')){ //extra decimals
        return state
      } else{ //displaying the operations
      return {...state, currentOperand: `${state.currentOperand}${action.payload}`}
     }

    case ACTIONS.EVALUATION: //calling evaluation function (when = is pressed)
        const numbers = state.currentOperand.split(/([-+*/])/g) // the number is evaluated
        const result = evaluateNum(numbers[0], numbers[1],numbers[2])
        return {currentOperand : result} // AFTER THIS COMMAND, UNABLE TO USE ANY ARTHEMATIC OPERATORS OR
                                       //DELETE BUTTON
    default:
      return state
   }
}
 ----------------------------UPTO HERE ------------------------------------------------------------
// evaluation function
function evaluateNum( prevOperand, operation, currentOperand){
   let prevNum = parseFloat(prevOperand)
   let currentNum = parseFloat(currentOperand)
   console.log(prevNum)
   console.log(currentNum)
   if (operation === '+'){
       return prevNum + currentNum
   } else if(operation === '-') {
      return  prevNum - currentNum
   } else if(operation === '*') {
      return  prevNum * currentNum
   } else if(operation === '/' && currentOperand!= '0') {
      return prevNum / currentNum
   }
}

export default function App() {
  const [{prevOperand=null, currentOperand =0, operation=null}, dispatch] = useReducer(reducer,{})
  return (
    <div className="calculator-grid">
      <div className="output">
        <div className="prev-operand">{prevOperand} {operation}</div>
        <div className="current-operand">{currentOperand}</div>
      </div>
        <button className="span-two" onClick={()=> {
          dispatch({type: ACTIONS.CLEAR , payload:null})
        }}>AC</button>
        <button onClick={()=> {
          dispatch({type: ACTIONS.DELETE_DIGIT , payload:null})
        }}>DEL</button>
        <ButtonOperation operation='/' dispatch={dispatch}/>
        <ButtonDigit number="1" dispatch={dispatch}/>
        <ButtonDigit number="2" dispatch={dispatch}/>
        <ButtonDigit number="3" dispatch={dispatch}/>
        <ButtonOperation operation='*' dispatch={dispatch}/>
        <ButtonDigit number="4" dispatch={dispatch}/>
        <ButtonDigit number="5" dispatch={dispatch}/>
        <ButtonDigit number="6" dispatch={dispatch}/>
        <ButtonOperation operation='+' dispatch={dispatch}/>
        <ButtonDigit number="7" dispatch={dispatch}/>
        <ButtonDigit number="8" dispatch={dispatch}/>
        <ButtonDigit number="9" dispatch={dispatch}/>
        <ButtonOperation operation='-' dispatch={dispatch}/>
        <ButtonOperation operation='.' dispatch={dispatch}/>
        <ButtonDigit number="0" dispatch={dispatch}/>
        <button className="span-two" onClick={()=> {
          dispatch({type: ACTIONS.EVALUATION , payload:'='})
        }}>=</button>
    </div>
  );
}

 </code>```

 THE ACTIONS OBJECT PASSED INTO THE REDUCER  ---->

CHOOSE_DIGIT: ADDING DIGIT TO STRING/DISPLAY

DELETE_DIGIT: REMOVE THE LAST CHARACTER ENTERED

CLEAR: EMPTY THE DISPLAY AND VARIABLES

CHOOSE_OPERATION: SELECT *, /,+,-, . (DECIMAL)

EVALUATION: PRESS = SIGN
```

Body:
I have made a basic calculator in React using the reducer hook, however, there are two issues arising:
I have the state as {prevOperand,currentOperand,operation}

In the case where two operators are clicked consecutively, I want to check if the last character in the string in the currentOperand contains any of the arithematic operators so that I can return the same state back (preventing the second selected operator from entering). However, the .match method doesn't seem to be working, and the return statement in the 'if' loop isn't getting executed. What might be the problem here?

I have used a function for evaluating the numbers entered in currentOperand, which returns the value of the varible "result", which is equated to the currentOperand.Afterwards, when I press any operation (or) the DEL (DELETE) button , I am getting an error. How to resolve this????

import { ACTIONS } from "./Actions";

var symbol ;

function reducer (state, action) {
  symbol = ['*','.','+','-','/']
  console.log(state)
  console.log(action)
  switch(action.type){
    case ACTIONS.ADD_DIGIT: //add digit
      return {...state, currentOperand: `${state.currentOperand || ""}${action.payload}`}
    case ACTIONS.DELETE_DIGIT: //single digit
      return {...state, currentOperand: state.currentOperand.substring(0,state.currentOperand.length-1)}
    case ACTIONS.CLEAR:  //clear output
      return { prevOperand: null, currentOperand: 0 ,operation: null}
    case ACTIONS.CHOOSE_OPERATION:
     if(action.payload && state.currentOperand == null) { // operation and evaluation shouldn't be the first button pressed
        return state
      } else if(state.currentOperand.includes('/') || state.currentOperand.includes('*') ||
      state.currentOperand.includes('+')|| state.currentOperand.includes('-')) {
        // CHECK FOR THE ERROR FROM HERE ON --------------------------------------
          let string = state.currentOperand
          let variable = '/^[*+-/]*$/'
          console.log(string)
          if(string.charAt([string.length - 1]).match(variable)) {
            console.log("operator present")
             return state  // FIRST RETURN STATEMENT -------------------
          }
              const numbers = state.currentOperand.split(/([-+*/])/g) // the number is evaluated
              const result = evaluateNum(numbers[0], numbers[1],numbers[2])
              return {currentOperand : result} //SECOND RETURN STATEMENT -------------------

      } else if(action.payload ==='.' && state.currentOperand.includes('.')){ //extra decimals
        return state
      } else{ //displaying the operations
      return {...state, currentOperand: `${state.currentOperand}${action.payload}`}
     }

    case ACTIONS.EVALUATION: //calling evaluation function (when = is pressed)
        const numbers = state.currentOperand.split(/([-+*/])/g) // the number is evaluated
        const result = evaluateNum(numbers[0], numbers[1],numbers[2])
        return {currentOperand : result} // AFTER THIS COMMAND, UNABLE TO USE ANY ARTHEMATIC OPERATORS OR
                                       //DELETE BUTTON
    default:
      return state
   }
}
 ----------------------------UPTO HERE ------------------------------------------------------------
// evaluation function
function evaluateNum( prevOperand, operation, currentOperand){
   let prevNum = parseFloat(prevOperand)
   let currentNum = parseFloat(currentOperand)
   console.log(prevNum)
   console.log(currentNum)
   if (operation === '+'){
       return prevNum + currentNum
   } else if(operation === '-') {
      return  prevNum - currentNum
   } else if(operation === '*') {
      return  prevNum * currentNum
   } else if(operation === '/' && currentOperand!= '0') {
      return prevNum / currentNum
   }
}

export default function App() {
  const [{prevOperand=null, currentOperand =0, operation=null}, dispatch] = useReducer(reducer,{})
  return (

{prevOperand} {operation}

{currentOperand}

        <button className="span-two" onClick={()=> {
          dispatch({type: ACTIONS.CLEAR , payload:null})
        }}>AC</button>
        <button onClick={()=> {
          dispatch({type: ACTIONS.DELETE_DIGIT , payload:null})
        }}>DEL</button>
        <ButtonOperation operation='/' dispatch={dispatch}/>
        <ButtonDigit number="1" dispatch={dispatch}/>
        <ButtonDigit number="2" dispatch={dispatch}/>
        <ButtonDigit number="3" dispatch={dispatch}/>
        <ButtonOperation operation='*' dispatch={dispatch}/>
        <ButtonDigit number="4" dispatch={dispatch}/>
        <ButtonDigit number="5" dispatch={dispatch}/>
        <ButtonDigit number="6" dispatch={dispatch}/>
        <ButtonOperation operation='+' dispatch={dispatch}/>
        <ButtonDigit number="7" dispatch={dispatch}/>
        <ButtonDigit number="8" dispatch={dispatch}/>
        <ButtonDigit number="9" dispatch={dispatch}/>
        <ButtonOperation operation='-' dispatch={dispatch}/>
        <ButtonOperation operation='.' dispatch={dispatch}/>
        <ButtonDigit number="0" dispatch={dispatch}/>
        <button className="span-two" onClick={()=> {
          dispatch({type: ACTIONS.EVALUATION , payload:'='})
        }}>=</button>

  );
}

 ```

 THE ACTIONS OBJECT PASSED INTO THE REDUCER  ---->

CHOOSE_DIGIT: ADDING DIGIT TO STRING/DISPLAY

DELETE_DIGIT: REMOVE THE LAST CHARACTER ENTERED

CLEAR: EMPTY THE DISPLAY AND VARIABLES

CHOOSE_OPERATION: SELECT *, /,+,-, . (DECIMAL)

EVALUATION: PRESS = SIGN


问:
how to create a data connector for Azure key vault in Sentinel using terraform?
I want to assign policy to my keyvault using Azure sentinel data connectors uisng terraform code.
I dont find any data connectors related to key vault data connectors, is it still not existing or any document on how to achive this?

the params to be updated:

scope ( subscription/RG name)
Log analytics workspace name
Need terraform code for this Azure portal

I tried checking the code in Hashicorp website,
In the sentinel sub tab, I found few data connectors related to AD but not related to keyvault and firewall..

look for the keyvault data connector asisgn policy code


问:
allowing run time location permission in android, also turn on the device location icon?
```<code>public int numbPermissions = 9;
  public String[] permissions = new String[numbPermissions];

@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    permissions[0] = android.Manifest.permission.ACCESS_NETWORK_STATE;
    permissions[1] = android.Manifest.permission.ACCESS_WIFI_STATE;
    permissions[2] = android.Manifest.permission.CHANGE_WIFI_STATE;
    permissions[3] = android.Manifest.permission.INTERNET;
    permissions[4] = android.Manifest.permission.READ_EXTERNAL_STORAGE;
    permissions[5] = android.Manifest.permission.CHANGE_NETWORK_STATE;
    permissions[6] = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
    permissions[7] = android.Manifest.permission.ACCESS_COARSE_LOCATION;
    permissions[8] = android.Manifest.permission.ACCESS_FINE_LOCATION;
    //permissions[9] = android.Manifest.permission.ACCESS_BACKGROUND_LOCATION;

    if (!checkPermissions()) {
      ActivityCompat.requestPermissions(MainActivity.this, permissions, 49);
    } else {
      Intent intent = new Intent(MainActivity.this, FileActivity.class);
//      intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
      this.startActivity(intent);
    }

  }
</code>```

Above code is in onCreate. Below code is as follows:

```<code>@Override
      public void onRequestPermissionsResult(int requestCode,
                                             @NonNull String permissions[], @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
          case 49: {
            if (!checkPermissions()) {
              ActivityCompat.requestPermissions(MainActivity.this, permissions, 49);
            } else {
              Intent intent = new Intent(MainActivity.this, FileActivity.class);
    //          intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
              this.startActivity(intent);
            }
          }
        }
      }

  public boolean checkPermissions() {
    for (int i = 0; i < numbPermissions; i++) {
      if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED)
        return false;
    }
    return true;
  }
</code>```

I am using above code for runtime location permission. but
when I am allowing location permission, it is not turning on the location icon of android device.

what is wrong I am doing here?

Body:
public int numbPermissions = 9;
  public String[] permissions = new String[numbPermissions];

@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    permissions[0] = android.Manifest.permission.ACCESS_NETWORK_STATE;
    permissions[1] = android.Manifest.permission.ACCESS_WIFI_STATE;
    permissions[2] = android.Manifest.permission.CHANGE_WIFI_STATE;
    permissions[3] = android.Manifest.permission.INTERNET;
    permissions[4] = android.Manifest.permission.READ_EXTERNAL_STORAGE;
    permissions[5] = android.Manifest.permission.CHANGE_NETWORK_STATE;
    permissions[6] = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
    permissions[7] = android.Manifest.permission.ACCESS_COARSE_LOCATION;
    permissions[8] = android.Manifest.permission.ACCESS_FINE_LOCATION;
    //permissions[9] = android.Manifest.permission.ACCESS_BACKGROUND_LOCATION;

    if (!checkPermissions()) {
      ActivityCompat.requestPermissions(MainActivity.this, permissions, 49);
    } else {
      Intent intent = new Intent(MainActivity.this, FileActivity.class);
//      intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
      this.startActivity(intent);
    }

  }

Above code is in onCreate. Below code is as follows:

@Override
      public void onRequestPermissionsResult(int requestCode,
                                             @NonNull String permissions[], @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
          case 49: {
            if (!checkPermissions()) {
              ActivityCompat.requestPermissions(MainActivity.this, permissions, 49);
            } else {
              Intent intent = new Intent(MainActivity.this, FileActivity.class);
    //          intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
              this.startActivity(intent);
            }
          }
        }
      }

  public boolean checkPermissions() {
    for (int i = 0; i < numbPermissions; i++) {
      if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED)
        return false;
    }
    return true;
  }

I am using above code for runtime location permission. but
when I am allowing location permission, it is not turning on the location icon of android device.

what is wrong I am doing here?


问:
the userAction option of vue-video-player does not work
I want to remove the click event which switch player status between play and pause.

Here is my code.

```<code><template>
  <video-player
    ref="videoPlayer"
    :options="playerOptions"
    :playsinline="false"
    @play="onPlayerPlay($event)"
    @pause="onPlayerPause($event)"
    @ended="onPlayerEnded($event)"
    @loadeddata="onPlayerLoadeddata($event)"
    @waiting="onPlayerWaiting($event)"
    @playing="onPlayerPlaying($event)"
    @timeupdate="onPlayerTimeupdate($event)"
    @canplay="onPlayerCanplay($event)"
    @canplaythrough="onPlayerCanplaythrough($event)"
    @ready="playerReadied"
    @statechanged="playerStateChanged($event)"
  />
</template>

.........................
data() {
    return {
      // videojs options
      playerOptions: {
        autoplay: false,
        muted: false,
        preload: 'auto',
        language: 'zh-CN',
        playbackRates: [0.75, 1.0, 1.25, 1.5, 2.0], // 播放速度
        aspectRatio: '16:9',
        fluid: true,//  当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        notSupportedMessage: '此视频暂无法播放，请刷新后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controls: true, // 下面的控制按钮
        bigPlayButton: false,
        controlBar: {
          playToggle: false, // 播放按钮
          timeDivider: false, // 时间分割线
          durationDisplay: false, // 总时间
          remainingTimeDisplay: false, // 剩余播放时间
          progressControl: true, // 进度条
          fullscreenToggle: false // 全屏按钮
        },
        sources: [{
          type: 'video/mp4',
          // mp4
          src: ''
          // webm
          // src: "https://cdn.theguardian.tv/webM/2015/07/20/150716YesMen_synd_768k_vp8.webm"
        }],
        userActions: {
          click: false // it does not work
        }
      }
    }
  },
</code>```

refer to userAction

Controls how clicking on the player/tech operates. If set to false, clicking is disabled and will no longer cause the player to toggle between paused and playing. If controls are disabled with controls: false, this will not call the handler function.
If undefined or set to true, clicking is enabled and toggles the player between paused and play. To override the default click handling, set userActions.click to a function which accepts a click event (in this example it will request Full Screen, the same as a userAction.doubleClick):

Body:
I want to remove the click event which switch player status between play and pause.

Here is my code.

<template>
  <video-player
    ref="videoPlayer"
    :options="playerOptions"
    :playsinline="false"
    @play="onPlayerPlay($event)"
    @pause="onPlayerPause($event)"
    @ended="onPlayerEnded($event)"
    @loadeddata="onPlayerLoadeddata($event)"
    @waiting="onPlayerWaiting($event)"
    @playing="onPlayerPlaying($event)"
    @timeupdate="onPlayerTimeupdate($event)"
    @canplay="onPlayerCanplay($event)"
    @canplaythrough="onPlayerCanplaythrough($event)"
    @ready="playerReadied"
    @statechanged="playerStateChanged($event)"
  />
</template>

.........................
data() {
    return {
      // videojs options
      playerOptions: {
        autoplay: false,
        muted: false,
        preload: 'auto',
        language: 'zh-CN',
        playbackRates: [0.75, 1.0, 1.25, 1.5, 2.0], // 播放速度
        aspectRatio: '16:9',
        fluid: true,//  当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        notSupportedMessage: '此视频暂无法播放，请刷新后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controls: true, // 下面的控制按钮
        bigPlayButton: false,
        controlBar: {
          playToggle: false, // 播放按钮
          timeDivider: false, // 时间分割线
          durationDisplay: false, // 总时间
          remainingTimeDisplay: false, // 剩余播放时间
          progressControl: true, // 进度条
          fullscreenToggle: false // 全屏按钮
        },
        sources: [{
          type: 'video/mp4',
          // mp4
          src: ''
          // webm
          // src: "https://cdn.theguardian.tv/webM/2015/07/20/150716YesMen_synd_768k_vp8.webm"
        }],
        userActions: {
          click: false // it does not work
        }
      }
    }
  },

refer to userAction

Controls how clicking on the player/tech operates. If set to false, clicking is disabled and will no longer cause the player to toggle between paused and playing. If controls are disabled with controls: false, this will not call the handler function.
If undefined or set to true, clicking is enabled and toggles the player between paused and play. To override the default click handling, set userActions.click to a function which accepts a click event (in this example it will request Full Screen, the same as a userAction.doubleClick):


问:
TreeView Using QAbstractItemModel
Is there any step to create a model from QAbstractItemModel in c++ and expose it to qml ?

I have seen the examples in QT like SimpleItemEditor etc but there they have given a text as default.I want  string names given in c++ using QAbstractItemModel to be shown in treeview.

I donot know how to create a model. PLease help me.

Title: TreeView Using QAbstractItemModel


问:
Google user content caching is making png have black background in email?
Expected behaviour:

email presents png with transparent background as uploaded

Current behaviour:

png in email comes out with a black background

Suspected cause:

google caching.

if i remove this prefix from the url, the png views correctly with a transparent background.
https://ci5.googleusercontent.com/proxy/I5j9QBhyftkmDL2c6wlKMnOTXRL8JJNuD4l__CCYWs0tOrZOGLSLC9rLfDgH5iny2QhmowCBjEWS_tSmy2LrzAgEKsx3Owa2UalLrLMgeFGxLphwNdqOat3WT8VEDH-3TnwLPdLJvqB-wNsm6mXB=s0-d-e1-ft#

the whole url looks like this:

https://ci5.googleusercontent.com/proxy/I5j9QBhyftkmDL2c6wlKMnOTXRL8JJNuD4l__CCYWs0tOrZOGLSLC9rLfDgH5iny2QhmowCBjEWS_tSmy2LrzAgEKsx3Owa2UalLrLMgeFGxLphwNdqOat3WT8VEDH-3TnwLPdLJvqB-wNsm6mXB=s0-d-e1-ft#https://cdn.mywebsite.com/media/email/logo/stores/1/my_website_logo.png

Tried:

loading the image in jpg and png formats

checking the url without the cdn to see if that was causing the problem with google


问:
Rotating double X Axis Plotly
using my last answer (Plotly line, changing colour to NaN segments) I would like to ask something new.

Following the code below I plotted 2 xAxis where ARE shared between themselves to assure when moving one xAxis the other one is moving too. But I need to rotate xAxis labels from both xAxis because when my data is more than 12 entries the labels overlaps each other and rotating may avoid this. If I add rotation to update_layout to xaxis1 or xaxis2 just repetition label is rotating, date ticks are not rotating.

BTW, is there any way to remove the dividers between repetitions/dates from xAxis?

```<code>import plotly.express as px
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import itertools as it
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import column_or_1d

class MyLabelEncoder(LabelEncoder):
    def fit(self, y):
        y = column_or_1d(y, warn=True)
        self.classes_ = pd.Series(y).unique()
        return self

df = pd.DataFrame([1, None, None, 4, 6, None, 2, 1], columns=["y"])
df["x"] = [1, 2, 3, 4, 5, 6, 7, 8]
df["rank"] = [
    "baseline",
    "beginner",
    "beginner",
    "apprentice",
    "apprentice",
    "expert",
    "expert",
    "expert",
]
df["x_dates"] = [
    "2022-01-01",
    "2022-01-04",
    "2022-01-07",
    "2022-01-10",
    "2022-01-13",
    "2022-01-16",
    "2022-01-19",
    "2022-01-22",
]

le = MyLabelEncoder()

le.fit(df["rank"])

rank = le.transform(df["rank"]) + 1

fig = make_subplots(specs=[[{"secondary_y": True}]])

# generate color list
df.loc[df["y"].isna(), "line_color"] = "red"
df.loc[df["y"].isna(), "line_type"] = "dash"

df.loc[df["y"].notna(), "line_color"] = "black"
df.loc[df["y"].notna(), "line_type"] = "solid"

df["y"] = df["y"].interpolate(method="pad")

# create coordinate  pairs
x_pairs = it.pairwise(df["x"])
x_dates = it.pairwise(df["x_dates"])
y_pairs = it.pairwise(df["y"])

for x_data, x_date, y, line_color, line_type in zip(
    x_pairs,
    x_dates,
    y_pairs,
    df["line_color"].values,
    df["line_type"].values,
):
    # create trace
    fig.add_trace(
        go.Scatter(
            x=[x_date, x_data],
            y=y,
            mode="lines",
            line=dict(color=line_color, dash=line_type),
            showlegend=False,
        ),
        secondary_y=True,
    )

fig.add_trace(
    go.Bar(
        x=[df["x_dates"], df["x"]],
        y=rank,
        showlegend=False,
        text=rank,
        # marker_color="rgb(158,202,225)",
        # marker_line_color="black",
        # marker_line_width=1.5,
        # opacity=0.6,
    ),
    secondary_y=False,
)

fig.update_layout(
    {
        "xaxis1": {
            "title_text": "Repetition/Date",
        },
        "yaxis": {
            "title_text": "placeholder",
            "showgrid": False,
            "anchor": "x",
            "domain": [0.0, 1.0],
            "side": "right",
        },
        "yaxis2": {
            "title_text": "data",
            "anchor": "x",
            "overlaying": "y",
            "side": "left",
        },
        "xaxis2": {
            "tickvals": np.arange(
                0,
                np.max(df["x"]) + 1,
                1,
            ),
        },
    }
)

fig.show()

</code>```

Thanks in advance.

Title: Rotating double X Axis Plotly

Body:
using my last answer (Plotly line, changing colour to NaN segments) I would like to ask something new.

Following the code below I plotted 2 xAxis where ARE shared between themselves to assure when moving one xAxis the other one is moving too. But I need to rotate xAxis labels from both xAxis because when my data is more than 12 entries the labels overlaps each other and rotating may avoid this. If I add rotation to update_layout to xaxis1 or xaxis2 just repetition label is rotating, date ticks are not rotating.

BTW, is there any way to remove the dividers between repetitions/dates from xAxis?

import plotly.express as px
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import itertools as it
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import column_or_1d

class MyLabelEncoder(LabelEncoder):
    def fit(self, y):
        y = column_or_1d(y, warn=True)
        self.classes_ = pd.Series(y).unique()
        return self

df = pd.DataFrame([1, None, None, 4, 6, None, 2, 1], columns=["y"])
df["x"] = [1, 2, 3, 4, 5, 6, 7, 8]
df["rank"] = [
    "baseline",
    "beginner",
    "beginner",
    "apprentice",
    "apprentice",
    "expert",
    "expert",
    "expert",
]
df["x_dates"] = [
    "2022-01-01",
    "2022-01-04",
    "2022-01-07",
    "2022-01-10",
    "2022-01-13",
    "2022-01-16",
    "2022-01-19",
    "2022-01-22",
]

le = MyLabelEncoder()

le.fit(df["rank"])

rank = le.transform(df["rank"]) + 1

fig = make_subplots(specs=[[{"secondary_y": True}]])

# generate color list
df.loc[df["y"].isna(), "line_color"] = "red"
df.loc[df["y"].isna(), "line_type"] = "dash"

df.loc[df["y"].notna(), "line_color"] = "black"
df.loc[df["y"].notna(), "line_type"] = "solid"

df["y"] = df["y"].interpolate(method="pad")

# create coordinate  pairs
x_pairs = it.pairwise(df["x"])
x_dates = it.pairwise(df["x_dates"])
y_pairs = it.pairwise(df["y"])

for x_data, x_date, y, line_color, line_type in zip(
    x_pairs,
    x_dates,
    y_pairs,
    df["line_color"].values,
    df["line_type"].values,
):
    # create trace
    fig.add_trace(
        go.Scatter(
            x=[x_date, x_data],
            y=y,
            mode="lines",
            line=dict(color=line_color, dash=line_type),
            showlegend=False,
        ),
        secondary_y=True,
    )

fig.add_trace(
    go.Bar(
        x=[df["x_dates"], df["x"]],
        y=rank,
        showlegend=False,
        text=rank,
        # marker_color="rgb(158,202,225)",
        # marker_line_color="black",
        # marker_line_width=1.5,
        # opacity=0.6,
    ),
    secondary_y=False,
)

fig.update_layout(
    {
        "xaxis1": {
            "title_text": "Repetition/Date",
        },
        "yaxis": {
            "title_text": "placeholder",
            "showgrid": False,
            "anchor": "x",
            "domain": [0.0, 1.0],
            "side": "right",
        },
        "yaxis2": {
            "title_text": "data",
            "anchor": "x",
            "overlaying": "y",
            "side": "left",
        },
        "xaxis2": {
            "tickvals": np.arange(
                0,
                np.max(df["x"]) + 1,
                1,
            ),
        },
    }
)

fig.show()

Thanks in advance.


问:
Error 404 on an existing file in golang/gin
ANS: Don't use a RELATIVE path, it caused the error. Use the ABSOLUTE one. Using full path automatically changes c.File() path behavior from using relative path to absolute path.

UPD: The endpoint is being reached, but there is another problem. c.File in referral.ValidateReferral can't find registration.html, although the path should be correct. The file-tree, they are on the same level. See path below.

I have an HTML form, which submits to /referral/validate endpoint using POST method:

```<code><form action="/referral/validate" method="POST">
  <input type="text" name="referral">
  <input type="submit" value="Next">
</form>
</code>```

This is the endpoint:

```<code>ref := r.Group("/referral")
{
    ref.GET("/validate", func(c *gin.Context) {
        // c.String(200, "Referral Input HTML")
        c.File("../../html/referral.html")
    })

    ref.POST("/validate", referral.ValidateReferral)
</code>```

ValidateReferral:

```<code>func ValidateReferral(c *gin.Context) {
    referral := c.PostForm("referral")
    ok, err := CheckReferral(referral)
    if err != nil || !ok {
        c.AbortWithStatus(http.StatusUnauthorized)
        return
    }

    c.File("../../../html/registration.html")
}
</code>```

Same path in powershell

This returns 404, what's the problem with it? Why can't it find the file? Path seems quite correct.

Body:
ANS: Don't use a RELATIVE path, it caused the error. Use the ABSOLUTE one. Using full path automatically changes c.File() path behavior from using relative path to absolute path.

UPD: The endpoint is being reached, but there is another problem. c.File in referral.ValidateReferral can't find registration.html, although the path should be correct. The file-tree, they are on the same level. See path below.

I have an HTML form, which submits to /referral/validate endpoint using POST method:

<form action="/referral/validate" method="POST">
  <input type="text" name="referral">
  <input type="submit" value="Next">
</form>

This is the endpoint:

ref := r.Group("/referral")
{
    ref.GET("/validate", func(c *gin.Context) {
        // c.String(200, "Referral Input HTML")
        c.File("../../html/referral.html")
    })

    ref.POST("/validate", referral.ValidateReferral)

ValidateReferral:

func ValidateReferral(c *gin.Context) {
    referral := c.PostForm("referral")
    ok, err := CheckReferral(referral)
    if err != nil || !ok {
        c.AbortWithStatus(http.StatusUnauthorized)
        return
    }

    c.File("../../../html/registration.html")
}

Same path in powershell

This returns 404, what's the problem with it? Why can't it find the file? Path seems quite correct.


问:
Adding sortInfo and/or filterValue to DataGrid breaks sorting/filtering functionality
I am trying to add some 'save preferences' functionality to a DataGrid using https://reactdatagrid.io/docs/miscellaneous but when I add sortInfo makes columns unsortable, the same happens for filterValue (trying to save filtering strings/data). Code here:

```<code>import React, { useCallback, useState } from 'react';
import DataGrid from '@inovua/reactdatagrid-enterprise';
import { columnFilters, eeOverviewColumns, filterTypes } from "./overview-columns";
import '@inovua/reactdatagrid-enterprise/index.css';
import { TypeRowProps, TypeRowSelection } from '@inovua/reactdatagrid-community/types';
import { TypeOnSelectionChangeArg } from "@inovua/reactdatagrid-community/types/TypeDataGridProps"
import { Button, FormControl, MenuItem, Select, SelectChangeEvent, TextField } from '@mui/material';
import { TypeColumn, TypeFilterValue, TypeSortInfo } from '@inovua/reactdatagrid-enterprise/types';

interface StoreLayout {
    columns: TypeColumn[];
    sortInfo: TypeSortInfo;
    columnOrder : string[];
    filterValue: TypeFilterValue;
}

let STORE: StoreLayout = {
    columns: eeOverviewColumns,
    sortInfo: [],
    columnOrder: eeOverviewColumns.map(ee => ee.name) as string[],
    filterValue: columnFilters,
}

let VIEWS= [
    {
        id: 0,
        name: "Default view",
        state: STORE
    }
]

const EEOverview = (props: any) => {
    const dataSource = props.eeData

    // Checkbox selection
    const [selected, setSelected] = useState<TypeRowSelection>();

    const onSelectionChange = useCallback(
        (config: TypeOnSelectionChangeArg) => {
            setSelected(config.selected)
        },
        [],
    );

    const goToEe = useCallback((rowProps: TypeRowProps) => {
        window.location.href = `${window.location.href}/${rowProps.data.key}`;
    }, [])

    const initialState = Object.assign({}, STORE, {});
    const [state, setState] = useState(initialState);

    const [viewName, setViewName] = useState('')
    const sendViewName = (viewName: string) => { setViewName(viewName) }
    const saveState = () => {
        if (!viewName || viewName.length === 0 ) {
            alert("View name not provided")
            return
        }
        STORE = {
            columnOrder: state.columnOrder,
            columns: state.columns,
            sortInfo: state.sortInfo,
            filterValue: state.filterValue
        }
        setState(Object.assign({}, state, {}))

        if(VIEWS.map(view => view.name).some(name => name === viewName)) {
            const view = VIEWS.find(view => view.name === viewName)!
            view.state = state
        } else {
            VIEWS.push({
                id: VIEWS.length,
                name: viewName,
                state: state
            })
        }
    }
    const onSortInfoChange = (sortInfo: TypeSortInfo) => {
        setState(Object.assign({}, state, { sortInfo }));
    }

    const onColumnOrderChange = (columnOrder: string[]) => {
        setState(Object.assign({}, state, { columnOrder }));
    }

    const onFilterValueChange = (filterValue: TypeFilterValue) => {
        setState(Object.assign({}, state, { filterValue }));
    }

    const onBatchColumnResize = (batchColumnInfo: any, { reservedViewportWidth }: any) => {
        const colsMap = batchColumnInfo.reduce((acc: any, colInfo: any) => {
            const { column, width, flex } = colInfo
            acc[column.name] = { width, flex }
            return acc
        }, {})

        const columns = state.columns.map((c: any) => {
            return Object.assign({}, c, colsMap[c.name])
        })

        setState(Object.assign({}, state, {
            columns,
            reservedViewportWidth
        }))
    }

    return (
        <div>
            <ViewSelector state = {state} onChange = {setState} ></ViewSelector>
            <ViewText onChange = {sendViewName} ></ViewText>
            <Button sx={{ mx: 2, my: 2, minWidth: 80 }} variant="contained"
                onClick = {saveState}
                >
                Save view
            </Button>
            <DataGrid
                idProperty="key"
                theme="default-light"
                className="data-grid"
                defaultFilterValue={columnFilters}
                filterTypes={filterTypes}
                filterValue={state.filterValue} //<- here
                onRowClick={goToEe}
                columns={state.columns}
                sortInfo={state.sortInfo}       //<- and here
                columnOrder={state.columnOrder}
                pagination="local"
                dataSource={dataSource}
                onSelectionChange={onSelectionChange}
                sortable={true}
                checkboxColumn
                selected={selected}
                enableSelection={true}
                onSortInfoChange={onSortInfoChange}
                onBatchColumnResize={onBatchColumnResize}
                onColumnOrderChange={onColumnOrderChange}
                onFilterValueChange={onFilterValueChange}
            />
        </div>
    );
}
export default EEOverview;

const ViewText = ({onChange}: {onChange: any}) => {
    const onViewNameChange = (viewName: string) => {
        onChange(viewName)
    }
    return (
        <TextField sx={{ mx: 2, my: 2 }}
            id="search"
            variant="outlined"
            size="small"
            label="Name current view"
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => { onViewNameChange(e.target.value) }}
        />
    )
}

const ViewSelector = ({state, onChange}: {state:any, onChange: any}) => {

    const [selectedView, setSelectedView] = useState(0)

    const handleViewChange = (event: SelectChangeEvent<number>) => {
        const selectedView = VIEWS.find(view => view.id===event.target.value)!
        setSelectedView(selectedView.id)
        const selectedState = selectedView.state
        onChange(Object.assign({},selectedState, {}))
    }

    return (
        <FormControl sx={{ m: 2, minWidth: 140 }} >
            <Select labelId="view" variant="standard" size="medium" value={selectedView}
                renderValue={(selected: any) => { return <div>{VIEWS[selected].name}</div>; }}
                onChange={handleViewChange}>
                {VIEWS.map((val, key) => (
                    <MenuItem value={key}>{val.name}</MenuItem>
                ))}
            </Select>
        </FormControl>
    )
}
</code>```

If I remove sortInfo/filterValue from passing to DataGrid, it behaves correctly, but it won't be saved to preferences.

Tried to move dataSource from props to state but it has the same behaviour

Body:
I am trying to add some 'save preferences' functionality to a DataGrid using https://reactdatagrid.io/docs/miscellaneous but when I add sortInfo makes columns unsortable, the same happens for filterValue (trying to save filtering strings/data). Code here:

import React, { useCallback, useState } from 'react';
import DataGrid from '@inovua/reactdatagrid-enterprise';
import { columnFilters, eeOverviewColumns, filterTypes } from "./overview-columns";
import '@inovua/reactdatagrid-enterprise/index.css';
import { TypeRowProps, TypeRowSelection } from '@inovua/reactdatagrid-community/types';
import { TypeOnSelectionChangeArg } from "@inovua/reactdatagrid-community/types/TypeDataGridProps"
import { Button, FormControl, MenuItem, Select, SelectChangeEvent, TextField } from '@mui/material';
import { TypeColumn, TypeFilterValue, TypeSortInfo } from '@inovua/reactdatagrid-enterprise/types';

interface StoreLayout {
    columns: TypeColumn[];
    sortInfo: TypeSortInfo;
    columnOrder : string[];
    filterValue: TypeFilterValue;
}

let STORE: StoreLayout = {
    columns: eeOverviewColumns,
    sortInfo: [],
    columnOrder: eeOverviewColumns.map(ee => ee.name) as string[],
    filterValue: columnFilters,
}

let VIEWS= [
    {
        id: 0,
        name: "Default view",
        state: STORE
    }
]

const EEOverview = (props: any) => {
    const dataSource = props.eeData

    // Checkbox selection
    const [selected, setSelected] = useState<TypeRowSelection>();

    const onSelectionChange = useCallback(
        (config: TypeOnSelectionChangeArg) => {
            setSelected(config.selected)
        },
        [],
    );

    const goToEe = useCallback((rowProps: TypeRowProps) => {
        window.location.href = `${window.location.href}/${rowProps.data.key}`;
    }, [])

    const initialState = Object.assign({}, STORE, {});
    const [state, setState] = useState(initialState);

    const [viewName, setViewName] = useState('')
    const sendViewName = (viewName: string) => { setViewName(viewName) }
    const saveState = () => {
        if (!viewName || viewName.length === 0 ) {
            alert("View name not provided")
            return
        }
        STORE = {
            columnOrder: state.columnOrder,
            columns: state.columns,
            sortInfo: state.sortInfo,
            filterValue: state.filterValue
        }
        setState(Object.assign({}, state, {}))

        if(VIEWS.map(view => view.name).some(name => name === viewName)) {
            const view = VIEWS.find(view => view.name === viewName)!
            view.state = state
        } else {
            VIEWS.push({
                id: VIEWS.length,
                name: viewName,
                state: state
            })
        }
    }
    const onSortInfoChange = (sortInfo: TypeSortInfo) => {
        setState(Object.assign({}, state, { sortInfo }));
    }

    const onColumnOrderChange = (columnOrder: string[]) => {
        setState(Object.assign({}, state, { columnOrder }));
    }

    const onFilterValueChange = (filterValue: TypeFilterValue) => {
        setState(Object.assign({}, state, { filterValue }));
    }

    const onBatchColumnResize = (batchColumnInfo: any, { reservedViewportWidth }: any) => {
        const colsMap = batchColumnInfo.reduce((acc: any, colInfo: any) => {
            const { column, width, flex } = colInfo
            acc[column.name] = { width, flex }
            return acc
        }, {})

        const columns = state.columns.map((c: any) => {
            return Object.assign({}, c, colsMap[c.name])
        })

        setState(Object.assign({}, state, {
            columns,
            reservedViewportWidth
        }))
    }

    return (

            <ViewSelector state = {state} onChange = {setState} ></ViewSelector>
            <ViewText onChange = {sendViewName} ></ViewText>
            <Button sx={{ mx: 2, my: 2, minWidth: 80 }} variant="contained"
                onClick = {saveState}
                >
                Save view
            </Button>
            <DataGrid
                idProperty="key"
                theme="default-light"
                className="data-grid"
                defaultFilterValue={columnFilters}
                filterTypes={filterTypes}
                filterValue={state.filterValue} //<- here
                onRowClick={goToEe}
                columns={state.columns}
                sortInfo={state.sortInfo}       //<- and here
                columnOrder={state.columnOrder}
                pagination="local"
                dataSource={dataSource}
                onSelectionChange={onSelectionChange}
                sortable={true}
                checkboxColumn
                selected={selected}
                enableSelection={true}
                onSortInfoChange={onSortInfoChange}
                onBatchColumnResize={onBatchColumnResize}
                onColumnOrderChange={onColumnOrderChange}
                onFilterValueChange={onFilterValueChange}
            />

    );
}
export default EEOverview;

const ViewText = ({onChange}: {onChange: any}) => {
    const onViewNameChange = (viewName: string) => {
        onChange(viewName)
    }
    return (
        <TextField sx={{ mx: 2, my: 2 }}
            id="search"
            variant="outlined"
            size="small"
            label="Name current view"
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => { onViewNameChange(e.target.value) }}
        />
    )
}

const ViewSelector = ({state, onChange}: {state:any, onChange: any}) => {

    const [selectedView, setSelectedView] = useState(0)

    const handleViewChange = (event: SelectChangeEvent<number>) => {
        const selectedView = VIEWS.find(view => view.id===event.target.value)!
        setSelectedView(selectedView.id)
        const selectedState = selectedView.state
        onChange(Object.assign({},selectedState, {}))
    }

    return (
        <FormControl sx={{ m: 2, minWidth: 140 }} >
            <Select labelId="view" variant="standard" size="medium" value={selectedView}
                renderValue={(selected: any) => { return
{VIEWS[selected].name}
; }}
                onChange={handleViewChange}>
                {VIEWS.map((val, key) => (
                    <MenuItem value={key}>{val.name}</MenuItem>
                ))}
            </Select>
        </FormControl>
    )
}

If I remove sortInfo/filterValue from passing to DataGrid, it behaves correctly, but it won't be saved to preferences.

Tried to move dataSource from props to state but it has the same behaviour


问:
How to change the default name of Scrrenshot taken from Print screen button on Windows 11?
Please help me to change the default name of the screenshot taken by pressing the PrtScr button on Windows 11.


问:
SQL Query - Identifying entries between payment dates greater than 6 years
I have this table (in reality it has more fields but for simplicity, it will demonstrate what I'm after)

Payment_Type
Person ID
Payment_date
Payment_Amount

Normal
1
2015-01-01
£1.00

Normal
1
2017-01-01
£2.00

Reversal
1
2022-01-09
£3.00

Normal
2
2016-12-29
£3.00

Reversal
2
2022-01-02
£4.00

I need 2 specific things from this:

I need all entries where there is over 6 years difference between any given payment dates (when its been greater than or equal to 6 years from the date of the latest payment date). I don't need to count them, I just need it to return all the entries that meet this criteria.

I also need it to specify where a normal payment hasn't been made for 6 years or more from todays date but a reversal has however occurred within the last 6 years. (This might need to be a separate query but will take suggestions)

I'm using Data Lake (Hue).

Thank you.

I've tried to run a sub query with join and union but I'm not getting the desired results so will need to start from scratch. Any advice/insight on this is greatly appreciated.

Ideally, query one will show:

Payment_Type
Person ID
Payment_date
Payment_Amount

Normal
1
2015-01-01
£1.00

Normal
1
2017-01-01
£2.00

Normal
2
2016-12-29
£3.00

Query 2 results should show:

Payment_Type
Person ID
Payment_date
Payment_Amount

Normal
1
2017-01-01
£2.00

Reversal
1
2022-01-09
£3.00

Normal
2
2016-12-29
£3.00

Reversal
2
2022-01-02
£4.00


问:
How do I check a website http connectivity by using NSCP in NSClient++?
I tried check-network command but I'm unsure how to use it to insert a http or is it possible to do so?

NSCP command to check http connectivity in Windows Command Prompt.


问:
How to compile with C# Wrapper of OpenSSL 3.0
We are upgrading from openssl 1.0.2 to 3.0.1. With openssl 1.0.2, we were using this wrapper -  https://github.com/openssl-net/openssl-net/blob/master/ManagedOpenSsl/Core/Native.cs

Any idea from where to get the latest C# wrapper for openssl 3.0

Searched on internet, not able to find any C# wrapper for 3.0.1


问:
mail sending failed from localhost in laravel 8
Env configuration:

```<code>    MAIL_MAILER=smtp
    MAIL_HOST=smtpgmail.com
    MAIL_PORT=587
    MAIL_USERNAME=laravellocal***@gmail.com
    MAIL_PASSWORD=*******
    MAIL_ENCRYPTION=tls
    MAIL_FROM_ADDRESS=laravellocalhost@gmail.com
    MAIL_FROM_NAME="${APP_NAME}"
</code>```

I used this function to send link on mail

public function forgotPassword(Request $request) {
    $request->validate([
        'email'=> 'required|email',
    ]);

    $email = $request->email;
    $user = User::where('email', $email)->first();

    if (! $user) {
        return response([
            'message' => 'Email not exist',
            'status' => 'failed'
        ], 404);
    }

    $token = Str::random(40);

    PasswordReset::updateOrCreate([
        'email' => $email,
        'token' => $token,
        'created_at' => Carbon::now()
    ]);

    // dump('http://127.0.0.1:8000/api/v1/reset' . $token);

    Mail::send('forgotPassword', ['token' => $token], function( Message $message) use ($email) {
        $message->subject('Reset You password');
        $message->to($email);
    });

    return response([
        'message' => 'Password Reset link sent.. Check your Email',
        'status' => 'Success'
    ], 200);
}
```

But I got this error in postman:

Connection could not be established with host localhost :stream_socket_client(): unable to connect to tcp://localhost:587 (No connection could be made because the target machine actively refused it.)

Body:
Env configuration:

    MAIL_MAILER=smtp
    MAIL_HOST=smtpgmail.com
    MAIL_PORT=587
    MAIL_USERNAME=laravellocal***@gmail.com
    MAIL_PASSWORD=*******
    MAIL_ENCRYPTION=tls
    MAIL_FROM_ADDRESS=laravellocalhost@gmail.com
    MAIL_FROM_NAME="${APP_NAME}"

I used this function to send link on mail

public function forgotPassword(Request $request) {
    $request->validate([
        'email'=> 'required|email',
    ]);

    $email = $request->email;
    $user = User::where('email', $email)->first();

    if (! $user) {
        return response([
            'message' => 'Email not exist',
            'status' => 'failed'
        ], 404);
    }

    $token = Str::random(40);

    PasswordReset::updateOrCreate([
        'email' => $email,
        'token' => $token,
        'created_at' => Carbon::now()
    ]);

    // dump('http://127.0.0.1:8000/api/v1/reset' . $token);

    Mail::send('forgotPassword', ['token' => $token], function( Message $message) use ($email) {
        $message->subject('Reset You password');
        $message->to($email);
    });

    return response([
        'message' => 'Password Reset link sent.. Check your Email',
        'status' => 'Success'
    ], 200);
}

But I got this error in postman:

Connection could not be established with host localhost :stream_socket_client(): unable to connect to tcp://localhost:587 (No connection could be made because the target machine actively refused it.)


问:
Build failed with an exception Could not resolve io.github.g00fy2:versioncompare:1.5.0

cordova.cmd build android --release
The "" tags were detected and are no longer supported. Please migrate to the "preference" tag "AndroidWindowSplashScreenAnimatedIcon".
cordova-plugin-androidx-adapter: Processed 34 source files in 588ms
Checking Java JDK and Android SDK versions
ANDROID_HOME=C:\Users\iamsh\AppData\Local\Android\Sdk (recommended setting)
ANDROID_SDK_ROOT=C:\android-sdk-windows (DEPRECATED)
Using Android SDK: C:\android-sdk-windows
Subproject Path: CordovaLib
Subproject Path: app

FAILURE: Build failed with an exception.

Where:
Build file 'C:\Webtrikon\quickchicken\platforms\android\build.gradle' line: 21

What went wrong:
A problem occurred evaluating root project 'Quick Chicken'.

Could not resolve all files for configuration 'classpath'.
Could not resolve io.github.g00fy2:versioncompare:1.5.0.
Required by:
unspecified:unspecified:unspecified
> Could not resolve io.github.g00fy2:versioncompare:1.5.0.
> Could not get resource 'https://repo.maven.apache.org/maven2/io/github/g00fy2/versioncompare/1.5.0/versioncompare-1.5.0.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/io/github/g00fy2/versioncompare/1.5.0/versioncompare-1.5.0.pom'.
> The server may not support the client's requested TLS protocol versions: (TLSv1.2, TLSv1.3). You may need to configure the client to allow other protocols to be used. See: https://docs.gradle.org/7.4.2/userguide/build_environment.html#gradle_system_properties
> Remote host terminated the handshake

Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.4.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 3s
Command failed with exit code 1: C:\Webtrikon\quickchicken\platforms\android\gradlew :app:bundleRelease -b C:\Webtrikon\quickchicken\platforms\android\build.gradle
[ERROR] An error occurred while running subprocess cordova.

```<code>    cordova.cmd build android --release exited with exit code 1.

    Re-running this command with the --verbose flag may provide more information.
</code>```

how to solve this error, Stuck with it from past 4 days.

Body:
cordova.cmd build android --release
The "" tags were detected and are no longer supported. Please migrate to the "preference" tag "AndroidWindowSplashScreenAnimatedIcon".
cordova-plugin-androidx-adapter: Processed 34 source files in 588ms
Checking Java JDK and Android SDK versions
ANDROID_HOME=C:\Users\iamsh\AppData\Local\Android\Sdk (recommended setting)
ANDROID_SDK_ROOT=C:\android-sdk-windows (DEPRECATED)
Using Android SDK: C:\android-sdk-windows
Subproject Path: CordovaLib
Subproject Path: app

FAILURE: Build failed with an exception.

Where:
Build file 'C:\Webtrikon\quickchicken\platforms\android\build.gradle' line: 21

What went wrong:
A problem occurred evaluating root project 'Quick Chicken'.

Could not resolve all files for configuration 'classpath'.
Could not resolve io.github.g00fy2:versioncompare:1.5.0.
Required by:
unspecified:unspecified:unspecified
> Could not resolve io.github.g00fy2:versioncompare:1.5.0.
> Could not get resource 'https://repo.maven.apache.org/maven2/io/github/g00fy2/versioncompare/1.5.0/versioncompare-1.5.0.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/io/github/g00fy2/versioncompare/1.5.0/versioncompare-1.5.0.pom'.
> The server may not support the client's requested TLS protocol versions: (TLSv1.2, TLSv1.3). You may need to configure the client to allow other protocols to be used. See: https://docs.gradle.org/7.4.2/userguide/build_environment.html#gradle_system_properties
> Remote host terminated the handshake

Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.4.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 3s
Command failed with exit code 1: C:\Webtrikon\quickchicken\platforms\android\gradlew :app:bundleRelease -b C:\Webtrikon\quickchicken\platforms\android\build.gradle
[ERROR] An error occurred while running subprocess cordova.

    cordova.cmd build android --release exited with exit code 1.

    Re-running this command with the --verbose flag may provide more information.

how to solve this error, Stuck with it from past 4 days.


问:
Combine two streams to then assign to a custom user model
I'm making an app with authentication using Flutter and Firebase. I'm using StreamBuilder to pass the data of the user who is logged in to a custom user model that I created. Here's how the custom user model looks:

```<code>User? userSnapshot;

class User {
  final String? uid;
  final String? email;
  final String? dateOfBirth;
  final String? name;
  final String? profileBio;

  User({this.uid, this.email, this.dateOfBirth, this.name, this.profileBio});
}
</code>```

The problem is that, in Firestore, name and profileBio are saved in the user document, while email and dateOfBirth are saved in another document inside a subcollection named "secrets". After getting the data from StreamBuilder, I wanted to assign that to an instance of the User class called userSnapshot so I can easily retrieve it later. However, since the data is split in different places in Firestore, I need two streams to get them. Then, I can't simply assign the snapshots from both streams to the User class instance because the fields are final, so I need to assign them once when creating it.
Therefore, all I want to do is to combine the two streams into a single stream to then assign all the user data to the User class instance.

```<code>class AuthenticationWrapper extends StatelessWidget {
  const AuthenticationWrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    final user = Provider.of<User?>(context);

    if (user == null) {
      return const LoginScreen();
    } else {
      return StreamBuilder<User?>(
          stream: DatabaseService(uid: user.uid).userSecrets,
          builder: (context, snapshot1) {
          return StreamBuilder<user?>(
              stream: DatabaseService(uid: user.uid).user,
              builder: (context, snapshot2) {
                if(snapshot1.hasData && snapshot2.hasData) {

                  // I NEED TO DO SOMETHING LIKE THIS:
                  // userSnapshot = snapshot1.data + snapshot2.data;

                  return HomeScreen();
                } else {
                  return Loading();
                }
              }
          );
        },
      );
    }
  }
}

class DatabaseService {
  final String? uid;

  //Get user doc stream
  Stream<User> get user{
    return usersCollection.doc(uid).snapshots().map(_userDataFromSnapshot);
  }

  //Get user doc stream
  Stream<User> get userSecrets{
    return usersCollection.doc(uid).collection("secrets").doc("user_secrets").snapshots().map(_userSecretDataFromSnapshot);
  }

  //User data from snapshot
  User _userDataFromSnapshot(DocumentSnapshot snapshot){
    return User(
      uid: uid,
      name: snapshot['name'],
      profileBio: snapshot['profile_bio'],
    );
  }

  //User data from snapshot
  User _userSecretDataFromSnapshot(DocumentSnapshot snapshot){
    return User(
      email: snapshot['email'],
      dateOfBirth: snapshot['date_of_birth'],
    );
  }
}
</code>```

I saw other questions about combining streams but I couldn't replicate them in my situation to assign to my custom User model. Any ideas of how to achieve this?

Body:
I'm making an app with authentication using Flutter and Firebase. I'm using StreamBuilder to pass the data of the user who is logged in to a custom user model that I created. Here's how the custom user model looks:

User? userSnapshot;

class User {
  final String? uid;
  final String? email;
  final String? dateOfBirth;
  final String? name;
  final String? profileBio;

  User({this.uid, this.email, this.dateOfBirth, this.name, this.profileBio});
}

The problem is that, in Firestore, name and profileBio are saved in the user document, while email and dateOfBirth are saved in another document inside a subcollection named "secrets". After getting the data from StreamBuilder, I wanted to assign that to an instance of the User class called userSnapshot so I can easily retrieve it later. However, since the data is split in different places in Firestore, I need two streams to get them. Then, I can't simply assign the snapshots from both streams to the User class instance because the fields are final, so I need to assign them once when creating it.
Therefore, all I want to do is to combine the two streams into a single stream to then assign all the user data to the User class instance.

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

  @override
  Widget build(BuildContext context) {

    final user = Provider.of<User?>(context);

    if (user == null) {
      return const LoginScreen();
    } else {
      return StreamBuilder<User?>(
          stream: DatabaseService(uid: user.uid).userSecrets,
          builder: (context, snapshot1) {
          return StreamBuilder<user?>(
              stream: DatabaseService(uid: user.uid).user,
              builder: (context, snapshot2) {
                if(snapshot1.hasData && snapshot2.hasData) {

                  // I NEED TO DO SOMETHING LIKE THIS:
                  // userSnapshot = snapshot1.data + snapshot2.data;

                  return HomeScreen();
                } else {
                  return Loading();
                }
              }
          );
        },
      );
    }
  }
}

class DatabaseService {
  final String? uid;

  //Get user doc stream
  Stream<User> get user{
    return usersCollection.doc(uid).snapshots().map(_userDataFromSnapshot);
  }

  //Get user doc stream
  Stream<User> get userSecrets{
    return usersCollection.doc(uid).collection("secrets").doc("user_secrets").snapshots().map(_userSecretDataFromSnapshot);
  }

  //User data from snapshot
  User _userDataFromSnapshot(DocumentSnapshot snapshot){
    return User(
      uid: uid,
      name: snapshot['name'],
      profileBio: snapshot['profile_bio'],
    );
  }

  //User data from snapshot
  User _userSecretDataFromSnapshot(DocumentSnapshot snapshot){
    return User(
      email: snapshot['email'],
      dateOfBirth: snapshot['date_of_birth'],
    );
  }
}

I saw other questions about combining streams but I couldn't replicate them in my situation to assign to my custom User model. Any ideas of how to achieve this?


问:
Task.whenAllSuccess function always gives me the same task
I have a small problem with the processing of my task. I have a list (listImg) which contains bitmaps. Now I try to upload each image to Firebase Storage through a forEach loop and then pack it in an UploadTask. In the addOnSuccessListener, however, the same image is called every time. For example, I have 3 images in the listImg. All 3 show up correctly in the loop. I pack these into the task array. However, in the Task.whenAllSuccess function, each URL of the 3 tasks leads to the same image
What is it?</p>
```<code>downloadUrls = mutableListOf<String>()

val tasks = mutableListOf<UploadTask>()

listImg.forEach {
        if(bitmap!!.byteCount != it.byteCount) {
            var spaceRef = storageRef.child("objektImages/"+UUID.randomUUID().toString()+".jpg")
            val bitmap = it
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos)
            val data = baos.toByteArray()
            var uploadTask = spaceRef.putBytes(data)

            //Here log gives me different images, which is also intended
            Log.d("URL:",bitmap.toString())
            tasks.add(uploadTask)
        }
 }

Tasks.whenAllSuccess<UploadTask.TaskSnapshot>(tasks).addOnSuccessListener { taskSnapshot ->

       taskSnapshot!!.forEach {

        it.metadata!!.reference!!.downloadUrl.addOnSuccessListener { url->

          //But here every downloadUrl leads to the same image.
           downloadUrls.add(url.toString())
              ...

          }

       }
    }
</code>```

Body:
I have a small problem with the processing of my task. I have a list (listImg) which contains bitmaps. Now I try to upload each image to Firebase Storage through a forEach loop and then pack it in an UploadTask. In the addOnSuccessListener, however, the same image is called every time. For example, I have 3 images in the listImg. All 3 show up correctly in the loop. I pack these into the task array. However, in the Task.whenAllSuccess function, each URL of the 3 tasks leads to the same image
What is it?

downloadUrls = mutableListOf<String>()

val tasks = mutableListOf<UploadTask>()

listImg.forEach {
        if(bitmap!!.byteCount != it.byteCount) {
            var spaceRef = storageRef.child("objektImages/"+UUID.randomUUID().toString()+".jpg")
            val bitmap = it
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos)
            val data = baos.toByteArray()
            var uploadTask = spaceRef.putBytes(data)

            //Here log gives me different images, which is also intended
            Log.d("URL:",bitmap.toString())
            tasks.add(uploadTask)
        }
 }

Tasks.whenAllSuccess<UploadTask.TaskSnapshot>(tasks).addOnSuccessListener { taskSnapshot ->

       taskSnapshot!!.forEach {

        it.metadata!!.reference!!.downloadUrl.addOnSuccessListener { url->

          //But here every downloadUrl leads to the same image.
           downloadUrls.add(url.toString())
              ...

          }

       }
    }


问:
How to trigger GCP Cloud Function when Dataproc Job state change and read the events
I am trying to figure out the equivalent of AWS lambda EventBridge (CloudWatch Events) where the lambda is triggered when a Glue job state changed. But In GCP I am not found a way how to do it.
If anyone knows please describe or share some resources.

I am using Pub/Sub but it doesn't help out.


问:
I tried to run RabbitMQ server but it returned a Segmentation error?
I am trying to run a repo in my local machine that requires Postgres, RabbitMQ, Celery.

My system is a MAC.

When I try to start the rabbitmq server I get this error:

rabbitmq-server start
/usr/local/sbin/rabbitmq-server: line 150: 78860 Segmentation fault: 11  start_rabbitmq_server "$@"

I cannot seem to find a relevant answer around.

I just tried to run the rabbitMQserver but it didn't start.


问:
How to add a gradient color and solve the wrong cursor indicating issue in vega chart

Current mouse cursor is not working well.
It indicates wrong tooltip.
And I want to set item gradient color.

current code is like this

```<code>import React from "react";
import { Vega } from "react-vega";

function BubbleChart() {
  const spec = {
    $schema: "https://vega.github.io/schema/vega/v5.json",
    width: 1960,
    height: 800,
    padding: { left: 5, right: 5, top: 20, bottom: 0 },
    autosize: "none",
    signals: [
      { name: "cx", update: "width / 2" },
      { name: "cy", update: "height / 2" },
      {
        name: "gravityX",
        value: 0,
      },
      {
        name: "gravityY",
        value: 0.2,
      },
    ],
    data: [
      {
        name: "table",
        values: [
          { category: "A", amount: 0.28 },
          { category: "B", amount: 0.55 },
          { category: "C", amount: 0.43 },
          { category: "D", amount: 0.31 },
          { category: "E", amount: 0.81 },
          { category: "F", amount: 0.53 },
          { category: "G", amount: 0.19 },
          { category: "H", amount: 0.87 },
          { category: "I", amount: 0.28 },
          { category: "J", amount: 0.55 },
          { category: "K", amount: 0.43 },
          { category: "L", amount: 0.91 },
          { category: "M", amount: 0.81 },
          { category: "Government", amount: 0.99 },
          { category: "Service", amount: 0.59 },
          { category: "Army", amount: 0.27 },
        ],
      },
    ],
    scales: [
      {
        name: "size",
        domain: { data: "table", field: "amount" },
        range: [5000, 20000],
      },
      {
        name: "color",
        type: "ordinal",
        domain: { data: "table", field: "category" },
        range: "ramp",
      },
    ],
    marks: [
      {
        name: "nodes",
        type: "symbol",
        from: { data: "table" },
        encode: {
          enter: {
            fill: { scale: "color", field: "category" },
            xfocus: { signal: "cx" },
            yfocus: { signal: "cy" },
          },
          update: {
            size: { signal: "pow(2 * datum.amount, 2)", scale: "size" },
            stroke: { value: "#fff" },
            strokeWidth: { value: 0 },
            tooltip: { signal: "datum" },
          },
        },
        transform: [
          {
            type: "force",
            iterations: 100,
            static: true,
            forces: [
              {
                force: "collide",
                iterations: 2,
                radius: { expr: "sqrt(datum.size) / 1.5" },
              },
              { force: "center", x: { signal: "cx" }, y: { signal: "cy" } },
              { force: "x", x: "xfocus", strength: { signal: "gravityX" } },
              { force: "y", y: "yfocus", strength: { signal: "gravityY" } },
            ],
          },
        ],
      },
      {
        type: "text",
        from: { data: "nodes" },
        encode: {
          enter: {
            align: { value: "center" },
            baseline: { value: "middle" },
            fontSize: { value: 30 },
            fontFamily: { value: "Helvetica" },
            fontWeight: { value: 400 },
            fill: { value: "#fff" },
            text: { field: "datum.category" },
          },
          update: { x: { field: "x" }, y: { field: "y" } },
        },
      },
    ],
  };

  return (
    <>
      <Vega spec={spec} actions={false} />
    </>
  );
}

export default BubbleChart;

</code>```

Please check and let me know how add gradient color and solve incorrect cursor indicating issue.

I want to build this gradient item

Body:
Current mouse cursor is not working well.
It indicates wrong tooltip.
And I want to set item gradient color.

current code is like this

import React from "react";
import { Vega } from "react-vega";

function BubbleChart() {
  const spec = {
    $schema: "https://vega.github.io/schema/vega/v5.json",
    width: 1960,
    height: 800,
    padding: { left: 5, right: 5, top: 20, bottom: 0 },
    autosize: "none",
    signals: [
      { name: "cx", update: "width / 2" },
      { name: "cy", update: "height / 2" },
      {
        name: "gravityX",
        value: 0,
      },
      {
        name: "gravityY",
        value: 0.2,
      },
    ],
    data: [
      {
        name: "table",
        values: [
          { category: "A", amount: 0.28 },
          { category: "B", amount: 0.55 },
          { category: "C", amount: 0.43 },
          { category: "D", amount: 0.31 },
          { category: "E", amount: 0.81 },
          { category: "F", amount: 0.53 },
          { category: "G", amount: 0.19 },
          { category: "H", amount: 0.87 },
          { category: "I", amount: 0.28 },
          { category: "J", amount: 0.55 },
          { category: "K", amount: 0.43 },
          { category: "L", amount: 0.91 },
          { category: "M", amount: 0.81 },
          { category: "Government", amount: 0.99 },
          { category: "Service", amount: 0.59 },
          { category: "Army", amount: 0.27 },
        ],
      },
    ],
    scales: [
      {
        name: "size",
        domain: { data: "table", field: "amount" },
        range: [5000, 20000],
      },
      {
        name: "color",
        type: "ordinal",
        domain: { data: "table", field: "category" },
        range: "ramp",
      },
    ],
    marks: [
      {
        name: "nodes",
        type: "symbol",
        from: { data: "table" },
        encode: {
          enter: {
            fill: { scale: "color", field: "category" },
            xfocus: { signal: "cx" },
            yfocus: { signal: "cy" },
          },
          update: {
            size: { signal: "pow(2 * datum.amount, 2)", scale: "size" },
            stroke: { value: "#fff" },
            strokeWidth: { value: 0 },
            tooltip: { signal: "datum" },
          },
        },
        transform: [
          {
            type: "force",
            iterations: 100,
            static: true,
            forces: [
              {
                force: "collide",
                iterations: 2,
                radius: { expr: "sqrt(datum.size) / 1.5" },
              },
              { force: "center", x: { signal: "cx" }, y: { signal: "cy" } },
              { force: "x", x: "xfocus", strength: { signal: "gravityX" } },
              { force: "y", y: "yfocus", strength: { signal: "gravityY" } },
            ],
          },
        ],
      },
      {
        type: "text",
        from: { data: "nodes" },
        encode: {
          enter: {
            align: { value: "center" },
            baseline: { value: "middle" },
            fontSize: { value: 30 },
            fontFamily: { value: "Helvetica" },
            fontWeight: { value: 400 },
            fill: { value: "#fff" },
            text: { field: "datum.category" },
          },
          update: { x: { field: "x" }, y: { field: "y" } },
        },
      },
    ],
  };

  return (
    <>
      <Vega spec={spec} actions={false} />
    </>
  );
}

export default BubbleChart;

Please check and let me know how add gradient color and solve incorrect cursor indicating issue.

I want to build this gradient item


问:
Python, PySide6; JS not receiving data from QWebChannel
I've seen many many answers about this question, but still cannot figure it  out.
I made two files, one - html with qrc definition + new QWebChannel, and second python file with Object and QWebEngineView.
JS script seems to not working. It doesn't binding channel object to local var.
I've tried many examples from many pages, looking native QT language or C++, I cannot figure it out.
QWebChannel definition and qt object are found.

Maybe something is not ok with PySide6? Please help me figure it out.

My code:

index.html

```<code><head>
    <title>Test</title>
     <script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
    <script type="text/javascript">
        let dataSource = null
        window.onload = function () {
            alert('before') //works
            new QWebChannel(qt.webChannelTransport, function (channel) {
                    alert('inside') //not working
                    dataSource = channel.objects.backend;
                }
            );
            alert('after') //works
            alert(dataSource) //null
        }
   </script>
</head>
<body>
<p>Hello</p>
</body>
</html>
</code>```

main.py

```<code>import sys, os

from PySide6.QtCore import Signal, QUrl, Slot, QObject
from PySide6.QtWidgets import QMainWindow, QApplication, QVBoxLayout, QWidget
from PySide6.QtWebEngineWidgets import *
from PySide6.QtWebEngineCore import *
from PySide6.QtWebChannel import QWebChannel

class Backend(QObject):
    @Slot(result=int)
    def getValue(self):
        return 1

    @Slot(int)
    def printValue(self, val):
        print(val)

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow,self).__init__(*args, **kwargs)
        self.browser = QWebEngineView()

        backend = Backend()
        channel = QWebChannel()
        channel.registerObject("backend", backend)
        self.browser.page().setWebChannel(channel)

        current_dir = os.path.dirname(os.path.realpath(__file__))
        filename = os.path.join(current_dir, "index.html")
        url = QUrl.fromLocalFile(filename)
        self.browser.load(url)

        self.setCentralWidget(self.browser)
        self.resize(1200,900)
        self.show()

app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec())
</code>```

UPDATE:

I extended view, added dev tool and jquery to check objects - that what I have:

UPDATE 2:
I removed PySide6, installed PyQt5 and used example from here:
How to receive data from python to js using QWebChannel?

Everything works :/
I spend whole day to figure it out. I don't know why it's not working.

Body:
I've seen many many answers about this question, but still cannot figure it  out.
I made two files, one - html with qrc definition + new QWebChannel, and second python file with Object and QWebEngineView.
JS script seems to not working. It doesn't binding channel object to local var.
I've tried many examples from many pages, looking native QT language or C++, I cannot figure it out.
QWebChannel definition and qt object are found.

Maybe something is not ok with PySide6? Please help me figure it out.

My code:

index.html

    <title>Test</title>

Hello

main.py

import sys, os

from PySide6.QtCore import Signal, QUrl, Slot, QObject
from PySide6.QtWidgets import QMainWindow, QApplication, QVBoxLayout, QWidget
from PySide6.QtWebEngineWidgets import *
from PySide6.QtWebEngineCore import *
from PySide6.QtWebChannel import QWebChannel

class Backend(QObject):
    @Slot(result=int)
    def getValue(self):
        return 1

    @Slot(int)
    def printValue(self, val):
        print(val)

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow,self).__init__(*args, **kwargs)
        self.browser = QWebEngineView()

        backend = Backend()
        channel = QWebChannel()
        channel.registerObject("backend", backend)
        self.browser.page().setWebChannel(channel)

        current_dir = os.path.dirname(os.path.realpath(__file__))
        filename = os.path.join(current_dir, "index.html")
        url = QUrl.fromLocalFile(filename)
        self.browser.load(url)

        self.setCentralWidget(self.browser)
        self.resize(1200,900)
        self.show()

app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec())

UPDATE:

I extended view, added dev tool and jquery to check objects - that what I have:

UPDATE 2:
I removed PySide6, installed PyQt5 and used example from here:
How to receive data from python to js using QWebChannel?

Everything works :/
I spend whole day to figure it out. I don't know why it's not working.


问:
How to create tableOfcContents using Remirror react
I have configure my editor using Remirror.

I am not able to create tableOfContents from a blog post

Help needed


问:
My website needs to be restarted after specific number of requests in IIS
I have an API application and .NET Core Application which are connected to the API. My issue is after a specific number of requests, there is a message that says "The service is unavailable."

this screen appears after undefined requests:enter image description here

enter image description here

I expects that the application always works unless I logout but this did not happen