问:
Homework Help - Checking data on Form button
I'm really not used to creating Forms with any programming language and I'm still learning about in. Currently, I have a homework that involves Form in C++.

I would appreciate your help since I'm used to code in win32 rather than Form. I feel like a total stranger even though it's in the same language that I'm currently learning.

Here's the question:
In the button btn_calculate, write the codes that can validate the input sales amount is in correct format (double). If wrong input type is given, show a pop up window with error message “please enter amount in number only”. Calculate the total payment amount by adding 6% of goods and services tax to the entered sales amount. Display the total amount in the label lbl_total with the message given.

The problem:
In the button btn_calculate, write the codes that can validate the input sales amount is in correct format (double).

I'm clueless on how to proceed with this problem but I've already finished up coding the rest of the questions except the first sentence of the problem.

This is the logic that can I came up with but I know it is wrong:

```<code>for (int i = 0; i < txtbox_amount->MaxLength; i++)
        {
            if (txtbox_amount[i] == 'A' /*until*/ 'Z' /*capital and lower case character*/)
            {
                //throw 0;
            }
        }
</code>```

This is the my whole logic for the question:

```<code>private: System::Void btn_calculate_Click(System::Object^  sender, System::EventArgs^  e) {

    try
    {
        for (int i = 0; i < txtbox_amount->MaxLength; i++)
        {
            if (txtbox_amount[i] == 'A' /*until*/ 'Z' /*capital and lower case character*/)
            {
                //throw 0;
            }
        }

        double amount = Convert::ToDouble(txtbox_amount->Text);

        if (amount > 0)
        {
            double total = amount * 1.06;
            lbl_total->Text = "The total payment amount is RM" + total;
        }
        else
        {
            throw 1;
        }
    }
    catch (int errorNum)
    {
        if (errorNum = 0)
        {
            MessageBox::Show("Please enter amount in number only", "Error",
            MessageBoxButtons::OKCancel,
            MessageBoxIcon::Error);
        }
        else if (errorNum = 1)
        {
            MessageBox::Show("Negative input! Try again.", "Error",
            MessageBoxButtons::OKCancel,
            MessageBoxIcon::Error);
        }
    }
}
</code>```

I really would appreciate your help and inputs on how to tackle this problem so that I can improve in the future. Thank you

答:
First of all, MaxLength doc:

Gets or sets the maximum number of characters that can be manually entered into the text box.

If you want to get the length of your Textbox's content, you have to usethe property Length of the String^ returned from Textbox::Text.

Next you have to check if txtbox_amount->Text[i] >= 'A' && txtbox_amount->Text[i] <= 'Z' and the same with lowercase characters.

Body:
I'm really not used to creating Forms with any programming language and I'm still learning about in. Currently, I have a homework that involves Form in C++.

I would appreciate your help since I'm used to code in win32 rather than Form. I feel like a total stranger even though it's in the same language that I'm currently learning.

Here's the question:
In the button btn_calculate, write the codes that can validate the input sales amount is in correct format (double). If wrong input type is given, show a pop up window with error message “please enter amount in number only”. Calculate the total payment amount by adding 6% of goods and services tax to the entered sales amount. Display the total amount in the label lbl_total with the message given.

The problem:
In the button btn_calculate, write the codes that can validate the input sales amount is in correct format (double).

I'm clueless on how to proceed with this problem but I've already finished up coding the rest of the questions except the first sentence of the problem.

This is the logic that can I came up with but I know it is wrong:

for (int i = 0; i < txtbox_amount->MaxLength; i++)
        {
            if (txtbox_amount[i] == 'A' /*until*/ 'Z' /*capital and lower case character*/)
            {
                //throw 0;
            }
        }

This is the my whole logic for the question:

private: System::Void btn_calculate_Click(System::Object^  sender, System::EventArgs^  e) {

    try
    {
        for (int i = 0; i < txtbox_amount->MaxLength; i++)
        {
            if (txtbox_amount[i] == 'A' /*until*/ 'Z' /*capital and lower case character*/)
            {
                //throw 0;
            }
        }

        double amount = Convert::ToDouble(txtbox_amount->Text);

        if (amount > 0)
        {
            double total = amount * 1.06;
            lbl_total->Text = "The total payment amount is RM" + total;
        }
        else
        {
            throw 1;
        }
    }
    catch (int errorNum)
    {
        if (errorNum = 0)
        {
            MessageBox::Show("Please enter amount in number only", "Error",
            MessageBoxButtons::OKCancel,
            MessageBoxIcon::Error);
        }
        else if (errorNum = 1)
        {
            MessageBox::Show("Negative input! Try again.", "Error",
            MessageBoxButtons::OKCancel,
            MessageBoxIcon::Error);
        }
    }
}

I really would appreciate your help and inputs on how to tackle this problem so that I can improve in the future. Thank you


来源: stackexchange

问:
Binding Source in MediaTimeline
I am trying to have the mediatimeline bind to a Uri like so:

```<code><UserControl.Resources>
    <Storyboard x:Key="myStoryboard">
        <MediaTimeline Storyboard.TargetName="myMediaPlayer"
                       Source="{Binding MediaSource}"
                       RepeatBehavior="Forever" />
    </Storyboard>
</UserControl.Resources>

<UserControl.Triggers>
    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
        <BeginStoryboard Storyboard="{StaticResource myStoryboard}" />
    </EventTrigger>
</UserControl.Triggers>

<Grid>
    <MediaElement x:Name="mymediaPlayer" />
</Grid>
</code>```

However, when I do this, it says that I need to "Must Specify URI." Dispatcher exception. In the viewmodel, I have a property like:

```<code>    public Uri MediaSource
    {
        get { return _mediaSource; }
        set
        {
            if (_oscilloscopeSource != value)
            {
                _mediaSource= value;
                OnPropertyChanged("MediaSource");
            }
        }
    }
</code>```

It seems as though when the media player is loaded, it doesn't read the source from the binding. What gives?

In the constructor, I have:

```<code>_mediaSource = new Uri(@"C:\someMovie.mov", UriKind.Absolute);
</code>```

Thanks.

答:
Update

Can't get this to work so shooting in the dark now. Does moving the trigger to MediaElement make a difference?

```<code><MediaElement x:Name="myMediaPlayer">
    <MediaElement.Triggers>
        <EventTrigger RoutedEvent="FrameworkElement.Loaded">
            <BeginStoryboard Storyboard="{StaticResource myStoryboard}" />
        </EventTrigger>
    </MediaElement.Triggers>
</MediaElement>
</code>```

I tried this out and it works for me. Possible reasons I can think of.

Do you have the DataContext set for the UserControl?

Setting _mediaSource directly won't call OnPropertyChanged since you're not setting the CLR property. Set MediaSource instead.

Your MediaElement is named mymediaPlayer and not myMediaPlayer as the TargetName. (Typo?)

Except for the MediaElement Name which I changed, my working xaml is identical to yours. This is my full code behind file

```<code>public partial class UserControl1 : UserControl, INotifyPropertyChanged
{
    public UserControl1()
    {
        InitializeComponent();
        MediaSource = new Uri("C:\\C1.MOV");
        this.DataContext = this;
    }

    private Uri _mediaSource;
    public Uri MediaSource
    {
        get
        {
            return _mediaSource;
        }
        set
        {
            _mediaSource = value;
            OnPropertyChanged("MediaSource");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Binding Source in MediaTimeline

Body:
I am trying to have the mediatimeline bind to a Uri like so:

<UserControl.Resources>
    <Storyboard x:Key="myStoryboard">
        <MediaTimeline Storyboard.TargetName="myMediaPlayer"
                       Source="{Binding MediaSource}"
                       RepeatBehavior="Forever" />
    </Storyboard>
</UserControl.Resources>

<UserControl.Triggers>
    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
        <BeginStoryboard Storyboard="{StaticResource myStoryboard}" />
    </EventTrigger>
</UserControl.Triggers>

<Grid>
    <MediaElement x:Name="mymediaPlayer" />
</Grid>

However, when I do this, it says that I need to "Must Specify URI." Dispatcher exception. In the viewmodel, I have a property like:

    public Uri MediaSource
    {
        get { return _mediaSource; }
        set
        {
            if (_oscilloscopeSource != value)
            {
                _mediaSource= value;
                OnPropertyChanged("MediaSource");
            }
        }
    }

It seems as though when the media player is loaded, it doesn't read the source from the binding. What gives?

In the constructor, I have:

_mediaSource = new Uri(@"C:\someMovie.mov", UriKind.Absolute);

Thanks.

Body:
Update

Can't get this to work so shooting in the dark now. Does moving the trigger to MediaElement make a difference?

<MediaElement x:Name="myMediaPlayer">
    <MediaElement.Triggers>
        <EventTrigger RoutedEvent="FrameworkElement.Loaded">
            <BeginStoryboard Storyboard="{StaticResource myStoryboard}" />
        </EventTrigger>
    </MediaElement.Triggers>
</MediaElement>

I tried this out and it works for me. Possible reasons I can think of.

Do you have the DataContext set for the UserControl?

Setting _mediaSource directly won't call OnPropertyChanged since you're not setting the CLR property. Set MediaSource instead.

Your MediaElement is named mymediaPlayer and not myMediaPlayer as the TargetName. (Typo?)

Except for the MediaElement Name which I changed, my working xaml is identical to yours. This is my full code behind file

public partial class UserControl1 : UserControl, INotifyPropertyChanged
{
    public UserControl1()
    {
        InitializeComponent();
        MediaSource = new Uri("C:\\C1.MOV");
        this.DataContext = this;
    }

    private Uri _mediaSource;
    public Uri MediaSource
    {
        get
        {
            return _mediaSource;
        }
        set
        {
            _mediaSource = value;
            OnPropertyChanged("MediaSource");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}


问:
Unity3D does sprite sheet automatically batched?
I know I can use sprite packer to pack sprites so that there will be only one drawCall. If I slice a sprite sheet into multiple sprites, will it have the same effect? I experimented on my own, but there is no batching saved and I am afraid I did something wrong?

I used UI Image. And I used same material on them to hope batch them.

答:
You may open the Frame Debugger to inspect whether your sprites are batched.

See also DrawCallBatching for more details on when and how draw-calls will be batched.

ContentLicense: CC BY-SA 3.0


问:
How to make wave animation in HTML
I want to create wave animation with 3-4 waves in HTML.
and also I want to make responsive for mobile,tablet etc.

I have also attached the image which I want to use as wave.

答:
You can remove the up and down movement of the elements by animating the transform property instead of the height of the elements.

You can use the scaleY() function to make the elements grow on the Y axis (height).

Making a wave animation

Title: How to make wave animation in HTML


问:
Regex match all strings between 2 characters
I tried a couple of other links like Regex Match all characters between two strings and Regex get all content between two characters
but they don't seem to fit this use case.

I want to get all the names, potato and tomato. Eg, from | to >.

```<code>text = "with <@U0D08NR3|potato> and <@U1698M96|tomato> please"
</code>```

text.scan((?<=|).*?(?=>)) doesnt seem to work either..

Please guide me regex gods.

答:
Try this:

```<code>text.scan(/\|(\w*)\>/).flatten
# Returns => ["potato", "tomato"]
</code>```

Not exactly sure why this works. Something to do with greedy and non-greedy matching. See this

Body:
I tried a couple of other links like Regex Match all characters between two strings and Regex get all content between two characters
but they don't seem to fit this use case.

I want to get all the names, potato and tomato. Eg, from | to >.

text = "with <@U0D08NR3|potato> and <@U1698M96|tomato> please"

text.scan((?<=|).*?(?=>)) doesnt seem to work either..

Please guide me regex gods.

Body:
Try this:

text.scan(/\|(\w*)\>/).flatten
# Returns => ["potato", "tomato"]

Not exactly sure why this works. Something to do with greedy and non-greedy matching. See this


问:
Removing .txt from my file name and sheet name
Pleas help guys!! In the section of code below (which works great btw), I keep getting .txt in the actually file name and sheet name. I have been looking at what I need to take out to solve this but I can't work it out. I am pretty new to VBA so I am doing my best Please help?!</p>

```<code> 'Opens the folder to location to select txt file
  fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
    If fileToOpen <> False Then
    Workbooks.OpenText fileName:=fileToOpen, _
    DataType:=xlDelimited, Tab:=True
    End If
 'Creates the file name based on txt file name
  fileName = Mid(fileToOpen, InStrRev(fileToOpen, "\") + 1)
 'Creates the sheet name based on the active txt file
  sheetName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)

 'Rename the original text file
   ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\" & "DNU_" & fileName & ".txt")
</code>```

答:
you can use a regex and extract file name without extension and use it </p>

```<code>public String extractFileName(String fullPathFile){
        try {
            Pattern regex = Pattern.compile(EXTRACT_FILE_NAME_REGEX);
            Matcher regexMatcher = regex.matcher(fullPathFile);
            if (regexMatcher.find()){
                return regexMatcher.group(1);
            }
        } catch (PatternSyntaxException ex) {
            LOG.info("extractFileName::pattern problem <"+fullPathFile+">",ex);
        }
        return fullPathFile;
    }
</code>```

Body:
Pleas help guys!! In the section of code below (which works great btw), I keep getting .txt in the actually file name and sheet name. I have been looking at what I need to take out to solve this but I can't work it out. I am pretty new to VBA so I am doing my best Please help?!

 'Opens the folder to location to select txt file
  fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
    If fileToOpen <> False Then
    Workbooks.OpenText fileName:=fileToOpen, _
    DataType:=xlDelimited, Tab:=True
    End If
 'Creates the file name based on txt file name
  fileName = Mid(fileToOpen, InStrRev(fileToOpen, "\") + 1)
 'Creates the sheet name based on the active txt file
  sheetName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)

 'Rename the original text file
   ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\" & "DNU_" & fileName & ".txt")

Body:
you can use a regex and extract file name without extension and use it

public String extractFileName(String fullPathFile){
        try {
            Pattern regex = Pattern.compile(EXTRACT_FILE_NAME_REGEX);
            Matcher regexMatcher = regex.matcher(fullPathFile);
            if (regexMatcher.find()){
                return regexMatcher.group(1);
            }
        } catch (PatternSyntaxException ex) {
            LOG.info("extractFileName::pattern problem <"+fullPathFile+">",ex);
        }
        return fullPathFile;
    }


问:
dyld: Library not loaded: @rpath/CoreNFC.framework/CoreNFC, iOS11 and Xcode 9 beta
I get this error and app get crash while run CoreNFC sample code in Xcode 9.0 beta 2

```<code>dyld: Library not loaded: @rpath/CoreNFC.framework/CoreNFC
  Referenced from: /var/containers/Bundle/Application/2837709C-C852-4811-B696-38F2725554D4/iOS-11-by-Examples.app/iOS-11-by-Examples
  Reason: image not found
</code>```

Does anyone knows how to fix this?

答:
CoreNFC is only available on iPhone 7 and iPhone 7 Plus devices. Make sure you're running your code on one of those.

See the WWDC session and the relevant documentation for more information.

https://developer.apple.com/videos/play/wwdc2017/718/

https://developer.apple.com/documentation/corenfc

Body:
I get this error and app get crash while run CoreNFC sample code in Xcode 9.0 beta 2

dyld: Library not loaded: @rpath/CoreNFC.framework/CoreNFC
  Referenced from: /var/containers/Bundle/Application/2837709C-C852-4811-B696-38F2725554D4/iOS-11-by-Examples.app/iOS-11-by-Examples
  Reason: image not found

Does anyone knows how to fix this?


问:
MS Access SQL: Troubles combining UNION ALL with a LEFT JOIN
I have created a query in MS Access to simulate a FULL OUTER JOIN and combine the results that looks something like the following:

```<code>SELECT NZ(estimates.employee_id, actuals.employee_id) AS employee_id
, NZ(estimates.a_date, actuals.a_date) AS a_date
, estimates.estimated_hours
, actuals.actual_hours
FROM (SELECT *
      FROM estimates
      LEFT JOIN actuals ON estimates.employee_id = actuals.employee_id
         AND estimates.a_date = actuals.a_date
      UNION ALL
      SELECT *
      FROM estimates
      RIGHT JOIN actuals ON estimates.employee_id = actuals.employee_id
         AND estimates.a_date = actuals.a_date
      WHERE estimates.employee_id IS NULL
         OR estimates.a_date IS NULL) AS qFullJoinEstimatesActuals
</code>```

I have saved this query as an object (let's call it qEstimatesAndActuals).  My objective is to LEFT JOIN qEstimatesAndActuals with another table.  Something like the following:

```<code>SELECT *
FROM qJoinedTable
LEFT JOIN (SELECT *
           FROM labor_rates) AS rates
ON qJoinedTable.employee_id = rates.employee_id
   AND qJoinedTable.a_date BETWEEN rates.begin_date AND rates.end_date
</code>```

MS Access accepts the syntax and runs the query, but it omits results that are clearly within the result set.  Wondering if the date format was somehow lost, I placed a FORMAT around the begin_date and end_date to force them to be interpreted as Short Dates.  Oddly, this produced a different result set, but it still omitted result that it shouldn't have.

I am wondering if the queries are performed in such a way that you can't LEFT JOIN the result set of a UNION ALL.  Does anyone have any thoughts/ideas on this?  Is there a better way of accomplishing the end goal?

答:
I would try breaking each part of the query into its own access query object, e.g.

```<code>SELECT *
  FROM estimates
  LEFT JOIN actuals ON estimates.employee_id = actuals.employee_id
     AND estimates.a_date = actuals.a_date
</code>```

Would be qryOne

```<code>SELECT *
  FROM estimates
  RIGHT JOIN actuals ON estimates.employee_id = actuals.employee_id
     AND estimates.a_date = actuals.a_date
  WHERE estimates.employee_id IS NULL
     OR estimates.a_date IS NULL
</code>```

Would be qryTwo

```<code>SELECT * FROM qryOne
UNION ALL
SELECT * FROM qryTwo
</code>```

Would be qryFullJoinEstimatesActuals, and finally

```<code>SELECT NZ(estimates.employee_id, actuals.employee_id) AS employee_id
, NZ(estimates.a_date, actuals.a_date) AS a_date
, estimates.estimated_hours
, actuals.actual_hours
FROM qryFullJoinEstimatesActuals
</code>```

I've found that constructs that don't work in complex Access SQL statements often do work properly if they are broken down into individual query objects and reassembled step-by-step. Additionally, you can test each part of the query individually. This will help you find a workaround if one proves to be necessary.

Body:
I have created a query in MS Access to simulate a FULL OUTER JOIN and combine the results that looks something like the following:

SELECT NZ(estimates.employee_id, actuals.employee_id) AS employee_id
, NZ(estimates.a_date, actuals.a_date) AS a_date
, estimates.estimated_hours
, actuals.actual_hours
FROM (SELECT *
      FROM estimates
      LEFT JOIN actuals ON estimates.employee_id = actuals.employee_id
         AND estimates.a_date = actuals.a_date
      UNION ALL
      SELECT *
      FROM estimates
      RIGHT JOIN actuals ON estimates.employee_id = actuals.employee_id
         AND estimates.a_date = actuals.a_date
      WHERE estimates.employee_id IS NULL
         OR estimates.a_date IS NULL) AS qFullJoinEstimatesActuals

I have saved this query as an object (let's call it qEstimatesAndActuals).  My objective is to LEFT JOIN qEstimatesAndActuals with another table.  Something like the following:

SELECT *
FROM qJoinedTable
LEFT JOIN (SELECT *
           FROM labor_rates) AS rates
ON qJoinedTable.employee_id = rates.employee_id
   AND qJoinedTable.a_date BETWEEN rates.begin_date AND rates.end_date

MS Access accepts the syntax and runs the query, but it omits results that are clearly within the result set.  Wondering if the date format was somehow lost, I placed a FORMAT around the begin_date and end_date to force them to be interpreted as Short Dates.  Oddly, this produced a different result set, but it still omitted result that it shouldn't have.

I am wondering if the queries are performed in such a way that you can't LEFT JOIN the result set of a UNION ALL.  Does anyone have any thoughts/ideas on this?  Is there a better way of accomplishing the end goal?

Body:
I would try breaking each part of the query into its own access query object, e.g.

SELECT *
  FROM estimates
  LEFT JOIN actuals ON estimates.employee_id = actuals.employee_id
     AND estimates.a_date = actuals.a_date

Would be qryOne

SELECT *
  FROM estimates
  RIGHT JOIN actuals ON estimates.employee_id = actuals.employee_id
     AND estimates.a_date = actuals.a_date
  WHERE estimates.employee_id IS NULL
     OR estimates.a_date IS NULL

Would be qryTwo

SELECT * FROM qryOne
UNION ALL
SELECT * FROM qryTwo

Would be qryFullJoinEstimatesActuals, and finally

SELECT NZ(estimates.employee_id, actuals.employee_id) AS employee_id
, NZ(estimates.a_date, actuals.a_date) AS a_date
, estimates.estimated_hours
, actuals.actual_hours
FROM qryFullJoinEstimatesActuals

I've found that constructs that don't work in complex Access SQL statements often do work properly if they are broken down into individual query objects and reassembled step-by-step. Additionally, you can test each part of the query individually. This will help you find a workaround if one proves to be necessary.


问:
Pass TextInput props between different screens in React Navigation
I am totally lost on how to grab two parameters from a form screen and pass them via React Navigator and display them on the previous screen.

The app section in question works like this:

1. touchablehighlight to form screen.

2. input title and description and press submit onpress

3. the onpress runs a function that dispatches the parameters to the previous page via a key.

4. then returns back to the origin page, with the props on display.

I am having multiple issues with the process:

1. if I am understanding the docs correctly, each page has a unique key and i tried to find it via this.props.navigation.state.key, however unknown to me, on refresh the id number would change.

2. that leads to problem 2 where the function will run, but it will not redirect back to the original page.

3. i have tried .navigate line after .dispatch but it would open a new copy of the original page and not display the new props that supposively were passed down.

import React from 'react';
import styles from '../styling/style.js';
import { Text, View, Image, TouchableHighlight, TextInput, Alert } from 'react-native';
import { StackNavigator, NavigationActions } from 'react-navigation';
import Forms from './formGenerator';

export default class Workout extends React.Component {
constructor(props) {
  super(props);
  this.state = {
     programTitle: '',
     programDescription: ''
  }
}

render() {
  const {navigate} = this.props.navigation;
  return (
    <Image style={styles.workoutContainer, { flex: 1}} source={require("../images/HomepageBackground.jpg")}>
      <View style={styles.workoutBody}>
          <Text style={styles.workoutTextBody}> {this.state.programTitle}</Text>
          <Text style={styles.workoutTextBody}>{this.state.programDescription}</Text>
      </View>
        <View style={styles.createButton}>
        <TouchableHighlight onPress={Alert.alert(this.props.navigation.state.key)} style={styles.addButtonTouch} title='test' >
         <Text style={styles.addButtonText}>+</Text>
        </TouchableHighlight>
        </View>
    </Image>
    );
  }

// End of the render
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react';
import styles from '../styling/style.js';
import { Text, View, Image, TouchableHighlight, TextInput, Button, Alert } from 'react-native';
import Workout from './workouts';
import { NavigationActions } from 'react-navigation';

export default class Forms extends React.Component {
constructor(props) {
  super(props);
  this.state = {
     programTitle: '',
     programDescription: ''
  }
}

render() {
  const {goBack} = this.props.navigation;
  const {params} = this.props.navigation.state;
  return (
    <Image style={styles.workoutContainer, { flex: 1}} source={require("../images/HomepageBackground.jpg")}>
      <View style={styles.workoutBody}>
        <Text style={styles.formHeader}>Program Title</Text>
          <TextInput
            autoFocus={true}
            style={styles.formBody}
            onChangeText={(programTitle) => this.setState({programTitle})}
            placeholder='Title'
            value={this.state.programTitle} />
        <Text style={styles.formHeader}>Description (Ex. 4sets x 10reps)</Text>
          <TextInput
            autoFocus={true}
            style={styles.formBody}
            placeholder='Description'
            onChangeText={(programDescription) => this.setState({programDescription})}
            value={this.state.programDescription} />
        <TouchableHighlight onPress={this.addProgram} style={styles.buttonBody} title="Add Program" >
          <Text>Add Program</Text>
        </TouchableHighlight>
      </View>
    </Image>
    );
  }

addProgram = () => {
  Alert.alert(this.props.navigation.state.key);
  this.setState({programTitle: ''});
  this.setState({programDescription: ''});
  const setParamsAction = NavigationActions.setParams({
  params: { programTitle: this.state.programTitle, programDescription: this.state.programDescription },
  key: ,
})
this.props.navigation.dispatch(setParamsAction)
};

}</code>```

答:
If you are trying to get parameter from "Next Page", you could have two approaches.

1, save the params in AsyncStorage (suggested)

2, using navigation setParams function with the params

```<code>const setParamsAction = NavigationActions.setParams({
  params: { title: 'Hello' },
  key: 'screen-123',
})
this.props.navigation.dispatch(setParamsAction)
</code>```

https://reactnavigation.org/docs/navigators/navigation-actions

Body:
I am totally lost on how to grab two parameters from a form screen and pass them via React Navigator and display them on the previous screen.

The app section in question works like this:

1. touchablehighlight to form screen.

2. input title and description and press submit onpress

3. the onpress runs a function that dispatches the parameters to the previous page via a key.

4. then returns back to the origin page, with the props on display.

I am having multiple issues with the process:

1. if I am understanding the docs correctly, each page has a unique key and i tried to find it via this.props.navigation.state.key, however unknown to me, on refresh the id number would change.

2. that leads to problem 2 where the function will run, but it will not redirect back to the original page.

3. i have tried .navigate line after .dispatch but it would open a new copy of the original page and not display the new props that supposively were passed down.

import React from 'react';
import styles from '../styling/style.js';
import { Text, View, Image, TouchableHighlight, TextInput, Alert } from 'react-native';
import { StackNavigator, NavigationActions } from 'react-navigation';
import Forms from './formGenerator';

export default class Workout extends React.Component {
constructor(props) {
  super(props);
  this.state = {
     programTitle: '',
     programDescription: ''
  }
}

render() {
  const {navigate} = this.props.navigation;
  return (
    <Image style={styles.workoutContainer, { flex: 1}} source={require("../images/HomepageBackground.jpg")}>
      <View style={styles.workoutBody}>
          <Text style={styles.workoutTextBody}> {this.state.programTitle}</Text>
          <Text style={styles.workoutTextBody}>{this.state.programDescription}</Text>
      </View>
        <View style={styles.createButton}>
        <TouchableHighlight onPress={Alert.alert(this.props.navigation.state.key)} style={styles.addButtonTouch} title='test' >
         <Text style={styles.addButtonText}>+</Text>
        </TouchableHighlight>
        </View>
    </Image>
    );
  }

// End of the render
}

import React from 'react';
import styles from '../styling/style.js';
import { Text, View, Image, TouchableHighlight, TextInput, Button, Alert } from 'react-native';
import Workout from './workouts';
import { NavigationActions } from 'react-navigation';

export default class Forms extends React.Component {
constructor(props) {
  super(props);
  this.state = {
     programTitle: '',
     programDescription: ''
  }
}

render() {
  const {goBack} = this.props.navigation;
  const {params} = this.props.navigation.state;
  return (
    <Image style={styles.workoutContainer, { flex: 1}} source={require("../images/HomepageBackground.jpg")}>
      <View style={styles.workoutBody}>
        <Text style={styles.formHeader}>Program Title</Text>
          <TextInput
            autoFocus={true}
            style={styles.formBody}
            onChangeText={(programTitle) => this.setState({programTitle})}
            placeholder='Title'
            value={this.state.programTitle} />
        <Text style={styles.formHeader}>Description (Ex. 4sets x 10reps)</Text>
          <TextInput
            autoFocus={true}
            style={styles.formBody}
            placeholder='Description'
            onChangeText={(programDescription) => this.setState({programDescription})}
            value={this.state.programDescription} />
        <TouchableHighlight onPress={this.addProgram} style={styles.buttonBody} title="Add Program" >
          <Text>Add Program</Text>
        </TouchableHighlight>
      </View>
    </Image>
    );
  }

addProgram = () => {
  Alert.alert(this.props.navigation.state.key);
  this.setState({programTitle: ''});
  this.setState({programDescription: ''});
  const setParamsAction = NavigationActions.setParams({
  params: { programTitle: this.state.programTitle, programDescription: this.state.programDescription },
  key: ,
})
this.props.navigation.dispatch(setParamsAction)
};

}

Body:
If you are trying to get parameter from "Next Page", you could have two approaches.

1, save the params in AsyncStorage (suggested)

2, using navigation setParams function with the params

const setParamsAction = NavigationActions.setParams({
  params: { title: 'Hello' },
  key: 'screen-123',
})
this.props.navigation.dispatch(setParamsAction)

https://reactnavigation.org/docs/navigators/navigation-actions


问:
Selenium: Automate Vertical Scrolling in Java
I need to automate scrolling down using the scroll bar. This is what the scroll bar looks like.
This is the html code of the scroll bar:

```<code><div class="z-biglistbox-wscroll-vertical">
    <div class="z-biglistbox-wscroll-drag" style="top: 132.253px;">
        <div class="z-biglistbox-wscroll-home" title="Home"></div>
        <div class="z-biglistbox-wscroll-up" title="Previous"></div>
        <div class="z-biglistbox-wscroll-down" title="Next"></div>
        <div class="z-biglistbox-wscroll-end" title="End"></div>
    </div>
</div>
</code>```

I think of maybe clicking the "Next" button of the scroll bar but my code's not working. I did something like the following:

```<code>((JavascriptExecutor)driver).executeScript("arguments[0].click();", scroll_down);
</code>```

.

```<code>WebElement scroll_down = driver.findElement(By.cssSelector(".z-biglistbox-wscroll-down"));
scroll_down.click();
</code>```

Neither of the two worked. Can anyone give me an idea how to do it?

UPDATE:
This problem was already solved. Refer to alecxe's answer in this link for the solution that worked for me.

答:
Try below code for scrolling your window to bottom :  </p>

```<code>WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;

JavascriptExecutor jsx = (JavascriptExecutor) driver;
jsx.executeScript("window.scrollBy(0,500)", "");
</code>```

Body:
I need to automate scrolling down using the scroll bar. This is what the scroll bar looks like.
This is the html code of the scroll bar:

I think of maybe clicking the "Next" button of the scroll bar but my code's not working. I did something like the following:

((JavascriptExecutor)driver).executeScript("arguments[0].click();", scroll_down);

.

WebElement scroll_down = driver.findElement(By.cssSelector(".z-biglistbox-wscroll-down"));
scroll_down.click();

Neither of the two worked. Can anyone give me an idea how to do it?

UPDATE:
This problem was already solved. Refer to alecxe's answer in this link for the solution that worked for me.

Body:
Try below code for scrolling your window to bottom :

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;

JavascriptExecutor jsx = (JavascriptExecutor) driver;
jsx.executeScript("window.scrollBy(0,500)", "");


问:
Django custom save and update
I have a custom save method for a model.

```<code>class Ticket(models.Model):
    show = models.ForeignKey(Show)
    seat = models.ForeignKey(Seat)
    ref = models.CharField(max_length=100)
    paid = models.BooleanField(default=False)

    class Meta:
        unique_together = ('show', 'seat')

    def save(self, *args, **kwargs):
        if self.paid:
            do_something()
</code>```

In the view I would like to update multiple Ticket objects:

```<code>Ticket.objects.filter(ref='ref').update(paid=True)
</code>```

But, since this won't call the custom save method. The method do_something() won't be processed. Is there any way to solve this problem?

答:
```<code>def save(self, *args, **kwargs):
        if self.paid:
            do_something()
    super(Ticket, self).save(*args, **kwargs)
</code>```

use this and add the custom code inside self.paid, hope it helps

Title: Django custom save and update

Body:
I have a custom save method for a model.

class Ticket(models.Model):
    show = models.ForeignKey(Show)
    seat = models.ForeignKey(Seat)
    ref = models.CharField(max_length=100)
    paid = models.BooleanField(default=False)

    class Meta:
        unique_together = ('show', 'seat')

    def save(self, *args, **kwargs):
        if self.paid:
            do_something()

In the view I would like to update multiple Ticket objects:

Ticket.objects.filter(ref='ref').update(paid=True)

But, since this won't call the custom save method. The method do_something() won't be processed. Is there any way to solve this problem?

Body:
def save(self, *args, **kwargs):
        if self.paid:
            do_something()
    super(Ticket, self).save(*args, **kwargs)

use this and add the custom code inside self.paid, hope it helps


问:
IE ans Excel VBA - choose item from drop-down list
I would like to login into a webpage, however I did not succeed and could not find any useful tutorial, description or advice. On this page: https://emir.palyazat.gov.hu/nd/eupalyazat/index.php?tip=100009&opid=9#login_jelzo I would like to choose from the list “GOP-2.1.3-11” (value: 1950), then another (former hidden) list will appear. From this list I have to choose  GOP-2.1.3-11-2011-0085 (value: 74347). At the first step I got stuck with the code below:

```<code>Sub IEopen()

Dim IE As New SHDocVw.InternetExplorer
Dim HTMLDoc As MSHTML.HTMLDocument
Dim HTMLInput As MSHTML.IHTMLElement
Dim HTMLButtons As MSHTML.IHTMLElementCollection
Dim HTMLButton As MSHTML.IHTMLElement
Dim HTMLTable As MSHTML.IHTMLElement
Dim HTMLTables As MSHTML.IHTMLElementCollection
Dim HTMLRow As MSHTML.IHTMLElement

IE.Visible = True
IE.Navigate "https://emir.palyazat.gov.hu/nd/eupalyazat/index.php?tip=100009&opid=9#login_jelzo"

Do While IE.ReadyState <> READYSTATE_COMPLETE
Loop

Set HTMLDoc = IE.Document

Set HTMLRow = HTMLDoc.getElementById("id_paly_altip")
HTMLRow.Value = "1950"
End Sub
</code>```

I have to manage more accounts on that page and it would be very easy to login by clicking on a button .

References: Microsoft Internet Control, Microsoft HTML Object Library, Microsoft xml, v6.0, and Microsoft_Jscript.

Thanks for your help in advance and if you there is a comprehensive description on handling webpages in VBA please paste in it your answer too. Thank you very much.

答:
I had to use application.sendkeys, but at the end it was success:

```<code>Set HTMLRow = HTMLDoc.getElementById("id_paly_altip")
HTMLRow.Value = "XXXXXXXXXXX"
Application.SendKeys ("{up}")
Application.Wait (Now + TimeValue("0:00:01"))
Application.SendKeys ("{down}")
Application.Wait (Now + TimeValue("0:00:01"))

Application.SendKeys ("{tab}")

Set HTMLRow = HTMLDoc.getElementById("palyazat_szama")
HTMLRow.Value = "XXXXXXXXXXXXX"
Application.SendKeys ("{up}")
Application.Wait (Now + TimeValue("0:00:01"))
Application.SendKeys ("{down}")
Application.Wait (Now + TimeValue("0:00:01"))

Set HTMLRow = HTMLDoc.getElementById("lb_felhasznalo")
HTMLRow.Value = "XXXXXXXXXXXXXXXX"

Application.SendKeys ("{tab 2}")
Application.SendKeys ("XXXXXXXXXXXXXXXXXXXXXXX")

Application.Wait (Now + TimeValue("0:00:01"))

Set HTMLButton = HTMLDoc.getElementById("login_submit")
HTMLButton.disabled = ""
HTMLButton.Click

Application.SendKeys "{NUMLOCK}%s"

End Sub
</code>```

However, I did not find any comprehensive description about IE and VBA. Would you please recommend one? THX

Body:
I would like to login into a webpage, however I did not succeed and could not find any useful tutorial, description or advice. On this page: https://emir.palyazat.gov.hu/nd/eupalyazat/index.php?tip=100009&opid=9#login_jelzo I would like to choose from the list “GOP-2.1.3-11” (value: 1950), then another (former hidden) list will appear. From this list I have to choose  GOP-2.1.3-11-2011-0085 (value: 74347). At the first step I got stuck with the code below:

Sub IEopen()

Dim IE As New SHDocVw.InternetExplorer
Dim HTMLDoc As MSHTML.HTMLDocument
Dim HTMLInput As MSHTML.IHTMLElement
Dim HTMLButtons As MSHTML.IHTMLElementCollection
Dim HTMLButton As MSHTML.IHTMLElement
Dim HTMLTable As MSHTML.IHTMLElement
Dim HTMLTables As MSHTML.IHTMLElementCollection
Dim HTMLRow As MSHTML.IHTMLElement

IE.Visible = True
IE.Navigate "https://emir.palyazat.gov.hu/nd/eupalyazat/index.php?tip=100009&opid=9#login_jelzo"

Do While IE.ReadyState <> READYSTATE_COMPLETE
Loop

Set HTMLDoc = IE.Document

Set HTMLRow = HTMLDoc.getElementById("id_paly_altip")
HTMLRow.Value = "1950"
End Sub

I have to manage more accounts on that page and it would be very easy to login by clicking on a button .

References: Microsoft Internet Control, Microsoft HTML Object Library, Microsoft xml, v6.0, and Microsoft_Jscript.

Thanks for your help in advance and if you there is a comprehensive description on handling webpages in VBA please paste in it your answer too. Thank you very much.

Body:
I had to use application.sendkeys, but at the end it was success:

Set HTMLRow = HTMLDoc.getElementById("id_paly_altip")
HTMLRow.Value = "XXXXXXXXXXX"
Application.SendKeys ("{up}")
Application.Wait (Now + TimeValue("0:00:01"))
Application.SendKeys ("{down}")
Application.Wait (Now + TimeValue("0:00:01"))

Application.SendKeys ("{tab}")

Set HTMLRow = HTMLDoc.getElementById("palyazat_szama")
HTMLRow.Value = "XXXXXXXXXXXXX"
Application.SendKeys ("{up}")
Application.Wait (Now + TimeValue("0:00:01"))
Application.SendKeys ("{down}")
Application.Wait (Now + TimeValue("0:00:01"))

Set HTMLRow = HTMLDoc.getElementById("lb_felhasznalo")
HTMLRow.Value = "XXXXXXXXXXXXXXXX"

Application.SendKeys ("{tab 2}")
Application.SendKeys ("XXXXXXXXXXXXXXXXXXXXXXX")

Application.Wait (Now + TimeValue("0:00:01"))

Set HTMLButton = HTMLDoc.getElementById("login_submit")
HTMLButton.disabled = ""
HTMLButton.Click

Application.SendKeys "{NUMLOCK}%s"

End Sub

However, I did not find any comprehensive description about IE and VBA. Would you please recommend one? THX


问:
INVALID_SESSION_ID in getting leads from salesforce through Rest api php
Hi i need to get the leads from the salesforce through rest api for this i have done so far a successful oauth through rest api and i got a following response

```<code>stdClass Object
(
    [access_token] => 1111xxxxxxxx44444444444444
    [instance_url] => https://eu7.salesforce.com
    [id] => https://login.salesforce.com/id/000000000
    [token_type] => Bearer
    [issued_at] => xxxxxxxxxxxx
    [signature] => xxxxxxxxxxxx
)
</code>```

after that for getting contact leads i am using the below code

```<code>$email = 'test_@gmail.com';
$query = 'SELECT Id, Email FROM Lead';
if($email != null){
$query .= sprintf("WHERE Email ='%s'", $email);
}
$url = $instance_url. '/services/data/v33.0/query?q=' . urlencode($query);
$paramsnew = "access_token=$access_token";
$urlcurl = curl_init($url);
curl_setopt($urlcurl, CURLOPT_HEADER, false);
curl_setopt($urlcurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($urlcurl, CURLOPT_POST, true);
curl_setopt($urlcurl, CURLOPT_POSTFIELDS, $paramsnew);
curl_setopt($urlcurl, CURLOPT_SSL_VERIFYPEER, false);
$urljson_response = curl_exec($urlcurl);
echo $urljson_response;
curl_close($urlcurl);
</code>```

but in response i am getting below

```<code>[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]
</code>```

Please suggest how can i fix this.

答:
Finally i fixed it by using the below code.

```<code>$firstname = 'rohit';
$query = 'SELECT FirstName , LastName ,Id, Email FROM Lead ';
if($firstname != null){
$query .= sprintf("WHERE FirstName ='%s'", $firstname);
}
$url = $instance_url. '/services/data/v33.0/query?q=' . urlencode($query);
$paramsnew = "access_token=$access_token";
$urlcurl = curl_init($url);
curl_setopt($urlcurl, CURLOPT_HEADER, false);
curl_setopt($urlcurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($urlcurl, CURLOPT_HTTPGET, 1);
curl_setopt($urlcurl, CURLOPT_HTTPHEADER,
    array("Authorization: OAuth $access_token"));
curl_setopt($urlcurl, CURLOPT_SSL_VERIFYPEER, false);
$urljson_response = curl_exec($urlcurl);
print_r(json_decode($urljson_response));
curl_close($urlcurl);
</code>```

we need to pass the access token like

```<code>curl_setopt($urlcurl, CURLOPT_HTTPHEADER,
    array("Authorization: OAuth $access_token"));
</code>```

and we need to use get method of curl.

```<code>curl_setopt($urlcurl, CURLOPT_HTTPGET, 1);
</code>```

Body:
Hi i need to get the leads from the salesforce through rest api for this i have done so far a successful oauth through rest api and i got a following response

stdClass Object
(
    [access_token] => 1111xxxxxxxx44444444444444
    [instance_url] => https://eu7.salesforce.com
    [id] => https://login.salesforce.com/id/000000000
    [token_type] => Bearer
    [issued_at] => xxxxxxxxxxxx
    [signature] => xxxxxxxxxxxx
)

after that for getting contact leads i am using the below code

$email = 'test_@gmail.com';
$query = 'SELECT Id, Email FROM Lead';
if($email != null){
$query .= sprintf("WHERE Email ='%s'", $email);
}
$url = $instance_url. '/services/data/v33.0/query?q=' . urlencode($query);
$paramsnew = "access_token=$access_token";
$urlcurl = curl_init($url);
curl_setopt($urlcurl, CURLOPT_HEADER, false);
curl_setopt($urlcurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($urlcurl, CURLOPT_POST, true);
curl_setopt($urlcurl, CURLOPT_POSTFIELDS, $paramsnew);
curl_setopt($urlcurl, CURLOPT_SSL_VERIFYPEER, false);
$urljson_response = curl_exec($urlcurl);
echo $urljson_response;
curl_close($urlcurl);

but in response i am getting below

[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]

Please suggest how can i fix this.

Body:
Finally i fixed it by using the below code.

$firstname = 'rohit';
$query = 'SELECT FirstName , LastName ,Id, Email FROM Lead ';
if($firstname != null){
$query .= sprintf("WHERE FirstName ='%s'", $firstname);
}
$url = $instance_url. '/services/data/v33.0/query?q=' . urlencode($query);
$paramsnew = "access_token=$access_token";
$urlcurl = curl_init($url);
curl_setopt($urlcurl, CURLOPT_HEADER, false);
curl_setopt($urlcurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($urlcurl, CURLOPT_HTTPGET, 1);
curl_setopt($urlcurl, CURLOPT_HTTPHEADER,
    array("Authorization: OAuth $access_token"));
curl_setopt($urlcurl, CURLOPT_SSL_VERIFYPEER, false);
$urljson_response = curl_exec($urlcurl);
print_r(json_decode($urljson_response));
curl_close($urlcurl);

we need to pass the access token like

curl_setopt($urlcurl, CURLOPT_HTTPHEADER,
    array("Authorization: OAuth $access_token"));

and we need to use get method of curl.

curl_setopt($urlcurl, CURLOPT_HTTPGET, 1);


问:
GUI Framework for new Windows OSs
Is there any swing like framework for the newer Windows OS's?  Vista and & 7 apps have a different menuing and taskbar thing going and was wondering if there is any GUI components to utilize this new application look for Java.</p>

答:
There is no need to replace the whole of Swing in order to get a new component. You can use the Flamingo component suite to provide a ribbon.

Alternatively you may prefer SWT, which provides a more native look-and-feel in general (i.e. your application will look more like a "normal" Windows Vista/7 application). SWT also has a third-party ribbon component.

Title: GUI Framework for new Windows OSs


问:
Hibernate Search: Store List of Children and retrieve via projection
I have the following 2 classes with hibernate and hibernate search annotations:

Parent Class:

```<code>@Indexed
@Entity
public class Parent {
    @Id
    @Column(name="parent_id")
    private Long id;

    @Field(store = Store.YES)
    private String name;

    @IndexedEmbedded
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", targetEntity = Child.class)
    private List<Child> childList;

    //getters and setters
}
</code>```

Child Class:

```<code>@Entity
public class Child {
    @Id
    private Long id;

    @ManyToOne(targetEntity = Parent.class)
    @ContainedIn
    @JoinColumn(name = "parent_id")
    private Parent parent;

    @Field(store = Store.YES)
    private String name;
}
</code>```

I created an index for the above scenario. Now I am trying to get all the child names by searching a given parent name.

I used projection on the field as follows:

```<code>Query searchQuery = queryBuilder.keyword().onField("name").matching("test").createQuery();
FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(searchQuery, Parent.class);
fullTextQuery.setProjection("childList.name");
</code>```

Now when I try to run the query to retrieve the search results, I am getting the name of only first child of the parent model.

When I see the indexes using Luke, I am able to see all the values in the document.

How to get the list of all the child names stored in index?

答:
In this example you have a model which required "turning around".

Your goal is to query a list child names so you need to search for the Child entity.

You can still include the "parent's name" in each child, and restrict your query on that.

```<code>@Entity @Indexed
public class Child {
...

Query searchQuery = queryBuilder.keyword().onField("parent.name").matching("test").createQuery();
FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(searchQuery, Child.class);
fullTextQuery.setProjection("name");
</code>```

Body:
I have the following 2 classes with hibernate and hibernate search annotations:

Parent Class:

@Indexed
@Entity
public class Parent {
    @Id
    @Column(name="parent_id")
    private Long id;

    @Field(store = Store.YES)
    private String name;

    @IndexedEmbedded
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", targetEntity = Child.class)
    private List<Child> childList;

    //getters and setters
}

Child Class:

@Entity
public class Child {
    @Id
    private Long id;

    @ManyToOne(targetEntity = Parent.class)
    @ContainedIn
    @JoinColumn(name = "parent_id")
    private Parent parent;

    @Field(store = Store.YES)
    private String name;
}

I created an index for the above scenario. Now I am trying to get all the child names by searching a given parent name.

I used projection on the field as follows:

Query searchQuery = queryBuilder.keyword().onField("name").matching("test").createQuery();
FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(searchQuery, Parent.class);
fullTextQuery.setProjection("childList.name");

Now when I try to run the query to retrieve the search results, I am getting the name of only first child of the parent model.

When I see the indexes using Luke, I am able to see all the values in the document.

How to get the list of all the child names stored in index?

Body:
In this example you have a model which required "turning around".

Your goal is to query a list child names so you need to search for the Child entity.

You can still include the "parent's name" in each child, and restrict your query on that.

@Entity @Indexed
public class Child {
...

Query searchQuery = queryBuilder.keyword().onField("parent.name").matching("test").createQuery();
FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(searchQuery, Child.class);
fullTextQuery.setProjection("name");


问:
Reference a constant from one function in another
I am attempting to send user information gathered from the facebookSDK and perform an HTTP POST sending the details I gathered stored in constants.

I am new to swift development and although this solution may be straight forward I am unable to configure a workable solution.

I need to pass the data in the fetchProfile() function into the data_request() function to pass data to the API.

The image shows the data_request function, highlighted is the line where i need to reference the data stored in constants within the fetchProfile() function

This image shows the fetchProfile() function holding the data needed to be passed to data_request()

Any feedback or guidance is greatly appreciated.

答:
Both your function have closures, which means the call back from a async network call. So your main function will finish first, and then when your network call is finished, the closure is called. So in your situation, you need to wait until fetchProfile() finished the async call in order to get data, and then use it in data_request() function. So it will look like

```<code>func fetchProfile(){
    //...
    FBSDKGraphRequest....
        void in
        //prepare your data here
        //call data_request
}
</code>```

Body:
Both your function have closures, which means the call back from a async network call. So your main function will finish first, and then when your network call is finished, the closure is called. So in your situation, you need to wait until fetchProfile() finished the async call in order to get data, and then use it in data_request() function. So it will look like

func fetchProfile(){
    //...
    FBSDKGraphRequest....
        void in
        //prepare your data here
        //call data_request
}


问:
Modify IPublishedContent properties in Umbraco custom controller
First of all, I realise that the core of my problmen probably is the way that I'm trying to solve it, so let me first explain what I'm trying to do.

I have a Layout where I output a property.

Layout.cshtml

```<code>inherits Umbraco.Web.Mvc.UmbracoTemplatePage
...
//More of the layout here

<title>@Model.Content.GetPropertyValue("title")</title>

...
</code>```

This is the base of the other templates:

FullWidth.cshtml

```<code>@{ Layout = "Layout.cshtml"; }
... layout here
</code>```

This all works well, I make sure every document type has a property called title and it gets printed all the time.

Now I'm creating a page, where some data from a database is being displayed. So I created a custom controller:

```<code>public class ProductController : RenderMvcController
{
    public ActionResult Index(Rendermodel model, int id)
    {
          var viewModel = new CustomRenderModel(model.Content);
          viewModel.Product = Database.GetProductById(id);
          return CurrentTemplate(viewModel);
    }

}
</code>```

This works great too, but the next thing I want to do is also set the title based on whatever is retrieved from the database. Something like this:

```<code>var viewModel = new CustomRenderModel(model.Content);
var product = Database.GetProductById(id);
viewModel.Product = product;
viewModel.Content.SetPropertyValue("title", product.name");
</code>```

Obviously this doesnt work because the IPublishedContent is readonly. I'm just wondering what the best way is to modify a property like that.

I realise that exposing a SetPropertyValue is a bad idea probably, but what would be the way to solve this.

答:
I would render this title in a separate partial view and give that partial view a specific model to render.

Have a look at this blog post I wrote which shows you how to do that.
http://www.codeshare.co.uk/blog/how-to-optimise-your-website-for-search-engines-seo-in-umbraco/

Kind regards

Paul

Body:
First of all, I realise that the core of my problmen probably is the way that I'm trying to solve it, so let me first explain what I'm trying to do.

I have a Layout where I output a property.

Layout.cshtml

inherits Umbraco.Web.Mvc.UmbracoTemplatePage
...
//More of the layout here

<title>@Model.Content.GetPropertyValue("title")</title>

...

This is the base of the other templates:

FullWidth.cshtml

@{ Layout = "Layout.cshtml"; }
... layout here

This all works well, I make sure every document type has a property called title and it gets printed all the time.

Now I'm creating a page, where some data from a database is being displayed. So I created a custom controller:

public class ProductController : RenderMvcController
{
    public ActionResult Index(Rendermodel model, int id)
    {
          var viewModel = new CustomRenderModel(model.Content);
          viewModel.Product = Database.GetProductById(id);
          return CurrentTemplate(viewModel);
    }

}

This works great too, but the next thing I want to do is also set the title based on whatever is retrieved from the database. Something like this:

var viewModel = new CustomRenderModel(model.Content);
var product = Database.GetProductById(id);
viewModel.Product = product;
viewModel.Content.SetPropertyValue("title", product.name");

Obviously this doesnt work because the IPublishedContent is readonly. I'm just wondering what the best way is to modify a property like that.

I realise that exposing a SetPropertyValue is a bad idea probably, but what would be the way to solve this.


问:
excel vba finding with like or regex
I'm writing a VBA program.
I have a problem with finding this string [BLOCKED] in one column

```<code>For j = 0 To 4
    For i = 2 To lastrow
        If Cells(i, 12).Value = groupnames(j) And Cells(i, 8).Value Like "*" & "[BLOCKED]" & "*" Then
            groupsum(j) = groupsum(j) + 1
        End If
    Next i
Next j
</code>```

The problem is I have 96 cells for this string but the program found 500 how can I do this to going work?

Thanks for help

答:
here is my code

```<code>Sub blocked()

Dim SfileUsers As String
Dim path As String
Dim pathread As String
Dim sFileread As String
Dim lastrow As Long
Dim keres() As Variant
Dim groupadd() As String
Dim groupnames(4) As String
Dim groupsum(4) As Long

path = "C:\Users\uids9282\Desktop\"
SfileUsers = "Users.xlsx"
Workbooks.Open path & SfileUsers
Dim hossz As Long
hossz = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
ReDim keres(hossz)
ReDim groupadd(hossz)
For i = 2 To hossz
keres(i) = Sheets(1).Cells(i, 2).Value
groupadd(i) = Sheets(1).Cells(i, 4).Value
Next i

'fájlmegnyitás
pathread = "C:\Users\uids9282\Desktop\20170703\"
sFileread = "open.xml"
        If Dir(pathread & sFileread) = sFileread Then
            Workbooks.Open pathread & sFileread
            lastrow = Workbooks(sFileread).Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row

            Else
            MsgBox ("Nincs ilyen nevű excel táblázat. Kérem próbálkozzon újra")
        End If

'groupok hozzáadása a fájlhoz
Dim user As String
For j = 2 To hossz
    For i = 2 To lastrow
    user = Trim(Cells(i, 5).Value)
        If user = keres(j) Then
            Cells(i, 12).Value = groupadd(j)
        End If
    Next i
Next j

'group szummázása és átírása
ThisWorkbook.Activate
For i = 2 To 6
groupnames(i - 2) = Cells(i, 1).Value
Next i
Workbooks(sFileread).Activate
For j = 0 To 4
    For i = 2 To lastrow
        If Cells(i, 12).Value = groupnames(j) And Cells(i, 8).Value Like "*[[]BLOCKED[]]*" Then 'itt van benne a hiba!!         groupsum(j) = groupsum(j) + 1
        End If
    Next i
Next j
ThisWorkbook.Activate
For j = 2 To 6
    Cells(j, 4).Value = groupsum(j - 2)
Next j

Workbooks(SfileUsers).Close SaveChanges:=False
Workbooks(sFileread).Close SaveChanges:=True

End Sub
</code>```

this is my excel file where i want to searching

Title: excel vba finding with like or regex

Body:
I'm writing a VBA program.
I have a problem with finding this string [BLOCKED] in one column

For j = 0 To 4
    For i = 2 To lastrow
        If Cells(i, 12).Value = groupnames(j) And Cells(i, 8).Value Like "*" & "[BLOCKED]" & "*" Then
            groupsum(j) = groupsum(j) + 1
        End If
    Next i
Next j

The problem is I have 96 cells for this string but the program found 500 how can I do this to going work?

Thanks for help

Body:
here is my code

Sub blocked()

Dim SfileUsers As String
Dim path As String
Dim pathread As String
Dim sFileread As String
Dim lastrow As Long
Dim keres() As Variant
Dim groupadd() As String
Dim groupnames(4) As String
Dim groupsum(4) As Long

path = "C:\Users\uids9282\Desktop\"
SfileUsers = "Users.xlsx"
Workbooks.Open path & SfileUsers
Dim hossz As Long
hossz = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
ReDim keres(hossz)
ReDim groupadd(hossz)
For i = 2 To hossz
keres(i) = Sheets(1).Cells(i, 2).Value
groupadd(i) = Sheets(1).Cells(i, 4).Value
Next i

'fájlmegnyitás
pathread = "C:\Users\uids9282\Desktop\20170703\"
sFileread = "open.xml"
        If Dir(pathread & sFileread) = sFileread Then
            Workbooks.Open pathread & sFileread
            lastrow = Workbooks(sFileread).Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row

            Else
            MsgBox ("Nincs ilyen nevű excel táblázat. Kérem próbálkozzon újra")
        End If

'groupok hozzáadása a fájlhoz
Dim user As String
For j = 2 To hossz
    For i = 2 To lastrow
    user = Trim(Cells(i, 5).Value)
        If user = keres(j) Then
            Cells(i, 12).Value = groupadd(j)
        End If
    Next i
Next j

'group szummázása és átírása
ThisWorkbook.Activate
For i = 2 To 6
groupnames(i - 2) = Cells(i, 1).Value
Next i
Workbooks(sFileread).Activate
For j = 0 To 4
    For i = 2 To lastrow
        If Cells(i, 12).Value = groupnames(j) And Cells(i, 8).Value Like "*[[]BLOCKED[]]*" Then 'itt van benne a hiba!!         groupsum(j) = groupsum(j) + 1
        End If
    Next i
Next j
ThisWorkbook.Activate
For j = 2 To 6
    Cells(j, 4).Value = groupsum(j - 2)
Next j

Workbooks(SfileUsers).Close SaveChanges:=False
Workbooks(sFileread).Close SaveChanges:=True

End Sub

this is my excel file where i want to searching


问:
npm init error - cannot create application
Totally new to NodeJS

when trying to create a new application getting the following :
it does not create instead exits with a error log at the location

```<code>H:\app>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (app)

H:\app>
</code>```

Contents of error log :

```<code>0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'init' ]
2 info using npm@3.10.10
3 info using node@v6.11.0
4 verbose stack Error: read EINVAL
4 verbose stack     at exports._errnoException (util.js:1018:11)
4 verbose stack     at TTY.onread (net.js:568:26)
5 verbose cwd H:\app
6 error Windows_NT 6.1.7601
7 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "init"
8 error node v6.11.0
9 error npm  v3.10.10
10 error code EINVAL
11 error errno EINVAL
12 error syscall read
13 error read EINVAL
14 error If you need help, you may report this error at:
14 error     <https://github.com/npm/npm/issues>
15 verbose exit [ 1, true ]
</code>```

any help is much appreciated!

答:
Try this command: npm init - y

By default the command above will create a default package.json at the current directory. It seems there is some problem regarding access. Once the default package.json file is created you can update it afterwards.

Body:
Totally new to NodeJS

when trying to create a new application getting the following :
it does not create instead exits with a error log at the location

H:\app>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (app)

H:\app>

Contents of error log :

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'init' ]
2 info using npm@3.10.10
3 info using node@v6.11.0
4 verbose stack Error: read EINVAL
4 verbose stack     at exports._errnoException (util.js:1018:11)
4 verbose stack     at TTY.onread (net.js:568:26)
5 verbose cwd H:\app
6 error Windows_NT 6.1.7601
7 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "init"
8 error node v6.11.0
9 error npm  v3.10.10
10 error code EINVAL
11 error errno EINVAL
12 error syscall read
13 error read EINVAL
14 error If you need help, you may report this error at:
14 error     <https://github.com/npm/npm/issues>
15 verbose exit [ 1, true ]

any help is much appreciated!


问:
After upgrading XAMPP 5.6 to XAMPP 7.2, I have --> Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in
I have a problem with my result on PHP code after upgrading the XAMPP 5.6 to XAMPP 7.2. in my MacPro.
What is an adjustment to fix the code in PHP script? because they gave me a warning:

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result,
  boolean given in ...

My code:

```<code><?php

include ("../inc/link.php");

    $alert  =   "none";

    if(isset($_POST["btn-login"]))  {
    //echo "Run Action Of Form Login";

    //echo $_POST["username"];
    //echo $_POST["password"];

    $username   = $_POST["username"];
    $password   = $_POST["password"];
    $query          =   mysqli_query($conex,"SELECT * FROM table_admin  WHERE adm_name='".$username."' AND adm_password='".md5($password)."' ");
    $count          = mysqli_num_rows($query);

    echo        $count;

}

?>
</code>```

答:
```<code><?php

$conex = mysqli_connect("localhost","root","","javamartDB") or die ("Can not connect to the database");

    $alert  =   "none";

    if(isset($_POST["btn-login"]))  {
    //echo "Run Action Of Form Login";

    //echo $_POST["username"];
    //echo $_POST["password"];

    $username   = $_POST["username"];
    $password   = $_POST["password"];
    $query      = mysqli_query($conex,"SELECT * FROM table_admin ");
    $count      = mysqli_num_rows($query);
if(mysqli_num_rows($count)>0){
 while($row=  mysqli_fetch_row( $query));
        print_r($row[0],$row[1]);
        die;
}

}

?>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem with my result on PHP code after upgrading the XAMPP 5.6 to XAMPP 7.2. in my MacPro.
What is an adjustment to fix the code in PHP script? because they gave me a warning:

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result,
  boolean given in ...

My code:

<?php

include ("../inc/link.php");

    $alert  =   "none";

    if(isset($_POST["btn-login"]))  {
    //echo "Run Action Of Form Login";

    //echo $_POST["username"];
    //echo $_POST["password"];

    $username   = $_POST["username"];
    $password   = $_POST["password"];
    $query          =   mysqli_query($conex,"SELECT * FROM table_admin  WHERE adm_name='".$username."' AND adm_password='".md5($password)."' ");
    $count          = mysqli_num_rows($query);

    echo        $count;

}

?>


问:
phpmyadmin server conncetion localhost/login.php not posting anything
What is physically wrong with this code.

```<code><?php
require "conn.php";
$user_name = "1234";
$user_pass = "4321";
$mysql_qry = "SELECT * FROM employee_data WHERE username like '$user_name'
&& password like '$user_pass';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result > 0) {
echo "login success";
}
else{
echo "login not success";
}

?>
</code>```

(when I run it on the local host, there is nothing there [localhost/login.php])

答:
You have a missing bracket in if statement after '$result'.
it should be</p>

```<code>if(mysqli_num_rows($result) > 0)
</code>```

Body:
What is physically wrong with this code.

<?php
require "conn.php";
$user_name = "1234";
$user_pass = "4321";
$mysql_qry = "SELECT * FROM employee_data WHERE username like '$user_name'
&& password like '$user_pass';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result > 0) {
echo "login success";
}
else{
echo "login not success";
}

?>

(when I run it on the local host, there is nothing there [localhost/login.php])

Body:
You have a missing bracket in if statement after '$result'.
it should be

if(mysqli_num_rows($result) > 0)


问:
Android SharedPreferences not loading and saving properly
I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.

My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.

Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.

```<code>public SharedPreferences sp;
public Editor e;

public void savethethings(){ //run this when enter is pressed/savew
    EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
    EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
    EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
    EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);

    String introstring = smsintro_hint.getText().toString();
    String bodystring = smsbody_hint.getText().toString();
  String checkboxbodystring = checkboxbody_hint.getText().toString();
  String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();

      e.putString("intro", introstring);
      e.commit(); // you forgot to commit

  if(!bodystring.isEmpty())
  {
      e.putString("body", bodystring);
      e.commit();
  }

  if(!checkboxbodystring.isEmpty())
  {
      e.putString("checkbody", checkboxbodystring);
      e.commit();
  }

  if(!checkboxdescriptionstring.isEmpty())
  {
      e.putString("checkboxdescr", checkboxdescriptionstring);
      e.commit();
  }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.settingmenu);

    //SP
    sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
    // named preferences - get the default ones and finish with it
    e = sp.edit();

    Button tt = (Button)findViewById(R.id.savebutton);
    tt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                finish();

        }
    });

public void save(View view)
{
    //THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
    savethethings();

    this.finish();
    return;
}
</code>```

```<code>public String finishedtext(String userstring)
{

    smsintroduction = (sp.getString("intro", ""));
    smsbody = (sp.getString("body", ""));
    checkboxtext = (sp.getString("checkbody", ""));
    checkboxmessage = (sp.getString("checkboxdescr", ""));

    if(smsintroduction.isEmpty())
    {
        if(smsbody.isEmpty())
        {
            if(checkboxtext.isEmpty())

            {
                if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
                {
                    //Essentially the DEFAULT if they're ALL null
                    smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
                }
            }
        }
    }

    Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();

    String thetext = "";

    thetext = smsintroduction + " " + smsbody + " " + checkboxtext;

    return thetext;
}

public void savethethings(){ //run this when enter is pressed/savew
    EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
    EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
    EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
    EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);

    String introstring = smsintro_hint.getText().toString();
    String bodystring = smsbody_hint.getText().toString();
  String checkboxbodystring = checkboxbody_hint.getText().toString();
  String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();

  //      if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
  //      {
      e.putString("intro", introstring);
      e.commit(); // you forgot to commit

  if(!bodystring.isEmpty())
  {
      e.putString("body", bodystring);
      e.commit();
  }

  if(!checkboxbodystring.isEmpty())
  {
      e.putString("checkbody", checkboxbodystring);
      e.commit();
  }

  if(!checkboxdescriptionstring.isEmpty())
  {
      e.putString("checkboxdescr", checkboxdescriptionstring);
      e.commit();
  }
}
</code>```

答:
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
 Sample code given below.

```<code>public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;

public SessionManager(Context context) {
    this._context = context;
    pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
    editor = pref.edit();
    editor.apply();
}

public void setIntroMessage(String data) {
    editor.putString("intro", data);
    editor.commit();
}

public String getIntroMessage() {
    return pref.getString("intro", null);
}
</code>```

}

Body:
I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.

My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.

Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.

public SharedPreferences sp;
public Editor e;

public void savethethings(){ //run this when enter is pressed/savew
    EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
    EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
    EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
    EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);

    String introstring = smsintro_hint.getText().toString();
    String bodystring = smsbody_hint.getText().toString();
  String checkboxbodystring = checkboxbody_hint.getText().toString();
  String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();

      e.putString("intro", introstring);
      e.commit(); // you forgot to commit

  if(!bodystring.isEmpty())
  {
      e.putString("body", bodystring);
      e.commit();
  }

  if(!checkboxbodystring.isEmpty())
  {
      e.putString("checkbody", checkboxbodystring);
      e.commit();
  }

  if(!checkboxdescriptionstring.isEmpty())
  {
      e.putString("checkboxdescr", checkboxdescriptionstring);
      e.commit();
  }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.settingmenu);

    //SP
    sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
    // named preferences - get the default ones and finish with it
    e = sp.edit();

    Button tt = (Button)findViewById(R.id.savebutton);
    tt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                finish();

        }
    });

public void save(View view)
{
    //THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
    savethethings();

    this.finish();
    return;
}

public String finishedtext(String userstring)
{

    smsintroduction = (sp.getString("intro", ""));
    smsbody = (sp.getString("body", ""));
    checkboxtext = (sp.getString("checkbody", ""));
    checkboxmessage = (sp.getString("checkboxdescr", ""));

    if(smsintroduction.isEmpty())
    {
        if(smsbody.isEmpty())
        {
            if(checkboxtext.isEmpty())

            {
                if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
                {
                    //Essentially the DEFAULT if they're ALL null
                    smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
                }
            }
        }
    }

    Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();

    String thetext = "";

    thetext = smsintroduction + " " + smsbody + " " + checkboxtext;

    return thetext;
}

public void savethethings(){ //run this when enter is pressed/savew
    EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
    EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
    EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
    EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);

    String introstring = smsintro_hint.getText().toString();
    String bodystring = smsbody_hint.getText().toString();
  String checkboxbodystring = checkboxbody_hint.getText().toString();
  String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();

  //      if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
  //      {
      e.putString("intro", introstring);
      e.commit(); // you forgot to commit

  if(!bodystring.isEmpty())
  {
      e.putString("body", bodystring);
      e.commit();
  }

  if(!checkboxbodystring.isEmpty())
  {
      e.putString("checkbody", checkboxbodystring);
      e.commit();
  }

  if(!checkboxdescriptionstring.isEmpty())
  {
      e.putString("checkboxdescr", checkboxdescriptionstring);
      e.commit();
  }
}

Body:
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
 Sample code given below.

public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;

public SessionManager(Context context) {
    this._context = context;
    pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
    editor = pref.edit();
    editor.apply();
}

public void setIntroMessage(String data) {
    editor.putString("intro", data);
    editor.commit();
}

public String getIntroMessage() {
    return pref.getString("intro", null);
}

}


问:
React Native - Async storage information is extracted after componentWillMount()
I am storing if a checkbox is checked or not using AsyncStorage. When I reload the app, I see from logs that inside the asynchronous variable the correct information is stored. But, it is loaded after componentWillMount. Because of that, the checkbox does not appear checked, as it should be.

I think a good workaround will be to change the checkbox properties inside the asynchronous function. Do you think that would be a good solution? Do you have other suggestions for showing the correct checkbox value?

My code:

```<code>constructor(props) {
    super(props)
    this.state = {isChecked: false}
    this.switchStatus = this.switchStatus.bind(this)
  }

  async getCache(key) {
    try {
      const status = await AsyncStorage.getItem(key);
      if (status == null)
        status = false
      console.log("my async status is " + status)
      return status
    } catch(error) {
      console.log("error", e)
    }
  }

  componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString()
    this.getCache = this.getCache.bind(this)
    this.setState({isChecked: (this.getCache(key) == 'true')})
    console.log("my state is" + this.state.isChecked)
  }

  switchStatus () {
    const newStatus = this.state.isChecked == false ? true : false
    AsyncStorage.setItem("status_" + this.props.data.id.toString(), newStatus.toString());
    console.log("hi my status is " + newStatus)
    this.setState({isChecked: newStatus})
  }

  render({ data, onPress} = this.props) {
    const {id, title, checked} = data
    return (
      <ListItem button onPress={onPress}>
        <CheckBox
          style={{padding: 1}}
          onPress={(this.switchStatus}
          checked={this.state.isChecked}
        />
        <Body>
          <Text>{title}</Text>
        </Body>
        <Right>
          <Icon name="arrow-forward" />
        </Right>
      </ListItem>
    )
  }
</code>```

There is no difference if I put everything in componentWillMount in the constructor.

答:
Thank you for your answers. I am pretty sure await will work too, but I solved the problem before getting an answer. What I did was set the state to false in the beginning, and then update it in getCache. This way, it will always be set after getting the information from the local phone storage.</p>

```<code>async getCache(key) {
    try {
      let status = await AsyncStorage.getItem(key);
      if (status == null) {
        status = false
      }
      this.setState({ isChecked: (status == 'true') })
    } catch(e) {
      console.log("error", e);
    }
  }
</code>```

Body:
I am storing if a checkbox is checked or not using AsyncStorage. When I reload the app, I see from logs that inside the asynchronous variable the correct information is stored. But, it is loaded after componentWillMount. Because of that, the checkbox does not appear checked, as it should be.

I think a good workaround will be to change the checkbox properties inside the asynchronous function. Do you think that would be a good solution? Do you have other suggestions for showing the correct checkbox value?

My code:

constructor(props) {
    super(props)
    this.state = {isChecked: false}
    this.switchStatus = this.switchStatus.bind(this)
  }

  async getCache(key) {
    try {
      const status = await AsyncStorage.getItem(key);
      if (status == null)
        status = false
      console.log("my async status is " + status)
      return status
    } catch(error) {
      console.log("error", e)
    }
  }

  componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString()
    this.getCache = this.getCache.bind(this)
    this.setState({isChecked: (this.getCache(key) == 'true')})
    console.log("my state is" + this.state.isChecked)
  }

  switchStatus () {
    const newStatus = this.state.isChecked == false ? true : false
    AsyncStorage.setItem("status_" + this.props.data.id.toString(), newStatus.toString());
    console.log("hi my status is " + newStatus)
    this.setState({isChecked: newStatus})
  }

  render({ data, onPress} = this.props) {
    const {id, title, checked} = data
    return (
      <ListItem button onPress={onPress}>
        <CheckBox
          style={{padding: 1}}
          onPress={(this.switchStatus}
          checked={this.state.isChecked}
        />

          <Text>{title}</Text>

        <Right>
          <Icon name="arrow-forward" />
        </Right>
      </ListItem>
    )
  }

There is no difference if I put everything in componentWillMount in the constructor.

Body:
Thank you for your answers. I am pretty sure await will work too, but I solved the problem before getting an answer. What I did was set the state to false in the beginning, and then update it in getCache. This way, it will always be set after getting the information from the local phone storage.

async getCache(key) {
    try {
      let status = await AsyncStorage.getItem(key);
      if (status == null) {
        status = false
      }
      this.setState({ isChecked: (status == 'true') })
    } catch(e) {
      console.log("error", e);
    }
  }


问:
Getting error : Unable to Use Amazon Authorization Manager. APIKey is incorrect or does not exist
I am trying to use Amazon Alexa in my android App.
I have added api_key.txt in my asset folder but still getting above error.</p>

答:
the api_key should be generated from the android developer site withe the MD5 and SHA-256 of your application then only it will work properly. Check the link for detailed information.
https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/getting-started-with-the-alexa-voice-service</p>


问:
HTML select option set selected default echo get value php
I have a simple HTML form with a simple select like this

```<code><select name="myselect"  selected="<?php echo $_GET['brand'];?>">

<option value="" <?php if($brand== "") echo "selected"; ?>>all brands</option>
<option value="samsung" <?php if($brand== "samsung") echo "selected"; ?>>Samsung</option>
<option value="motorola" <?php if($brand== "motorola") echo "selected"; ?>>Motorola</option>

</select>
</code>```

What I am trying to do is because its a search filtering results form if the user choose Samsung as default brand to search next page with filteres search results will the select option default selected Samsung and no other. If user select to search Motorola then the selected option default will be Motorola.

How do I fix this?

答:
```<code><?php $selected_brand = $_GET['brand'];

$temp_str = '';
$temp_str .= '<select name="myselect">';

$brands_array = array("all" => "all brands", "samsung" => "Samsung", "motorola" => "Motorola");
    foreach ($brands_array as $key => $value) {
        if($key == $selected_brand){
            // For selected option.
            $temp_str .= '<option value="'.$key.'" selected>'.$value.'</option>';
        } else {
            $temp_str .= '<option value="'.$key.'">'.$value.'</option>';
        }
    }

$temp_str .= '</select>';

echo $temp_str; // Select box.
?>
</code>```

Body:
I have a simple HTML form with a simple select like this

<select name="myselect"  selected="<?php echo $_GET['brand'];?>">

<option value="" <?php if($brand== "") echo "selected"; ?>>all brands</option>
<option value="samsung" <?php if($brand== "samsung") echo "selected"; ?>>Samsung</option>
<option value="motorola" <?php if($brand== "motorola") echo "selected"; ?>>Motorola</option>

</select>

What I am trying to do is because its a search filtering results form if the user choose Samsung as default brand to search next page with filteres search results will the select option default selected Samsung and no other. If user select to search Motorola then the selected option default will be Motorola.

How do I fix this?


问:
How to modify python module content?
I have file named config.py, content like below:

```<code>logindata = [
  {'user': '18320967034', 'password': '123456'}
]
</code>```

I wanna modify the logindata and write it back,

```<code>import config
config.logindata[0]['password'] = 'xxxx'
</code>```

How can I write it back to config.py?

Please don't tell me to use .ini/configparser

答:
If you are absolutely dead set on doing this you will likely need to hack this together. You can do something like the following

```<code>import json
import config

with open("config.py", "w") as config:
    config.logindata[0]['password'] = 'xxxx'
    code = "logindata = " + json.dumps(config.logindata)
    config.write(code)
</code>```

I just want to say that doing this is really hacky and is not a good way to be doing this. But I don't know any other way to do this without using a proper saving and loading protocol.

Title: How to modify python module content?

Body:
I have file named config.py, content like below:

logindata = [
  {'user': '18320967034', 'password': '123456'}
]

I wanna modify the logindata and write it back,

import config
config.logindata[0]['password'] = 'xxxx'

How can I write it back to config.py?

Please don't tell me to use .ini/configparser

Body:
If you are absolutely dead set on doing this you will likely need to hack this together. You can do something like the following

import json
import config

with open("config.py", "w") as config:
    config.logindata[0]['password'] = 'xxxx'
    code = "logindata = " + json.dumps(config.logindata)
    config.write(code)

I just want to say that doing this is really hacky and is not a good way to be doing this. But I don't know any other way to do this without using a proper saving and loading protocol.


问:
Make Qlabel clickable or double clickable in Qt
I am beginner in Qt, now I want to make my label clickable, I have searched so much online, but no one gives my a real example of how they made it. So can someone teach me step by step? Now my basic thinking is creating a new .c file and new .h file respectively and then include them into my mainwindow.c and then connect it with the existing label in ui form. These are what I was trying to do, but can not make it. Hope someone can teach and better put the step picture in the command, thanks.
Here is the clicklabel.h code:

```<code>#ifndef CLICKEDLABEL_H
#define CLICKEDLABEL_H

#include <QWidget>
#include <QLabel>

class ClickedLabel : public QLabel
{
    Q_OBJECT
public:
    ClickedLabel(QWidget *parent=0): QLabel(parent){}
    ~ClickedLabel() {}
signals:
    void clicked(ClickedLabel* click);
protected:
    void mouseReleaseEvent(QMouseEvent*);
};

#endif // CLICKEDLABEL_H
</code>```

This the clicklabel.c code:

```<code>#include "clicklabel.h"
void ClickedLabel::mouseReleaseEvent(QMouseEvent *)
{
    emit clicked(this);
}
</code>```

These are what I added into my mainwindow.c( the name of the label is click_test):

```<code>void data_labeling::on_label_clicked()
{
    QString path="/home/j/Pictures/images.jpeg";
    QPixmap cat(path);
    connect(ui->click_test, SIGNAL(clicked()), this,
SLOT(on_label_clicked()));
    ui->click_test->setPixmap(cat);
    ui->click_test->resize(cat.width(),cat.height());

}
</code>```

Of course I have promoted it to clicklabel.h and also I have added void on_label_click() to my mainwindow.h under private slots, but nothing happened.

答:
Create a new class derived from QLabel, reimplement mousePressEvent to emit custom pressed() signal (or any other functionality you need)

If you need to use your clickable label in ui files, follow these steps:

Add QLabel to the form

Right-click on added label and select Promote to...

Enter your clickable label class name and its header file name

Press add, than select your label in the tree and select promote

Now you can use your subclassed label (this tutorial actually works for any subclassed widget) as any QWidget using ui->

Body:
I am beginner in Qt, now I want to make my label clickable, I have searched so much online, but no one gives my a real example of how they made it. So can someone teach me step by step? Now my basic thinking is creating a new .c file and new .h file respectively and then include them into my mainwindow.c and then connect it with the existing label in ui form. These are what I was trying to do, but can not make it. Hope someone can teach and better put the step picture in the command, thanks.
Here is the clicklabel.h code:

#ifndef CLICKEDLABEL_H
#define CLICKEDLABEL_H

#include <QWidget>
#include <QLabel>

class ClickedLabel : public QLabel
{
    Q_OBJECT
public:
    ClickedLabel(QWidget *parent=0): QLabel(parent){}
    ~ClickedLabel() {}
signals:
    void clicked(ClickedLabel* click);
protected:
    void mouseReleaseEvent(QMouseEvent*);
};

#endif // CLICKEDLABEL_H

This the clicklabel.c code:

#include "clicklabel.h"
void ClickedLabel::mouseReleaseEvent(QMouseEvent *)
{
    emit clicked(this);
}

These are what I added into my mainwindow.c( the name of the label is click_test):

void data_labeling::on_label_clicked()
{
    QString path="/home/j/Pictures/images.jpeg";
    QPixmap cat(path);
    connect(ui->click_test, SIGNAL(clicked()), this,
SLOT(on_label_clicked()));
    ui->click_test->setPixmap(cat);
    ui->click_test->resize(cat.width(),cat.height());

}

Of course I have promoted it to clicklabel.h and also I have added void on_label_click() to my mainwindow.h under private slots, but nothing happened.


问:
Minecraft Chat Message Replacement
I am making a permissions plugin, and want to replace the name of a player with their rank tag. For this, I have the following code:

```<code>public void playerChat(AsyncPlayerChatEvent e) {
    Player target = e.getPlayer();

    String message = e.getMessage().replaceAll(target.getName(), colorize(rFile.getString("players." + target)) + " " + target.getName());
    e.setMessage(message);
}
</code>```

Whenever I send a message to chat, it appears like it would normally.
What am I doing wrong here?

Additionally, I am using a config file (cFile) and a ranks.yml file (rFile).

答:
First off, make sure you include the @EventHandler annotation.

```<code>@EventHandler
public void playerChat(AsyncPlayerChatEvent e) {
   [...]
}
</code>```

Next, check if the listener is registered in your onEnable()method.
getServer().getPluginManager().registerEvents(new YourListener(...), this);

(Replace the YourListener with this in case it's your main class)

Finally, as Luftbaum said, use AsyncPlayerChatEvent#setFormat within the event.
Example Usage:

```<code> e.setFormat(colorize(rFile.getString("players." + target)) + ": " + e.getMessage());
</code>```

Edit:

In order to translate color codes such as '&3' to Bukkit's ChatColor format, you can use the ChatColor#translateAlternativeColorCodes method.

```<code>ChatColor.translateAlternateColorCodes('&', stringThatContainsCodes);
</code>```

Title: Minecraft Chat Message Replacement

Body:
I am making a permissions plugin, and want to replace the name of a player with their rank tag. For this, I have the following code:

public void playerChat(AsyncPlayerChatEvent e) {
    Player target = e.getPlayer();

    String message = e.getMessage().replaceAll(target.getName(), colorize(rFile.getString("players." + target)) + " " + target.getName());
    e.setMessage(message);
}

Whenever I send a message to chat, it appears like it would normally.
What am I doing wrong here?

Additionally, I am using a config file (cFile) and a ranks.yml file (rFile).

Body:
First off, make sure you include the @EventHandler annotation.

@EventHandler
public void playerChat(AsyncPlayerChatEvent e) {
   [...]
}

Next, check if the listener is registered in your onEnable()method.
getServer().getPluginManager().registerEvents(new YourListener(...), this);

(Replace the YourListener with this in case it's your main class)

Finally, as Luftbaum said, use AsyncPlayerChatEvent#setFormat within the event.
Example Usage:

 e.setFormat(colorize(rFile.getString("players." + target)) + ": " + e.getMessage());

Edit:

In order to translate color codes such as '&3' to Bukkit's ChatColor format, you can use the ChatColor#translateAlternativeColorCodes method.

ChatColor.translateAlternateColorCodes('&', stringThatContainsCodes);