问:
Nest a UICollectionView inside a UIVIew programmatically
I am attempting to get a UICollectionView to be inside a UIView as the framework I'm using requires a UIView to be returned. I have looked at this question: How do I add a UICollectionView to a UIView as a subview? and Adding UICollectionView inside UIView without Storyboards but not sure how to get it to work.

I have a attempted it like this:

```<code>class TopView : UIView, UICollectionViewDataSource, UICollectionViewDelegate {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .red

        addSubview(collectionView)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.delegate = self
        cv.dataSource = self
        cv.register(HeaderCell.self, forCellWithReuseIdentifier: "HeaderCell")
        cv.backgroundColor = .yellow

        return cv
    }()

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HeaderCell", for: indexPath) as! HeaderCell

        return cell

    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: self.collectionView.frame.width, height: 200)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfSections section: Int) -> Int {
        return 1
    }

}
</code>```

But I'm getting a blank screen.

Update:

This is how I add the TopView to a UIViewController:

```<code>class MainViewController: UIViewController {

    var mainView = TopView()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(mainView)
    }
}
</code>```

I get just a black screen.

答:
TopView.swift

```<code>class TopView : UIView, UICollectionViewDataSource, UICollectionViewDelegate {

    lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        //If you set it false, you have to add constraints.
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.delegate = self
        cv.dataSource = self
        cv.register(HeaderCell.self, forCellWithReuseIdentifier: "HeaderCell")
        cv.backgroundColor = .yellow
        return cv
    }()

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

        self.backgroundColor = .red

        addSubview(collectionView)

        //Add constraint
        collectionView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        collectionView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        collectionView.topAnchor.constraint(equalTo: topAnchor).isActive = true
        collectionView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfSections section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 30
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HeaderCell", for: indexPath) as! HeaderCell
        cell.backgroundColor = .cyan
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: self.collectionView.frame.size.width, height: 200)
    }
}
</code>```

ViewController.swift

```<code>lazy var topView: TopView = {
    let tv = TopView()
    tv.translatesAutoresizingMaskIntoConstraints = false
    return tv
}()

func addTopView() {
    view.addSubview(topView)

    topView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    topView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    topView.topAnchor.constraint(equalTo: view.topAnchor, constant: 300).isActive = true
    topView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
    topView.heightAnchor.constraint(equalToConstant: 200).isActive = true
}
</code>```

Call addTopView() from viewDidLoad()

Body:
I am attempting to get a UICollectionView to be inside a UIView as the framework I'm using requires a UIView to be returned. I have looked at this question: How do I add a UICollectionView to a UIView as a subview? and Adding UICollectionView inside UIView without Storyboards but not sure how to get it to work.

I have a attempted it like this:

class TopView : UIView, UICollectionViewDataSource, UICollectionViewDelegate {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .red

        addSubview(collectionView)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.delegate = self
        cv.dataSource = self
        cv.register(HeaderCell.self, forCellWithReuseIdentifier: "HeaderCell")
        cv.backgroundColor = .yellow

        return cv
    }()

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HeaderCell", for: indexPath) as! HeaderCell

        return cell

    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: self.collectionView.frame.width, height: 200)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfSections section: Int) -> Int {
        return 1
    }

}

But I'm getting a blank screen.

Update:

This is how I add the TopView to a UIViewController:

class MainViewController: UIViewController {

    var mainView = TopView()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(mainView)
    }
}

I get just a black screen.

Body:
TopView.swift

class TopView : UIView, UICollectionViewDataSource, UICollectionViewDelegate {

    lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        //If you set it false, you have to add constraints.
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.delegate = self
        cv.dataSource = self
        cv.register(HeaderCell.self, forCellWithReuseIdentifier: "HeaderCell")
        cv.backgroundColor = .yellow
        return cv
    }()

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

        self.backgroundColor = .red

        addSubview(collectionView)

        //Add constraint
        collectionView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        collectionView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        collectionView.topAnchor.constraint(equalTo: topAnchor).isActive = true
        collectionView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfSections section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 30
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HeaderCell", for: indexPath) as! HeaderCell
        cell.backgroundColor = .cyan
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: self.collectionView.frame.size.width, height: 200)
    }
}

ViewController.swift

lazy var topView: TopView = {
    let tv = TopView()
    tv.translatesAutoresizingMaskIntoConstraints = false
    return tv
}()

func addTopView() {
    view.addSubview(topView)

    topView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    topView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    topView.topAnchor.constraint(equalTo: view.topAnchor, constant: 300).isActive = true
    topView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
    topView.heightAnchor.constraint(equalToConstant: 200).isActive = true
}

Call addTopView() from viewDidLoad()


来源: stackexchange

问:
C1 Orckestra - Can a Global Datatype have a 1 to many relationship?
Is it possible to create a global datatype that has a 1 to many relationship?

Example

```<code>Create a global datatype for Dogs (some object on the website)
ID is a unique 8 character random string
Each Dog has several properties. (color, size, and so on)
Each Dog has many pictures. (as many as you would like, 1toMany)
</code>```

I can see how you can assign a "C1 Media Folder" to a field, but what we are trying to achieve, is when you are editing the Dog's data (or adding a new one), you can add as many pictures as you want at this moment. It would be nice if the media folder was created at the moment the new Dog's data object is created, and it uses the unique ID from them Dog object to name the Media Folder. This gets us close to what we want, but it still means you have to jump over to the Media Library to upload the images you want tied to the Dog object.

If this is not possible with the current C1 console, does the C1 API allow us to code our own methods for adding images to the media library?

Thank you.

答:
Your question seems to me to be not 100% specific, many things going on here which all should have its own question.

To answer what i see as the primary question based on the title, the answer is that you can do it in two ways.

Your pictures-field of the Dog object would contain a comma-separated list of media-item ids. This is the "C1" way of doing a 1-many relation and is what all the build-in multi-selector widgets in the C1 console supports.

Create a separate relationship holder object, call it DogPictureRelation which has a reference to a Dog objects and a Media object. And maybe a LocalOrdering field if the order of the pictures matters. This is the more correct way in a database world -we call it a relationship table, but unfortunately the built-in widgets don't support this and you would have to create your own Pictures-selector widget do work with this kind of datastructure.

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to create a global datatype that has a 1 to many relationship?

Example

Create a global datatype for Dogs (some object on the website)
ID is a unique 8 character random string
Each Dog has several properties. (color, size, and so on)
Each Dog has many pictures. (as many as you would like, 1toMany)

I can see how you can assign a "C1 Media Folder" to a field, but what we are trying to achieve, is when you are editing the Dog's data (or adding a new one), you can add as many pictures as you want at this moment. It would be nice if the media folder was created at the moment the new Dog's data object is created, and it uses the unique ID from them Dog object to name the Media Folder. This gets us close to what we want, but it still means you have to jump over to the Media Library to upload the images you want tied to the Dog object.

If this is not possible with the current C1 console, does the C1 API allow us to code our own methods for adding images to the media library?

Thank you.


问:
pset8; cs50; javascript; when to use a named function and when to use an anonymous function in callback
In pset8, I have thought out 2 solutions for showing the information window when the user clicks on the marker.

```<code> google.maps.event.addListener(marker, 'click', function() {
            showInfo(marker, articlesContent);
};
</code>```

and

```<code>google.maps.event.addListener(marker, 'click', showInfo(marker, articlesContent));
</code>```

why does the former/latter work or not work? I mean isn't showInfo also a function? Then why do you need to come up with another anonymous function to call the other function?

Apologies if this a newbie kind of mistake but I am completely new to Javascript and have been struggling for days for this pset. Would appreciate if someone could help me out!

答:
In the first case, you are passing the function as a parameter. In the second case, you are calling the function.

Example of the first case: https://jsfiddle.net/anqpby6s/

```<code>document.getElementById("myBtn").addEventListener("click", function(){
    alert("Hello World!");
});
</code>```

Notice the alert is called only when you click the button.

Example of the second case: https://jsfiddle.net/bwsps4b8/

```<code>document.getElementById("myBtn").addEventListener("click", alert("Hello World!"));
</code>```

Notice the alert is called immediately when the code is run - that is not what you want.

You can research about Javascript Callbacks to go further into it, I found this in-depth article in a quick search:
http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

Body:
In pset8, I have thought out 2 solutions for showing the information window when the user clicks on the marker.

 google.maps.event.addListener(marker, 'click', function() {
            showInfo(marker, articlesContent);
};

and

google.maps.event.addListener(marker, 'click', showInfo(marker, articlesContent));

why does the former/latter work or not work? I mean isn't showInfo also a function? Then why do you need to come up with another anonymous function to call the other function?

Apologies if this a newbie kind of mistake but I am completely new to Javascript and have been struggling for days for this pset. Would appreciate if someone could help me out!

Body:
In the first case, you are passing the function as a parameter. In the second case, you are calling the function.

Example of the first case: https://jsfiddle.net/anqpby6s/

document.getElementById("myBtn").addEventListener("click", function(){
    alert("Hello World!");
});

Notice the alert is called only when you click the button.

Example of the second case: https://jsfiddle.net/bwsps4b8/

document.getElementById("myBtn").addEventListener("click", alert("Hello World!"));

Notice the alert is called immediately when the code is run - that is not what you want.

You can research about Javascript Callbacks to go further into it, I found this in-depth article in a quick search:
http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/


问:
Hosting Angularjs 1.x application in tomcat server
How to host angular1 application tomcat server . I have developed one website in angularjs 1.x and want to host that on VPS server purchased from godaddy . </p>

答:
If your angularjs build is working properly you should have something like a "dist" folder with your complete app inside.
Enter that directory and create your .war file with:

$ jar -cvf theNameOfYourApp.war *

This will create a .war file that you can deploy on your tomcat server.


问:
Animating a single View based on multiple ScrollView(s)
I'm working on an application where I'm trying to Animate a View based on scroll Position of multiple ScrollViews.

This is how the screen looks.

The above screen has 2 parts

A View component on Top

A TabNavigator component at the Bottom

each tab in TabNavigator has a ScrollView in it (in this case there are 2 but can be more), What I want to achieve is to collapse the View as the user scrolls down and expand it when the user scrolls up.
On a single Tab I was doing well, it was working exactly how I wanted it to do, but the problem came when I added the 2nd Tab.

The Problem

When I scroll a bit on tab1 and move to tab2 and try to scroll, it gets jerky. see the GIF to understand what I'm trying to say

Update

Check this snack on expo.io to see the problem live

snack.expo.io/SytBkdBAW

What I tried

App.js

```<code>export default class App extends Component {

  constructor (props) {
    super(props)

    this.state = {
      /* omitted - not related */
      scrollY: new Animated.Value(0)
    }
  }

  render () {

    let translateY = this.state.scrollY.interpolate({
      inputRange: [0, 600],
      outputRange: [0, -290],
      extrapolate: 'clamp'
    });

    let TabsTranslateY = this.state.scrollY.interpolate({
      inputRange: [0, 600],
      outputRange: [0, -290],
      extrapolate: 'clamp'
    });

    return (
      <View style={styles.container}>
        <Animated.View style={{transform: [{translateY: translateY}], overflow: 'hidden'}}>
          <Text style={styles.welcome}>
            Welcome to React Native!!
          </Text>

          <Text style={styles.time}>
            {this.state.hour} : {this.state.minute}
          </Text>

          <TouchableOpacity onPress={() => { /* omitted */ }} style={styles.button}><Text style={styles.buttonText}>Set Time</Text></TouchableOpacity>
        </Animated.View>
        <Animated.View style={{
          flex: 0,
          transform: [{translateY: TabsTranslateY}],
          height: Dimensions.get('window').height
        }}>
          <Tabs removeClippedSubviews={false} screenProps={{animatedScrollY: this.state.scrollY}}/>
        </Animated.View>
      </View>
    )
  }
}

const styles = StyleSheet.create({/* omitted styles*/})
</code>```

Home.js (Tab1)

```<code>/* omitted imports */
export default class Home extends Component {
  /* omitted navigation options */
  constructor (props) {
    super(props)

    this.state = {
      scrollY: this.props.screenProps.animatedScrollY
    }

  }

  render () {
  return (
      <View>
        <Animated.ScrollView onScroll={Animated.event(
          [{nativeEvent: {contentOffset: {y: this.state.scrollY}}}],
          {useNativeDriver: true}
        )} scrollEventThrottle={16}>

          {Array(90).fill().map((v, i) => {
            return <Text key={i}
                         style={{flex: 1, backgroundColor: '#333', padding: 20, marginVertical: 10, color: 'white'}}>Item
              #{i + 1}</Text>
          })}
        </Animated.ScrollView>
      </View>
    )
  }
}
</code>```

Photos.js (Tab2)

```<code>/* omitted imports */
export default class Photos extends Component {
  /* omitted navigation options */
  constructor (props) {
    super(props)

    this.state = {
      PhotosScrollY: this.props.screenProps.animatedScrollY
    }
  }

  render () {
    return (
      <Animated.ScrollView onScroll={Animated.event(
        [{nativeEvent: {contentOffset: {y: this.state.PhotosScrollY}}}],
        {useNativeDriver: true}
      )} scrollEventThrottle={16}>

        <View style={{flex: 1,}}>
          {Array(90).fill().map((v, i) => {
            return <View key={i} style={/* omitted */}>
              <Text style={/* omitted */}>
                Photo #{i + 1}
              </Text>
            </View>
          })}
        </View>

      </Animated.ScrollView>
    )
  }
}
</code>```

I'm not sure how to overcome this problem, Any suggestions and solutions are appreciated.

Thanks.

答:
I faced this issue. I tried solving it this way. (Optimising it still..)

```<code><ParentComponent>
    <CollapsibleHeader/>
    <TabNavigator/>
</ParentComponent>
</code>```

The scrollState lies in Parent Component, and tabs inside TabNavigator has scrollView.
I update the state in the parent component using callback after binding the Animation event.

So whenever you move between two tabs, the state lies in the parent component and it is updated from a different place.

May be this could help you.

NOTE: Still optimising it.

---------Edit--------

Parent Component:

state: scrollY: new Animated.Value(0)

```<code>componentDidMount(){
    binding event.
}
componentWillUnmount(){
    Unbind event.
}
onScrollEventCaptured(){
  (update parent state and send it to <CollapsibleHeader/>)*
}
</code>```

Tab 1:
This has local state. (Optimising this part)
,scrollY: new Animated.Value(0)

Has a ListView

onScroll function on ListView:

```<code>onScroll={Animated.event([{
                        nativeEvent: {
                            contentOffset: {
                                y: this.state.scrollY
                            }
                        }
                    }], {
                        listener: (event) => {
                            AppEvents.fire("topBar", this.state.scrollY);
                        },
                    })}
</code>```

AppEvents.fire() is the event which is captured in Parent.
(The captured event then  sets state, then passed as a prop to the  which actually animates.)*

For Tab 2:
The same as tab 1.

*Both are same.

Still doing the optimisation work to this. The animation for me is little jerky in iOS development but it looks great in production iOS app. Android no words everywhere its jerky.

Body:
I'm working on an application where I'm trying to Animate a View based on scroll Position of multiple ScrollViews.

This is how the screen looks.

The above screen has 2 parts

A View component on Top

A TabNavigator component at the Bottom

each tab in TabNavigator has a ScrollView in it (in this case there are 2 but can be more), What I want to achieve is to collapse the View as the user scrolls down and expand it when the user scrolls up.
On a single Tab I was doing well, it was working exactly how I wanted it to do, but the problem came when I added the 2nd Tab.

The Problem

When I scroll a bit on tab1 and move to tab2 and try to scroll, it gets jerky. see the GIF to understand what I'm trying to say

Update

Check this snack on expo.io to see the problem live

snack.expo.io/SytBkdBAW

What I tried

App.js

export default class App extends Component {

  constructor (props) {
    super(props)

    this.state = {
      /* omitted - not related */
      scrollY: new Animated.Value(0)
    }
  }

  render () {

    let translateY = this.state.scrollY.interpolate({
      inputRange: [0, 600],
      outputRange: [0, -290],
      extrapolate: 'clamp'
    });

    let TabsTranslateY = this.state.scrollY.interpolate({
      inputRange: [0, 600],
      outputRange: [0, -290],
      extrapolate: 'clamp'
    });

    return (
      <View style={styles.container}>
        <Animated.View style={{transform: [{translateY: translateY}], overflow: 'hidden'}}>
          <Text style={styles.welcome}>
            Welcome to React Native!!
          </Text>

          <Text style={styles.time}>
            {this.state.hour} : {this.state.minute}
          </Text>

          <TouchableOpacity onPress={() => { /* omitted */ }} style={styles.button}><Text style={styles.buttonText}>Set Time</Text></TouchableOpacity>
        </Animated.View>
        <Animated.View style={{
          flex: 0,
          transform: [{translateY: TabsTranslateY}],
          height: Dimensions.get('window').height
        }}>
          <Tabs removeClippedSubviews={false} screenProps={{animatedScrollY: this.state.scrollY}}/>
        </Animated.View>
      </View>
    )
  }
}

const styles = StyleSheet.create({/* omitted styles*/})

Home.js (Tab1)

/* omitted imports */
export default class Home extends Component {
  /* omitted navigation options */
  constructor (props) {
    super(props)

    this.state = {
      scrollY: this.props.screenProps.animatedScrollY
    }

  }

  render () {
  return (
      <View>
        <Animated.ScrollView onScroll={Animated.event(
          [{nativeEvent: {contentOffset: {y: this.state.scrollY}}}],
          {useNativeDriver: true}
        )} scrollEventThrottle={16}>

          {Array(90).fill().map((v, i) => {
            return <Text key={i}
                         style={{flex: 1, backgroundColor: '#333', padding: 20, marginVertical: 10, color: 'white'}}>Item
              #{i + 1}</Text>
          })}
        </Animated.ScrollView>
      </View>
    )
  }
}

Photos.js (Tab2)

/* omitted imports */
export default class Photos extends Component {
  /* omitted navigation options */
  constructor (props) {
    super(props)

    this.state = {
      PhotosScrollY: this.props.screenProps.animatedScrollY
    }
  }

  render () {
    return (
      <Animated.ScrollView onScroll={Animated.event(
        [{nativeEvent: {contentOffset: {y: this.state.PhotosScrollY}}}],
        {useNativeDriver: true}
      )} scrollEventThrottle={16}>

        <View style={{flex: 1,}}>
          {Array(90).fill().map((v, i) => {
            return <View key={i} style={/* omitted */}>
              <Text style={/* omitted */}>
                Photo #{i + 1}
              </Text>
            </View>
          })}
        </View>

      </Animated.ScrollView>
    )
  }
}

I'm not sure how to overcome this problem, Any suggestions and solutions are appreciated.

Thanks.

Body:
I faced this issue. I tried solving it this way. (Optimising it still..)

<ParentComponent>
    <CollapsibleHeader/>
    <TabNavigator/>
</ParentComponent>

The scrollState lies in Parent Component, and tabs inside TabNavigator has scrollView.
I update the state in the parent component using callback after binding the Animation event.

So whenever you move between two tabs, the state lies in the parent component and it is updated from a different place.

May be this could help you.

NOTE: Still optimising it.

---------Edit--------

Parent Component:

state: scrollY: new Animated.Value(0)

componentDidMount(){
    binding event.
}
componentWillUnmount(){
    Unbind event.
}
onScrollEventCaptured(){
  (update parent state and send it to <CollapsibleHeader/>)*
}

Tab 1:
This has local state. (Optimising this part)
,scrollY: new Animated.Value(0)

Has a ListView

onScroll function on ListView:

onScroll={Animated.event([{
                        nativeEvent: {
                            contentOffset: {
                                y: this.state.scrollY
                            }
                        }
                    }], {
                        listener: (event) => {
                            AppEvents.fire("topBar", this.state.scrollY);
                        },
                    })}

AppEvents.fire() is the event which is captured in Parent.
(The captured event then  sets state, then passed as a prop to the  which actually animates.)*

For Tab 2:
The same as tab 1.

*Both are same.

Still doing the optimisation work to this. The animation for me is little jerky in iOS development but it looks great in production iOS app. Android no words everywhere its jerky.


问:
How to get key values in MultiMap Blackberry
How to get key values in MultiMap Blackberry while parsing XML</p>

答:
Did you read the apidocs for MultiMap? There's a keys() method that returns an enumeration.

http://www.blackberry.com/developers/docs/4.5.0api/net/rim/device/api/util/MultiMap.html

ContentLicense: CC BY-SA 2.5


问:
'if' v.s. `while` to a `functools.partial.func`
In Django documentation django.conf.urls | Django documentation | Django

There's such codes:

```<code>class RegexURLPattern(LocaleRegexProvider):
    ...
    def lookup_str(self)
        callback = self.callback
        # Python 3.5 collapses nested partials, so can change "while" to "if"
        # when it's the minimum supported version.
        while isinstance(callback, functools.partial):
            callback = callback.func
        ...
</code>```

The code is to callback the argument of funtion 'view' and execute it.

Why while is better than if excluding 'Python 3.5'?
There is only one callback argument passed in from django.conf.urls.url,which seen in:

```<code>def url(regex, view, kwargs=None, name=None):
    elif callable(view):
        return RegexURLPattern(regex, view, kwargs, name)
</code>```

It seems if is more readable than while.

答:
An impressive tutorial of functools

Cleaner Code Through Partial Function Application - Blogomatono

The callback function object in Django URLconf is not called - Stack Overflow

Body:
In Django documentation django.conf.urls | Django documentation | Django

There's such codes:

class RegexURLPattern(LocaleRegexProvider):
    ...
    def lookup_str(self)
        callback = self.callback
        # Python 3.5 collapses nested partials, so can change "while" to "if"
        # when it's the minimum supported version.
        while isinstance(callback, functools.partial):
            callback = callback.func
        ...

The code is to callback the argument of funtion 'view' and execute it.

Why while is better than if excluding 'Python 3.5'?
There is only one callback argument passed in from django.conf.urls.url,which seen in:

def url(regex, view, kwargs=None, name=None):
    elif callable(view):
        return RegexURLPattern(regex, view, kwargs, name)

It seems if is more readable than while.


问:
JHipster: how add sidebar menù
Can anyone please help with on how to add a sidebar to Hipster home page? I need to add a left side menu to my Jhipster app and no idea on how to do. Thanks.</p>

答:
Your question is too broad and leads to opinionated answers.
Anyway, you could try PrimeNG and this JHipster module and you'll get more than just a side menu.</p>

Title: JHipster: how add sidebar menù


问:
Page Links in Magento 2
I have created a About us page from backend and trying to link that page to the About-us at the footer. I am using:

```<code><a href="<?php echo $this->getUrl(''); ?>about-us"></a>
</code>```

After clicking on About Us It's working. URL: http://localhost/magento2/about-us but there is a blank page, no header and footer.

答:
Use this code to call your page in cms content to call URL directly</p>

```<code>{{store direct_url=about-us}}
</code>```

Title: Page Links in Magento 2

Body:
I have created a About us page from backend and trying to link that page to the About-us at the footer. I am using:

<a href="<?php echo $this->getUrl(''); ?>about-us">

After clicking on About Us It's working. URL: http://localhost/magento2/about-us but there is a blank page, no header and footer.

Body:
Use this code to call your page in cms content to call URL directly

{{store direct_url=about-us}}


问:
how to update the number component in a list of strings
I have a list:

```<code>['a1', 'a2', 'a3']
</code>```

I want to update it so that each number component is incremented by 1:

```<code>['a2', 'a3', 'a4']
</code>```

What would be the most efficient way to do it?

答:
This solution will work with example you provided:</p>

```<code>import re
lst = ['a1', 'a2', 'a3']

def increment(word):
    return re.findall('[a-z]+', word)[0] + str(int(re.findall('\d+', word)[0])+1)

print([increment(i) for i in lst])
#['a2', 'a3', 'a4']
</code>```

Body:
I have a list:

['a1', 'a2', 'a3']

I want to update it so that each number component is incremented by 1:

['a2', 'a3', 'a4']

What would be the most efficient way to do it?

Body:
This solution will work with example you provided:

import re
lst = ['a1', 'a2', 'a3']

def increment(word):
    return re.findall('[a-z]+', word)[0] + str(int(re.findall('\d+', word)[0])+1)

print([increment(i) for i in lst])
#['a2', 'a3', 'a4']


问:
pickle.load - EOFError: Ran out of input
I have an .obj file in which, previously, I transformed an image to base64 and saved with pickle.

The problem is when I try to load the .obj file with pickle, convert the code into image from base64, and load it with pygame.

The function that loads the image:

```<code>def mainDisplay_load(self):
    main_folder = path.dirname(__file__)
    img_main_folder = path.join(main_folder, "sd_graphics")

    # loadImg
    self.mainTerminal = pg.image.load(path.join(img_main_folder, self.main_uncode("tr.obj"))).convert_alpha()
</code>```

The function that decodes the file:

```<code>def main_uncode(self, object):
    openFile = open(object, "rb")
    str = pickle.load(openFile)
    openFile.close()
    fileData = base64.b64decode(str)
    return fileData
</code>```

The error I get when the code is run:

```<code>str = pickle.load(openFile)
</code>```

EOFError: Ran out of input

How can I fix it?

Python version: 3.6.2

Pygame version: 1.9.3

Update 1

This is the code I used to create the .obj file:

```<code>import base64, pickle

with open("terminal.png", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    print(str)

file_pi = open("tr.obj","wb")
pickle.dump(str,file_pi)
file_pi.close()

file_pi2 = open("tr.obj","rb")
str2 = pickle.load(file_pi2)
file_pi2.close()

imgdata = base64.b64decode(str2)
filename = 'some_image.jpg'  # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
    f.write(imgdata)
</code>```

Once the file is created, it is loaded and a second image is created. This is to check if the image is the same or there are errors in the conversion.

As you can see, I used part of the code to load the image, but instead of saving it, it is loaded into pygame. And that's where the mistake occurs.

Update 2

I finally managed to solve it.

In the main code:

```<code>def mainDisplay_load(self):
    self.all_graphics = pg.sprite.Group()
    self.graphics_menu = pg.sprite.Group()

    # loadImg
    self.img_mainTerminal = mainGraphics(self, 0, 0, "sd_graphics/tr.obj")
</code>```

In the library containing graphics classes:

```<code>import pygame as pg
import base64 as bs
import pickle as pk
from io import BytesIO as by
from lib.setting import *

class mainGraphics(pg.sprite.Sprite):
    def __init__(self, game, x, y, object):
        self.groups = game.all_graphics, game.graphics_menu
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.object = object
        self.outputGraphics = by()

        self.x = x
        self.y = y

        self.eventType()

        self.rect = self.image.get_rect()
        self.rect.x = self.x * tilesizeDefault
        self.rect.y = self.y * tilesizeDefault

    def eventType(self):
        openFile = open(self.object, "rb")
        str = pk.load(openFile)
        openFile.close()
        self.outputGraphics.write(bs.b64decode(str))
        self.outputGraphics.seek(0)
        self.image = pg.image.load(self.outputGraphics).convert_alpha()
</code>```

For the question of why I should do such a thing, it is simple:

any attacker with sufficient motivation can still get to it easily

Python is free and open.

On the one hand, we have a person who intentionally goes and modify and recover the hidden data. But if Python is an open language, as with even more complicated and protected languages, the most motivated are able to crack the game or program and retrieve the same data.

On the other hand, we have a person who knows only the basics, or not even that. A person who cannot access the files without knowing more about the language, or decoding the files.

So you can understand that decoding files, from my point of view, does not need to be protected from a motivated person. Because even with a more complex and protected language, that motivated person will be able to get what he wants. The protection is used against people who have no knowledge of the language.

答:
So, if the error you get is indeed "pickle: run out of input", that propably means you messed your directories in the code above, and are trying to read an empty file with the same name as your obj file is.

Actually, as it is, this line in your code:

```<code>self.mainTerminal=pg.image.load(path.join(img_main_folder,self.main_uncode
("tr.obj"))).convert_alpha()
</code>```

Is completly messed up. Just read it and you can see the problem: you are passing to the main_uncode method just the file name, without directory information.  And then, if it would by chance have worked, as I have poitned in the comments a while ago, you would try to use the unserialized image data as a filename from where to read your image. (You or someone else had probably thought that main_uncode should write a temporary image file and writ the image data to that, so that  Pygame could read it, but as it is, it is just returning the raw image data in a string).

Threfore, by fixing the above call and passing an actual path to main_uncode, and further modifying it to write the temporary data to a file and return its path would fix the snippets of code above.

Second thing is I can't figure out why do you need this ".obj" file at all. If it is just for "security through obscurity" hopping people get your bundled file can't open the images, that is a thing far from a recommended practice. To sum up just one thing: it will delay legitimate uses of your file (like, you yourself does not seem to be able to use it ), while any attacker with sufficient motivation can still get to it easily. By opening an image, base-64 encoding and pickling it, and doing the reverse process you are doing essentially a no-operation. Even more, a pickle file can serialize and write to disk complex Python objects - but a base64 serialization of an image could be written directly to a file, with no need for pickle.

Third thing: just use  with to open all the files, not just the ones you read with the imaging library, Take your time to learn a little bit more about Python.

Body:
I have an .obj file in which, previously, I transformed an image to base64 and saved with pickle.

The problem is when I try to load the .obj file with pickle, convert the code into image from base64, and load it with pygame.

The function that loads the image:

def mainDisplay_load(self):
    main_folder = path.dirname(__file__)
    img_main_folder = path.join(main_folder, "sd_graphics")

    # loadImg
    self.mainTerminal = pg.image.load(path.join(img_main_folder, self.main_uncode("tr.obj"))).convert_alpha()

The function that decodes the file:

def main_uncode(self, object):
    openFile = open(object, "rb")
    str = pickle.load(openFile)
    openFile.close()
    fileData = base64.b64decode(str)
    return fileData

The error I get when the code is run:

str = pickle.load(openFile)

EOFError: Ran out of input

How can I fix it?

Python version: 3.6.2

Pygame version: 1.9.3

Update 1

This is the code I used to create the .obj file:

import base64, pickle

with open("terminal.png", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    print(str)

file_pi = open("tr.obj","wb")
pickle.dump(str,file_pi)
file_pi.close()

file_pi2 = open("tr.obj","rb")
str2 = pickle.load(file_pi2)
file_pi2.close()

imgdata = base64.b64decode(str2)
filename = 'some_image.jpg'  # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
    f.write(imgdata)

Once the file is created, it is loaded and a second image is created. This is to check if the image is the same or there are errors in the conversion.

As you can see, I used part of the code to load the image, but instead of saving it, it is loaded into pygame. And that's where the mistake occurs.

Update 2

I finally managed to solve it.

In the main code:

def mainDisplay_load(self):
    self.all_graphics = pg.sprite.Group()
    self.graphics_menu = pg.sprite.Group()

    # loadImg
    self.img_mainTerminal = mainGraphics(self, 0, 0, "sd_graphics/tr.obj")

In the library containing graphics classes:

import pygame as pg
import base64 as bs
import pickle as pk
from io import BytesIO as by
from lib.setting import *

class mainGraphics(pg.sprite.Sprite):
    def __init__(self, game, x, y, object):
        self.groups = game.all_graphics, game.graphics_menu
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.object = object
        self.outputGraphics = by()

        self.x = x
        self.y = y

        self.eventType()

        self.rect = self.image.get_rect()
        self.rect.x = self.x * tilesizeDefault
        self.rect.y = self.y * tilesizeDefault

    def eventType(self):
        openFile = open(self.object, "rb")
        str = pk.load(openFile)
        openFile.close()
        self.outputGraphics.write(bs.b64decode(str))
        self.outputGraphics.seek(0)
        self.image = pg.image.load(self.outputGraphics).convert_alpha()

For the question of why I should do such a thing, it is simple:

any attacker with sufficient motivation can still get to it easily

Python is free and open.

On the one hand, we have a person who intentionally goes and modify and recover the hidden data. But if Python is an open language, as with even more complicated and protected languages, the most motivated are able to crack the game or program and retrieve the same data.

On the other hand, we have a person who knows only the basics, or not even that. A person who cannot access the files without knowing more about the language, or decoding the files.

So you can understand that decoding files, from my point of view, does not need to be protected from a motivated person. Because even with a more complex and protected language, that motivated person will be able to get what he wants. The protection is used against people who have no knowledge of the language.

Body:
So, if the error you get is indeed "pickle: run out of input", that propably means you messed your directories in the code above, and are trying to read an empty file with the same name as your obj file is.

Actually, as it is, this line in your code:

self.mainTerminal=pg.image.load(path.join(img_main_folder,self.main_uncode
("tr.obj"))).convert_alpha()

Is completly messed up. Just read it and you can see the problem: you are passing to the main_uncode method just the file name, without directory information.  And then, if it would by chance have worked, as I have poitned in the comments a while ago, you would try to use the unserialized image data as a filename from where to read your image. (You or someone else had probably thought that main_uncode should write a temporary image file and writ the image data to that, so that  Pygame could read it, but as it is, it is just returning the raw image data in a string).

Threfore, by fixing the above call and passing an actual path to main_uncode, and further modifying it to write the temporary data to a file and return its path would fix the snippets of code above.

Second thing is I can't figure out why do you need this ".obj" file at all. If it is just for "security through obscurity" hopping people get your bundled file can't open the images, that is a thing far from a recommended practice. To sum up just one thing: it will delay legitimate uses of your file (like, you yourself does not seem to be able to use it ), while any attacker with sufficient motivation can still get to it easily. By opening an image, base-64 encoding and pickling it, and doing the reverse process you are doing essentially a no-operation. Even more, a pickle file can serialize and write to disk complex Python objects - but a base64 serialization of an image could be written directly to a file, with no need for pickle.

Third thing: just use  with to open all the files, not just the ones you read with the imaging library, Take your time to learn a little bit more about Python.


问:
Flickering issue when drawing div in Angular
In this plunk I have a div that needs to be drawn dragging the mouse. I'm using mouse up/move/down events. The problem that I have is that the div "flickers" when I drag down. How to fix this?

HTML

```<code><style>
  .frame {
      width: 300px;
      height: 300px;
      background-color: orange;
      position: relative;
  }
  .sel{
     border:2px solid black;
     background-color: #ffffff;
     position:absolute;
  }
</style>
<div class="frame" ng-mousedown="mouseDown($event)"
                   ng-mousemove="mouseMove($event)"
                   ng-mouseup="mouseUp()">
  <div class="sel" ng-show="show"
       ng-style="{top:selTop+'px', left:selLeft+'px', width:selWidth+'px', height:selHeight+'px'}"></div>
</div>
</code>```

Javascript:

```<code>var app = angular.module('app', []);
app.controller('ctl', function ($scope) {

     $scope.startPoint = {};
     $scope.show = false;

     $scope.mouseDown = function(event) {
            $scope.startPoint = { x: event.offsetX, y: event.offsetY };
            $scope.show = true;
        };

       $scope.mouseMove = function(event) {
            if (!$scope.startPoint.x)
                return;
            $scope.selTop = $scope.startPoint.y;
            $scope.selLeft = $scope.startPoint.x;
            $scope.selHeight = event.offsetY - $scope.startPoint.y;
            $scope.selWidth = event.offsetX - $scope.startPoint.x;
       };

       $scope.mouseUp = function() {
            $scope.startPoint = {};
            $scope.show = false;
       };

});
</code>```

答:
just add these css properties

```<code>border: none;
color: transparent;
text-shadow: 0 0 0 gray;
text-align: center;
&:focus {
outline: none;
}
</code>```

see the plunker http://embed.plnkr.co/9WntGyBLQxYSxkFjDAy2/

Body:
In this plunk I have a div that needs to be drawn dragging the mouse. I'm using mouse up/move/down events. The problem that I have is that the div "flickers" when I drag down. How to fix this?

HTML

Javascript:

var app = angular.module('app', []);
app.controller('ctl', function ($scope) {

     $scope.startPoint = {};
     $scope.show = false;

     $scope.mouseDown = function(event) {
            $scope.startPoint = { x: event.offsetX, y: event.offsetY };
            $scope.show = true;
        };

       $scope.mouseMove = function(event) {
            if (!$scope.startPoint.x)
                return;
            $scope.selTop = $scope.startPoint.y;
            $scope.selLeft = $scope.startPoint.x;
            $scope.selHeight = event.offsetY - $scope.startPoint.y;
            $scope.selWidth = event.offsetX - $scope.startPoint.x;
       };

       $scope.mouseUp = function() {
            $scope.startPoint = {};
            $scope.show = false;
       };

});

Body:
just add these css properties

border: none;
color: transparent;
text-shadow: 0 0 0 gray;
text-align: center;
&:focus {
outline: none;
}

see the plunker http://embed.plnkr.co/9WntGyBLQxYSxkFjDAy2/


问:
Change character to Superscript using applescript and quarkxpress
I have a list of of houses (see blow) with different sizes stated in (m2), I would like to replace all those instances with m2 and "2" set in superscript.

The list of houses:

R45m     HOUSE. Landmark property with panoramic views, 2000m2 on over 8
200m2. web ref: 3036011

R27.5m HOUSE. Ambassadorial 6 bedroomed home on over 5000m2 web ref:
3137592.

My script:

```<code>tell application "QuarkXPress"
tell document 1
    tell story 1 of current box
        set xx to 2
        set character style of xx to superscript
        set text of every paragraph where it is "m2" to "m" & xx
    end tell
end tell
end tell
</code>```

I get the following error:

Can’t set «class CHSS» of 2 to superscript.

Please help, not sure if I'm going about it the wrong way.
Much appreciated!

答:
After pulling may hair out I managed to come up with a solution I hope this would help someone else.

Alterations to the script below:

```<code>tell application "QuarkXPress"
tell document 1
tell story 1 of current box

set xx to («data utxt006D» as Unicode text) & «data utxt00B2» as  Unicode text
set text of every paragraph where it is "m2" to xx

end tell
end tell
end tell
</code>```

Body:
I have a list of of houses (see blow) with different sizes stated in (m2), I would like to replace all those instances with m2 and "2" set in superscript.

The list of houses:

R45m     HOUSE. Landmark property with panoramic views, 2000m2 on over 8
200m2. web ref: 3036011

R27.5m HOUSE. Ambassadorial 6 bedroomed home on over 5000m2 web ref:
3137592.

My script:

tell application "QuarkXPress"
tell document 1
    tell story 1 of current box
        set xx to 2
        set character style of xx to superscript
        set text of every paragraph where it is "m2" to "m" & xx
    end tell
end tell
end tell

I get the following error:

Can’t set «class CHSS» of 2 to superscript.

Please help, not sure if I'm going about it the wrong way.
Much appreciated!

Body:
After pulling may hair out I managed to come up with a solution I hope this would help someone else.

Alterations to the script below:

tell application "QuarkXPress"
tell document 1
tell story 1 of current box

set xx to («data utxt006D» as Unicode text) & «data utxt00B2» as  Unicode text
set text of every paragraph where it is "m2" to xx

end tell
end tell
end tell


问:
-bash: find_git_branch: command not found
This should be very simple. I recently noticed that when I type anything into Terminal on Mac it shows this:

```<code>-bash: find_git_branch: command not found
bogon:git monty$ ls
1.txt       index.html
-bash: find_git_branch: command not found
bogon:git monty$ touch 2.txt
-bash: find_git_branch: command not found
bogon:git monty$ ls
1.txt       2.txt       index.html
-bash: find_git_branch: command not found
</code>```

When before it didn't. Can someone explain why and how to resolve.

答:
The issue is that the git maintainers only support MaxOS10.9 (mavericks). If you have an earlier version, you can't use their distribution.

Recommended by somebody else at work - use (home)brew. Basically with brew installed you can merely use:

```<code>brew install git
</code>```

and it will give you an up to date version. Subsequently to get a new version use:

brew upgrade git

Now brew itself uses git, so it might be that this install is recursive - I had to install it recently for another purpose and it took me several hours - but once you have it there, things should be OK. All I can say is that when I installed brew originally, "git" still referred to the 1.8.x Apple version, and with this change I'm now getting git v2.1.0.

Body:
This should be very simple. I recently noticed that when I type anything into Terminal on Mac it shows this:

-bash: find_git_branch: command not found
bogon:git monty$ ls
1.txt       index.html
-bash: find_git_branch: command not found
bogon:git monty$ touch 2.txt
-bash: find_git_branch: command not found
bogon:git monty$ ls
1.txt       2.txt       index.html
-bash: find_git_branch: command not found

When before it didn't. Can someone explain why and how to resolve.

Body:
The issue is that the git maintainers only support MaxOS10.9 (mavericks). If you have an earlier version, you can't use their distribution.

Recommended by somebody else at work - use (home)brew. Basically with brew installed you can merely use:

brew install git

and it will give you an up to date version. Subsequently to get a new version use:

brew upgrade git

Now brew itself uses git, so it might be that this install is recursive - I had to install it recently for another purpose and it took me several hours - but once you have it there, things should be OK. All I can say is that when I installed brew originally, "git" still referred to the 1.8.x Apple version, and with this change I'm now getting git v2.1.0.


问:
Compare columns in two indentical tables with respect to primary key and return mismatch rows in MySQL
```<code>Table1
id | Ans1| Ans2
 1 |yes | no
 2 | no| yes
 3 | no| no

Table2
id | Ans1| Ans2
 1 |yes | no
 2 | yes| no
 3 | no| yes
</code>```

Is there a way that i can return only the rows that are mismatch. here in this example i want the last two rows to be returned except the 1st row.

答:
You can achieve this with a JOIN of the tables. Your query may look like this (and there are other types of join you can use to achieve this results

```<code>select t1.*, t2.*
from Table1 t1
inner join Table2 t2 ON t1.id = t2.id and (t1.Ans1 <> t2.Ans1 OR t1.Ans2 <> t2.Ans2)
</code>```

Hopes this helps

Body:
Table1
id | Ans1| Ans2
 1 |yes | no
 2 | no| yes
 3 | no| no

Table2
id | Ans1| Ans2
 1 |yes | no
 2 | yes| no
 3 | no| yes

Is there a way that i can return only the rows that are mismatch. here in this example i want the last two rows to be returned except the 1st row.

Body:
You can achieve this with a JOIN of the tables. Your query may look like this (and there are other types of join you can use to achieve this results

select t1.*, t2.*
from Table1 t1
inner join Table2 t2 ON t1.id = t2.id and (t1.Ans1 <> t2.Ans1 OR t1.Ans2 <> t2.Ans2)

Hopes this helps


问:
Error : While installing dplyr in R
```<code>Error: package or namespace load failed for ‘dplyr’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):  there is no package called ‘R6’
</code>```

答:
You need to force the installation of the dependencies.

```<code>install.packages("dplyr", dependencies=TRUE)
</code>```

If this still doesn't work, try installing the missing packages yourself, e.g.

```<code>install.packages("R6", dependencies=TRUE)
</code>```

Title: Error : While installing dplyr in R

Body:
You need to force the installation of the dependencies.

install.packages("dplyr", dependencies=TRUE)

If this still doesn't work, try installing the missing packages yourself, e.g.

install.packages("R6", dependencies=TRUE)


问:
Bind Model to child components
I have 3 components. The 'Parent', 'Child 1' & 'Child 2'. On the load of the Parent component, I create a Model inside the 'Parent' and want to pass that Model to the child components, which then binds to the model and updates the parent Model.

Example:

Model:

```<code>export interface ITemplateModel {
    id: string;
    name: string;
    lastModified: Date;
    status: string;
    templateHistory: string;
}
</code>```

'Parent':

```<code>templateModel = ITemplateModel();
</code>```

From this point in the Parent HTML I'm unsure if this is right but shows the idea.

'Parent HTML':

```<code><app-child1 [(ngModel)]='templateModel'></app-child1>
<app-child2 [(ngModel)]='templateModel'></app-child2>
</code>```

'Child1':

```<code>{{templateModel.name}}
</code>```

'Child2':

```<code><input [(ngModel)]="templateModel.status">
</code>```

答:
No. I don't think your approach is correct.

If you need to pass data from Parent to child then you need to use @Input().

Reference you can check for @Input()

And If you need to pass data from Child to Parent then you need to use @Output().

Reference you can check for @Output()

This is the basic Example how you can use @Input & @Output parameters on child element.

HTML :

```<code><app-child *ngFor="let item of items"  [name]="itemName"  (onSelect)="selectedItemName($event)"> </app-child>
</code>```

TS :

```<code>export class ChildComponent {
  @Input()  name: string;
  @Output() onSelect = new EventEmitter<any>();

  sendSelect(selected: any) {
    this.onSelect.emit(selected);
  }
}
</code>```

Title: Bind Model to child components

Body:
I have 3 components. The 'Parent', 'Child 1' & 'Child 2'. On the load of the Parent component, I create a Model inside the 'Parent' and want to pass that Model to the child components, which then binds to the model and updates the parent Model.

Example:

Model:

export interface ITemplateModel {
    id: string;
    name: string;
    lastModified: Date;
    status: string;
    templateHistory: string;
}

'Parent':

templateModel = ITemplateModel();

From this point in the Parent HTML I'm unsure if this is right but shows the idea.

'Parent HTML':

<app-child1 [(ngModel)]='templateModel'></app-child1>
<app-child2 [(ngModel)]='templateModel'></app-child2>

'Child1':

{{templateModel.name}}

'Child2':

<input [(ngModel)]="templateModel.status">

Body:
No. I don't think your approach is correct.

If you need to pass data from Parent to child then you need to use @Input().

Reference you can check for @Input()

And If you need to pass data from Child to Parent then you need to use @Output().

Reference you can check for @Output()

This is the basic Example how you can use @Input & @Output parameters on child element.

HTML :

<app-child *ngFor="let item of items"  [name]="itemName"  (onSelect)="selectedItemName($event)"> </app-child>

TS :

export class ChildComponent {
  @Input()  name: string;
  @Output() onSelect = new EventEmitter<any>();

  sendSelect(selected: any) {
    this.onSelect.emit(selected);
  }
}


问:
Reading property file in Spring MVC app
I'm trying to read a property file using below code, basically I'm having a Spring Boot app and I'm trying to read the below non spring bean class.The property file is in src/main/resource directory.

```<code>public class VisaProperties {

    static Properties properties;

    static {
        try {
            properties = new Properties();
            String propertiesFile = System.getProperty("ftproperties");
            if (propertiesFile == null) {
                properties.load(VisaProperties.class.getResourceAsStream("motoconfig.cybersource.properties"));
            } else {
                properties.load(new FileReader(propertiesFile));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getProperty(Property property) {
        return (String) properties.get(property.getValue());
    }
}
</code>```

and trying call the end point property using below code getting null. How can I call the property?

```<code>VisaProperties.getProperty(Property.END_POINT)
</code>```

答:
Done, using the code below:</p>

```<code>Properties properties = new Properties();
            InputStream inputStream = VisaProperties.class
                    .getClassLoader()
                    .getResourceAsStream("config.properties");
            properties.load(inputStream);
            inputStream.close();
</code>```

Title: Reading property file in Spring MVC app

Body:
I'm trying to read a property file using below code, basically I'm having a Spring Boot app and I'm trying to read the below non spring bean class.The property file is in src/main/resource directory.

public class VisaProperties {

    static Properties properties;

    static {
        try {
            properties = new Properties();
            String propertiesFile = System.getProperty("ftproperties");
            if (propertiesFile == null) {
                properties.load(VisaProperties.class.getResourceAsStream("motoconfig.cybersource.properties"));
            } else {
                properties.load(new FileReader(propertiesFile));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getProperty(Property property) {
        return (String) properties.get(property.getValue());
    }
}

and trying call the end point property using below code getting null. How can I call the property?

VisaProperties.getProperty(Property.END_POINT)

Body:
Done, using the code below:

Properties properties = new Properties();
            InputStream inputStream = VisaProperties.class
                    .getClassLoader()
                    .getResourceAsStream("config.properties");
            properties.load(inputStream);
            inputStream.close();


问:
Export CSV is skipping first line of results
We have an online app built which our client can filter results from a table, and also export the results to CSV.

The trouble is when I export it to CSV it always skips the first line of the results.

Here is the code for the printcsv.php

```<code>$noheader = 1;
$protected = 1;

if(isset($_POST['query']) && $_POST['query'] != ''){
    $_GET['query'] = $_POST['query'];
}

if (isset($_GET['query'])){

    if(strpos($_GET['query'], 'limit')) {
        $_GET['query'] = substr($_GET['query'], 0, strpos($_GET['query'], 'limit'));
    }

    include('system/system.php');

    $results = SQLselectRA(stripslashes($_GET['query']));

    $x = 0;

    header('Content-Type: application/excel');
    header('Content-Disposition: attachment; filename="printcsv.csv"');
    $file = fopen("php://output","w");
    $header = array();

    foreach($results as $keyvalue => $row) {
        if($x == 0) {
        foreach($row as $key => $data) {
            $header[]= str_replace('_', ' ', strtoupper($key));
        }
        $row = $header;
    }
    fputcsv($file, $row);
    $x++;
    }
</code>```

If someone could help me out that would be great.

Regards

答:
You should write the header data using another variable than $row, which contained that first line of data, but that you're overwriting when you set the headers

```<code>foreach($results as $keyvalue => $row) {
    if($x == 0) {
        foreach($row as $key => $data) {
            $header[]= str_replace('_', ' ', strtoupper($key));
        }
        fputcsv($file, $header);
    }
    fputcsv($file, $row);
    $x++;
}
</code>```

Body:
We have an online app built which our client can filter results from a table, and also export the results to CSV.

The trouble is when I export it to CSV it always skips the first line of the results.

Here is the code for the printcsv.php

$noheader = 1;
$protected = 1;

if(isset($_POST['query']) && $_POST['query'] != ''){
    $_GET['query'] = $_POST['query'];
}

if (isset($_GET['query'])){

    if(strpos($_GET['query'], 'limit')) {
        $_GET['query'] = substr($_GET['query'], 0, strpos($_GET['query'], 'limit'));
    }

    include('system/system.php');

    $results = SQLselectRA(stripslashes($_GET['query']));

    $x = 0;

    header('Content-Type: application/excel');
    header('Content-Disposition: attachment; filename="printcsv.csv"');
    $file = fopen("php://output","w");
    $header = array();

    foreach($results as $keyvalue => $row) {
        if($x == 0) {
        foreach($row as $key => $data) {
            $header[]= str_replace('_', ' ', strtoupper($key));
        }
        $row = $header;
    }
    fputcsv($file, $row);
    $x++;
    }

If someone could help me out that would be great.

Regards

Body:
You should write the header data using another variable than $row, which contained that first line of data, but that you're overwriting when you set the headers

foreach($results as $keyvalue => $row) {
    if($x == 0) {
        foreach($row as $key => $data) {
            $header[]= str_replace('_', ' ', strtoupper($key));
        }
        fputcsv($file, $header);
    }
    fputcsv($file, $row);
    $x++;
}


问:
how do we represent an edge list given that we have a graph with nodes and edges.am not talking about adjacency lists
what is an edge list?not an adjacency list..
and how do we represent an edge list in C programming provided that we are given a graph with nodes and edges?</p>

答:
Here is the base structure

```<code>struct Edge
{
    int id;
    int weight; // If you need one
    vector<Edge *> neighbours; // List of references on your neightbours
}

vector<Edge> graph;
</code>```

But as Michael noticed it does look like a homework :) Take a look at boot graphs library.

UPDATE C version

```<code>struct Edge
{
    int id;
    int weight; // If you need one
    Edge *next; // Next edge in the list
    Edge *neighbours; // List of neightbours
}

Edge *graph;
</code>```

Body:
Here is the base structure

struct Edge
{
    int id;
    int weight; // If you need one
    vector<Edge *> neighbours; // List of references on your neightbours
}

vector<Edge> graph;

But as Michael noticed it does look like a homework :) Take a look at boot graphs library.

UPDATE C version

struct Edge
{
    int id;
    int weight; // If you need one
    Edge *next; // Next edge in the list
    Edge *neighbours; // List of neightbours
}

Edge *graph;


问:
Gradle does not find tools.jar
I am using javadoc doclets with gradle, so I need to use the package tools.jar, which is in the lib folder from the jdk (1.6.0_26 in my case).

The point is that gradle does not take it automatically, so I was adding that tools package to my libs folder, and then adding it to dependencies.gradle .

Now I want to take it directly from my JDK home into my dependencies.gradle. Is there a way to do that? I have tried the next in my dependencies.gradle:

```<code>compile files("${System.properties['java.home']}/lib/tools.jar")
</code>```

But it does not find it while compiling.

答:
Linux

Open /etc/environment in any text editor like nano or gedit and add the following line:

```<code>JAVA_HOME="/usr/lib/jvm/open-jdk"
</code>```

Windows

Start the System Control Panel applet (Start - Settings - Control
Panel - System).

Select the Advanced tab.

Click the Environment
Variables button.

Under System Variables, click add button, then past the following lines:

in Variable Name : JAVA_HOME

in Variable Value :  C:\Program Files\Java\jdk1.x.x_xxx

where x.x_xxx jdk version you can get your jdk version from here C:\Program Files\Java

Under System Variables, select Path, then click Edit,then click new button then past the following line:

%JAVA_HOME%/bin;

Title: Gradle does not find tools.jar

Body:
I am using javadoc doclets with gradle, so I need to use the package tools.jar, which is in the lib folder from the jdk (1.6.0_26 in my case).

The point is that gradle does not take it automatically, so I was adding that tools package to my libs folder, and then adding it to dependencies.gradle .

Now I want to take it directly from my JDK home into my dependencies.gradle. Is there a way to do that? I have tried the next in my dependencies.gradle:

compile files("${System.properties['java.home']}/lib/tools.jar")

But it does not find it while compiling.

Body:
Linux

Open /etc/environment in any text editor like nano or gedit and add the following line:

JAVA_HOME="/usr/lib/jvm/open-jdk"

Windows

Start the System Control Panel applet (Start - Settings - Control
Panel - System).

Select the Advanced tab.

Click the Environment
Variables button.

Under System Variables, click add button, then past the following lines:

in Variable Name : JAVA_HOME

in Variable Value :  C:\Program Files\Java\jdk1.x.x_xxx

where x.x_xxx jdk version you can get your jdk version from here C:\Program Files\Java

Under System Variables, select Path, then click Edit,then click new button then past the following line:

%JAVA_HOME%/bin;


问:
Convert specific number of rows to columns in R and repeat the process for a large dataset
I'm having a dataset of 15 million rows with single column. It looks like,

```<code>x_raw
A1
A2
A3
A4
B1
B2
B3
B4
C1
C2

I want to convert it to

A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4
</code>```

I was trying with 'for' loop, that will transpose every 4 rows, and add them to a 'final' dataframe, but as the dataset is too large, it'll iterate almost 2.7 million times which is not working that efficiently. Is there any other method or anything that I can use to do it efficiently?

Body:
I'm having a dataset of 15 million rows with single column. It looks like,

x_raw
A1
A2
A3
A4
B1
B2
B3
B4
C1
C2

I want to convert it to

A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4

I was trying with 'for' loop, that will transpose every 4 rows, and add them to a 'final' dataframe, but as the dataset is too large, it'll iterate almost 2.7 million times which is not working that efficiently. Is there any other method or anything that I can use to do it efficiently?

Body:
See this,

x_raw <- c("A1","A2","A3","A4","B1","B2","B3","B4","C1","C2","C3","C4","D1","D2","D3","D4")
x <- as.table(matrix(x_raw,ncol=4,byrow = T))
rownames(x) <- NULL
colnames(x) <- NULL
print(x)

It returns:

     [,1] [,2] [,3] [,4]
[1,] A1   A2   A3   A4
[2,] B1   B2   B3   B4
[3,] C1   C2   C3   C4
[4,] D1   D2   D3   D4


问:
Laravel redirecting when accessing post route directly
I do a post request to a route calculate-cars and display an other view with some data I query based on the data I entered in the form I do the post request from, but I want to redirect to the homepage when someone access this route directly.

Unfortunately I keep getting this error:

Symfony \ Component \ HttpKernel \ Exception \
  MethodNotAllowedHttpException No message

my route:

Route::post('calculate-cars', 'CarsController@calculateCars');

I know I get this error because I access a post route directly but I try this in my controller method but I still get the same error:

```<code>if (!$request->isMethod('post')) {
    return redirect()->to('/');
}
</code>```

答:
Rename your route to something different and test it again.

For instance

Route::post('calculate-cars', 'CarsController@calculateCars');

could be like

Route::post('calculate-test-cars', 'CarsController@calculateCars');

I have had cases where changing the route might do the trick. Not sure if it's always like that.

Let me know

Body:
I do a post request to a route calculate-cars and display an other view with some data I query based on the data I entered in the form I do the post request from, but I want to redirect to the homepage when someone access this route directly.

Unfortunately I keep getting this error:

Symfony \ Component \ HttpKernel \ Exception \
  MethodNotAllowedHttpException No message

my route:

Route::post('calculate-cars', 'CarsController@calculateCars');

I know I get this error because I access a post route directly but I try this in my controller method but I still get the same error:

if (!$request->isMethod('post')) {
    return redirect()->to('/');
}


问:
How to get the first numbers in a SQL string
I need to get the first number(s) in a string:

1-2-3 --> 1

45-6  --> 45

777 8 --> 777

9ab10 --> 9

How can I do that with SQL?

答:
You can use function PATINDEX to search for the first non-numeric character

```<code>SELECT LEFT(s,ISNULL(NULLIF(PATINDEX('%[^0-9]%',s),0)-1,LEN(s)))
FROM
  (
    VALUES
      ('1-2-3'),
      ('45-6'),
      ('777 8'),
      ('9ab10'),
      ('123'),
      ('abc')
  ) v(s)
</code>```

If string starts with non-numeric prefix then we can delete this prefix first of all

```<code>SELECT
  LEFT(s,ISNULL(NULLIF(PATINDEX('%[^0-9]%',s),0)-1,LEN(s)))
FROM
  (
    SELECT
      -- delete non-numberic prefix
      IIF(s NOT LIKE '[0-9]%',STUFF(s,1,PATINDEX('%[0-9]%',s)-1,''),s) s
    FROM
      (
        VALUES
          ('1-2-3'),
          ('45-6'),
          ('777 8'),
          ('9ab10'),
          ('123'),
          ('abc'),
          ('#12test'),
          ('No999-888')
      ) v(s)
  ) q
</code>```

Body:
You can use function PATINDEX to search for the first non-numeric character

SELECT LEFT(s,ISNULL(NULLIF(PATINDEX('%[^0-9]%',s),0)-1,LEN(s)))
FROM
  (
    VALUES
      ('1-2-3'),
      ('45-6'),
      ('777 8'),
      ('9ab10'),
      ('123'),
      ('abc')
  ) v(s)

If string starts with non-numeric prefix then we can delete this prefix first of all

SELECT
  LEFT(s,ISNULL(NULLIF(PATINDEX('%[^0-9]%',s),0)-1,LEN(s)))
FROM
  (
    SELECT
      -- delete non-numberic prefix
      IIF(s NOT LIKE '[0-9]%',STUFF(s,1,PATINDEX('%[0-9]%',s)-1,''),s) s
    FROM
      (
        VALUES
          ('1-2-3'),
          ('45-6'),
          ('777 8'),
          ('9ab10'),
          ('123'),
          ('abc'),
          ('#12test'),
          ('No999-888')
      ) v(s)
  ) q


问:
Ext.panel.Panel Items is not appearing
I've defined a panel class* which is wrapped by another panel**. Somehow subclass' items are not rendering? I've tried several layouts and configs, as well tried to set flex config but none of those adjustment worked. Why it could be?

Thanks in advance...

(*) Panel:

```<code>Ext.define('AP.view.dashboard.BPanel', {
    extend: 'Ext.panel.Panel',
    xtype: 'bpanel',

    requires: [
        'Ext.layout.container.HBox',
        'Ext.layout.container.VBox',
        'Ext.ProgressBar'
    ],

        layout : {type  : 'vbox', align : 'stretch', pack: 'center'},

    items: [
        {
          xtype: 'panel',
          layout: 'vbox',
          items: [
              {
                  xtype: 'component',
                  html: 'TEXT'
              },
              {
                  xtype: 'component',
                  html: '20.82%'
              }
          ]
        },
        {
            xtype: 'panel',
            layout: 'vbox',
            items: [
                {
                    xtype: 'progressbar',
                    flex: 1,
                    cls: 'left-top-text progressbar-no-text',
                    height: 7.5,
                    hideMode: 'display',
                    margin: '0 15 0 0',
                    maxHeight: 10,
                    minHeight: 3,
                    value: 0.7,
                    text: ''
                },
                {
                    xtype: 'panel',
                    layout: 'hbox',
                    items: [
                        {
                            xtype: 'panel',
                            layout: 'vbox',
                            items: [
                                {
                                    xtype: 'component',
                                    html: '2016'
                                },
                                {
                                    xtype: 'component',
                                    html: '3750'
                                }
                            ]
                        },
                        {
                            xtype: 'panel',
                            layout: 'vbox',
                            items: [
                                {
                                    xtype: 'component',
                                    html: '2017'
                                },
                                {
                                    xtype: 'component',
                                    html: '4550'
                                }
                            ]
                        },
                        {
                            xtype: 'panel',
                            layout: 'vbox',
                            items: [
                                {
                                    xtype: 'component',
                                    html: 'Trend'
                                },
                                {
                                    xtype: 'chartvisitors',
                                    flex: 1,
                                    cls: 'graph-analysis-right-inner-container right-value',
                                    bind: {
                                        store: '{visitors}'
                                    }
                                }
                            ]
                        }
                    ]
                }
            ]
        }

    ]
});
</code>```

(**) The panel above called by this one:

```<code>Ext.define('AP.view.dashboard.DashMid', {
    extend: 'Ext.panel.Panel',
    xtype: 'dashmid',

    requires: [
        'Ext.layout.container.HBox',
        'Ext.layout.container.VBox',
        'HR.view.dashboard.APanel',
        'HR.view.dashboard.BPanel',
        'HR.view.dashboard.CPanel'
    ],

    layout: {type: 'hbox'},
    padding: 5,

    items: [
        {
           xtype: 'apanel'

        },
        {
            xtype: 'panel',
            layout: {type: 'vbox'},
            items: [
                {
                    xtype: 'bpanel'
                }
            ]
        },
        {
            xtype: 'cpanel'
        }
    ]
});
</code>```

答:
Well, I've found solution depends on some other stackoverflow questions and NAmorim's comment. Unfortunately because of on-going refactoring I won't repost code snippets, otherwise you could be more confuse.

The first mistake I've been done is about extended classes. I've crated nested panels. I had to extend several of them with Container class, instead of Panel class. So firstly refactored this step. Here is the Sencha documentation that explains which class to extend.

Secondly I've used vbox & hbox layouts but haven't stated any flex or width config. I've refactored those items through NAmorim's comment.

Thanks a lot.

Title: Ext.panel.Panel Items is not appearing

Body:
I've defined a panel class* which is wrapped by another panel**. Somehow subclass' items are not rendering? I've tried several layouts and configs, as well tried to set flex config but none of those adjustment worked. Why it could be?

Thanks in advance...

(*) Panel:

Ext.define('AP.view.dashboard.BPanel', {
    extend: 'Ext.panel.Panel',
    xtype: 'bpanel',

    requires: [
        'Ext.layout.container.HBox',
        'Ext.layout.container.VBox',
        'Ext.ProgressBar'
    ],

        layout : {type  : 'vbox', align : 'stretch', pack: 'center'},

    items: [
        {
          xtype: 'panel',
          layout: 'vbox',
          items: [
              {
                  xtype: 'component',
                  html: 'TEXT'
              },
              {
                  xtype: 'component',
                  html: '20.82%'
              }
          ]
        },
        {
            xtype: 'panel',
            layout: 'vbox',
            items: [
                {
                    xtype: 'progressbar',
                    flex: 1,
                    cls: 'left-top-text progressbar-no-text',
                    height: 7.5,
                    hideMode: 'display',
                    margin: '0 15 0 0',
                    maxHeight: 10,
                    minHeight: 3,
                    value: 0.7,
                    text: ''
                },
                {
                    xtype: 'panel',
                    layout: 'hbox',
                    items: [
                        {
                            xtype: 'panel',
                            layout: 'vbox',
                            items: [
                                {
                                    xtype: 'component',
                                    html: '2016'
                                },
                                {
                                    xtype: 'component',
                                    html: '3750'
                                }
                            ]
                        },
                        {
                            xtype: 'panel',
                            layout: 'vbox',
                            items: [
                                {
                                    xtype: 'component',
                                    html: '2017'
                                },
                                {
                                    xtype: 'component',
                                    html: '4550'
                                }
                            ]
                        },
                        {
                            xtype: 'panel',
                            layout: 'vbox',
                            items: [
                                {
                                    xtype: 'component',
                                    html: 'Trend'
                                },
                                {
                                    xtype: 'chartvisitors',
                                    flex: 1,
                                    cls: 'graph-analysis-right-inner-container right-value',
                                    bind: {
                                        store: '{visitors}'
                                    }
                                }
                            ]
                        }
                    ]
                }
            ]
        }

    ]
});

(**) The panel above called by this one:

Ext.define('AP.view.dashboard.DashMid', {
    extend: 'Ext.panel.Panel',
    xtype: 'dashmid',

    requires: [
        'Ext.layout.container.HBox',
        'Ext.layout.container.VBox',
        'HR.view.dashboard.APanel',
        'HR.view.dashboard.BPanel',
        'HR.view.dashboard.CPanel'
    ],

    layout: {type: 'hbox'},
    padding: 5,

    items: [
        {
           xtype: 'apanel'

        },
        {
            xtype: 'panel',
            layout: {type: 'vbox'},
            items: [
                {
                    xtype: 'bpanel'
                }
            ]
        },
        {
            xtype: 'cpanel'
        }
    ]
});


问:
Insert Base64 image to pdf using pyfpdf
I'm using pyfpdf in python to generate pdf files. I have a Base64 which I want to insert into a pdf file without having to save it as an image in my file system. But the pyfpdf image function only accepts file path.

```<code>fpdf.image(name, x = None, y = None, w = 0, h = 0, type = '', link = '')
</code>```

Is there a way (hack) to directly insert base64 or buffered image from memory, without having to save into the file system beforehand? I even checked their source code on github and couldn't figure.

link : https://github.com/reingart/pyfpdf/tree/master/fpdf

答:
As @pvg mentioned in the comments, overriding load_resource function with your base64 functionality does the trick.

```<code>import base64,io

def load_resource(self, reason, filename):
    if reason == "image":
        if filename.startswith("http://") or filename.startswith("https://"):
            f = BytesIO(urlopen(filename).read())
        elif filename.startswith("data"):
            f = filename.split('base64,')[1]
            f = base64.b64decode(f)
            f = io.BytesIO(f)
        else:
            f = open(filename, "rb")
        return f
    else:
        self.error("Unknown resource loading reason \"%s\"" % reason)
</code>```

EDIT :

This is a sample code to insert images into pdf. I commented some instructions in code.

```<code>from fpdf import FPDF
import os
import io
import base64

class PDF(FPDF):

    def load_resource(self, reason, filename):
        if reason == "image":
            if filename.startswith("http://") or filename.startswith("https://"):
                f = BytesIO(urlopen(filename).read())
            elif filename.startswith("data"):
                f = filename.split('base64,')[1]
                f = base64.b64decode(f)
                f = io.BytesIO(f)
            else:
                f = open(filename, "rb")
            return f
        else:
            self.error("Unknown resource loading reason \"%s\"" % reason)

    def sample_pdf(self,img,path):

        self.image(img,h=70,w=150,x=30,y=100,type="jpg")
        #make sure you use appropriate image format here jpg/png
        pdf.output(path, 'F')

if __name__ == '__main__':
    img = # pass your base64 image
    # you can find sample base64 here : https://pastebin.com/CaZJ7n6s

    pdf = PDF()
    pdf.add_page()
    pdf_path = # give path to where you want to save pdf
    pdf.sample_pdf(img,pdf_path)
</code>```

Title: Insert Base64 image to pdf using pyfpdf

Body:
I'm using pyfpdf in python to generate pdf files. I have a Base64 which I want to insert into a pdf file without having to save it as an image in my file system. But the pyfpdf image function only accepts file path.

fpdf.image(name, x = None, y = None, w = 0, h = 0, type = '', link = '')

Is there a way (hack) to directly insert base64 or buffered image from memory, without having to save into the file system beforehand? I even checked their source code on github and couldn't figure.

link : https://github.com/reingart/pyfpdf/tree/master/fpdf

Body:
As @pvg mentioned in the comments, overriding load_resource function with your base64 functionality does the trick.

import base64,io

def load_resource(self, reason, filename):
    if reason == "image":
        if filename.startswith("http://") or filename.startswith("https://"):
            f = BytesIO(urlopen(filename).read())
        elif filename.startswith("data"):
            f = filename.split('base64,')[1]
            f = base64.b64decode(f)
            f = io.BytesIO(f)
        else:
            f = open(filename, "rb")
        return f
    else:
        self.error("Unknown resource loading reason \"%s\"" % reason)

EDIT :

This is a sample code to insert images into pdf. I commented some instructions in code.

from fpdf import FPDF
import os
import io
import base64

class PDF(FPDF):

    def load_resource(self, reason, filename):
        if reason == "image":
            if filename.startswith("http://") or filename.startswith("https://"):
                f = BytesIO(urlopen(filename).read())
            elif filename.startswith("data"):
                f = filename.split('base64,')[1]
                f = base64.b64decode(f)
                f = io.BytesIO(f)
            else:
                f = open(filename, "rb")
            return f
        else:
            self.error("Unknown resource loading reason \"%s\"" % reason)

    def sample_pdf(self,img,path):

        self.image(img,h=70,w=150,x=30,y=100,type="jpg")
        #make sure you use appropriate image format here jpg/png
        pdf.output(path, 'F')

if __name__ == '__main__':
    img = # pass your base64 image
    # you can find sample base64 here : https://pastebin.com/CaZJ7n6s

    pdf = PDF()
    pdf.add_page()
    pdf_path = # give path to where you want to save pdf
    pdf.sample_pdf(img,pdf_path)


问:
How do I populate one listbox from another listbox using JavaScript?
Can anyone tell me how to populate one listbox from another listbox item using JavaScript or ASP.NET 2.0?

Duplicate

How would I move one list box items to another listbox items in JavaScript?

For ex--My 1st listbox is Region then accourding to region selection the second listbox country will be display and accourding to country seletion state listbox will display all will come from database depends on Region Id or Country id n all

答: Your question leaves out a lot of detail, but basically you would wire a function to the onchange event of the first listbox, that would populate the second listbox.  If the contents would need to be dynamically loaded, you would then need to use AJAX (or similar) to pull them from the server and push them into the second box; alternatively if your contents are statically defined and not too weighty, it would be more responsive to serve them with the original document (perhaps as an associative array keyed on the values of the first listbox) and then update the second listbox based on an array lookup.

OwnerDisplayName: priti

OwnerDisplayName: dtsazza


问:
Process Manager
I'm trying to make a kernel simulation as my DSA (data structure and algorithm) project in C++. There will be different modules(process manager, memory manager etc.) in it. Right now i have to make a Process Manager and I've only a little a idea about it (like, i can use a queue). Can anyone help me how can i make a process manager in c++. </p>

答:
First make a scheduler (unless you understand "process manager" as what is commonly known as a "scheduler".) you must decide upon multitasking model, cooperative vs preemptive. Preemptive may be difficult - use some kind of interrupts and so on... may be unnecessarily complex for a school project.

If you don't know which model to pick, I strongly suggest cooperative multitasking. It is where each process takes a certain small slice of time, then returns control to the scheduler by itself - say, after going through one iteration of its "main loop". Usually done by the main loop calling some kind of "task()" function of the process-class, and the task() ending with a 'return', with no long loops underway.

Start with a model of a "task/process". Should it be loadable (say, as a shared object file), or predefined at startup (a class). Entry point, persistent state storage, "main loop" routine with a finite state machine (usually implemented as a switch that moves between various states). The task works by repeatedly launching the "entry point" routine.

The states to be implemented will likely be:

init, launched on startup, once

idle - check for requests for activity, if none, return control

various "work" states.

Once you have that, prepare a dynamic queue of such tasks. Adding, removing, iterating, elevated priority = call out of order, and so on. The "scheduler" iterates through all the tasks and starts the "startup routine" of each of them.

When you have that ready, you can write what is commonly known as "task manager" - a program that edits the list. Remove a program from the queue, add a new one, change priority, pause etc.

To help you imagine, you currently usually write:

```<code> int main()
 {

      do_something1();
      do_something2();
 }

 void do_something1()
 {

      //initialize
      ...perform stuff
     int x=0;
      //main loop
      do {
           if(condition...) {
                ...perform stuff
           } else {
                ...perform other stuff
                blargh(x);
                x++;
           }
      } while(!end);

      //ending

      //finish...
      ...mop up.
 }
</code>```

What you need to write:

```<code> int main()
 {

      //main loop
      do {
           do_something1();
           do_something2();

      } while(!global_end);
 }

 void do_something1()
 {
      static state_enum state = STATE_INI;
      static int x=0;

      switch(state)
      {
      case STATE_INI:
           //initialize
           ...perform stuff
           state = STATE_WORK1;
           x=0;
      break;
      case STATE_WORK1:
           //main loop, mode 1
           ...perform stuff
           if(condition) state = STATE_WORK2;
           if(condition2) state = STATE_END;
           if(condition4) state = STATE_IDLE;
      break;
      case STATE_WORK2:
           //main loop, mode 2
           ...perform stuff
              blargh(x);
              x++;
           if(condition3) state = STATE_WORK1;
           if(condition4) state = STATE_IDLE;
      break;
      case STATE_IDLE:
           //do nothing
           //don't do any stuff.
           if(any_condition) state = STATE_WORK1;
      break;
      case STATE_END:
           //finish...
           ...mop up.
      break;
      }

      return;
 }
</code>```

...and your process manager will be replacing what constitutes static calls to

```<code>           do_something1();
           do_something2();
</code>```

with a dynamic list of functions to call.

fyi, writing apps for preemptive scheduling system is much easier, you just write them like in the first version, never worrying about preserving state between calls (static), or returning control, or keeping each case statement short and sweet with very short, if any loops inside, unrolling bigger ones. But writing the scheduler itself, interrupting a program and saving its state, then restoring it and resuming from where it interrupted is much, much harder.

Title: Process Manager

Body:
First make a scheduler (unless you understand "process manager" as what is commonly known as a "scheduler".) you must decide upon multitasking model, cooperative vs preemptive. Preemptive may be difficult - use some kind of interrupts and so on... may be unnecessarily complex for a school project.

If you don't know which model to pick, I strongly suggest cooperative multitasking. It is where each process takes a certain small slice of time, then returns control to the scheduler by itself - say, after going through one iteration of its "main loop". Usually done by the main loop calling some kind of "task()" function of the process-class, and the task() ending with a 'return', with no long loops underway.

Start with a model of a "task/process". Should it be loadable (say, as a shared object file), or predefined at startup (a class). Entry point, persistent state storage, "main loop" routine with a finite state machine (usually implemented as a switch that moves between various states). The task works by repeatedly launching the "entry point" routine.

The states to be implemented will likely be:

init, launched on startup, once

idle - check for requests for activity, if none, return control

various "work" states.

Once you have that, prepare a dynamic queue of such tasks. Adding, removing, iterating, elevated priority = call out of order, and so on. The "scheduler" iterates through all the tasks and starts the "startup routine" of each of them.

When you have that ready, you can write what is commonly known as "task manager" - a program that edits the list. Remove a program from the queue, add a new one, change priority, pause etc.

To help you imagine, you currently usually write:

 int main()
 {

      do_something1();
      do_something2();
 }

 void do_something1()
 {

      //initialize
      ...perform stuff
     int x=0;
      //main loop
      do {
           if(condition...) {
                ...perform stuff
           } else {
                ...perform other stuff
                blargh(x);
                x++;
           }
      } while(!end);

      //ending

      //finish...
      ...mop up.
 }

What you need to write:

 int main()
 {

      //main loop
      do {
           do_something1();
           do_something2();

      } while(!global_end);
 }

 void do_something1()
 {
      static state_enum state = STATE_INI;
      static int x=0;

      switch(state)
      {
      case STATE_INI:
           //initialize
           ...perform stuff
           state = STATE_WORK1;
           x=0;
      break;
      case STATE_WORK1:
           //main loop, mode 1
           ...perform stuff
           if(condition) state = STATE_WORK2;
           if(condition2) state = STATE_END;
           if(condition4) state = STATE_IDLE;
      break;
      case STATE_WORK2:
           //main loop, mode 2
           ...perform stuff
              blargh(x);
              x++;
           if(condition3) state = STATE_WORK1;
           if(condition4) state = STATE_IDLE;
      break;
      case STATE_IDLE:
           //do nothing
           //don't do any stuff.
           if(any_condition) state = STATE_WORK1;
      break;
      case STATE_END:
           //finish...
           ...mop up.
      break;
      }

      return;
 }

...and your process manager will be replacing what constitutes static calls to

           do_something1();
           do_something2();

with a dynamic list of functions to call.

fyi, writing apps for preemptive scheduling system is much easier, you just write them like in the first version, never worrying about preserving state between calls (static), or returning control, or keeping each case statement short and sweet with very short, if any loops inside, unrolling bigger ones. But writing the scheduler itself, interrupting a program and saving its state, then restoring it and resuming from where it interrupted is much, much harder.


问:
How do I override a magento 2 theme's phtml with my own custom theme?
I'm attempting to customise the ultimo theme (although presumably this would apply to any magento theme). I have created a new custom theme which (using theme.xml) uses Infortis/ultimo as it's parent.

Ultimo has the following path for it's header.phtml

```<code>ultimo/default/template/page/html/header.phtml
</code>```

I've tried a number of different options for my theme to override this - none of which appear to work e.g.

```<code>frontend/my_theme/default/template/html/header.phtml
frontend/my_theme/default/template/page/html/header.phtml
</code>```

Does anyone have any ideas?

答:
Use the theme path to override your template

Like app/design/<Vendor>/<Package>/<Module_Package>/templates/your.phtml

Body:
I'm attempting to customise the ultimo theme (although presumably this would apply to any magento theme). I have created a new custom theme which (using theme.xml) uses Infortis/ultimo as it's parent.

Ultimo has the following path for it's header.phtml

ultimo/default/template/page/html/header.phtml

I've tried a number of different options for my theme to override this - none of which appear to work e.g.

frontend/my_theme/default/template/html/header.phtml
frontend/my_theme/default/template/page/html/header.phtml

Does anyone have any ideas?


问:
How to use grafana-cli on docker installed Grafana?
I have installed grafana via docker.

Is it possible to export and run grafana-cli on my host?

答:
For a full automatic setup of your Grafana install with the plugins you want I would follow Ricardo's suggestion. Its much better if you can configure your entire container as wanted in a single hit like that.

However if you are just playing with the plugins and want to install some manually, then you can access a shell on the running docker instance from the host.

host:~$ docker exec -it grafana /bin/bash

... assuming you named the docker container "grafana" otherwise you will need to substitute the given container name. The shell prompt that returns will allow you to run the standard

root@3e04b4578ebe:/# grafana-cli plugins install ....

Be warned that it may tell you to run service grafana-server restart afterwards. In my experience that didn't work (Not sure it runs as a traditional service in the container). However if you exit the container, and restart the container from the host...

host:~$ docker restart grafana

That should restart the grafana service and your new plugins should be in place.


问:
Get the string from the given string
I want get the string value after the '\' from this NSString

```<code>   NSString *text = @"\"jkhfjkhfds" ;
</code>```

How can I do it??

答:
```<code>NSString *text = @"\"jkhfjkhfds" ;
text = [text stringByReplacingOccurrencesOfString:@"\\" withString:@""];
text= [text stringByReplacingOccurrencesOfString:@"\"" withString:@""];
NSLOg( NSLog(@"result = %@",text)`;`
</code>```

Title: Get the string from the given string

Body:
I want get the string value after the '\' from this NSString

   NSString *text = @"\"jkhfjkhfds" ;

How can I do it??