问:
Make sliding view stay inside the borders of background view
I need to make slider for user to slide left and right to confirm he wants to buy something

I make slider move by updating offset of the leading constraint.
The problem is that i can't make slider stay in borders of a background view.
I tried to save current offset and check for the difference of coordinates after every touch but it doesn't work.

```<code> var diff: CGFloat {
        return startCoordinate - endCoordinate
    }

private func updateConstraints(_ diff: CGFloat) {
        if diff + appearance.sliderLeadingOffset + currentOffset <= appearance.sliderMaxLeadingOffset {
            sliderView.snp.updateConstraints { make in
                make.leading.equalTo(backgroundView.snp.leading).offset(-diff)
            }
            startCoordinate = diff
            currentOffset = diff + appearance.sliderLeadingOffset
        }

    }

    @objc private func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
        switch gestureRecognizer.state {
        case .began:
            let touchLocation = gestureRecognizer.location(in: sliderView)
            touchOffset = sliderView.bounds.minX + touchLocation.x
            startCoordinate = touchLocation.x - touchOffset
        case .ended:
            endCoordinate = gestureRecognizer.location(in: sliderView).x
        case .changed:
            let location = gestureRecognizer.location(in: sliderView)
            if backgroundView.frame.contains(location) {
                endCoordinate = location.x - touchOffset
            }
            updateConstraints(diff)
        default: break
        }
    }
</code>```

答:
Below is full code for a fully functioning slider button.
Create a new Swift File and name it SlidingButton.swift

```<code>import Foundation
import UIKit

protocol SlideButtonDelegate{
    func buttonStatus(status:String, sender:SlidingButton)
}

@IBDesignable class SlidingButton: UIView{

var delegate: SlideButtonDelegate?

@IBInspectable var dragPointWidth: CGFloat = 100 {
    didSet{
        setStyle()
    }
}

@IBInspectable var dragPointColor: UIColor = UIColor.darkGray {
    didSet{
        setStyle()
    }
}

@IBInspectable var buttonColor: UIColor = UIColor.gray {
    didSet{
        setStyle()
    }
}

@IBInspectable var buttonText: String = "Slide Here" {
    didSet{
        setStyle()
    }
}

@IBInspectable var imageName: UIImage = UIImage() {
    didSet{
        setStyle()
    }
}

@IBInspectable var buttonTextColor: UIColor = UIColor.white {
    didSet{
        setStyle()
    }
}

@IBInspectable var dragPointTextColor: UIColor = UIColor.white {
    didSet{
        setStyle()
    }
}

@IBInspectable var buttonFinishedSliding: UIColor = UIColor.white {
    didSet{
        setStyle()
    }
}

@IBInspectable var buttonCornerRadius: CGFloat = 30 {
    didSet{
        setStyle()
    }
}

var buttonFont = UIFont.boldSystemFont(ofSize: 35)

var dragPoint = UIView()
var buttonLabel = UILabel()
var dragPointButtonLabel = UILabel()
var imageView = UIImageView()
var layoutSet = false

override init (frame : CGRect) {
    super.init(frame : frame)
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!

}

override func layoutSubviews() {
    if !layoutSet{
        self.setUpButton()
        self.layoutSet = true
    }
}

func setStyle(){
    self.buttonLabel.text = self.buttonText
    self.dragPointButtonLabel.text = self.buttonText
    self.dragPoint.frame.size.width = self.dragPointWidth
    self.dragPoint.backgroundColor = self.dragPointColor
    self.backgroundColor = self.buttonColor
    self.imageView.image = imageName
    self.buttonLabel.textColor = self.buttonTextColor
    self.dragPointButtonLabel.textColor = self.dragPointTextColor

    self.dragPoint.layer.cornerRadius = buttonCornerRadius
    self.layer.cornerRadius = buttonCornerRadius
}

func setUpButton(){

    self.backgroundColor = self.buttonColor
    self.dragPoint = UIView(frame: CGRect(x: dragPointWidth - self.frame.size.width, y: 0, width: self.frame.size.width, height: self.frame.size.height))
    self.dragPoint.backgroundColor = dragPointColor
    self.dragPoint.layer.cornerRadius = buttonCornerRadius
    self.addSubview(self.dragPoint)

    if !self.buttonText.isEmpty{

        self.buttonLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
        self.buttonLabel.textAlignment = .center
        self.buttonLabel.text = buttonText
        self.buttonLabel.textColor = UIColor.white
        self.buttonLabel.font = self.buttonFont
        self.buttonLabel.textColor = self.buttonTextColor
        self.addSubview(self.buttonLabel)

        self.dragPointButtonLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
        self.dragPointButtonLabel.textAlignment = .center
        self.dragPointButtonLabel.text = buttonText
        self.dragPointButtonLabel.textColor = UIColor.white
        self.dragPointButtonLabel.font = self.buttonFont
        self.dragPointButtonLabel.textColor = self.dragPointTextColor
        self.dragPoint.addSubview(self.dragPointButtonLabel)
    }
    self.bringSubviewToFront(self.dragPoint)

    if self.imageName != UIImage(){
        self.imageView = UIImageView(frame: CGRect(x: self.frame.size.width - dragPointWidth, y: 0, width: self.dragPointWidth, height: self.frame.size.height))
        self.imageView.contentMode = .center
        self.imageView.image = self.imageName
        self.dragPoint.addSubview(self.imageView)
    }

    self.layer.masksToBounds = true

    // start detecting pan gesture
    let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.panDetected(sender:)))
    panGestureRecognizer.minimumNumberOfTouches = 1
    self.dragPoint.addGestureRecognizer(panGestureRecognizer)
}

@objc func panDetected(sender: UIPanGestureRecognizer){
    var translatedPoint = sender.translation(in: self)
    translatedPoint     = CGPoint(x: translatedPoint.x, y: self.frame.size.height / 2)
    sender.view?.frame.origin.x = (dragPointWidth - self.frame.size.width) + translatedPoint.x
    if sender.state == .ended{

        let velocityX = sender.velocity(in: self).x * 0.2
        var finalX = translatedPoint.x + velocityX
        if finalX < 0{
            finalX = 0
        }else if finalX + self.dragPointWidth  >  (self.frame.size.width - 60){
            // final point reached, do somethign here
        }

        let animationDuration:Double = abs(Double(velocityX) * 0.0002) + 0.2
        UIView.transition(with: self, duration: animationDuration, options: UIView.AnimationOptions.curveEaseOut, animations: {
            }, completion: { (Status) in
                if Status{
                    self.animationFinished()
                }
        })
    }
}
}
</code>```

USAGE:

Add a UIVIEW and conform it to the above SlidingButton Class

You can then adjust as needed using the storyboard

Body:
I need to make slider for user to slide left and right to confirm he wants to buy something

I make slider move by updating offset of the leading constraint.
The problem is that i can't make slider stay in borders of a background view.
I tried to save current offset and check for the difference of coordinates after every touch but it doesn't work.

 var diff: CGFloat {
        return startCoordinate - endCoordinate
    }

private func updateConstraints(_ diff: CGFloat) {
        if diff + appearance.sliderLeadingOffset + currentOffset <= appearance.sliderMaxLeadingOffset {
            sliderView.snp.updateConstraints { make in
                make.leading.equalTo(backgroundView.snp.leading).offset(-diff)
            }
            startCoordinate = diff
            currentOffset = diff + appearance.sliderLeadingOffset
        }

    }

    @objc private func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
        switch gestureRecognizer.state {
        case .began:
            let touchLocation = gestureRecognizer.location(in: sliderView)
            touchOffset = sliderView.bounds.minX + touchLocation.x
            startCoordinate = touchLocation.x - touchOffset
        case .ended:
            endCoordinate = gestureRecognizer.location(in: sliderView).x
        case .changed:
            let location = gestureRecognizer.location(in: sliderView)
            if backgroundView.frame.contains(location) {
                endCoordinate = location.x - touchOffset
            }
            updateConstraints(diff)
        default: break
        }
    }

Body:
Below is full code for a fully functioning slider button.
Create a new Swift File and name it SlidingButton.swift

import Foundation
import UIKit

protocol SlideButtonDelegate{
    func buttonStatus(status:String, sender:SlidingButton)
}

@IBDesignable class SlidingButton: UIView{

var delegate: SlideButtonDelegate?

@IBInspectable var dragPointWidth: CGFloat = 100 {
    didSet{
        setStyle()
    }
}

@IBInspectable var dragPointColor: UIColor = UIColor.darkGray {
    didSet{
        setStyle()
    }
}

@IBInspectable var buttonColor: UIColor = UIColor.gray {
    didSet{
        setStyle()
    }
}

@IBInspectable var buttonText: String = "Slide Here" {
    didSet{
        setStyle()
    }
}

@IBInspectable var imageName: UIImage = UIImage() {
    didSet{
        setStyle()
    }
}

@IBInspectable var buttonTextColor: UIColor = UIColor.white {
    didSet{
        setStyle()
    }
}

@IBInspectable var dragPointTextColor: UIColor = UIColor.white {
    didSet{
        setStyle()
    }
}

@IBInspectable var buttonFinishedSliding: UIColor = UIColor.white {
    didSet{
        setStyle()
    }
}

@IBInspectable var buttonCornerRadius: CGFloat = 30 {
    didSet{
        setStyle()
    }
}

var buttonFont = UIFont.boldSystemFont(ofSize: 35)

var dragPoint = UIView()
var buttonLabel = UILabel()
var dragPointButtonLabel = UILabel()
var imageView = UIImageView()
var layoutSet = false

override init (frame : CGRect) {
    super.init(frame : frame)
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!

}

override func layoutSubviews() {
    if !layoutSet{
        self.setUpButton()
        self.layoutSet = true
    }
}

func setStyle(){
    self.buttonLabel.text = self.buttonText
    self.dragPointButtonLabel.text = self.buttonText
    self.dragPoint.frame.size.width = self.dragPointWidth
    self.dragPoint.backgroundColor = self.dragPointColor
    self.backgroundColor = self.buttonColor
    self.imageView.image = imageName
    self.buttonLabel.textColor = self.buttonTextColor
    self.dragPointButtonLabel.textColor = self.dragPointTextColor

    self.dragPoint.layer.cornerRadius = buttonCornerRadius
    self.layer.cornerRadius = buttonCornerRadius
}

func setUpButton(){

    self.backgroundColor = self.buttonColor
    self.dragPoint = UIView(frame: CGRect(x: dragPointWidth - self.frame.size.width, y: 0, width: self.frame.size.width, height: self.frame.size.height))
    self.dragPoint.backgroundColor = dragPointColor
    self.dragPoint.layer.cornerRadius = buttonCornerRadius
    self.addSubview(self.dragPoint)

    if !self.buttonText.isEmpty{

        self.buttonLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
        self.buttonLabel.textAlignment = .center
        self.buttonLabel.text = buttonText
        self.buttonLabel.textColor = UIColor.white
        self.buttonLabel.font = self.buttonFont
        self.buttonLabel.textColor = self.buttonTextColor
        self.addSubview(self.buttonLabel)

        self.dragPointButtonLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
        self.dragPointButtonLabel.textAlignment = .center
        self.dragPointButtonLabel.text = buttonText
        self.dragPointButtonLabel.textColor = UIColor.white
        self.dragPointButtonLabel.font = self.buttonFont
        self.dragPointButtonLabel.textColor = self.dragPointTextColor
        self.dragPoint.addSubview(self.dragPointButtonLabel)
    }
    self.bringSubviewToFront(self.dragPoint)

    if self.imageName != UIImage(){
        self.imageView = UIImageView(frame: CGRect(x: self.frame.size.width - dragPointWidth, y: 0, width: self.dragPointWidth, height: self.frame.size.height))
        self.imageView.contentMode = .center
        self.imageView.image = self.imageName
        self.dragPoint.addSubview(self.imageView)
    }

    self.layer.masksToBounds = true

    // start detecting pan gesture
    let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.panDetected(sender:)))
    panGestureRecognizer.minimumNumberOfTouches = 1
    self.dragPoint.addGestureRecognizer(panGestureRecognizer)
}

@objc func panDetected(sender: UIPanGestureRecognizer){
    var translatedPoint = sender.translation(in: self)
    translatedPoint     = CGPoint(x: translatedPoint.x, y: self.frame.size.height / 2)
    sender.view?.frame.origin.x = (dragPointWidth - self.frame.size.width) + translatedPoint.x
    if sender.state == .ended{

        let velocityX = sender.velocity(in: self).x * 0.2
        var finalX = translatedPoint.x + velocityX
        if finalX < 0{
            finalX = 0
        }else if finalX + self.dragPointWidth  >  (self.frame.size.width - 60){
            // final point reached, do somethign here
        }

        let animationDuration:Double = abs(Double(velocityX) * 0.0002) + 0.2
        UIView.transition(with: self, duration: animationDuration, options: UIView.AnimationOptions.curveEaseOut, animations: {
            }, completion: { (Status) in
                if Status{
                    self.animationFinished()
                }
        })
    }
}
}

USAGE:

Add a UIVIEW and conform it to the above SlidingButton Class

You can then adjust as needed using the storyboard


来源: stackexchange

问:
how to filter properties with values in Neptune + nodejs
with Neptune + nodejs

g.V().hasLabel('A').properties()

returns:

```<code>id, label, value
1, 'p1','v1'
2, 'p1','b2'
3, 'p1','b3'
4, 'p1','d4'
</code>```

how can I do a filter so it only returns:

```<code>id, label, value
2, 'p1','b2'
3, 'p1','b3'

</code>```

I tried

g.V().hasLabel('Device').properties().value().is(containing('b'))

but it throws error UnsupportedOperationException

I also tried
g.V().hasLabel('Device').where(properties().value().is(containing('b')))

same error, but i think it is because i have different data type in multiple properties, the containing method failed when it come across number type.....

答:
You probably do not need to use properties unless you are planning to do something like drop the property. You should be able to simply do:

```<code>g.V().hasLabel('Device').has('value',containing('b'))
</code>```

I am assuming that "value" is the name of your property. If it is not please clarify.

EDITED to add more examples.

If you wanted to test all properties you could do something like this which wil find the matching properties.

```<code>gremlin> g.addV('test').property('x','Hello').
                        property('y','Another one').
           addV('test').property('y','Goodbye')

==>v[12b93051-decf-3be5-85cd-cbc4c27e42f9]

g.V().hasLabel('test').
      properties().hasValue(TextP.containing('ll'))

==>vp[x->Hello]
</code>```

If you want the vertex that contains the properties

```<code>gremlin> g.V().hasLabel('test').
             where(properties().hasValue(TextP.containing('ll')))

==>v[14b93051-dece-db72-9f46-46df7513a14c]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
with Neptune + nodejs

g.V().hasLabel('A').properties()

returns:

id, label, value
1, 'p1','v1'
2, 'p1','b2'
3, 'p1','b3'
4, 'p1','d4'

how can I do a filter so it only returns:

id, label, value
2, 'p1','b2'
3, 'p1','b3'

I tried

g.V().hasLabel('Device').properties().value().is(containing('b'))

but it throws error UnsupportedOperationException

I also tried
g.V().hasLabel('Device').where(properties().value().is(containing('b')))

same error, but i think it is because i have different data type in multiple properties, the containing method failed when it come across number type.....

Body:
You probably do not need to use properties unless you are planning to do something like drop the property. You should be able to simply do:

g.V().hasLabel('Device').has('value',containing('b'))

I am assuming that "value" is the name of your property. If it is not please clarify.

EDITED to add more examples.

If you wanted to test all properties you could do something like this which wil find the matching properties.

gremlin> g.addV('test').property('x','Hello').
                        property('y','Another one').
           addV('test').property('y','Goodbye')

==>v[12b93051-decf-3be5-85cd-cbc4c27e42f9]

g.V().hasLabel('test').
      properties().hasValue(TextP.containing('ll'))

==>vp[x->Hello]

If you want the vertex that contains the properties

gremlin> g.V().hasLabel('test').
             where(properties().hasValue(TextP.containing('ll')))

==>v[14b93051-dece-db72-9f46-46df7513a14c]


问:
How to use IFileOperation from ctypes
I want to use IFileOperation to copy files from python code -

It's fast(er than python)

You get a nice dialog

Doesn't block Python

On Windows 10, Python 3.8 -

```<code>import ctypes

ctypes.windll.shell32.IFileOperation
</code>```

doesn't seem to exist.

How can I reach IFileOperation (Not the deprecated SHFileOperation API) using ctypes?

答:
Sure, it's located in pythoncom and shell for constants, for example:

```<code>from win32com.shell import shell
import pythoncom

# create an instance of IFileOperation
fo = pythoncom.CoCreateInstance(shell.CLSID_FileOperation, None, pythoncom.CLSCTX_ALL, shell.IID_IFileOperation)

# here you can use SetOperationFlags, progress Sinks, etc.

# create an instance of IShellItem for the source item
item1 = shell.SHCreateItemFromParsingName("c:\\temp\\source.txt", None, shell.IID_IShellItem)

# create an instance of IShellItem for the target folder
folder = shell.SHCreateItemFromParsingName("c:\\another", None, shell.IID_IShellItem)

# queue the copy operation
fo.CopyItem(item1, folder, "new name.txt", None)

# commit
fo.PerformOperations()
</code>```

Title: How to use IFileOperation from ctypes

Body:
I want to use IFileOperation to copy files from python code -

It's fast(er than python)

You get a nice dialog

Doesn't block Python

On Windows 10, Python 3.8 -

import ctypes

ctypes.windll.shell32.IFileOperation

doesn't seem to exist.

How can I reach IFileOperation (Not the deprecated SHFileOperation API) using ctypes?

Body:
Sure, it's located in pythoncom and shell for constants, for example:

from win32com.shell import shell
import pythoncom

# create an instance of IFileOperation
fo = pythoncom.CoCreateInstance(shell.CLSID_FileOperation, None, pythoncom.CLSCTX_ALL, shell.IID_IFileOperation)

# here you can use SetOperationFlags, progress Sinks, etc.

# create an instance of IShellItem for the source item
item1 = shell.SHCreateItemFromParsingName("c:\\temp\\source.txt", None, shell.IID_IShellItem)

# create an instance of IShellItem for the target folder
folder = shell.SHCreateItemFromParsingName("c:\\another", None, shell.IID_IShellItem)

# queue the copy operation
fo.CopyItem(item1, folder, "new name.txt", None)

# commit
fo.PerformOperations()


问:
Using Passwords to Navigate Screens
I am doing a react native + firebase app. At the moment, I am struggling to make a message pop up asking for a certain password whenever I press one of the page routers. I have 3 pages nested in an StackNavigator at App.js.

As you can see on the following code, I have 3 routers to those pages (which are HelderScreen.js, LolsScreen.js and AthleanScreen.js). Whenever I click on these routers, I want a message pop up to ask for a unique password to each of those routers.

This is my Home.js main code

```<code>import React from 'react';
import { StyleSheet, Text, View, SafeAreaView, TextInput, TouchableOpacity, LayoutAnimation, Image, FlatList, ScrollView } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

export default class HomeScreen extends React.Component {
return (
  <View style={styles.container}>
    <ScrollView style={styles.flatlist}>
      <View style={styles.flatlist1}>
        <TouchableOpacity onPress={() => this.props.navigation.navigate('Helder')}>
          <Text style={styles.item}>Empresa do Helder</Text>
        </TouchableOpacity>
      </View>
      <View style={styles.flatlist1}>
        <TouchableOpacity onPress={() => this.props.navigation.navigate('Lols')}>
          <Text style={styles.item}>Lols Inc</Text>
        </TouchableOpacity>
      </View>
      <View style={styles.flatlist1}>
        <TouchableOpacity onPress={() => this.props.navigation.navigate('Athlean')}>
          <Text style={styles.item}>Tesla Portugal</Text>
        </TouchableOpacity>
      </View>
    </ScrollView>
  </View>
);
  }
}
</code>```

And this is the main code from my App.js, which has the StackNavigator and the BottomStackNavigator

```<code>const HomeStack = createStackNavigator({
  Home: {
screen: HomeScreen,
navigationOptions: () => ({
    headerShown: false
})
  },
  Helder: {
screen: HelderScreen,
navigationOptions: () => ({
  title: "Helder"
})
  },
  Athlean: {
screen: AthleanScreen,
navigationOptions: () => ({
  title: "Athlean"
})
  },
  Lols : {
screen: LolsScreen,
navigationOptions: () => ({
  title: "Lols"
})
  }
});

const AppContainer = createBottomTabNavigator (
  {
        Home: {
      screen: HomeStack,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => <Ionicons name='ios-home' size={24} color={tintColor}/>
      }
    },
    Message: {
      screen: MessageScreen,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => <Ionicons name='ios-chatboxes' size={24} color={tintColor}/>
      }
    },
    Notification: {
      screen: NotificationScreen,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => <Ionicons name='ios-notifications' size={24} color={tintColor}/>
      }
    },
    Profile: {
      screen: DrawerNavigator,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => <Ionicons name='ios-person' size={24} color={tintColor}/>
      }
    },
  },
  {
    defaultNavigationOptions:{
      tabBarOnPress: ({navigation, defaultHandler}) => {
        if (navigation.state.key === 'Post'){
          navigation.navigate('postModal')
        } else {
          defaultHandler()
        }
      }
    },

    tabBarOptions:{
      activeTintColor: 'orange',
      inactiveTintColor: 'black',
      showLabel: false
    }
  },
 {
mode: 'modal',
headerMode: 'none'
  }
)
</code>```

I am new to React Native, could you please help me?

答:
You need react-native-modal in order to achieve this behavior. What you have to do is,

1) Create a Modal which contains a TextInput to type password and a Submit button.

2) Once the user clicked on the button in the Home.js screen, the Modal should be opened and ask for the password. (Please make sure that you have a ref to the modal and you have implemented necessary things to open the modal on button press using ref.

3) When the user entered the password, you can authenticate and then navigate to the screen you want if it is authenticated. (You can write the code for authentication and navigation inside your Modal implementation js file.)

Here is a sample code...

PasswordInputModal.js

```<code>import React, { Component } from 'react';
import { View, TextInput, Button } from 'react-native';
import Modal from 'react-native-modal';

export default class PasswordInputModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      password  : '',
      isVisible : false,
      navigateTo: null,
    };
  }

  open = (navigateTo) => this.setState({ isVisible: true, navigateTo: navigateTo });

  close = () => this.setState({ isVisible: false });

  onPressSubmitButton = () => {
    //Use any authentication method you want according to your requirement.
    //Here, it is taken as authenticated if and only if the input password is "12345".

    const isAuthenticated = ("12345" == this.state.password); //If input password is '12345', isAuthenticated gets true boolean value and false otherwise.

    if(isAuthenticated) {
      this.props.navigation.navigate(this.state.navigateTo);
    }
    else {
      console.log("Invalid password"); //Prompt an error alert or whatever you prefer.
    }

    this.close();
  }

  renderModalContent = () => (
    <View>
      <TextInput type={'password'} value={this.state.password} onChangeText={(password) => this.setState({ password })} />
      <Button onPress={() => this.onPressSubmitButton()} title="Submit" color="#841584" />
    </View>
  );

  render() {
    return (
      <Modal
        isVisible={this.state.isVisible}
        backdropColor="#000000"
        backdropOpacity={0.9}
        animationIn="zoomInDown"
        animationOut="zoomOutUp"
        animationInTiming={600}
        animationOutTiming={600}
        backdropTransitionInTiming={600}
        backdropTransitionOutTiming={600}
      >
        {this.renderModalContent()}
      </Modal>
    );
  }
}
</code>```

Home.js

```<code>import React, { Component } from 'react';
import { Text, View, TouchableOpacity, ScrollView } from 'react-native';
import PasswordInputModal from './PasswordInputModal.js'

export default class HomeScreen extends Component {
  render() {
    return (
      <View style={styles.container}>
        <ScrollView style={styles.flatlist}>
          <View style={styles.flatlist1}>
            <TouchableOpacity onPress={() => this.PasswordInputModal.open('Helder')}>
              <Text style={styles.item}>Empresa do Helder</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.flatlist1}>
            <TouchableOpacity onPress={() => this.PasswordInputModal.open('Lols')}>
              <Text style={styles.item}>Lols Inc</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.flatlist1}>
            <TouchableOpacity onPress={() => this.PasswordInputModal.open('Athlean')}>
              <Text style={styles.item}>Tesla Portugal</Text>
            </TouchableOpacity>
          </View>
        </ScrollView>

        <PasswordInputModal
          ref={modal => this.PasswordInputModal = modal}
          navigation={this.props.navigation} />
      </View>
    );
  }
}
</code>```

When opening the modal, I've passed the name of the screen which you want to navigate after successful authentication. That screen name is passed as an argument of the open() function and, a state is set for using when to navigate.

I didn't test this code and the styles of the modal are not applied by me. Please go through this and try to do it as you want. Feel free to ask me if you have any problems. Good luck!

Title: Using Passwords to Navigate Screens

Body:
I am doing a react native + firebase app. At the moment, I am struggling to make a message pop up asking for a certain password whenever I press one of the page routers. I have 3 pages nested in an StackNavigator at App.js.

As you can see on the following code, I have 3 routers to those pages (which are HelderScreen.js, LolsScreen.js and AthleanScreen.js). Whenever I click on these routers, I want a message pop up to ask for a unique password to each of those routers.

This is my Home.js main code

import React from 'react';
import { StyleSheet, Text, View, SafeAreaView, TextInput, TouchableOpacity, LayoutAnimation, Image, FlatList, ScrollView } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

export default class HomeScreen extends React.Component {
return (
  <View style={styles.container}>
    <ScrollView style={styles.flatlist}>
      <View style={styles.flatlist1}>
        <TouchableOpacity onPress={() => this.props.navigation.navigate('Helder')}>
          <Text style={styles.item}>Empresa do Helder</Text>
        </TouchableOpacity>
      </View>
      <View style={styles.flatlist1}>
        <TouchableOpacity onPress={() => this.props.navigation.navigate('Lols')}>
          <Text style={styles.item}>Lols Inc</Text>
        </TouchableOpacity>
      </View>
      <View style={styles.flatlist1}>
        <TouchableOpacity onPress={() => this.props.navigation.navigate('Athlean')}>
          <Text style={styles.item}>Tesla Portugal</Text>
        </TouchableOpacity>
      </View>
    </ScrollView>
  </View>
);
  }
}

And this is the main code from my App.js, which has the StackNavigator and the BottomStackNavigator

const HomeStack = createStackNavigator({
  Home: {
screen: HomeScreen,
navigationOptions: () => ({
    headerShown: false
})
  },
  Helder: {
screen: HelderScreen,
navigationOptions: () => ({
  title: "Helder"
})
  },
  Athlean: {
screen: AthleanScreen,
navigationOptions: () => ({
  title: "Athlean"
})
  },
  Lols : {
screen: LolsScreen,
navigationOptions: () => ({
  title: "Lols"
})
  }
});

const AppContainer = createBottomTabNavigator (
  {
        Home: {
      screen: HomeStack,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => <Ionicons name='ios-home' size={24} color={tintColor}/>
      }
    },
    Message: {
      screen: MessageScreen,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => <Ionicons name='ios-chatboxes' size={24} color={tintColor}/>
      }
    },
    Notification: {
      screen: NotificationScreen,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => <Ionicons name='ios-notifications' size={24} color={tintColor}/>
      }
    },
    Profile: {
      screen: DrawerNavigator,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => <Ionicons name='ios-person' size={24} color={tintColor}/>
      }
    },
  },
  {
    defaultNavigationOptions:{
      tabBarOnPress: ({navigation, defaultHandler}) => {
        if (navigation.state.key === 'Post'){
          navigation.navigate('postModal')
        } else {
          defaultHandler()
        }
      }
    },

    tabBarOptions:{
      activeTintColor: 'orange',
      inactiveTintColor: 'black',
      showLabel: false
    }
  },
 {
mode: 'modal',
headerMode: 'none'
  }
)

I am new to React Native, could you please help me?

Body:
You need react-native-modal in order to achieve this behavior. What you have to do is,

1) Create a Modal which contains a TextInput to type password and a Submit button.

2) Once the user clicked on the button in the Home.js screen, the Modal should be opened and ask for the password. (Please make sure that you have a ref to the modal and you have implemented necessary things to open the modal on button press using ref.

3) When the user entered the password, you can authenticate and then navigate to the screen you want if it is authenticated. (You can write the code for authentication and navigation inside your Modal implementation js file.)

Here is a sample code...

PasswordInputModal.js

import React, { Component } from 'react';
import { View, TextInput, Button } from 'react-native';
import Modal from 'react-native-modal';

export default class PasswordInputModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      password  : '',
      isVisible : false,
      navigateTo: null,
    };
  }

  open = (navigateTo) => this.setState({ isVisible: true, navigateTo: navigateTo });

  close = () => this.setState({ isVisible: false });

  onPressSubmitButton = () => {
    //Use any authentication method you want according to your requirement.
    //Here, it is taken as authenticated if and only if the input password is "12345".

    const isAuthenticated = ("12345" == this.state.password); //If input password is '12345', isAuthenticated gets true boolean value and false otherwise.

    if(isAuthenticated) {
      this.props.navigation.navigate(this.state.navigateTo);
    }
    else {
      console.log("Invalid password"); //Prompt an error alert or whatever you prefer.
    }

    this.close();
  }

  renderModalContent = () => (
    <View>
      <TextInput type={'password'} value={this.state.password} onChangeText={(password) => this.setState({ password })} />
      <Button onPress={() => this.onPressSubmitButton()} title="Submit" color="#841584" />
    </View>
  );

  render() {
    return (
      <Modal
        isVisible={this.state.isVisible}
        backdropColor="#000000"
        backdropOpacity={0.9}
        animationIn="zoomInDown"
        animationOut="zoomOutUp"
        animationInTiming={600}
        animationOutTiming={600}
        backdropTransitionInTiming={600}
        backdropTransitionOutTiming={600}
      >
        {this.renderModalContent()}
      </Modal>
    );
  }
}

Home.js

import React, { Component } from 'react';
import { Text, View, TouchableOpacity, ScrollView } from 'react-native';
import PasswordInputModal from './PasswordInputModal.js'

export default class HomeScreen extends Component {
  render() {
    return (
      <View style={styles.container}>
        <ScrollView style={styles.flatlist}>
          <View style={styles.flatlist1}>
            <TouchableOpacity onPress={() => this.PasswordInputModal.open('Helder')}>
              <Text style={styles.item}>Empresa do Helder</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.flatlist1}>
            <TouchableOpacity onPress={() => this.PasswordInputModal.open('Lols')}>
              <Text style={styles.item}>Lols Inc</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.flatlist1}>
            <TouchableOpacity onPress={() => this.PasswordInputModal.open('Athlean')}>
              <Text style={styles.item}>Tesla Portugal</Text>
            </TouchableOpacity>
          </View>
        </ScrollView>

        <PasswordInputModal
          ref={modal => this.PasswordInputModal = modal}
          navigation={this.props.navigation} />
      </View>
    );
  }
}

When opening the modal, I've passed the name of the screen which you want to navigate after successful authentication. That screen name is passed as an argument of the open() function and, a state is set for using when to navigate.

I didn't test this code and the styles of the modal are not applied by me. Please go through this and try to do it as you want. Feel free to ask me if you have any problems. Good luck!


问:
how to create custom progress bar with circles in android
I am working on an app in which I want to show a ProgressBar, but I want to replace the default Android ProgressBar.

custom progressbar

how to create this progressbar. i tried alot but cant do it.

it should increse with button click

if i could apply animation it would be better

thanks for the help.

答:
can you use in library custom progress bar

Add ProgressBar to your gradle

```<code>  compile 'com.ashutosh.progress-nevigation-bar:library:1.0.0'
</code>```

xml:

```<code><com.library.NavigationBar
    android:id="@+id/navBar"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="#ffffffff"
    android:padding="6dp"
    app:central_line_height="1dp"
    app:enable_border="true"
    app:only_border="false"
    app:tab_border_color_array="@array/border_state_colors"
    app:tab_color_array="@array/indicator_colors"
    app:tab_indicator_color="@color/darkYellow"
    app:tab_padding="48dp"
    app:tab_strok_width="3dp"
    app:tab_text_color_array="@array/text_state_colors"
    app:tab_text_size="18sp"/>
</code>```

and java:

```<code>NavigationBar bar = (NavigationBar) findViewById(R.id.navBar);
    bar.setOnTabSelected(this);
    bar.setOnTabClick(this);

    bar.setTabCount(count);
    bar.animateView(3000);
    bar.setCurrentPosition(pos);
</code>```

Body:
can you use in library custom progress bar

Add ProgressBar to your gradle

  compile 'com.ashutosh.progress-nevigation-bar:library:1.0.0'

xml:

<com.library.NavigationBar
    android:id="@+id/navBar"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="#ffffffff"
    android:padding="6dp"
    app:central_line_height="1dp"
    app:enable_border="true"
    app:only_border="false"
    app:tab_border_color_array="@array/border_state_colors"
    app:tab_color_array="@array/indicator_colors"
    app:tab_indicator_color="@color/darkYellow"
    app:tab_padding="48dp"
    app:tab_strok_width="3dp"
    app:tab_text_color_array="@array/text_state_colors"
    app:tab_text_size="18sp"/>

and java:

NavigationBar bar = (NavigationBar) findViewById(R.id.navBar);
    bar.setOnTabSelected(this);
    bar.setOnTabClick(this);

    bar.setTabCount(count);
    bar.animateView(3000);
    bar.setCurrentPosition(pos);


问:
Unittest for C++ running on an AtMega32a
I've made a workflow to unit test C code for an AtMega32a. I've used a combination of the C test framework "unity"[1] and the AVR simulator "simavr"[2]. After I write the C code, I push it to a Gitlab server. The Gitlab server downloads and runs a docker container, installs gccavr, simavr to it, compiles the C code, and then runs the code in Simavr. Simavr pipes the messages from unity from the serial port to the console. When the tests are complete, the gitlab server sends me an e-mail with the results.

[1] http://www.throwtheswitch.org/unity

[2] https://github.com/buserror/simavr

Now I would like to do the same, but this time with C++ code. I'm therefore looking for a C++ test suite that:

a) Is written in C++, or can be called from C++ code

b) Runs on an AVR

c) Can send it's messages to the serial port. (So I can run the code also in a real AtMega32a connected to a serial port of my PC)

Do you know of such a suite?

Cheers,
Cedric

答:
Google recently released pigweed, a framework for embedded development in C++, which includes unit test functionality.

It's platform-agnostic and doesn't require heap allocations, so you'd only need to implement an Event Handler interface to report your results through something like the serial port. It also includes a handler example, which you can reimplement the WriteLine function for your platform.

Now, if I recall correctly, the AVR-GCC doesn't include the C++ Standard Library, which would be a problem, because pigweed requires some Standard Library headers. For that, I recommend taking a look at something like ETL, which should implement most of what you need.


问:
Add listener to bootstrap modal getting closed using Javascript ONLY
I want to fire an event every time the modal gets closed. Since it can be closed from multiple places I just want to add a listener to when it does get closed. I have browsed the internet for possible solutions for listening to the bootstrap modal close event but they all use JQuery. Is there any way I can do that using just plain javascript?

Here is the solution in JQuery:

```<code><script>
$(document).ready(function(){
  $("#myBtn").click(function(){
    $("#myModal").modal("show");
  });
  $("#myModal").on('hidden.bs.modal', function(){
    alert('The modal is now hidden.');
  });
});
</script>
</code>```

If I could add a listener to hidden.bs.modal using javascript alone that would be great. I've tried

```<code>document.addEventListener("hidden.bs.modal", function(){
  console.log('modal closed!')
});
</code>```

but its not working.

答:
hidden.bs.modal is not an event, so there's no way to listen for it directly with addEventListener.

What you can do is listen for attribute changes of a specific element, using a mutation observer.

You need to setup a call back that is essentially your event handler, and attach that to a mutation observer, and then set the observer to observer your modal element.

const target = document.getElementById('target');
document.getElementById('btn1').addEventListener('click', e => target.classList.add('hidden', 'bs', 'modal'));

document.getElementById('btn2').addEventListener('click', e => target.classList.remove('hidden', 'bs', 'modal'));

const config = { attributes: true, childList: false, subtree: false };

function callback(mutationsList, observer)
{
  for(let mutation of mutationsList)
  {
    if(mutation.attributeName == 'class')
    {
      let cls = mutation.target.getAttribute('class');
      if(cls.includes('hidden') && cls.includes('bs') && cls.includes('modal'))
      {
        console.log('the modal is now hidden');
      }
    }
  }
}

const observer = new MutationObserver(callback);

observer.observe(target, config);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden
{
 color:green;
}
.bs
{
 background: red;
}
.modal
{
 border:black dashed 3px;
}</code>```

hello

<input type="button" id="btn1" value="switch on">

<input type="button" id="btn2" value="switch off">
```

Body:
I want to fire an event every time the modal gets closed. Since it can be closed from multiple places I just want to add a listener to when it does get closed. I have browsed the internet for possible solutions for listening to the bootstrap modal close event but they all use JQuery. Is there any way I can do that using just plain javascript?

Here is the solution in JQuery:

If I could add a listener to hidden.bs.modal using javascript alone that would be great. I've tried

document.addEventListener("hidden.bs.modal", function(){
  console.log('modal closed!')
});

but its not working.

Body:
hidden.bs.modal is not an event, so there's no way to listen for it directly with addEventListener.

What you can do is listen for attribute changes of a specific element, using a mutation observer.

You need to setup a call back that is essentially your event handler, and attach that to a mutation observer, and then set the observer to observer your modal element.

const target = document.getElementById('target');
document.getElementById('btn1').addEventListener('click', e => target.classList.add('hidden', 'bs', 'modal'));

document.getElementById('btn2').addEventListener('click', e => target.classList.remove('hidden', 'bs', 'modal'));

const config = { attributes: true, childList: false, subtree: false };

function callback(mutationsList, observer)
{
  for(let mutation of mutationsList)
  {
    if(mutation.attributeName == 'class')
    {
      let cls = mutation.target.getAttribute('class');
      if(cls.includes('hidden') && cls.includes('bs') && cls.includes('modal'))
      {
        console.log('the modal is now hidden');
      }
    }
  }
}

const observer = new MutationObserver(callback);

observer.observe(target, config);

.hidden
{
 color:green;
}
.bs
{
 background: red;
}
.modal
{
 border:black dashed 3px;
}

<p id="target">hello</p>
<p><input type="button" id="btn1" value="switch on"></p>
<p><input type="button" id="btn2" value="switch off"></p>


问:
Function which takes function as input and makes its expressions visible when called
Building on this SO question here I want to write a function that manipulates other functions by (1) setting each line visible () and by (2) wrapping withAutoprint({}) around the body of the function. First, I though some call to trace() would yield my desired result, but somehow I can't figure it out.

Here is a simple example:

```<code># Input function foo
foo <- function(x)
{
  line1 <- x
  line2 <- 0
  line3 <- line1 + line2
  return(line3)
}

# some function which alters foo (here called make_visible() )
foo2 <- make_visible(foo)

# so that foo2 looks like this after being altered
foo2 <- function(x)
{
 withAutoprint({
  (line1 <- x)
  (line2 <- 0)
  (line3 <- line1 + line2)

  (return(line3))
 })
}

# example of calling foo2 and desired output/result
> foo2(2)
> (line1 <- x)
[1] 2
> (line2 <- 0)
[1] 0
> (line3 <- line1 + line2)
[1] 2
> (return(line3))
[1] 2
</code>```

background / motivation

Turning functions visible line by line is helpful with longer custom functions when no real error is thrown, but the functions takes a wrong turn and returns and unwanted output. The alternative is using the debugger clicking next and checking each variable step by step. A function like make_visible might save some time here.

Use case

I see an actual use case for this kind of function, when debugging map or lapply functions which do not through an error, but produce an undesired result somewhere in the function that is being looped over.

答:
Here's a solution that creates exactly the body of the solution you proposed in your question, with the addition of the 2 tests you used in your answer :

make_visible <- function(f) {
  if (typeof(f) %in% c("special", "builtin")) {
    stop("make_visible cannot be applied to primitive functions")
  }

  if (! typeof(f) %in% "closure") {
    stop("make_visible only takes functions of type closures as argument")
  }
  f2 <- f
  bod <- body(f)
  if(!is.call(bod) || !identical(bod[[1]], quote(`{`)))
    bod <- call("(",body(f))
  else
    bod[-1] <- lapply(as.list(bod[-1]), function(expr) call("(", expr))
  body(f2) <- call("[[",call("withAutoprint", bod),"value")
  f2
}
```

```# solve foo issue with standard adverb way
foo <- function(x)
{
  line1 <- x
  line2 <- 0
  line3 <- line1 + line2
  return(line3)
}

foo2 <- make_visible(foo)

foo2
#> function (x)
#> withAutoprint({
#>     (line1 <- x)
#>     (line2 <- 0)
#>     (line3 <- line1 + line2)
#>     (return(line3))
#> })[["value"]]

foo2(2)
#> > (line1 <- x)
#> [1] 2
#> > (line2 <- 0)
#> [1] 0
#> > (line3 <- line1 + line2)
#> [1] 2
#> > (return(line3))
#> [1] 2
#> [1] 2
```

<p>Here's another take, printing nicer as your own second proposal : </p>

<pre class="lang-r prettyprint-override"><code>make_visible2 <- function(f) {
  if (typeof(f) %in% c("special", "builtin")) {
    stop("make_visible cannot be applied to primitive functions")
  }

  if (! typeof(f) %in% "closure") {
    stop("make_visible only takes functions of type closures as argument")
  }
  f2 <- f
  bod <- body(f)
  if(!is.call(bod) || !identical(bod[[1]], quote(`{`))) {
    bod <- bquote({
      message(deparse(quote(.(bod))))
      print(.(bod))
    })
  }  else {
    bod[-1] <- lapply(as.list(bod[-1]), function(expr) {
      bquote({
        message(deparse(quote(.(expr))))
        print(.(expr))
      })
    })
  }
  body(f2) <- bod
  f2
}
</code>```

```<code>foo3 <- make_visible2(foo)
foo3
#> function (x)
#> {
#>     {
#>         message(deparse(quote(line1 <- x)))
#>         print(line1 <- x)
#>     }
#>     {
#>         message(deparse(quote(line2 <- 0)))
#>         print(line2 <- 0)
#>     }
#>     {
#>         message(deparse(quote(line3 <- line1 + line2)))
#>         print(line3 <- line1 + line2)
#>     }
#>     {
#>         message(deparse(quote(return(line3))))
#>         print(return(line3))
#>     }
#> }
</code>```

```<code>foo3(2)
#> line1 <- x
#> [1] 2
#> line2 <- 0
#> [1] 0
#> line3 <- line1 + line2
#> [1] 2
#> return(line3)
#> [1] 2
</code>```

Body:
Building on this SO question here I want to write a function that manipulates other functions by (1) setting each line visible () and by (2) wrapping withAutoprint({}) around the body of the function. First, I though some call to trace() would yield my desired result, but somehow I can't figure it out.

Here is a simple example:

# Input function foo
foo <- function(x)
{
  line1 <- x
  line2 <- 0
  line3 <- line1 + line2
  return(line3)
}

# some function which alters foo (here called make_visible() )
foo2 <- make_visible(foo)

# so that foo2 looks like this after being altered
foo2 <- function(x)
{
 withAutoprint({
  (line1 <- x)
  (line2 <- 0)
  (line3 <- line1 + line2)

  (return(line3))
 })
}

# example of calling foo2 and desired output/result
> foo2(2)
> (line1 <- x)
[1] 2
> (line2 <- 0)
[1] 0
> (line3 <- line1 + line2)
[1] 2
> (return(line3))
[1] 2

background / motivation

Turning functions visible line by line is helpful with longer custom functions when no real error is thrown, but the functions takes a wrong turn and returns and unwanted output. The alternative is using the debugger clicking next and checking each variable step by step. A function like make_visible might save some time here.

Use case

I see an actual use case for this kind of function, when debugging map or lapply functions which do not through an error, but produce an undesired result somewhere in the function that is being looped over.

Body:
Here's a solution that creates exactly the body of the solution you proposed in your question, with the addition of the 2 tests you used in your answer :

make_visible <- function(f) {
  if (typeof(f) %in% c("special", "builtin")) {
    stop("make_visible cannot be applied to primitive functions")
  }

  if (! typeof(f) %in% "closure") {
    stop("make_visible only takes functions of type closures as argument")
  }
  f2 <- f
  bod <- body(f)
  if(!is.call(bod) || !identical(bod[[1]], quote(`{`)))
    bod <- call("(",body(f))
  else
    bod[-1] <- lapply(as.list(bod[-1]), function(expr) call("(", expr))
  body(f2) <- call("[[",call("withAutoprint", bod),"value")
  f2
}

# solve foo issue with standard adverb way
foo <- function(x)
{
  line1 <- x
  line2 <- 0
  line3 <- line1 + line2
  return(line3)
}

foo2 <- make_visible(foo)

foo2
#> function (x)
#> withAutoprint({
#>     (line1 <- x)
#>     (line2 <- 0)
#>     (line3 <- line1 + line2)
#>     (return(line3))
#> })[["value"]]

foo2(2)
#> > (line1 <- x)
#> [1] 2
#> > (line2 <- 0)
#> [1] 0
#> > (line3 <- line1 + line2)
#> [1] 2
#> > (return(line3))
#> [1] 2
#> [1] 2

Here's another take, printing nicer as your own second proposal :

make_visible2 <- function(f) {
  if (typeof(f) %in% c("special", "builtin")) {
    stop("make_visible cannot be applied to primitive functions")
  }

  if (! typeof(f) %in% "closure") {
    stop("make_visible only takes functions of type closures as argument")
  }
  f2 <- f
  bod <- body(f)
  if(!is.call(bod) || !identical(bod[[1]], quote(`{`))) {
    bod <- bquote({
      message(deparse(quote(.(bod))))
      print(.(bod))
    })
  }  else {
    bod[-1] <- lapply(as.list(bod[-1]), function(expr) {
      bquote({
        message(deparse(quote(.(expr))))
        print(.(expr))
      })
    })
  }
  body(f2) <- bod
  f2
}

foo3 <- make_visible2(foo)
foo3
#> function (x)
#> {
#>     {
#>         message(deparse(quote(line1 <- x)))
#>         print(line1 <- x)
#>     }
#>     {
#>         message(deparse(quote(line2 <- 0)))
#>         print(line2 <- 0)
#>     }
#>     {
#>         message(deparse(quote(line3 <- line1 + line2)))
#>         print(line3 <- line1 + line2)
#>     }
#>     {
#>         message(deparse(quote(return(line3))))
#>         print(return(line3))
#>     }
#> }

foo3(2)
#> line1 <- x
#> [1] 2
#> line2 <- 0
#> [1] 0
#> line3 <- line1 + line2
#> [1] 2
#> return(line3)
#> [1] 2


问:
3-D surface chart showing the 30 variables with 10000 data points
I have 30 files, each having 10000 data points related to its 30 variables. I am expected to generate a plot like the attachment. Has anyone tried this before

答: im not sure how you are planning on plotting 30 variables in 3D space. But matplotlib is a python library that has a wide range of plotting tools. you can install it using pip install matplotlib


问:
How to use a conditional aggregate for total gross
I have this query:

```<code>SELECT CAST(co.DateCreated AS DATE) AS Date,
SUM(w.Gross),
       SUM(CASE WHEN co.BookingSourceId = 1 THEN 1 ELSE 0 END) as Website,
       SUM(CASE WHEN co.BookingSourceId = 2 THEN 1 ELSE 0 END) as Phone,
       COUNT(*) as Total_Orders
FROM [Sterlingbuild].[dbo].[CustomerOrder] co
INNER JOIN ( SELECT Gross, CustomerOrderId, p.ProductBrandId
             FROM [Sterlingbuild].[dbo].[CustomerOrderItem] coi
             INNER JOIN [Sterlingbuild].[dbo].[Product] p ON coi.ProductId = p.ProductId
             ) w ON co.CustomerOrderId = w.CustomerOrderId
WHERE CustomerOrderStatusId = 7 AND DepartmentId = 1 AND w.ProductBrandId = 7
GROUP BY CAST(co.DateCreated AS DATE)
ORDER BY CAST(co.DateCreated AS DATE)
</code>```

At the moment it returns the number of orders made by phone/website however I want the total GROSS for both phone/website how do I amend the query to achieve this.

Using SQL server

答:
Sum the gross:

```<code>   SUM(CASE WHEN co.BookingSourceId = 1 THEN w.gross ELSE 0 END) as Website_gross,
   SUM(CASE WHEN co.BookingSourceId = 2 THEN w.gross ELSE 0 END) as Phone_gross,
</code>```

Body:
I have this query:

SELECT CAST(co.DateCreated AS DATE) AS Date,
SUM(w.Gross),
       SUM(CASE WHEN co.BookingSourceId = 1 THEN 1 ELSE 0 END) as Website,
       SUM(CASE WHEN co.BookingSourceId = 2 THEN 1 ELSE 0 END) as Phone,
       COUNT(*) as Total_Orders
FROM [Sterlingbuild].[dbo].[CustomerOrder] co
INNER JOIN ( SELECT Gross, CustomerOrderId, p.ProductBrandId
             FROM [Sterlingbuild].[dbo].[CustomerOrderItem] coi
             INNER JOIN [Sterlingbuild].[dbo].[Product] p ON coi.ProductId = p.ProductId
             ) w ON co.CustomerOrderId = w.CustomerOrderId
WHERE CustomerOrderStatusId = 7 AND DepartmentId = 1 AND w.ProductBrandId = 7
GROUP BY CAST(co.DateCreated AS DATE)
ORDER BY CAST(co.DateCreated AS DATE)

At the moment it returns the number of orders made by phone/website however I want the total GROSS for both phone/website how do I amend the query to achieve this.

Using SQL server

Body:
Sum the gross:

   SUM(CASE WHEN co.BookingSourceId = 1 THEN w.gross ELSE 0 END) as Website_gross,
   SUM(CASE WHEN co.BookingSourceId = 2 THEN w.gross ELSE 0 END) as Phone_gross,


问:
How can I execute command line arguments in a node.js script
Im pretty new to programming and im trying to make efforts - probably this question is not really worth to be asked but I am not making any progress since.. way too long.

I am trying to do a discovery search on all devices that are connected to my local network in a node.js script.

I found this npm module which should do the job: https://www.npmjs.com/package/local-devices/v/3.0.0

So I just tried to copy-paste the example they have given to search my network for all devices:

```<code>const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  devices /*
  [
    { name: '?', ip: '192.168.0.10', mac: '...' },
    { name: '...', ip: '192.168.0.17', mac: '...' },
    { name: '...', ip: '192.168.0.21', mac: '...' },
    { name: '...', ip: '192.168.0.22', mac: '...' }
  ]
  */
})
</code>```

But if I run the script now, nothing happens.

What i've tried so far:
1. I tried to save the output in a constant and tried to output this on a console

```<code>const found = find().then(devices => {
    devices
    /*[
      { name: '?', ip: '192.168.0.10', mac: '...' },
      { name: '...', ip: '192.168.0.17', mac: '...' },
      { name: '...', ip: '192.168.0.21', mac: '...' },
      { name: '...', ip: '192.168.0.22', mac: '...' }
    ]
    return devices
  })
  console.log(found);
</code>```

then the console output is Promise { <pending> }. I couldnt figure out what to do with this yet.

there is this command line argument arp -a which, if executed in the command line, lists all ip adresses of all devices in the network in the terminal. So it basically does exactly what I want, but I need to work with that output in the following code (I need to find one specific ip adress of a smart plug from this list, but that is a different story).

How can I take this command line argument, and execute it in my javascript code/ my node.js script, and save the output in a variable/const?

Best regards,
Michael

答:
The issue you're facing is very common in the JS world. I'll try my best to explain it to you. It's called concurrency, and in very simple terms it means that two or more processes (or threads) run together, but not at the same time. Only one process executes at once.

Even simpler: it means that the code inside the then callback is being delayed for when the CPU is free.

What you see when printing the found object is a Promise { <pending> }. It's an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to associate handlers/callbacks with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

But why do we care? you might say. Well, it's because you simply can think of find function as a "linear" operation. You have to imagine that you pass some sort of callback (through then) that will be executed as soon as it finds all local network devices.

So you could rewrite your code like:

const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  console.log(devices) /*
  [
    { name: '?', ip: '192.168.0.10', mac: '...' },
    { name: '...', ip: '192.168.0.17', mac: '...' },
    { name: '...', ip: '192.168.0.21', mac: '...' },
    { name: '...', ip: '192.168.0.22', mac: '...' }
  ]
  */
})
```

<blockquote>
  <p>But what if you wanted to avoid the callback hell</p>
</blockquote>

<p>Well, JavaScript offers the <code>async</code> & <code>await</code> keywords to help you with that. It's just a fancy way of hiding/dealing with callbacks.</p>

<p>First, we need to be inside an <code>async</code> function, it's a requirement to use <code>await</code>. In the example below, I'll use a self-invoking function to makes things nicer. We can then use <code>await</code> to get the result from the <code>find</code> function:</p>

<pre class="lang-js prettyprint-override"><code>(async () => {
  const find = require('local-devices');

  // Find all local network devices.
  const devices = await find()

  console.log(devices)
})()
</code>```

Body:
Im pretty new to programming and im trying to make efforts - probably this question is not really worth to be asked but I am not making any progress since.. way too long.

I am trying to do a discovery search on all devices that are connected to my local network in a node.js script.

I found this npm module which should do the job: https://www.npmjs.com/package/local-devices/v/3.0.0

So I just tried to copy-paste the example they have given to search my network for all devices:

const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  devices /*
  [
    { name: '?', ip: '192.168.0.10', mac: '...' },
    { name: '...', ip: '192.168.0.17', mac: '...' },
    { name: '...', ip: '192.168.0.21', mac: '...' },
    { name: '...', ip: '192.168.0.22', mac: '...' }
  ]
  */
})

But if I run the script now, nothing happens.

What i've tried so far:
1. I tried to save the output in a constant and tried to output this on a console

const found = find().then(devices => {
    devices
    /*[
      { name: '?', ip: '192.168.0.10', mac: '...' },
      { name: '...', ip: '192.168.0.17', mac: '...' },
      { name: '...', ip: '192.168.0.21', mac: '...' },
      { name: '...', ip: '192.168.0.22', mac: '...' }
    ]
    return devices
  })
  console.log(found);

then the console output is Promise { <pending> }. I couldnt figure out what to do with this yet.

there is this command line argument arp -a which, if executed in the command line, lists all ip adresses of all devices in the network in the terminal. So it basically does exactly what I want, but I need to work with that output in the following code (I need to find one specific ip adress of a smart plug from this list, but that is a different story).

How can I take this command line argument, and execute it in my javascript code/ my node.js script, and save the output in a variable/const?

Best regards,
Michael

Body:
The issue you're facing is very common in the JS world. I'll try my best to explain it to you. It's called concurrency, and in very simple terms it means that two or more processes (or threads) run together, but not at the same time. Only one process executes at once.

Even simpler: it means that the code inside the then callback is being delayed for when the CPU is free.

What you see when printing the found object is a Promise { <pending> }. It's an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to associate handlers/callbacks with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

But why do we care? you might say. Well, it's because you simply can think of find function as a "linear" operation. You have to imagine that you pass some sort of callback (through then) that will be executed as soon as it finds all local network devices.

So you could rewrite your code like:

const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  console.log(devices) /*
  [
    { name: '?', ip: '192.168.0.10', mac: '...' },
    { name: '...', ip: '192.168.0.17', mac: '...' },
    { name: '...', ip: '192.168.0.21', mac: '...' },
    { name: '...', ip: '192.168.0.22', mac: '...' }
  ]
  */
})

But what if you wanted to avoid the callback hell

Well, JavaScript offers the async & await keywords to help you with that. It's just a fancy way of hiding/dealing with callbacks.

First, we need to be inside an async function, it's a requirement to use await. In the example below, I'll use a self-invoking function to makes things nicer. We can then use await to get the result from the find function:

(async () => {
  const find = require('local-devices');

  // Find all local network devices.
  const devices = await find()

  console.log(devices)
})()


问:
axio. to get the data in a different file
I hope you can help me.

I'm trying to get a response from an API and use that information in another file.

I have 3 files:

api.jsx

```<code>import axios from 'axios';
export const api = (url, data) => {

    const { path, method } = url;

    let result ={};
    axios({
            method: method,
            url: path,
            data: data
        })
        .then(res => {

            result = res.data;
            console.log(res.data);
        })
        .catch(err => console.error(err));
    return result;
};

</code>```

url.jsx

```<code>    export const URL = {
    users:
        {
            getAllUsers: { path:'/users', method: 'post'},
            login: { path:'/login', method: 'post'},
            register: { path:'/register', method: 'post'},
            version: { path:'/', method: 'get'},
        }

}
</code>```

app.js (within the render)

```<code>
    const data = {
      email: 'hello@world.com',
      password: '12345',
      };

    let result = api(URL.users.login, data);

    console.log(result);

</code>```

In the api file i get the proper response but in the react component no. I am aware that It's a problem of sync as i get first the console of app.jsx and later on the console of the api.jsx but i would like to respect the current structure or make something similar.

Any idea how to fix this without many changes?

PS. sorry about the mess. I tried to highlight all the code but for some reason it is not working fine.

答:
You want to return a Promise in api.jsx

api.jsx

export const api = (url, data) => {
  const { path, method } = url
  return axios({ // the axios call returns a promise because of its .then; you can just return it
    method: method,
    url: path,
    data: data
  })
  .then(res => {
    return res.data;
  })
  .catch(err => {
    console.error(err)
  })
}
```

Body:
I hope you can help me.

I'm trying to get a response from an API and use that information in another file.

I have 3 files:

api.jsx

import axios from 'axios';
export const api = (url, data) => {

    const { path, method } = url;

    let result ={};
    axios({
            method: method,
            url: path,
            data: data
        })
        .then(res => {

            result = res.data;
            console.log(res.data);
        })
        .catch(err => console.error(err));
    return result;
};

url.jsx

    export const URL = {
    users:
        {
            getAllUsers: { path:'/users', method: 'post'},
            login: { path:'/login', method: 'post'},
            register: { path:'/register', method: 'post'},
            version: { path:'/', method: 'get'},
        }

}

app.js (within the render)

    const data = {
      email: 'hello@world.com',
      password: '12345',
      };

    let result = api(URL.users.login, data);

    console.log(result);

In the api file i get the proper response but in the react component no. I am aware that It's a problem of sync as i get first the console of app.jsx and later on the console of the api.jsx but i would like to respect the current structure or make something similar.

Any idea how to fix this without many changes?

PS. sorry about the mess. I tried to highlight all the code but for some reason it is not working fine.


问:
Flutter: Could not instantiate image codec when calling Image.memory
I want to create a simple profile picture for my app.
I thought it would work like this, but it throws an exception when calling it and I
can't figure out why.

```<code>Widget _buildProfilePicture(double size) {
      if (user.profileImage != null) {
        return ClipRRect(
          borderRadius: BorderRadius.circular(8.0),
          child: Image.memory(
            user.profileImage,
            width: size,
            height: size,
          ),
        );
      }
}
</code>```

The attribute user.profileImage has the datatype Uint8List.

When I call it, it throws this exception:

```<code>════════ Exception caught by image resource service ════════════════════════════════════════════════
The following _Exception was thrown while resolving an image:
Exception: Could not instantiate image codec.

When the exception was thrown, this was the stack:
#0      _futurize (dart:ui/painting.dart:4304:5)
#1      instantiateImageCodec (dart:ui/painting.dart:1682:10)
#2      PaintingBinding.instantiateImageCodec (package:flutter/src/painting/binding.dart:88:12)
#3      MemoryImage._loadAsync (package:flutter/src/painting/image_provider.dart:714:18)
#4      MemoryImage.load (package:flutter/src/painting/image_provider.dart:706:14)
...
Image provider: MemoryImage(Uint8List#2592a, scale: 1.0)
Image configuration: ImageConfiguration(bundle: PlatformAssetBundle#633d8(), devicePixelRatio: 2.6, locale: en_US, textDirection: TextDirection.ltr, size: Size(50.0, 50.0), platform: android)
Image key: MemoryImage(Uint8List#2592a, scale: 1.0)
</code>```

I think it's caused by Image.memory.

Thanks for answers in advance!

答:
My problem was try load and image in base64 type jpg or png with Image.memory() but the image was svg, so i just wrote:

```<code> String _imageBase64;
 Uint8List bytes;

  @override
  Widget build(BuildContext context) {

    final size = getMediaSize(context);
    _imageBase64 = widget.reward.img;
    const Base64Codec base64 = Base64Codec();

    bytes = base64.decode(_imageBase64);
    return SvgPicture.memory(
      bytes,
      fit: BoxFit.fill,
      height: size.width * 0.1,
      width: size.width * 0.1,
    );}
</code>```

I hope it helps, happy coding.

Body:
I want to create a simple profile picture for my app.
I thought it would work like this, but it throws an exception when calling it and I
can't figure out why.

Widget _buildProfilePicture(double size) {
      if (user.profileImage != null) {
        return ClipRRect(
          borderRadius: BorderRadius.circular(8.0),
          child: Image.memory(
            user.profileImage,
            width: size,
            height: size,
          ),
        );
      }
}

The attribute user.profileImage has the datatype Uint8List.

When I call it, it throws this exception:

════════ Exception caught by image resource service ════════════════════════════════════════════════
The following _Exception was thrown while resolving an image:
Exception: Could not instantiate image codec.

When the exception was thrown, this was the stack:
#0      _futurize (dart:ui/painting.dart:4304:5)
#1      instantiateImageCodec (dart:ui/painting.dart:1682:10)
#2      PaintingBinding.instantiateImageCodec (package:flutter/src/painting/binding.dart:88:12)
#3      MemoryImage._loadAsync (package:flutter/src/painting/image_provider.dart:714:18)
#4      MemoryImage.load (package:flutter/src/painting/image_provider.dart:706:14)
...
Image provider: MemoryImage(Uint8List#2592a, scale: 1.0)
Image configuration: ImageConfiguration(bundle: PlatformAssetBundle#633d8(), devicePixelRatio: 2.6, locale: en_US, textDirection: TextDirection.ltr, size: Size(50.0, 50.0), platform: android)
Image key: MemoryImage(Uint8List#2592a, scale: 1.0)

I think it's caused by Image.memory.

Thanks for answers in advance!

Body:
My problem was try load and image in base64 type jpg or png with Image.memory() but the image was svg, so i just wrote:

 String _imageBase64;
 Uint8List bytes;

  @override
  Widget build(BuildContext context) {

    final size = getMediaSize(context);
    _imageBase64 = widget.reward.img;
    const Base64Codec base64 = Base64Codec();

    bytes = base64.decode(_imageBase64);
    return SvgPicture.memory(
      bytes,
      fit: BoxFit.fill,
      height: size.width * 0.1,
      width: size.width * 0.1,
    );}

I hope it helps, happy coding.


问:
Exception has occurred: TypeError 'in <string>' requires string as left operand, not Series
I am working with Pandas in python I have 2 Dataframes that I am trying to pull infromation from one to the other.  Here is a example of the code.

```<code>    import pandas as pd

employees = {'Names': ['John','Jack','Frank','Mike'],
             'Employee_id': ['123', '124', '125', '126'],
             'Leader': ['','','','']}

df1 = pd.DataFrame(employees, columns = ['Names', 'Employee_id', 'Leader'])

print(df1)

leader = {'Employee_id': ['123', '124', '125', '126'],
          'Supervisor': ['Nick', 'Jeff', 'Nick', 'Jeff']}

df2 = pd.DataFrame(leader, columns = ['Employee_id', 'Supervisor'])
print(df2)

df1['Leader'] = df1['Employee_id'].map(lambda x: df2['Supervisor'] if df2['Employee_id'] in x else "")

print(df1)
</code>```

Here is the error.

```<code>Exception has occurred: TypeError
'in <string>' requires string as left operand, not Series
</code>```

Not sure what I am doing wrong.

Thank you for your help.

答:
In your code df2['Employee_id'] in x, x is a string and df2['Employee_id'] is a pandas series. Python doesn't know how to check for series in big_string operation. More specifically, it can only check for some_string in big_string.

IN your case, you can use map with a series:

```<code>df1['Leader'] = df1['Employee_id'].map(df2.set_index('Employee_id')['Supervisor'])
</code>```

Output:

```<code>   Names Employee_id Leader
0   John         123   Nick
1   Jack         124   Jeff
2  Frank         125   Nick
3   Mike         126   Jeff
</code>```

Body:
I am working with Pandas in python I have 2 Dataframes that I am trying to pull infromation from one to the other.  Here is a example of the code.

    import pandas as pd

employees = {'Names': ['John','Jack','Frank','Mike'],
             'Employee_id': ['123', '124', '125', '126'],
             'Leader': ['','','','']}

df1 = pd.DataFrame(employees, columns = ['Names', 'Employee_id', 'Leader'])

print(df1)

leader = {'Employee_id': ['123', '124', '125', '126'],
          'Supervisor': ['Nick', 'Jeff', 'Nick', 'Jeff']}

df2 = pd.DataFrame(leader, columns = ['Employee_id', 'Supervisor'])
print(df2)

df1['Leader'] = df1['Employee_id'].map(lambda x: df2['Supervisor'] if df2['Employee_id'] in x else "")

print(df1)

Here is the error.

Exception has occurred: TypeError
'in <string>' requires string as left operand, not Series

Not sure what I am doing wrong.

Thank you for your help.

Body:
In your code df2['Employee_id'] in x, x is a string and df2['Employee_id'] is a pandas series. Python doesn't know how to check for series in big_string operation. More specifically, it can only check for some_string in big_string.

IN your case, you can use map with a series:

df1['Leader'] = df1['Employee_id'].map(df2.set_index('Employee_id')['Supervisor'])

Output:

   Names Employee_id Leader
0   John         123   Nick
1   Jack         124   Jeff
2  Frank         125   Nick
3   Mike         126   Jeff


问:
Android app adding toolbar causes exception
I thought I should add a toolbar as I'll need a settings button.

So I added this to my main_activity.xml

```<code>    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:title="PSA MFD"
        app:subtitle="Multi functional display for Citroen and Peugeot"
        app:logo="@android:drawable/ic_menu_call"
        app:navigationIcon="@drawable/ic_fan"
 />
</code>```

But now my app won't run because:

```<code>    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rwb.psamfd/com.rwb.psamfd.MainActivity}: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class android.support.v7.widget.Toolbar
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class android.support.v7.widget.Toolbar
     Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class android.support.v7.widget.Toolbar
     Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.widget.Toolbar" on path: DexPathList[[zip file "/data/app/com.rwb.psamfd-2/base.apk"],nativeLibraryDirectories=[/data/app/com.rwb.psamfd-2/lib/x86, /system/lib, /vendor/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.view.LayoutInflater.createView(LayoutInflater.java:609)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
        at com.rwb.psamfd.MainActivity.onCreate(MainActivity.kt:31)
        at android.app.Activity.performCreate(Activity.java:6662)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
</code>```

What do I ned to do? I have absolutely no idea. (I'm new to Android development -- and it's very difficult compared to C#).

答:
Method 1:

Add the following to your dependencies in build.gradle file:

```<code>dependencies {
  ...
  **implementation 'androidx.appcompat:appcompat:1.0.0'**
}
</code>```

And change your toolbar as:

```<code><androidx.appcompat.widget.Toolbar
  ....
  Your contents
  ....>
<androidx.appcompat.widget.Toolbar/>
</code>```

Method 2:

You can migrate to androidx directly.

Hope you will find the solution.

Body:
I thought I should add a toolbar as I'll need a settings button.

So I added this to my main_activity.xml

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:title="PSA MFD"
        app:subtitle="Multi functional display for Citroen and Peugeot"
        app:logo="@android:drawable/ic_menu_call"
        app:navigationIcon="@drawable/ic_fan"
 />

But now my app won't run because:

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rwb.psamfd/com.rwb.psamfd.MainActivity}: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class android.support.v7.widget.Toolbar
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class android.support.v7.widget.Toolbar
     Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class android.support.v7.widget.Toolbar
     Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.widget.Toolbar" on path: DexPathList[[zip file "/data/app/com.rwb.psamfd-2/base.apk"],nativeLibraryDirectories=[/data/app/com.rwb.psamfd-2/lib/x86, /system/lib, /vendor/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.view.LayoutInflater.createView(LayoutInflater.java:609)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
        at com.rwb.psamfd.MainActivity.onCreate(MainActivity.kt:31)
        at android.app.Activity.performCreate(Activity.java:6662)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

What do I ned to do? I have absolutely no idea. (I'm new to Android development -- and it's very difficult compared to C#).

Body:
Method 1:

Add the following to your dependencies in build.gradle file:

dependencies {
  ...
  **implementation 'androidx.appcompat:appcompat:1.0.0'**
}

And change your toolbar as:

<androidx.appcompat.widget.Toolbar
  ....
  Your contents
  ....>
<androidx.appcompat.widget.Toolbar/>

Method 2:

You can migrate to androidx directly.

Hope you will find the solution.


问:
How to revert initial git commit?
I commit to a git repository for the first time; I then regret the commit and want to revert it.  I try

```<code># git reset --hard HEAD~1
</code>```

I get this message:

```<code>fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
</code>```

This commit is the first commit of the repository. Any idea how to undo git's initial commit?

答:
I wonder why "amend" is not suggest and have been crossed out by @damkrat, as amend appears to me as just the right way to resolve the most efficiently the underlying problem of fixing the wrong commit since there is no purpose of having no initial commit. As some stressed out you should only modify "public" branch like master if no one has clone your repo...</p>

```<code>git add <your different stuff>
git commit --amend --author="author name <author.name@email.com>"-m "new message"
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to revert initial git commit?

Body:
I commit to a git repository for the first time; I then regret the commit and want to revert it.  I try

# git reset --hard HEAD~1

I get this message:

fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.

This commit is the first commit of the repository. Any idea how to undo git's initial commit?

Body:
I wonder why "amend" is not suggest and have been crossed out by @damkrat, as amend appears to me as just the right way to resolve the most efficiently the underlying problem of fixing the wrong commit since there is no purpose of having no initial commit. As some stressed out you should only modify "public" branch like master if no one has clone your repo...

git add <your different stuff>
git commit --amend --author="author name <author.name@email.com>"-m "new message"


问:
Multiple Default Buttons in a User Control
I have a user control that is comprised of 3 textboxes, 3 buttons and a gridview.  I can set the defaultbutton property of the form, but that would only affect one button.

Each textbox/button combo should have a behavior that when the textbox has focus, pressing Enter should fire its associated button.

To further complicate the issue, this is being used inside a Master Page implementation.

Is there any way to do this?  As far as I can tell, .NET will only allow one default button - it doesn't provide to explicitly associate textboxes and buttons.

I welcome your insights.

答:
Here is a sweet solution by usage of an Attached Property:
http://neilmosafi.blogspot.com/2007/04/default-buttons-in-wpf-and-multiple.html

Just create a class with the attached property code of the article and add it to controls, which encapsulate each TextBox and Button pair.

Example: <StackPanel ... local:AccessKeyScoper.IsAccessKeyScope="True"> <TextBox ... /> <Button ... /> </StackPanel>

Note:
If you add the file with the Dependency Property to a subdirectory, you need to use an other namespace definition instead of local:.

ContentLicense: CC BY-SA 2.5


问:
What is the code for key "Volume UP" in Microsoft SendKeys Class
I need to send "Volume Up" key with SendKeys Class. But I don't know what is the code for that key.

There is a list with key-codes, but there is no info about "Volume Up" key:

https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.sendkeys?view=netframework-4.8

(And I'm also searching for "Volume Down" and "Volume Mute")

答:
This is not supported by the SendKeys class. The documentation is correct.

You can also check the implementation to see what is supported.

For any code not contained in the allowed key list and not representing a single character, you will get an ArgumentException.

Use native Windows messages for sending that key to an application, as @HansPassant suggests in his comment. Here is his very helpful explanation how to do this.

You could also try third-party Windows input simulation solutions, like e.g. this open source WindowsInput library.


问:
Angular material 2 - mat-paginator [length] issue
I am trying to use the mat-paginator for a table where I want to show data retrieved via an HTTP call, but the problem I have is that I cannot set the length of the paginator to the total number of the results I get from the API. In this example, the length is hardcoded in the component, but it shoudn't be a problem (I tried also to set it on the view as [length]="100" and it doesn't work). Here is the HTML:

```<code><mat-table #table1="matSort" [dataSource]="dataSource1" matSort>

   <ng-container matColumnDef="id">
        <mat-header-cell *matHeaderCellDef>
            <mat-checkbox name="all" class="" [checked]="isAllChecked()" (change)="checkAll($event)" *ngIf="bulkView"></mat-checkbox>
        </mat-header-cell>
        <mat-cell *matCellDef="let element">
            <mat-checkbox class="" [checked]="isAllRowsSelected" [(ngModel)]="element.state" *ngIf="bulkView"></mat-checkbox>
        </mat-cell>
   </ng-container>

    <ng-container matColumnDef="firstName">
        <mat-header-cell *matHeaderCellDef mat-sort-header="CompanyAgent"> First name </mat-header-cell>
        <mat-cell *matCellDef="let element">
            <img class="personal-data-table__img" src="/assets/app/media/img/users/100_3.jpg" alt="user" width="50" />
                {{element.firstName}}
        </mat-cell>
    </ng-container>

    <ng-container matColumnDef="lastName">
        <mat-header-cell *matHeaderCellDef mat-sort-header="CompanyEmail"> Last name </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.lastName}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="city">
        <mat-header-cell *matHeaderCellDef mat-sort-header="Website"> City </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.city}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="actions">
        <mat-header-cell *matHeaderCellDef>Actions</mat-header-cell>
        <mat-cell *matCellDef="let element">
            <span class="btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill">
                <i class="la la-ellipsis-h"></i>
            </span>
            <span class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" (click)="editPersonalDataItem(element.RecordID)">
                <i class="la la-edit"></i>
            </span>
            <span class="btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill">
                <i class="la la-trash"></i>
            </span>
        </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>

<mat-paginator #paginator1
    [length]="pag1.pageLength"
    [pageSize]="pag1.pageSize"
    [pageSizeOptions]="pag1.pageSizeOptions"
    [pageIndex]="pag1.pageIndex"
    (page)="onPaginateChange1($event)">
</mat-paginator>
</code>```

and the component:

```<code>pag1 = {
    pageSize: 10,
    pageSizeOptions: [5, 10, 20],
    pageIndex: 0,
    pageLength: 100
  };

@ViewChild('paginator1') paginator1: MatPaginator;

this.route.data.subscribe(data => {
    this.personalData = data.users.data.persons;
    this.dataSource1 = new MatTableDataSource(this.personalData);
    this.dataSource1.paginator = this.paginator1;
    console.log('this.paginator1: ', this.paginator1);
});
</code>```

When I console.log this.paginator1, I can see the _length set to 100, but when I open the object, I see the value which is displayed in the browser (10).

The data is displaying fine in the browser, the only problem I have is that the paginator always shows 1-10 of 10 and I want it to show 1-10 of x, where x is the value I get from the API for the total number of items.
Please advise. Thanks!

答:
This worked for me

```<code><mat-paginator  [length]="length" (page)="getServerData($event)" #paginator [pageSizeOptions]="[5, 10, 20, 50]" showFirstLastButtons></mat-paginator>
</code>```

Add line

```<code>this.length = count;
</code>```

and remove line

```<code>this.dataSource1.paginator = this.paginator1;
</code>```

Body:
I am trying to use the mat-paginator for a table where I want to show data retrieved via an HTTP call, but the problem I have is that I cannot set the length of the paginator to the total number of the results I get from the API. In this example, the length is hardcoded in the component, but it shoudn't be a problem (I tried also to set it on the view as [length]="100" and it doesn't work). Here is the HTML:

<mat-table #table1="matSort" [dataSource]="dataSource1" matSort>

   <ng-container matColumnDef="id">
        <mat-header-cell *matHeaderCellDef>
            <mat-checkbox name="all" class="" [checked]="isAllChecked()" (change)="checkAll($event)" *ngIf="bulkView"></mat-checkbox>
        </mat-header-cell>
        <mat-cell *matCellDef="let element">
            <mat-checkbox class="" [checked]="isAllRowsSelected" [(ngModel)]="element.state" *ngIf="bulkView"></mat-checkbox>
        </mat-cell>
   </ng-container>

    <ng-container matColumnDef="firstName">
        <mat-header-cell *matHeaderCellDef mat-sort-header="CompanyAgent"> First name </mat-header-cell>
        <mat-cell *matCellDef="let element">

                {{element.firstName}}
        </mat-cell>
    </ng-container>

    <ng-container matColumnDef="lastName">
        <mat-header-cell *matHeaderCellDef mat-sort-header="CompanyEmail"> Last name </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.lastName}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="city">
        <mat-header-cell *matHeaderCellDef mat-sort-header="Website"> City </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.city}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="actions">
        <mat-header-cell *matHeaderCellDef>Actions</mat-header-cell>
        <mat-cell *matCellDef="let element">

        </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>

<mat-paginator #paginator1
    [length]="pag1.pageLength"
    [pageSize]="pag1.pageSize"
    [pageSizeOptions]="pag1.pageSizeOptions"
    [pageIndex]="pag1.pageIndex"
    (page)="onPaginateChange1($event)">
</mat-paginator>

and the component:

pag1 = {
    pageSize: 10,
    pageSizeOptions: [5, 10, 20],
    pageIndex: 0,
    pageLength: 100
  };

@ViewChild('paginator1') paginator1: MatPaginator;

this.route.data.subscribe(data => {
    this.personalData = data.users.data.persons;
    this.dataSource1 = new MatTableDataSource(this.personalData);
    this.dataSource1.paginator = this.paginator1;
    console.log('this.paginator1: ', this.paginator1);
});

When I console.log this.paginator1, I can see the _length set to 100, but when I open the object, I see the value which is displayed in the browser (10).

The data is displaying fine in the browser, the only problem I have is that the paginator always shows 1-10 of 10 and I want it to show 1-10 of x, where x is the value I get from the API for the total number of items.
Please advise. Thanks!

Body:
This worked for me

<mat-paginator  [length]="length" (page)="getServerData($event)" #paginator [pageSizeOptions]="[5, 10, 20, 50]" showFirstLastButtons></mat-paginator>

Add line

this.length = count;

and remove line

this.dataSource1.paginator = this.paginator1;


问:
Creating/accessing libraries in netbeans
I am a new netbeans user, and I'm having trouble importing user created libraries. </p>

<p>I created a library named "MyLibrary". I then added a folder that contains my saved projects (entitled "netbeansProjects") to the classpath, which I wrote in the netbeans IDE. Now I'm trying to import a class into a project I'm working on, but it wont allow to me to it. I'm getting the massage "Package does not exist". I would really appreciate some assistance on this problem. I searched online; I couldn't find anything.  </p>

答:
You'll have to create the library using the Netbeans Library Manager. Go to Tools ->Libraries then select the New Library... button and make a new Class Library. You will only be able to add jar files using this method not a Netbeans project.

To add a Netbeans project:

In the Netbeans Projects window right click on Libraries folder under your project, and select Add Project...  then navigate to the Netbeans project your would like use.
 You will have to do this for each project you would like to use.

Body:
I am a new netbeans user, and I'm having trouble importing user created libraries.

I created a library named "MyLibrary". I then added a folder that contains my saved projects (entitled "netbeansProjects") to the classpath, which I wrote in the netbeans IDE. Now I'm trying to import a class into a project I'm working on, but it wont allow to me to it. I'm getting the massage "Package does not exist". I would really appreciate some assistance on this problem. I searched online; I couldn't find anything.


问:
Plotly Gauge Dynamic
I have a problem with Plotly JS Gauge that I cannot solve and I have tried a thousand ways to solve it.

How can I use Plotly JS Gauge on real time, dynamically?

I have tried this but it does not work... ;-( :

```<code><script>
    function rand() {
        return Math.floor(Math.random() * (250 - 0) ) + 0;
    }

    var data = [
                {
                    domain: { x: [0, 1], y: [0, 1] },
                    value: 0,
                    title: { text: "Speed" },
                    type: "indicator",
                    mode: "gauge+number"
                }
            ];

    var layout = { width: 600, height: 500, margin: { t: 0, b: 0 } };
    Plotly.newPlot('myDiv', data, layout);

    var cnt = 0;
    var interval = setInterval(function() {
        Plotly.extendTraces('myDiv', {value: [[rand()]]}, [0])
        if(++cnt === 100) clearInterval(interval);
    }, 300);
</script>
</code>```

答:
Try using Plotly.update():

function rand() {
return Math.floor(Math.random() * (250 - 0) ) + 0;
}

var data = [
        {
            domain: { x: [0, 1], y: [0, 1] },
            value: 0,
            title: { text: "Speed" },
            type: "indicator",
            mode: "gauge+number"
        }
    ];

var layout = { width: 600, height: 500, margin: { t: 0, b: 0 } };
Plotly.newPlot('myDiv', data, layout);

var cnt = 0;
var interval = setInterval(function() {
Plotly.update('myDiv', {value: rand()}, {}, [0])
if(++cnt === 100) clearInterval(interval);
}, 800);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
 <!-- Load plotly.js into the DOM -->
 <script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>

<body>
 <div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body></code>```

Title: Plotly Gauge Dynamic

Body:
Try using Plotly.update():

function rand() {
return Math.floor(Math.random() * (250 - 0) ) + 0;
}

var data = [
        {
            domain: { x: [0, 1], y: [0, 1] },
            value: 0,
            title: { text: "Speed" },
            type: "indicator",
            mode: "gauge+number"
        }
    ];

var layout = { width: 600, height: 500, margin: { t: 0, b: 0 } };
Plotly.newPlot('myDiv', data, layout);

var cnt = 0;
var interval = setInterval(function() {
Plotly.update('myDiv', {value: rand()}, {}, [0])
if(++cnt === 100) clearInterval(interval);
}, 800);

<head>
 <!-- Load plotly.js into the DOM -->
 <script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>

<body>
 <div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>