问:
Why am I not able to call this method after I push a button?
I'm using a pushbutton as a toggle switch. Press it and it does "stuff A." Press it again and it does "stuff B." Why am I not able to call my method checkButtons_slow()?

```<code>int prev = 0;
int current = 0;
int val4 = 0;
int val5 = 0;
int ledPin = 13;
int prev = 0;
int current = 0;

Servo ZServo;

void setup() {
  ZServo.attach(9);
  pinMode(pushD3, INPUT_PULLUP);
  digitalWrite(3, HIGH);
  pinMode(pushD4, INPUT_PULLUP);
  digitalWrite(4, HIGH);
  pinMode(pushD5, INPUT_PULLUP);
  digitalWrite(5, HIGH);
  pinMode(pushD6, INPUT_PULLUP);
  digitalWrite(6, HIGH);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if(digitalRead(3) == LOW) {
    current = 1 - current;
  }
  if(current == 1 && prev == 0) {
    checkButtons_slow();
    //test: ZServo.write(110);
    delay(500); //half a second
  }
  if(current == 0 && prev == 1) {
    ZServo.write(80);
    delay(500); //half a second
  }
  prev = current;
}
</code>```

Here's my method:

```<code>void checkButtons_slow() {
  val4 = digitalRead(pushD4);
  val5 = digitalRead(pushD5);
  if (val4 == LOW) {
    ZServo.write(88);
  } else if (val5 == LOW) {
    ZServo.write(99);
  } else {
    ZServo.write(91); //GUESSED ON 92; SHOULD TECHNICALLY BE 90
  }
}
</code>```

So the commented out //test: ZServo.write(110); works. What am I missing with the checkButtons_slow();?

答:
If you change void loop() to this then it will work to toggle the method on and off.

```<code>void loop() {
  if (digitalRead(3) == LOW) {
    num_presses++;
    delay(500);
  }
  if ((num_presses % 2) == 0) {
    //even
    checkButtons_slow();
  }
  else if(num_presses == 0) {
    ZServo.write(90);
  }
  else {
    ZServo.write(85);
  }
}
</code>```

Body:
I'm using a pushbutton as a toggle switch. Press it and it does "stuff A." Press it again and it does "stuff B." Why am I not able to call my method checkButtons_slow()?

int prev = 0;
int current = 0;
int val4 = 0;
int val5 = 0;
int ledPin = 13;
int prev = 0;
int current = 0;

Servo ZServo;

void setup() {
  ZServo.attach(9);
  pinMode(pushD3, INPUT_PULLUP);
  digitalWrite(3, HIGH);
  pinMode(pushD4, INPUT_PULLUP);
  digitalWrite(4, HIGH);
  pinMode(pushD5, INPUT_PULLUP);
  digitalWrite(5, HIGH);
  pinMode(pushD6, INPUT_PULLUP);
  digitalWrite(6, HIGH);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if(digitalRead(3) == LOW) {
    current = 1 - current;
  }
  if(current == 1 && prev == 0) {
    checkButtons_slow();
    //test: ZServo.write(110);
    delay(500); //half a second
  }
  if(current == 0 && prev == 1) {
    ZServo.write(80);
    delay(500); //half a second
  }
  prev = current;
}

Here's my method:

void checkButtons_slow() {
  val4 = digitalRead(pushD4);
  val5 = digitalRead(pushD5);
  if (val4 == LOW) {
    ZServo.write(88);
  } else if (val5 == LOW) {
    ZServo.write(99);
  } else {
    ZServo.write(91); //GUESSED ON 92; SHOULD TECHNICALLY BE 90
  }
}

So the commented out //test: ZServo.write(110); works. What am I missing with the checkButtons_slow();?

Body:
If you change void loop() to this then it will work to toggle the method on and off.

void loop() {
  if (digitalRead(3) == LOW) {
    num_presses++;
    delay(500);
  }
  if ((num_presses % 2) == 0) {
    //even
    checkButtons_slow();
  }
  else if(num_presses == 0) {
    ZServo.write(90);
  }
  else {
    ZServo.write(85);
  }
}


来源: stackexchange

问:
Xcode Instruments - Allocations missing window
I'm running Xcode 8.3.1 and I'm having some trouble figuring out how to get this window in Allocations:
 .

The one I have looks like this:

答:
This is no longer in the right panel in Instruments. It is now located under "Recording Options..." on Instruments' "File" menu, yielding:

And the "Mark generation" is located at the bottom of the window while the profiling is taking place, having selected "Details" » "Generations" in the main panel while the "Allocations" tool is selected:

ContentLicense: CC BY-SA 3.0


问:
Converting C# Lambda to VB.NET
I'm trying to convert the following C# code to VB.NET. The issue is with the lambda expression.

```<code>public class UserStore
{
    private readonly IDatabaseFactory _databaseFactory;

    private DataContext _db;
    protected DataContext Db => _db ?? (_db = _databaseFactory.GetDataContext());

    public UserStore(IDatabaseFactory databaseFactory)
    {
        _databaseFactory = databaseFactory;
    }
}
</code>```

The following is what I've converted the code to:

```<code>Public Class UserStore
    Private ReadOnly _databaseFactory As IDatabaseFactory

    Private _db As DataContext
    Protected Db As DataContext = Function() As DataContext
                                     If _db Is Nothing Then
                                         _db = _databaseFactory.GetDataContext()
                                     End If
                                     Return _db
                                  End Function

    Public Sub New(databaseFactory As IDatabaseFactory)
        _databaseFactory = databaseFactory
    End Sub
End Class
</code>```

For some reason, the converted lambda gives the error Lambda expression cannot be converted to 'DataContext' because 'DataContext' is not a delegate type.

Can anybody tell me what I'm doing wrong here?

答:
I'm trying to convert the following C# code to VB.NET. The issue is with the lambda expression.

The issue is that you've mistaken an expression-bodied property for a lambda.

In C#

```<code>protected DataContext Db => _db ?? (_db = _databaseFactory.GetDataContext());
</code>```

is a short way of writing

```<code>protected DataContext Db {
  get
  {
    return _db ?? (_db = _databaseFactory.GetDataContext());
  }
}
</code>```

It's not a lambda at all; if you want to translate this to VB, just write a normal VB property getter.

Note that C# allows you to do this trick with methods as well:

```<code>public Abc Foo(Bar bar) => Blah(bar);
</code>```

is just a short way of writing

```<code>public Abc Foo(Bar bar)
{
  return Blah(bar);
}
</code>```

Title: Converting C# Lambda to VB.NET

Body:
I'm trying to convert the following C# code to VB.NET. The issue is with the lambda expression.

public class UserStore
{
    private readonly IDatabaseFactory _databaseFactory;

    private DataContext _db;
    protected DataContext Db => _db ?? (_db = _databaseFactory.GetDataContext());

    public UserStore(IDatabaseFactory databaseFactory)
    {
        _databaseFactory = databaseFactory;
    }
}

The following is what I've converted the code to:

Public Class UserStore
    Private ReadOnly _databaseFactory As IDatabaseFactory

    Private _db As DataContext
    Protected Db As DataContext = Function() As DataContext
                                     If _db Is Nothing Then
                                         _db = _databaseFactory.GetDataContext()
                                     End If
                                     Return _db
                                  End Function

    Public Sub New(databaseFactory As IDatabaseFactory)
        _databaseFactory = databaseFactory
    End Sub
End Class

For some reason, the converted lambda gives the error Lambda expression cannot be converted to 'DataContext' because 'DataContext' is not a delegate type.

Can anybody tell me what I'm doing wrong here?

Body:
I'm trying to convert the following C# code to VB.NET. The issue is with the lambda expression.

The issue is that you've mistaken an expression-bodied property for a lambda.

In C#

protected DataContext Db => _db ?? (_db = _databaseFactory.GetDataContext());

is a short way of writing

protected DataContext Db {
  get
  {
    return _db ?? (_db = _databaseFactory.GetDataContext());
  }
}

It's not a lambda at all; if you want to translate this to VB, just write a normal VB property getter.

Note that C# allows you to do this trick with methods as well:

public Abc Foo(Bar bar) => Blah(bar);

is just a short way of writing

public Abc Foo(Bar bar)
{
  return Blah(bar);
}


问:
Test case neither passes nor fails in VS
In VS Express 2013, I run the following program against certain test cases written in a spec file. The code and a portion of the spec file is as follows:

```<code>struct DOB {
    int date;
    int month;
    int year;
};

int stringToValue(char* temp) {
    int num = 0;
    while (*temp != '-' && *temp != '\0') {
        if (((*temp) >= '0') && ((*temp) <= '9')) {
            num = num * 10 + ((*temp) - '0');
            ++temp;
        }
    }
    return num;
}

int isValidFormat(char* dob) {
    int length = 0;
    for (int i = 0; dob[i] != '\0'; ++i) {
        if (!((dob[i] >= '0' && dob[i] <= '9' || dob[i] == '-')))
            return 0;
        ++length;
    }
    return length;
}

int function(int value1, int value2) {
    if (value1>value2) {
        return 2;
    }

    else if (value1<value2) {
        return 1;
    }
    else
        return 0;
}

int isLeap(int year) {
    if ((year % 4 == 0) && !(year % 100)) {
        return 1;
    }

    else {
        if (year % 400 == 0)
            return 1;
        else
            return 0;
    }
}

int isValid(struct DOB d) {
    if (d.year>0) {
        if (d.month>0 && d.month <= 12) {
            if (d.month == 2 && isLeap(d.year) == 1) {
                if (d.date>0 && d.date <= 29) {
                    return 1;
                }
                else if (d.date > 0 && d.date <= 28) {
                    return 1;
                }
                else
                    return 0;
            }
            else if (d.date == 1 || d.date == 3 || d.date == 5 || d.date == 7 || d.date == 8 || d.date == 10 || d.date == 12){
                if (d.date > 0 && d.date <= 31) {
                    return 1;
                }
                else
                    return 0;
            }
            else {
                if (d.date > 0 && d.date <= 30) {
                    return 1;
                }
                else
                    return 0;
            }
        }
        else {
            return 0;
        }
    }
    else {
        return 0;
    }
}

int isOlder(char* dob1, char* dob2) {
    struct DOB d1, d2;

    if (isValidFormat(dob1)!= 10 && isValidFormat(dob2) != 10)
        return -1;

    d1.date = stringToValue(dob1);
    d2.date = stringToValue(dob2);
    d1.month = stringToValue(dob1 + 3);
    d2.month = stringToValue(dob2 + 3);
    d1.year = stringToValue(dob1 + 6);
    d2.year = stringToValue(dob2 + 6);

    if (isValid(d1) == 1 && isValid(d2) == 1) {
        if (function(d1.year, d2.year) != 0)
            return function(d1.year, d2.year);
        else if (function(d1.month, d2.month) != 0)
            return function(d1.month, d2.month);
        else
            return function(d1.date, d2.date);
    }

    else {
        return -1;
    }
}
</code>```

In the spec file containing test cases:

```<code>TEST_METHOD(isOlderinvalid)
                {
                    Assert::AreEqual(-1, isOlder("1000", "15-07-2000"), L"isOlder: invalid input case failed", LINE_INFO());
                    Assert::AreEqual(-1, isOlder("15-07-2000", "000"), L"isOlder: invalid input case failed", LINE_INFO());
                    Assert::AreEqual(-1, isOlder("15-0A-2000", "15-07-2000"), L"isOlder: invalid input case failed", LINE_INFO());
                    Assert::AreEqual(-1, isOlder("15-13-2000", "15-07-2000"), L"isOlder: invalid input case failed", LINE_INFO());
                    Assert::AreEqual(-1, isOlder("29-02-2001", "15-07-2000"), L"isOlder: invalid input case failed", LINE_INFO());
                }
</code>```

When I run the following test cases on my local compiler, I get the expected output. But when I run the tests on the above code, I neither pass nor fail the above test cases. I'm honestly not sure what's wrong. It seems like a VS-specific problem rather than a problem with my code.

答:
Wrong error condition

```<code>// if (isValidFormat(dob1)!= 10 && isValidFormat(dob2) != 10)
if (isValidFormat(dob1)!= 10 || isValidFormat(dob2) != 10)
    return -1;
</code>```

When only 1 format was invalid, code called weak function stringToValue() which has an infinite loop with invalid input.

```<code>int stringToValue(char* temp) {
    int num = 0;
    while (*temp != '-' && *temp != '\0') {
        if (((*temp) >= '0') && ((*temp) <= '9')) {
            num = num * 10 + ((*temp) - '0');
            ++temp;  //  Move this to outside `if()` test
        }
    }
    return num;
}
</code>```

Perhaps additional problems.

Unclear how code "worked" on OP's local compiler.  Maybe Assert() was not active.

Body:
In VS Express 2013, I run the following program against certain test cases written in a spec file. The code and a portion of the spec file is as follows:

struct DOB {
    int date;
    int month;
    int year;
};

int stringToValue(char* temp) {
    int num = 0;
    while (*temp != '-' && *temp != '\0') {
        if (((*temp) >= '0') && ((*temp) <= '9')) {
            num = num * 10 + ((*temp) - '0');
            ++temp;
        }
    }
    return num;
}

int isValidFormat(char* dob) {
    int length = 0;
    for (int i = 0; dob[i] != '\0'; ++i) {
        if (!((dob[i] >= '0' && dob[i] <= '9' || dob[i] == '-')))
            return 0;
        ++length;
    }
    return length;
}

int function(int value1, int value2) {
    if (value1>value2) {
        return 2;
    }

    else if (value1<value2) {
        return 1;
    }
    else
        return 0;
}

int isLeap(int year) {
    if ((year % 4 == 0) && !(year % 100)) {
        return 1;
    }

    else {
        if (year % 400 == 0)
            return 1;
        else
            return 0;
    }
}

int isValid(struct DOB d) {
    if (d.year>0) {
        if (d.month>0 && d.month <= 12) {
            if (d.month == 2 && isLeap(d.year) == 1) {
                if (d.date>0 && d.date <= 29) {
                    return 1;
                }
                else if (d.date > 0 && d.date <= 28) {
                    return 1;
                }
                else
                    return 0;
            }
            else if (d.date == 1 || d.date == 3 || d.date == 5 || d.date == 7 || d.date == 8 || d.date == 10 || d.date == 12){
                if (d.date > 0 && d.date <= 31) {
                    return 1;
                }
                else
                    return 0;
            }
            else {
                if (d.date > 0 && d.date <= 30) {
                    return 1;
                }
                else
                    return 0;
            }
        }
        else {
            return 0;
        }
    }
    else {
        return 0;
    }
}

int isOlder(char* dob1, char* dob2) {
    struct DOB d1, d2;

    if (isValidFormat(dob1)!= 10 && isValidFormat(dob2) != 10)
        return -1;

    d1.date = stringToValue(dob1);
    d2.date = stringToValue(dob2);
    d1.month = stringToValue(dob1 + 3);
    d2.month = stringToValue(dob2 + 3);
    d1.year = stringToValue(dob1 + 6);
    d2.year = stringToValue(dob2 + 6);

    if (isValid(d1) == 1 && isValid(d2) == 1) {
        if (function(d1.year, d2.year) != 0)
            return function(d1.year, d2.year);
        else if (function(d1.month, d2.month) != 0)
            return function(d1.month, d2.month);
        else
            return function(d1.date, d2.date);
    }

    else {
        return -1;
    }
}

In the spec file containing test cases:

TEST_METHOD(isOlderinvalid)
                {
                    Assert::AreEqual(-1, isOlder("1000", "15-07-2000"), L"isOlder: invalid input case failed", LINE_INFO());
                    Assert::AreEqual(-1, isOlder("15-07-2000", "000"), L"isOlder: invalid input case failed", LINE_INFO());
                    Assert::AreEqual(-1, isOlder("15-0A-2000", "15-07-2000"), L"isOlder: invalid input case failed", LINE_INFO());
                    Assert::AreEqual(-1, isOlder("15-13-2000", "15-07-2000"), L"isOlder: invalid input case failed", LINE_INFO());
                    Assert::AreEqual(-1, isOlder("29-02-2001", "15-07-2000"), L"isOlder: invalid input case failed", LINE_INFO());
                }

When I run the following test cases on my local compiler, I get the expected output. But when I run the tests on the above code, I neither pass nor fail the above test cases. I'm honestly not sure what's wrong. It seems like a VS-specific problem rather than a problem with my code.

Body:
Wrong error condition

// if (isValidFormat(dob1)!= 10 && isValidFormat(dob2) != 10)
if (isValidFormat(dob1)!= 10 || isValidFormat(dob2) != 10)
    return -1;

When only 1 format was invalid, code called weak function stringToValue() which has an infinite loop with invalid input.

int stringToValue(char* temp) {
    int num = 0;
    while (*temp != '-' && *temp != '\0') {
        if (((*temp) >= '0') && ((*temp) <= '9')) {
            num = num * 10 + ((*temp) - '0');
            ++temp;  //  Move this to outside `if()` test
        }
    }
    return num;
}

Perhaps additional problems.

Unclear how code "worked" on OP's local compiler.  Maybe Assert() was not active.


问:
Fitting multimodal distrubtions
Let's assume we're having a linear combination of two normal distributions. I think one would call the result a multimodal distribution.

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

ls = np.linspace(0, 60, 1000)

distribution = norm.pdf(ls, 0, 5) + norm.pdf(ls, 20, 10)
distribution = (distribution * 1000).astype(int)
distribution = distribution/distribution.sum()

plt.plot(ls, distribution)
</code>```

As you can see, we are having a linear combination of two normal distributions having parameters (mu1 = 0, s1 = 5) and (mu2 = 20, s2 = 10). But of course, we usually do not know these parameters beforehand.

I would like to know how I can estimate or fit those parameters (mus and sigmas). I am confident there are methods that would allow to do this but I couldn't find any yet.

答:
You might want to use the Expectation Maximization algorithm.

It is an iterative approach that allows you to fit a model of mixture components.
There is a very convenient implementation in scikit-learn: GaussianMixture

I found it hard to figure out how to structure the data for this algorithm to work, so I set up a sample for you:
https://nbviewer.jupyter.org/gist/lhk/e566e2d6b67992eca062f9d96e2a14a2

ContentLicense: CC BY-SA 4.0

Title: Fitting multimodal distrubtions

Body:
Let's assume we're having a linear combination of two normal distributions. I think one would call the result a multimodal distribution.

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

ls = np.linspace(0, 60, 1000)

distribution = norm.pdf(ls, 0, 5) + norm.pdf(ls, 20, 10)
distribution = (distribution * 1000).astype(int)
distribution = distribution/distribution.sum()

plt.plot(ls, distribution)

As you can see, we are having a linear combination of two normal distributions having parameters (mu1 = 0, s1 = 5) and (mu2 = 20, s2 = 10). But of course, we usually do not know these parameters beforehand.

I would like to know how I can estimate or fit those parameters (mus and sigmas). I am confident there are methods that would allow to do this but I couldn't find any yet.


问:
XAML how to make a textblock/text box edit toggle?
I may be approaching this all wrong, so tell me if you have an alternative suggestions.

I'm making an app for windows RT that will have a bunch of text blocks displayed to the user, for example character stats.
The user will see:

```
Str: 10
Con: 10
Dex: 10
```

and so on.

I want them to be able to fill these in, then have a select view values calculated based on the result.

My though was to click an "Edit" button at the top and toggle some text boxes over each editable text block.

When trying to set this up using "Blend for Visual Studio" I can't seem to make a text box that is smaller than 49x34 (much larger than my text blocks).

I was going to find a way to generate a text box for each text block (using its dimensions) on button click, but since they will always be the same and there will be a lot of them I was trying to make them static via blend.

I'm pretty new to XAML, and I can't seem to find a good example of people setting up editable fields like this, so how should I make a bunch of static fields have editable text boxes?

答:
This builds off of BTownTKD's solution, but as I really do prefer as much WPF of a solution as possible here is a bit of a modification, in my case I'm trying to modify the name of a tab control.

My view model has the following code:

```<code>    private bool _isEditingName = false;

    public bool IsEditingName
    {
        get
        {
            return _isEditingName;
        }
        set
        {
            _isEditingName = value;
            OnPropertyChanged();
        }
    }

    public ICommand StartEditing
    {
        get
        {
            return new DelegateCommand(() =>
            {
                IsEditingName = true;
            });
        }
    }

    public ICommand EndEditing
    {
        get
        {
            return new DelegateCommand(() =>
            {
                IsEditingName = false;
            });
        }
    }
</code>```

Next is my view that has the data template for the tab (not the content just the tab):

```<code><TabControl ItemsSource="{Binding Items}" SelectedItem="{Binding ActiveItem}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <Grid VerticalAlignment="Center">
                <TextBlock x:Name="TabName" Text="{Binding Name}" Visibility="{Binding IsEditingName, Converter={StaticResource InvertedBoolToVisConverter}}" VerticalAlignment="Center" HorizontalAlignment="Stretch" TextAlignment="Left">
                    <TextBlock.InputBindings>
                        <MouseBinding MouseAction="LeftDoubleClick" Command="{Binding StartEditing}" />
                    </TextBlock.InputBindings>
                </TextBlock>
                <TextBox Text="{Binding Name}" Visibility="{Binding IsEditingName, Converter={StaticResource BoolToVisConverter}}" VerticalAlignment="Center" HorizontalContentAlignment="Stretch" TextAlignment="Left" IsVisibleChanged="TextBox_IsVisibleChanged">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="LostFocus">
                            <i:InvokeCommandAction Command="{Binding EndEditing}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                    <TextBox.InputBindings>
                        <KeyBinding  Key="Enter" Command="{Binding EndEditing}" />
                    </TextBox.InputBindings>
                </TextBox>
            </Grid>
        </DataTemplate>
    </TabControl.ItemTemplate>
</TabControl>
</code>```

And last but not least, I wanted a double click to put me in edit mode, and to auto focus on the textbox and select all of the content for immediate typing. None of the xaml solutions were as clean as a simple code behind so I finally just decided on adding this to the textbox on visibility changed handler:

```<code>    private void TextBox_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
    {
        var box = sender as TextBox;
        if (box != null)
        {
            if ((bool)e.NewValue)
            {
                box.Focus();
                box.SelectAll();
            }
        }
    }
</code>```

Out of all of the solutions I found, this was by far my favorite. Thanks everyone for your posts!! Helped me find a really good overall solution to my problem!

Body:
I may be approaching this all wrong, so tell me if you have an alternative suggestions.

I'm making an app for windows RT that will have a bunch of text blocks displayed to the user, for example character stats.
The user will see:

Str: 10
Con: 10
Dex: 10

and so on.

I want them to be able to fill these in, then have a select view values calculated based on the result.

My though was to click an "Edit" button at the top and toggle some text boxes over each editable text block.

When trying to set this up using "Blend for Visual Studio" I can't seem to make a text box that is smaller than 49x34 (much larger than my text blocks).

I was going to find a way to generate a text box for each text block (using its dimensions) on button click, but since they will always be the same and there will be a lot of them I was trying to make them static via blend.

I'm pretty new to XAML, and I can't seem to find a good example of people setting up editable fields like this, so how should I make a bunch of static fields have editable text boxes?

Body:
This builds off of BTownTKD's solution, but as I really do prefer as much WPF of a solution as possible here is a bit of a modification, in my case I'm trying to modify the name of a tab control.

My view model has the following code:

    private bool _isEditingName = false;

    public bool IsEditingName
    {
        get
        {
            return _isEditingName;
        }
        set
        {
            _isEditingName = value;
            OnPropertyChanged();
        }
    }

    public ICommand StartEditing
    {
        get
        {
            return new DelegateCommand(() =>
            {
                IsEditingName = true;
            });
        }
    }

    public ICommand EndEditing
    {
        get
        {
            return new DelegateCommand(() =>
            {
                IsEditingName = false;
            });
        }
    }

Next is my view that has the data template for the tab (not the content just the tab):

<TabControl ItemsSource="{Binding Items}" SelectedItem="{Binding ActiveItem}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <Grid VerticalAlignment="Center">
                <TextBlock x:Name="TabName" Text="{Binding Name}" Visibility="{Binding IsEditingName, Converter={StaticResource InvertedBoolToVisConverter}}" VerticalAlignment="Center" HorizontalAlignment="Stretch" TextAlignment="Left">
                    <TextBlock.InputBindings>
                        <MouseBinding MouseAction="LeftDoubleClick" Command="{Binding StartEditing}" />
                    </TextBlock.InputBindings>
                </TextBlock>
                <TextBox Text="{Binding Name}" Visibility="{Binding IsEditingName, Converter={StaticResource BoolToVisConverter}}" VerticalAlignment="Center" HorizontalContentAlignment="Stretch" TextAlignment="Left" IsVisibleChanged="TextBox_IsVisibleChanged">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="LostFocus">
                            <i:InvokeCommandAction Command="{Binding EndEditing}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                    <TextBox.InputBindings>
                        <KeyBinding  Key="Enter" Command="{Binding EndEditing}" />
                    </TextBox.InputBindings>
                </TextBox>
            </Grid>
        </DataTemplate>
    </TabControl.ItemTemplate>
</TabControl>

And last but not least, I wanted a double click to put me in edit mode, and to auto focus on the textbox and select all of the content for immediate typing. None of the xaml solutions were as clean as a simple code behind so I finally just decided on adding this to the textbox on visibility changed handler:

    private void TextBox_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
    {
        var box = sender as TextBox;
        if (box != null)
        {
            if ((bool)e.NewValue)
            {
                box.Focus();
                box.SelectAll();
            }
        }
    }

Out of all of the solutions I found, this was by far my favorite. Thanks everyone for your posts!! Helped me find a really good overall solution to my problem!


问:
How can I login a user for my Rails tests using Omniauth gem?
I've made an application with the omniauth-facebook gem.  All of my rails test were passing, but after adding in code to check for an authenticated user for access to certain actions - some of my tests fail.  How can I go about adding code to my tests to log in a "test" user so that I can simulate an authenticated user?  Most of the google results showed examples for Rspec or Devise examples, but I've been using the default testing suite for Rails 5, so it's been difficult for me to find some examples of how to properly do this.  Please let me know if you'd like me to provide any specific samples of my current tests. Nothing relevant came to mind to include since I'm not sure where to start with this.</p>

答:
So after reading through documentation here, and trying various things here's what I came up with...

test/test_helper.rb

```<code>ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  OmniAuth.config.test_mode = true
  OmniAuth.config.add_mock(:facebook, {:uid => '123456', info: { email: 'email_address_of_user_in_fixtures@gmail.com' }})

  def sign_in_admin
    Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
    get auth_facebook_callback_path
  end

end
</code>```

test/controllers/restaurants_controller_test.rb

```<code>require 'test_helper'

class RestaurantsControllerTest < ActionDispatch::IntegrationTest
  setup do
    # I sign in an admin user, and proceed
    sign_in_admin
    @restaurant = restaurants(:mcdonalds)
  end

  # other test methods for actions ...
end
</code>```

config/routes.rb

```<code>  Rails.application.routes.draw do
    #...
    get 'auth/facebook/callback', to: 'sessions#create'
    #...
  end
</code>```

Body:
So after reading through documentation here, and trying various things here's what I came up with...

test/test_helper.rb

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  OmniAuth.config.test_mode = true
  OmniAuth.config.add_mock(:facebook, {:uid => '123456', info: { email: 'email_address_of_user_in_fixtures@gmail.com' }})

  def sign_in_admin
    Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
    get auth_facebook_callback_path
  end

end

test/controllers/restaurants_controller_test.rb

require 'test_helper'

class RestaurantsControllerTest < ActionDispatch::IntegrationTest
  setup do
    # I sign in an admin user, and proceed
    sign_in_admin
    @restaurant = restaurants(:mcdonalds)
  end

  # other test methods for actions ...
end

config/routes.rb

  Rails.application.routes.draw do
    #...
    get 'auth/facebook/callback', to: 'sessions#create'
    #...
  end


问:
Dropdown menu shows up briefly then disappears
I'm creating a dropdown menu for my Chrome extension.  There is some Javascript code that causes the menu to show up, but when I click the button, the dropdown menu only shows up for a split second before disappearing (looks like a flicker effect). Any help would be appreciated.  Thanks!

welcome.html

```<code> <form>
                <div class="dropdown">
                <button id="dropdownbtn" class="dropbtn">Dropdown</button>
                  <div id="myDropdown" class="dropdown-content">
                    <a href="#home">Home</a>
                    <a href="#about">About</a>
                    <a href="#contact">Contact</a>
                  </div>
                </div>
                <input type="submit" id="signup" value="Get Started">
            </form>
</code>```

interface.js

```<code>    //Add dropdown
    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById("dropdownbtn").addEventListener("click", myFunction);
      //  document.getElementById("dropdownbtn").addEventListener("mouseout", myFunction);
    });

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction()  {
    console.log("in toggle");

    document.getElementById("myDropdown").classList.toggle("show");

}
</code>```

manifest.json

```<code>{
  "manifest_version": 2,

  "name": "Hello World",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",

  "browser_action": {
    "default_icon": "./icons/icon.png",
    "default_popup":  "account.html"
  },
  "manifest_version": 2,
  "content_scripts": [
    {
        "css": ["style.css"],

      "js": [ "content.bundle.js", "interface.js" ],
        "matches": ["<all_urls>"]
    }
  ]
}
</code>```

答:
```<code> document.getElementById("dropdownbtn").addEventListener("click", myFunction);

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction(e)  {
        e.preventDefault();
    console.log("in toggle");

   document.getElementById("myDropdown").classList.toggle("show");

}
</code>```

Working fiddle:
https://jsfiddle.net/uzps6Lr1/

Body:
I'm creating a dropdown menu for my Chrome extension.  There is some Javascript code that causes the menu to show up, but when I click the button, the dropdown menu only shows up for a split second before disappearing (looks like a flicker effect). Any help would be appreciated.  Thanks!

welcome.html

 <form>

                <button id="dropdownbtn" class="dropbtn">Dropdown</button>

                    Home
                    About
                    Contact

                <input type="submit" id="signup" value="Get Started">
            </form>

interface.js

    //Add dropdown
    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById("dropdownbtn").addEventListener("click", myFunction);
      //  document.getElementById("dropdownbtn").addEventListener("mouseout", myFunction);
    });

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction()  {
    console.log("in toggle");

    document.getElementById("myDropdown").classList.toggle("show");

}

manifest.json

{
  "manifest_version": 2,

  "name": "Hello World",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",

  "browser_action": {
    "default_icon": "./icons/icon.png",
    "default_popup":  "account.html"
  },
  "manifest_version": 2,
  "content_scripts": [
    {
        "css": ["style.css"],

      "js": [ "content.bundle.js", "interface.js" ],
        "matches": ["<all_urls>"]
    }
  ]
}

Body:
 document.getElementById("dropdownbtn").addEventListener("click", myFunction);

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction(e)  {
        e.preventDefault();
    console.log("in toggle");

   document.getElementById("myDropdown").classList.toggle("show");

}

Working fiddle:
https://jsfiddle.net/uzps6Lr1/


问:
Get methods and attributes from dll assembly
I'm trying to get a small plugin mechanism running by reflecting an dll file providing my class Plugin (implementing my Plugin-Interface shared among dll and main project / sorry for naming both the same) offering an attribute of type string and a main-method activate:

Interface:

```<code>public interface Plugin
{
    string pluginName{get;set;}
    void activate(System.Windows.Forms.Form main);
}
</code>```

dll class:

```<code>    public class Plugin : WhiteA.Plugin
        {
            public string pluginName{get;set;}

            public void activate(System.Windows.Forms.Form main){
                //find the right form to modify it
                IEnumerable<System.Windows.Forms.ComboBox> ie= GetControlsOfType<System.Windows.Forms.ComboBox>(main);
                System.Windows.Forms.ComboBox cb=GetControlsOfType<System.Windows.Forms.ComboBox>(main).FirstOrDefault();
                cb.Items.Add("Modification");
                System.Windows.Forms.MessageBox.Show(cb.SelectedItem.ToString());
            }

            public static IEnumerable<T> GetControlsOfType<T>(System.Windows.Forms.Control root)
                where T : System.Windows.Forms.Control
            {
                var t = root as T;
                if (t != null)
                    yield return t;

                var container = root as System.Windows.Forms.ContainerControl;
                if (container != null)
                    foreach (System.Windows.Forms.Control c in container.Controls)
                        foreach (var i in GetControlsOfType<T>(c))
                            yield return i;
            }
        }
</code>```

So here comes the problem, there is no type named "Plugin" to be found in the assembly. Tried to get all types from all assemblies in the directory, get all methods/members/custom attributes from them, have them logged etc, but there is nothing of my class Plugin to be found, while the dll definitely is being found, as it doesn't return the MessageBox.

```<code>string[] files=new string[]{};
            string path="Error retrieving path";
            try{
                path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                files = System.IO.Directory.GetFiles(path, "*.dll");
            }catch(Exception exF){

            }
            if(files.Length>0){
                foreach (string dll in files){
                    try{
                        System.Reflection.Assembly sampleAssembly = System.Reflection.Assembly.LoadFrom(dll);
                        Type myType = sampleAssembly.GetType("Plugin");
                        System.Reflection.MethodInfo method = myType.GetMethod("activate");
                        object myInstance = Activator.CreateInstance(myType);
                        method.Invoke(myInstance, new object[]{this});
                    }catch(Exception exL){

                    }
                }
            }else{
                MessageBox.Show("No working plugins detected in " + path.ToString(), "Nothing to activate", MessageBoxButtons.OK,  MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            }
</code>```

I know my code probably looks really messy to you all - I think the last try-block is the only thing relevant here, wanted to put in the class itself and the interface for a little bit transparency though - and my english isn't perfect, but I hope someone can help me out finding my attribute+method in the assembly.

EDIT:

```<code>                    try{
                        System.Reflection.Assembly sampleAssembly = System.Reflection.Assembly.LoadFrom(dll);

                        List<Type> list= sampleAssembly.GetTypes().Where(p =>
                                             p.Namespace == dll &&
                                             p.Name.Contains("Plugin")
                                            ).ToList();
                        Type myType=list.FirstOrDefault();

                        //Type myType = sampleAssembly.GetType("Plugin");
                        System.Reflection.MethodInfo method = myType.GetMethod("activate");
                        object myInstance = Activator.CreateInstance(myType);
                        method.Invoke(myInstance, new object[]{this});

                    }
</code>```

I did change it according to Getting all types in a namespace via reflection
Still the same result, what did I do wrong?

答:
As pointed out by @stuartd:

```<code>Type myType = sampleAssembly.GetType("WhiteA_Plugin_PausedVideo.Plugin");
</code>```

is the solution, missed the namespace

```<code>cb.Items.Add("Modification");
</code>```

doesn't work though...any suggestions?

Got it to work getting the form's children by Controls["nameOfChild"] directly, that help method to fetch all objects by class seems to be wrong here.

Plugin works now, thanks!

Body:
I'm trying to get a small plugin mechanism running by reflecting an dll file providing my class Plugin (implementing my Plugin-Interface shared among dll and main project / sorry for naming both the same) offering an attribute of type string and a main-method activate:

Interface:

public interface Plugin
{
    string pluginName{get;set;}
    void activate(System.Windows.Forms.Form main);
}

dll class:

    public class Plugin : WhiteA.Plugin
        {
            public string pluginName{get;set;}

            public void activate(System.Windows.Forms.Form main){
                //find the right form to modify it
                IEnumerable<System.Windows.Forms.ComboBox> ie= GetControlsOfType<System.Windows.Forms.ComboBox>(main);
                System.Windows.Forms.ComboBox cb=GetControlsOfType<System.Windows.Forms.ComboBox>(main).FirstOrDefault();
                cb.Items.Add("Modification");
                System.Windows.Forms.MessageBox.Show(cb.SelectedItem.ToString());
            }

            public static IEnumerable<T> GetControlsOfType<T>(System.Windows.Forms.Control root)
                where T : System.Windows.Forms.Control
            {
                var t = root as T;
                if (t != null)
                    yield return t;

                var container = root as System.Windows.Forms.ContainerControl;
                if (container != null)
                    foreach (System.Windows.Forms.Control c in container.Controls)
                        foreach (var i in GetControlsOfType<T>(c))
                            yield return i;
            }
        }

So here comes the problem, there is no type named "Plugin" to be found in the assembly. Tried to get all types from all assemblies in the directory, get all methods/members/custom attributes from them, have them logged etc, but there is nothing of my class Plugin to be found, while the dll definitely is being found, as it doesn't return the MessageBox.

string[] files=new string[]{};
            string path="Error retrieving path";
            try{
                path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                files = System.IO.Directory.GetFiles(path, "*.dll");
            }catch(Exception exF){

            }
            if(files.Length>0){
                foreach (string dll in files){
                    try{
                        System.Reflection.Assembly sampleAssembly = System.Reflection.Assembly.LoadFrom(dll);
                        Type myType = sampleAssembly.GetType("Plugin");
                        System.Reflection.MethodInfo method = myType.GetMethod("activate");
                        object myInstance = Activator.CreateInstance(myType);
                        method.Invoke(myInstance, new object[]{this});
                    }catch(Exception exL){

                    }
                }
            }else{
                MessageBox.Show("No working plugins detected in " + path.ToString(), "Nothing to activate", MessageBoxButtons.OK,  MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            }

I know my code probably looks really messy to you all - I think the last try-block is the only thing relevant here, wanted to put in the class itself and the interface for a little bit transparency though - and my english isn't perfect, but I hope someone can help me out finding my attribute+method in the assembly.

EDIT:

                    try{
                        System.Reflection.Assembly sampleAssembly = System.Reflection.Assembly.LoadFrom(dll);

                        List<Type> list= sampleAssembly.GetTypes().Where(p =>
                                             p.Namespace == dll &&
                                             p.Name.Contains("Plugin")
                                            ).ToList();
                        Type myType=list.FirstOrDefault();

                        //Type myType = sampleAssembly.GetType("Plugin");
                        System.Reflection.MethodInfo method = myType.GetMethod("activate");
                        object myInstance = Activator.CreateInstance(myType);
                        method.Invoke(myInstance, new object[]{this});

                    }

I did change it according to Getting all types in a namespace via reflection
Still the same result, what did I do wrong?

Body:
As pointed out by @stuartd:

Type myType = sampleAssembly.GetType("WhiteA_Plugin_PausedVideo.Plugin");

is the solution, missed the namespace

cb.Items.Add("Modification");

doesn't work though...any suggestions?

Got it to work getting the form's children by Controls["nameOfChild"] directly, that help method to fetch all objects by class seems to be wrong here.

Plugin works now, thanks!


问:
Access Tab Control - Set Pages Visibilty based on Subform Records
I know how to do this, but wondering if I might be able to write a more elegant solution.  I have a form with a tab control.  The control has 14 pages, each one, with it's own sub form.  One of the pages (pgRequirements) has a subform of requirements, with a combo control "Requirement Type". It is a continuous form, so the user can add as many requirements as they want, for the main record.

There are 9 of those requirements, which have their own tab control page / sub form.  I want to set visibility of those tab control pages, based on this parent's sub form requirements.  So a current main record, can have multiple sub-requirement records. If any of those match e.g. requirement type A, than page A should be visible, otherwise it should not be.

I need this code to run anytime the main form is loaded, and the detail is made visible (meaning a main record has been chosen from a find form). Also anytime a requirement record is added or removed.  The below is assuming that the parent-child links on the main form to subform will limit the requirement records, to just those that are for the current main record.

Here is the simple code, that will do the job, but is probably over-written:

```<code>If Me.FKRequirementType.Column(1) = "ReqType1" Then
    Me.Parent!pgReqType1.Visible = True
Else
    Me.Parent!pgReqType1.Visible = False
End If

If Me.FKRequirementType.Column(1) = "ReqType2" Then
    Me.Parent!pgReqType2.Visible = True
Else
    Me.Parent!pgReqType2.Visible = False
End If

If Me.FKRequirementType.Column(1) = "ReqType3" Then
    Me.Parent!pgReqType3.Visible = True
Else
    Me.Parent!pgReqType3.Visible = False
End If

If Me.FKRequirementType.Column(1) = "ReqType4" Then
    Me.Parent!pgReqType4.Visible = True
Else
    Me.Parent!pgReqType4.Visible = False
End If
</code>```

Thanks!

EDIT

I turned this into a public function, so I can call it from anywhere.  One problem.  It's not working lol (small problem).  I don't get any errors, but all the tab control pages are visible.  When I add a new record, most of them should be hidden.  I have a tblReqType table, with all the requirement types.  I added a column to this, with the exact name of it's corresponding tab control page name, so I can loop through that table, for all records where that page name is not null, and set their page visible or not, based on the current main record ID having a record-requirement (cross reference table) record for each requirement type.

This is the public function I wrote.  Can anyone help me understand what I'm missing in these loops for setting the visibility true (vtrue) vs setting the visibility false (vfalse)

```<code>Public Function ShowRequirements()
    Dim db As DAO.Database
    Dim strRstVTrue As String
    Dim rstvTrue As DAO.Recordset
    Dim strRstVFalse As String
    Dim rstvFalse As DAO.Recordset
    Dim strFieldName As String

    'Setup the recordset
    Set db = CurrentDb
    strRstVTrue = "SELECT tblMRecordRequirements.ID, tblMRecordRequirements.FKMC, tblReqType.txtRequirementPage " & _
    "FROM tblMRecordRequirements LEFT JOIN tblReqType ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & Nz(Forms!frmMRecords!ID, 0)

    strRstVFalse = "SELECT tblReqType.ID, tblReqType.txtRequirementPage, tblMRecordRequirements.FKMC " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblReqType.ID = tblMRecordRequirements.FKRequirementType " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC <> " & Nz(Forms!frmMRecords!ID, 0)

    Set rstvTrue = CurrentDb.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
    Set rstvFalse = CurrentDb.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
    strFieldName = "txtRequirementPage"
    Do While Not rstvTrue.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
    Loop
    Do While Not rstvFalse.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
    Loop
End Function
</code>```

If anyone can help me figure out my stupidity, you deserve an up vote, a check mark, and a cookie.

EDIT again

Below is updated code for the public function.  I fixed the rs for the true query, and I added in the MoveNext for the loops.

Public Function ShowRequirements()
        Dim db As DAO.Database
        Dim strRstVTrue As String
        Dim rstvTrue As DAO.Recordset
        Dim strRstVFalse As String
        Dim rstvFalse As DAO.Recordset
        Dim strFieldName As String

```<code>    'Setup the recordset
    Set db = CurrentDb
    strRstVTrue = "SELECT tblMRecordRequirements.ID, tblMRecordRequirements.FKMC, tblReqType.txtRequirementPage " & _
    "FROM tblMRecordRequirements LEFT JOIN tblReqType ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & Nz(Forms!frmMRecords!ID, 0)

    strRstVFalse = "SELECT tblReqType.ID, tblReqType.txtRequirementPage, tblMRecordRequirements.FKMC " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblReqType.ID = tblMRecordRequirements.FKRequirementType " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC <> Is Null"

    Set rstvTrue = CurrentDb.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
    Set rstvFalse = CurrentDb.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
    strFieldName = "txtRequirementPage"
    Do While Not rstvTrue.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
    rstvTrue.MoveNext
    Loop
    Do While Not rstvFalse.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
    rstvFalse.MoveNext
    Loop
End Function
</code>```

EDIT REDUX

I think I may have it worked out, but let me know what you all think.  I really appreciate all your thoughts on this, as I know you all have a lot of experience not just in figuring out these kinds of challenges, but ensuring the code is good and not prone to issues.

Here is where I am at:

```<code>Public Function ShowRequirements()
    Dim db As DAO.Database
    Dim db2 As DAO.Database
    Dim strRstVTrue As String
    Dim rstvTrue As DAO.Recordset
    Dim strRstVFalse As String
    Dim rstvFalse As DAO.Recordset
    Dim strFieldName As String

    strFieldName = "txtRequirementPage"
    Set db = CurrentDb
    Set db2 = CurrentDb

    strRstVTrue = "SELECT tblReqType.txtRequirementPage " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & MCID

    strRstVFalse = "SELECT tblReqType.txtRequirementPage " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblMRecordRequirements.ID Not In (Select ID From [tblMRecordRequirements] WHERE [tblMRecordRequirements]![FKMC] = " & MCID & _
    ") AND tblReqType.txtRequirementPage Is Not Null;"

    Set rstvTrue = db.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
    Set rstvFalse = db2.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
    Do While Not rstvTrue.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
    rstvTrue.MoveNext
    Loop
    Do While Not rstvFalse.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
    rstvFalse.MoveNext
    Loop
End Function
</code>```

答:
I need this code to run anytime the main form is loaded, and the detail is made visible (meaning a main record has been chosen from a find form). Also anytime a requirement record is added.

Put the code you shared inside a sub procedure and call the sub procedure from Form_Load(), Form_Current(), Form_AfterInsert() event handler, etc.

As for elegance, I'd focus on maintainability and efficiency rather than looks, but concise code is also nice.  1) You can use a With block to reduce redundant object method calls, but that'll only work for one reference at a time.  2) Instead create another variable to temporarily hold a value/object from a series of dot property-accessors.  3) It looks like pages and column values are already numbered with a consistent naming pattern, so leverage that in a loop.  4) Comparison operations in VBA are largely Boolean operations, so they return True or False.  The result of an entire Boolean expression can be assigned to another Boolean variable/property.  (Boolean operations can also return Null... which is usually, but not always, treated like False. If you're certain that your data doesn't have Null values, then you can simplify the code and ignore this issue.  If the data can contain null, then you need to adjust the code appropriately.)

Me.Parent!pgReqType1 is calling the default property of the Parent form which is Controls, which default property is Item.  The bang operator ! passes the code text as a string into the collection Item method.  In short, it is equivalent to Me.Parent.Controls.Item("pgReqType1").

```<code>Dim i as integer
Dim ctls as Controls
Dim reqValue as string

Set ctls = Me.Parent.Controls
reqValue = Me.FKRequirementType.Column(1)

For i = 1 to 4
  ctls.Item("pgReqType" & i).Visible = (reqValue = "ReqType" & i)
Next i
</code>```

About all I can do is translate the specific code snippet you show.  I have the feeling there is probably more to it than this, because the code snippet you shared ensures that there will only be one tab visible: It is testing the same column value multiple times which could only have one value.  Bug? Incomplete example?

Body:
I know how to do this, but wondering if I might be able to write a more elegant solution.  I have a form with a tab control.  The control has 14 pages, each one, with it's own sub form.  One of the pages (pgRequirements) has a subform of requirements, with a combo control "Requirement Type". It is a continuous form, so the user can add as many requirements as they want, for the main record.

There are 9 of those requirements, which have their own tab control page / sub form.  I want to set visibility of those tab control pages, based on this parent's sub form requirements.  So a current main record, can have multiple sub-requirement records. If any of those match e.g. requirement type A, than page A should be visible, otherwise it should not be.

I need this code to run anytime the main form is loaded, and the detail is made visible (meaning a main record has been chosen from a find form). Also anytime a requirement record is added or removed.  The below is assuming that the parent-child links on the main form to subform will limit the requirement records, to just those that are for the current main record.

Here is the simple code, that will do the job, but is probably over-written:

If Me.FKRequirementType.Column(1) = "ReqType1" Then
    Me.Parent!pgReqType1.Visible = True
Else
    Me.Parent!pgReqType1.Visible = False
End If

If Me.FKRequirementType.Column(1) = "ReqType2" Then
    Me.Parent!pgReqType2.Visible = True
Else
    Me.Parent!pgReqType2.Visible = False
End If

If Me.FKRequirementType.Column(1) = "ReqType3" Then
    Me.Parent!pgReqType3.Visible = True
Else
    Me.Parent!pgReqType3.Visible = False
End If

If Me.FKRequirementType.Column(1) = "ReqType4" Then
    Me.Parent!pgReqType4.Visible = True
Else
    Me.Parent!pgReqType4.Visible = False
End If

Thanks!

EDIT

I turned this into a public function, so I can call it from anywhere.  One problem.  It's not working lol (small problem).  I don't get any errors, but all the tab control pages are visible.  When I add a new record, most of them should be hidden.  I have a tblReqType table, with all the requirement types.  I added a column to this, with the exact name of it's corresponding tab control page name, so I can loop through that table, for all records where that page name is not null, and set their page visible or not, based on the current main record ID having a record-requirement (cross reference table) record for each requirement type.

This is the public function I wrote.  Can anyone help me understand what I'm missing in these loops for setting the visibility true (vtrue) vs setting the visibility false (vfalse)

Public Function ShowRequirements()
    Dim db As DAO.Database
    Dim strRstVTrue As String
    Dim rstvTrue As DAO.Recordset
    Dim strRstVFalse As String
    Dim rstvFalse As DAO.Recordset
    Dim strFieldName As String

    'Setup the recordset
    Set db = CurrentDb
    strRstVTrue = "SELECT tblMRecordRequirements.ID, tblMRecordRequirements.FKMC, tblReqType.txtRequirementPage " & _
    "FROM tblMRecordRequirements LEFT JOIN tblReqType ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & Nz(Forms!frmMRecords!ID, 0)

    strRstVFalse = "SELECT tblReqType.ID, tblReqType.txtRequirementPage, tblMRecordRequirements.FKMC " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblReqType.ID = tblMRecordRequirements.FKRequirementType " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC <> " & Nz(Forms!frmMRecords!ID, 0)

    Set rstvTrue = CurrentDb.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
    Set rstvFalse = CurrentDb.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
    strFieldName = "txtRequirementPage"
    Do While Not rstvTrue.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
    Loop
    Do While Not rstvFalse.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
    Loop
End Function

If anyone can help me figure out my stupidity, you deserve an up vote, a check mark, and a cookie.

EDIT again

Below is updated code for the public function.  I fixed the rs for the true query, and I added in the MoveNext for the loops.

Public Function ShowRequirements()
        Dim db As DAO.Database
        Dim strRstVTrue As String
        Dim rstvTrue As DAO.Recordset
        Dim strRstVFalse As String
        Dim rstvFalse As DAO.Recordset
        Dim strFieldName As String

    'Setup the recordset
    Set db = CurrentDb
    strRstVTrue = "SELECT tblMRecordRequirements.ID, tblMRecordRequirements.FKMC, tblReqType.txtRequirementPage " & _
    "FROM tblMRecordRequirements LEFT JOIN tblReqType ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & Nz(Forms!frmMRecords!ID, 0)

    strRstVFalse = "SELECT tblReqType.ID, tblReqType.txtRequirementPage, tblMRecordRequirements.FKMC " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblReqType.ID = tblMRecordRequirements.FKRequirementType " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC <> Is Null"

    Set rstvTrue = CurrentDb.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
    Set rstvFalse = CurrentDb.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
    strFieldName = "txtRequirementPage"
    Do While Not rstvTrue.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
    rstvTrue.MoveNext
    Loop
    Do While Not rstvFalse.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
    rstvFalse.MoveNext
    Loop
End Function

EDIT REDUX

I think I may have it worked out, but let me know what you all think.  I really appreciate all your thoughts on this, as I know you all have a lot of experience not just in figuring out these kinds of challenges, but ensuring the code is good and not prone to issues.

Here is where I am at:

Public Function ShowRequirements()
    Dim db As DAO.Database
    Dim db2 As DAO.Database
    Dim strRstVTrue As String
    Dim rstvTrue As DAO.Recordset
    Dim strRstVFalse As String
    Dim rstvFalse As DAO.Recordset
    Dim strFieldName As String

    strFieldName = "txtRequirementPage"
    Set db = CurrentDb
    Set db2 = CurrentDb

    strRstVTrue = "SELECT tblReqType.txtRequirementPage " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblReqType.txtRequirementPage Is Not Null AND tblMRecordRequirements.FKMC = " & MCID

    strRstVFalse = "SELECT tblReqType.txtRequirementPage " & _
    "FROM tblReqType LEFT JOIN tblMRecordRequirements ON tblMRecordRequirements.FKRequirementType = tblReqType.ID " & _
    "WHERE tblMRecordRequirements.ID Not In (Select ID From [tblMRecordRequirements] WHERE [tblMRecordRequirements]![FKMC] = " & MCID & _
    ") AND tblReqType.txtRequirementPage Is Not Null;"

    Set rstvTrue = db.OpenRecordset(strRstVTrue, dbOpenDynaset, dbSeeChanges)
    Set rstvFalse = db2.OpenRecordset(strRstVFalse, dbOpenDynaset, dbSeeChanges)
    Do While Not rstvTrue.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvTrue.Fields(strFieldName)).Visible = True
    rstvTrue.MoveNext
    Loop
    Do While Not rstvFalse.EOF
        Forms!frmMRecords.tbMRecordSubs.Pages(rstvFalse.Fields(strFieldName)).Visible = False
    rstvFalse.MoveNext
    Loop
End Function

Body:
I need this code to run anytime the main form is loaded, and the detail is made visible (meaning a main record has been chosen from a find form). Also anytime a requirement record is added.

Put the code you shared inside a sub procedure and call the sub procedure from Form_Load(), Form_Current(), Form_AfterInsert() event handler, etc.

As for elegance, I'd focus on maintainability and efficiency rather than looks, but concise code is also nice.  1) You can use a With block to reduce redundant object method calls, but that'll only work for one reference at a time.  2) Instead create another variable to temporarily hold a value/object from a series of dot property-accessors.  3) It looks like pages and column values are already numbered with a consistent naming pattern, so leverage that in a loop.  4) Comparison operations in VBA are largely Boolean operations, so they return True or False.  The result of an entire Boolean expression can be assigned to another Boolean variable/property.  (Boolean operations can also return Null... which is usually, but not always, treated like False. If you're certain that your data doesn't have Null values, then you can simplify the code and ignore this issue.  If the data can contain null, then you need to adjust the code appropriately.)

Me.Parent!pgReqType1 is calling the default property of the Parent form which is Controls, which default property is Item.  The bang operator ! passes the code text as a string into the collection Item method.  In short, it is equivalent to Me.Parent.Controls.Item("pgReqType1").

Dim i as integer
Dim ctls as Controls
Dim reqValue as string

Set ctls = Me.Parent.Controls
reqValue = Me.FKRequirementType.Column(1)

For i = 1 to 4
  ctls.Item("pgReqType" & i).Visible = (reqValue = "ReqType" & i)
Next i

About all I can do is translate the specific code snippet you show.  I have the feeling there is probably more to it than this, because the code snippet you shared ensures that there will only be one tab visible: It is testing the same column value multiple times which could only have one value.  Bug? Incomplete example?


问:
Rails - how to save existing record and apply update to a copy?
I have a webpage that tracks budgets containing a LOT of variables, stored in 40+ columns. Over time, adjustments are made to these budgets, but I need to be able to track changes over time and year to year. I tried adding a private method to my model that should create a duplicate of the existing record triggered by a :before_update callback. However, it's not working. The update changes the existing record, and the original is not preserved at all.

Model:

```<code>class Budget < ActiveRecord::Base

  before_update :copy_budget

  private

  def copy_budget
    @budget = Budget.find(params[:id])
    @budget.dup
    @budget.save
  end
end
</code>```

I'm still learning rails, (this is in Rails 4) and I think this would have been the best way to do this. If not, is there a better way to set the form to ALWAYS post a new record instead of routing to update if a record already exists?

Currently the form_for line looks like this:

<%= form_for(@budget) do |f| %>

Everything works as it should, with the exception of the duplication not happening. What am I missing? Is it possible the .dup function is also duplicating the :id? This is assigned by auto-increment in the MySQL db I an using, so if .dup is copying EVERYTHING, is there a way to copy all of the data except the :id into a new record?

Thanks in advance for any suggestions.

答:
the dup method returns the new object without an id, it doesn't update it in place. Since your copy_budget method is already an instance method on Budget, you also would not need to (and you wouldn't even be able to, since params aren't accessible in models) look up the budget by id and instead could just use the current instance (self). So the following changed would fix the copy_budget method for you, but you are still copying an already modified object, just before it gets saved to the database

```<code>def copy_budget
  copy_of_budget = self.dup
  copy_of_budget.save
end
</code>```

it would work the way you're expecting it to work. However, you aren't linking the copy in anyway to the current version of the Budget (no way to tell Budget id = 1 is an older version of Budget id = 2). I'd recommend taking a look at a gem such as PaperTrail (I'm sure there are lots of others if that one doesn't suit your needs) which has already thought through a lot of the problems and features with keeping a history of record changed.

Body:
I have a webpage that tracks budgets containing a LOT of variables, stored in 40+ columns. Over time, adjustments are made to these budgets, but I need to be able to track changes over time and year to year. I tried adding a private method to my model that should create a duplicate of the existing record triggered by a :before_update callback. However, it's not working. The update changes the existing record, and the original is not preserved at all.

Model:

class Budget < ActiveRecord::Base

  before_update :copy_budget

  private

  def copy_budget
    @budget = Budget.find(params[:id])
    @budget.dup
    @budget.save
  end
end

I'm still learning rails, (this is in Rails 4) and I think this would have been the best way to do this. If not, is there a better way to set the form to ALWAYS post a new record instead of routing to update if a record already exists?

Currently the form_for line looks like this:

<%= form_for(@budget) do |f| %>

Everything works as it should, with the exception of the duplication not happening. What am I missing? Is it possible the .dup function is also duplicating the :id? This is assigned by auto-increment in the MySQL db I an using, so if .dup is copying EVERYTHING, is there a way to copy all of the data except the :id into a new record?

Thanks in advance for any suggestions.

Body:
the dup method returns the new object without an id, it doesn't update it in place. Since your copy_budget method is already an instance method on Budget, you also would not need to (and you wouldn't even be able to, since params aren't accessible in models) look up the budget by id and instead could just use the current instance (self). So the following changed would fix the copy_budget method for you, but you are still copying an already modified object, just before it gets saved to the database

def copy_budget
  copy_of_budget = self.dup
  copy_of_budget.save
end

it would work the way you're expecting it to work. However, you aren't linking the copy in anyway to the current version of the Budget (no way to tell Budget id = 1 is an older version of Budget id = 2). I'd recommend taking a look at a gem such as PaperTrail (I'm sure there are lots of others if that one doesn't suit your needs) which has already thought through a lot of the problems and features with keeping a history of record changed.


问:
Using backcolor to compare in datagridview cells of current row to those of previous row in vb net
I am working out a sequential tank filling plan.

I use a datagridview. In part (2) of the following code, each row represents a sequence and each row cell (beginning from the fourth one in the row) the volume of liquid in a specific tank. If it appears by comparing the current row cell to that of the previous row that the volume has increased, I want the cell backcolor become green, if it decreased then it's yellow color and if no change the color remains white.

The cells receive their data from calculation results when clicking the TkFil button.

The issue I am facing is that the first four or eight cells of the row get their colors in a random order while all the rest behind are fine. I simply fail to understand and need some help: why is the colouring not working?

This is my full code:

```<code>Private Sub btnTkFil_Click(sender As System.Object, e As System.EventArgs) Handles btnTkFil.Click
    If Form36 Is Nothing Then
        MessageBox.Show("Please first open the Ballast Plan form")
    Else
        'PART(1)
        Form36.dgv1.CurrentRow.Cells(0).Value = Form1.txtCondition.Text.ToString
        Form36.dgv1.CurrentRow.Cells(1).Value = Val(Form1.txtAftDft.Text)
        Form36.dgv1.CurrentRow.Cells(2).Value = Val(Form1.txtForeDft.Text)
        Form36.dgv1.CurrentRow.Cells(3).Value = Val(tbGm1.Text)
        Try
            For i As Integer = 4 To CInt(Val(Form32.tbNbBox.Text) + 3)
                'For j As Integer = 0 To CInt(Val(Form32.tbNbBox.Text) - 1)
                For j As Integer = 0 To Form31.DataGridView1.Rows.Count - 1
                    For n As Integer = 0 To CInt(Val(Form32.tbNbBox.Text) - 1) Step +1
                        Form36.dgv1.Columns(i).Name = CStr(Form31.DataGridView1.Rows(j).Cells(0).Value)         ' noms blst tks
                        Form36.dgv1.Rows(0).Cells(i).Value = CStr(Form31.DataGridView1.Rows(j).Cells(1).Value)  'tank capa
                        If Form36.rBtn1.Checked = True And Form36.rBtn2.Checked = False Then
                            Colb(n).Text = CStr(Form31.DataGridView1.Rows(j).Cells(3).Value)                          'passe aux boxes "t" les valeurs seules reçues dans Form31.dgv et retranscrites dans GBox1.textbox en %
                            Form36.dgv1.CurrentRow.Cells(i).Value = Format(Val(Colb(n).Text), "0") & "%"
                        End If
                        If Form36.rBtn1.Checked = False And Form36.rBtn2.Checked = True Then
                            Colb(n).Text = CStr(CDbl(Form31.DataGridView1.Rows(j).Cells(1).Value) * CDbl(Form31.DataGridView1.Rows(j).Cells(3).Value) / 100)
                            Form36.dgv1.CurrentRow.Cells(i).Value = Format(Val(Colb(n).Text), "0")
                        End If
                        i += 1
                        j += 1
                    Next
                Next
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        'PART(2)
        Try
            For i As Integer = 4 To CInt(Val(Form32.tbNbBox.Text) + 3)
                For j As Integer = 2 To Form36.dgv1.Rows.Count - 2
                    Dim a As String = CStr(Form36.dgv1.Rows(j).Cells(i).Value)
                    Dim b As String = CStr(Form36.dgv1.Rows(j - 1).Cells(i).Value)
                    If a > b Then
                        Form36.dgv1.Rows(j).Cells(i).Style.BackColor = Color.PaleGreen
                    ElseIf a < b Then
                        Form36.dgv1.Rows(j).Cells(i).Style.BackColor = Color.Yellow
                    ElseIf a = b Then
                        Form36.dgv1.Rows(j).Cells(i).Style.BackColor = Color.White
                    End If
                Next
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End If
End Sub
</code>```

答:
You're using strings to compare what should be numbers. That can lead to unexpected results, for example 8 < 10 but "8" > "10"

You just need to modify the code in PART(2) to

```<code>Dim a As Double = CDbl(Form36.dgv1.Rows(j).Cells(i).Value)
Dim b As Double = CDbl(Form36.dgv1.Rows(j - 1).Cells(i).Value)
</code>```

Body:
I am working out a sequential tank filling plan.

I use a datagridview. In part (2) of the following code, each row represents a sequence and each row cell (beginning from the fourth one in the row) the volume of liquid in a specific tank. If it appears by comparing the current row cell to that of the previous row that the volume has increased, I want the cell backcolor become green, if it decreased then it's yellow color and if no change the color remains white.

The cells receive their data from calculation results when clicking the TkFil button.

The issue I am facing is that the first four or eight cells of the row get their colors in a random order while all the rest behind are fine. I simply fail to understand and need some help: why is the colouring not working?

This is my full code:

Private Sub btnTkFil_Click(sender As System.Object, e As System.EventArgs) Handles btnTkFil.Click
    If Form36 Is Nothing Then
        MessageBox.Show("Please first open the Ballast Plan form")
    Else
        'PART(1)
        Form36.dgv1.CurrentRow.Cells(0).Value = Form1.txtCondition.Text.ToString
        Form36.dgv1.CurrentRow.Cells(1).Value = Val(Form1.txtAftDft.Text)
        Form36.dgv1.CurrentRow.Cells(2).Value = Val(Form1.txtForeDft.Text)
        Form36.dgv1.CurrentRow.Cells(3).Value = Val(tbGm1.Text)
        Try
            For i As Integer = 4 To CInt(Val(Form32.tbNbBox.Text) + 3)
                'For j As Integer = 0 To CInt(Val(Form32.tbNbBox.Text) - 1)
                For j As Integer = 0 To Form31.DataGridView1.Rows.Count - 1
                    For n As Integer = 0 To CInt(Val(Form32.tbNbBox.Text) - 1) Step +1
                        Form36.dgv1.Columns(i).Name = CStr(Form31.DataGridView1.Rows(j).Cells(0).Value)         ' noms blst tks
                        Form36.dgv1.Rows(0).Cells(i).Value = CStr(Form31.DataGridView1.Rows(j).Cells(1).Value)  'tank capa
                        If Form36.rBtn1.Checked = True And Form36.rBtn2.Checked = False Then
                            Colb(n).Text = CStr(Form31.DataGridView1.Rows(j).Cells(3).Value)                          'passe aux boxes "t" les valeurs seules reçues dans Form31.dgv et retranscrites dans GBox1.textbox en %
                            Form36.dgv1.CurrentRow.Cells(i).Value = Format(Val(Colb(n).Text), "0") & "%"
                        End If
                        If Form36.rBtn1.Checked = False And Form36.rBtn2.Checked = True Then
                            Colb(n).Text = CStr(CDbl(Form31.DataGridView1.Rows(j).Cells(1).Value) * CDbl(Form31.DataGridView1.Rows(j).Cells(3).Value) / 100)
                            Form36.dgv1.CurrentRow.Cells(i).Value = Format(Val(Colb(n).Text), "0")
                        End If
                        i += 1
                        j += 1
                    Next
                Next
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        'PART(2)
        Try
            For i As Integer = 4 To CInt(Val(Form32.tbNbBox.Text) + 3)
                For j As Integer = 2 To Form36.dgv1.Rows.Count - 2
                    Dim a As String = CStr(Form36.dgv1.Rows(j).Cells(i).Value)
                    Dim b As String = CStr(Form36.dgv1.Rows(j - 1).Cells(i).Value)
                    If a > b Then
                        Form36.dgv1.Rows(j).Cells(i).Style.BackColor = Color.PaleGreen
                    ElseIf a < b Then
                        Form36.dgv1.Rows(j).Cells(i).Style.BackColor = Color.Yellow
                    ElseIf a = b Then
                        Form36.dgv1.Rows(j).Cells(i).Style.BackColor = Color.White
                    End If
                Next
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End If
End Sub

Body:
You're using strings to compare what should be numbers. That can lead to unexpected results, for example 8 < 10 but "8" > "10"

You just need to modify the code in PART(2) to

Dim a As Double = CDbl(Form36.dgv1.Rows(j).Cells(i).Value)
Dim b As Double = CDbl(Form36.dgv1.Rows(j - 1).Cells(i).Value)


问:
TypeError: 'module' object is not callable - using datetime
Sorry didn't find any other fix, so I created a new question.
I'm trying to run a code that prints to the screen the current hour, minute and second. The piece of code I'm using to do this is:

```<code>def time():
    import datetime
    import time
    time.sleep(1)
    nowTime = datetime.now()
    print ('Right now it's %s hours, %s minutes and %s seconds.' % (nowTime.hour,nowTime.minute,nowTime.second))
    time.sleep(5)
</code>```

I get the following error when this piece of code tries to execute:

```<code>Traceback (most recent call last):
  File "/Users/Teolicht/Desktop/Python/testy.py", line 219, in <module>
    start()
  File "/Users/Teolicht/Desktop/Python/testy.py", line 18, in start
    questions()
  File "/Users/Teolicht/Desktop/Python/testy.py", line 34, in questions
    day()
  File "/Users/Teolicht/Desktop/Python/testy.py", line 52, in day
    time()
TypeError: 'module' object is not callable
</code>```

start(), questions() and day() are some other functions the program went through before going through time(). If I try executing time() directly, it works! So, here's the entire code from the start till the end of the time() function:

```<code>from datetime import datetime
import time
import random
import sys

def start():
    import time
    name = input('Hi. What is your name? ')
    print ('Nice to meet you, ' + str(name) + '.')
    time.sleep(1)
    print ('How old are you?')
    age = input()
    time.sleep(1)
    print (age + '! Cool.')
    time.sleep(2)
    questions()

def questions():
    import time
    print ('Some things you can ask me:')
    time.sleep(1)
    print ('• What day is today? (qdh)')
    time.sleep(1)
    print ('• What time is it? (qhs)')
    time.sleep(1)
    print ('• I want to play a game! (qjj)')
    time.sleep(1)
    print ('• How many days till my birthday? (qda)')
    time.sleep(1)
    questionsAnswer = input()
    if questionsAnswer == 'qdh':
        day()
    elif questionsAnswer == 'qhs':
        time()
    elif questionsAnswer == 'qjj':
        game()
    else:
        birthday()

def day():
    import time
    time.sleep(1)
    nowDay = datetime.now()
    print ('Today is %s/%s/%s' % (nowDay.day,nowDay.month,nowDay.year))
    time.sleep(2)
    dayAnswer = input('Want to know what time it is? "Y" for yes and "N" for no: ').lower()
    if dayAnswer == 'n':
        questions()
    else:
        time()

def time():
    import time
    time.sleep(1)
    nowTime = datetime.now()
    print ('Right now it's %s hours, %s minutes and %s seconds.' % (nowTime.hour,nowTime.minute,nowTime.second))
    time.sleep(5)
        questions()
       ...
</code>```

It might be something in start(), questions() or day() causing the error. Any ideas? Thanks a bunch!

答:
It worked for me, try to not create your own time() method, I renamed it to "my_time()".

The time module defines a lot of functions so, or you just "import time" or you need to specify each function you wanna import like "from time import sleep"

```<code>from datetime import datetime
from time import time, sleep
import random
import sys

def questions():
    print ('Some things you can ask me:')
    sleep(1)
    print ('• What day is today? (qdh)')
    sleep(1)
    print ('• What time is it? (qhs)')
    sleep(1)
    print ('• I want to play a game! (qjj)')
    sleep(1)
    print ('• How many days till my birthday? (qda)')
    sleep(1)
    questionsAnswer = input()
    if questionsAnswer == 'qdh':
        day()
    elif questionsAnswer == 'qhs':
        my_time()
    elif questionsAnswer == 'qjj':
        my_game()
    else:
        my_birthday()

def day():
    sleep(1)
    nowDay = datetime.now()
    print ('Today is %s/%s/%s' % (nowDay.day,nowDay.month,nowDay.year))
    sleep(2)
    dayAnswer = input('Want to know what time it is? "Y" for yes and "N" for no: ').lower()
    if dayAnswer == 'n':
        questions()
    else:
        my_time()

def my_time():
    sleep(1)
    nowTime = datetime.now()
    print ('Right now it\'s %s hours, %s minutes and %s seconds.' % (nowTime.hour, nowTime.minute, nowTime.second))
    sleep(5)
    questions()

def my_game():
    pass

def my_birthday():
    pass

#def start():
name = input('Hi. What is your name? ')
print ('Nice to meet you, ' + str(name) + '.')
sleep(1)
print ('How old are you?')
age = input()
sleep(1)
print (age + '! Cool.')
sleep(2)
questions()
</code>```

Body:
Sorry didn't find any other fix, so I created a new question.
I'm trying to run a code that prints to the screen the current hour, minute and second. The piece of code I'm using to do this is:

def time():
    import datetime
    import time
    time.sleep(1)
    nowTime = datetime.now()
    print ('Right now it's %s hours, %s minutes and %s seconds.' % (nowTime.hour,nowTime.minute,nowTime.second))
    time.sleep(5)

I get the following error when this piece of code tries to execute:

Traceback (most recent call last):
  File "/Users/Teolicht/Desktop/Python/testy.py", line 219, in <module>
    start()
  File "/Users/Teolicht/Desktop/Python/testy.py", line 18, in start
    questions()
  File "/Users/Teolicht/Desktop/Python/testy.py", line 34, in questions
    day()
  File "/Users/Teolicht/Desktop/Python/testy.py", line 52, in day
    time()
TypeError: 'module' object is not callable

start(), questions() and day() are some other functions the program went through before going through time(). If I try executing time() directly, it works! So, here's the entire code from the start till the end of the time() function:

from datetime import datetime
import time
import random
import sys

def start():
    import time
    name = input('Hi. What is your name? ')
    print ('Nice to meet you, ' + str(name) + '.')
    time.sleep(1)
    print ('How old are you?')
    age = input()
    time.sleep(1)
    print (age + '! Cool.')
    time.sleep(2)
    questions()

def questions():
    import time
    print ('Some things you can ask me:')
    time.sleep(1)
    print ('• What day is today? (qdh)')
    time.sleep(1)
    print ('• What time is it? (qhs)')
    time.sleep(1)
    print ('• I want to play a game! (qjj)')
    time.sleep(1)
    print ('• How many days till my birthday? (qda)')
    time.sleep(1)
    questionsAnswer = input()
    if questionsAnswer == 'qdh':
        day()
    elif questionsAnswer == 'qhs':
        time()
    elif questionsAnswer == 'qjj':
        game()
    else:
        birthday()

def day():
    import time
    time.sleep(1)
    nowDay = datetime.now()
    print ('Today is %s/%s/%s' % (nowDay.day,nowDay.month,nowDay.year))
    time.sleep(2)
    dayAnswer = input('Want to know what time it is? "Y" for yes and "N" for no: ').lower()
    if dayAnswer == 'n':
        questions()
    else:
        time()

def time():
    import time
    time.sleep(1)
    nowTime = datetime.now()
    print ('Right now it's %s hours, %s minutes and %s seconds.' % (nowTime.hour,nowTime.minute,nowTime.second))
    time.sleep(5)
        questions()
       ...

It might be something in start(), questions() or day() causing the error. Any ideas? Thanks a bunch!

Body:
It worked for me, try to not create your own time() method, I renamed it to "my_time()".

The time module defines a lot of functions so, or you just "import time" or you need to specify each function you wanna import like "from time import sleep"

from datetime import datetime
from time import time, sleep
import random
import sys

def questions():
    print ('Some things you can ask me:')
    sleep(1)
    print ('• What day is today? (qdh)')
    sleep(1)
    print ('• What time is it? (qhs)')
    sleep(1)
    print ('• I want to play a game! (qjj)')
    sleep(1)
    print ('• How many days till my birthday? (qda)')
    sleep(1)
    questionsAnswer = input()
    if questionsAnswer == 'qdh':
        day()
    elif questionsAnswer == 'qhs':
        my_time()
    elif questionsAnswer == 'qjj':
        my_game()
    else:
        my_birthday()

def day():
    sleep(1)
    nowDay = datetime.now()
    print ('Today is %s/%s/%s' % (nowDay.day,nowDay.month,nowDay.year))
    sleep(2)
    dayAnswer = input('Want to know what time it is? "Y" for yes and "N" for no: ').lower()
    if dayAnswer == 'n':
        questions()
    else:
        my_time()

def my_time():
    sleep(1)
    nowTime = datetime.now()
    print ('Right now it\'s %s hours, %s minutes and %s seconds.' % (nowTime.hour, nowTime.minute, nowTime.second))
    sleep(5)
    questions()

def my_game():
    pass

def my_birthday():
    pass

#def start():
name = input('Hi. What is your name? ')
print ('Nice to meet you, ' + str(name) + '.')
sleep(1)
print ('How old are you?')
age = input()
sleep(1)
print (age + '! Cool.')
sleep(2)
questions()


问:
Rails 3: How does "accepts_nested_attributes_for" work?
Consider the following association:

```<code>class Product < ActiveRecord::Base
  belongs_to :shop
  accepts_nested_attributes_for :shop
end
</code>```

If

```<code>params[:product][:shop_attributes] = {"name" => "My Shop"}
</code>```

and I do:

```<code>@product = Product.new(params[:product])
@product.save
</code>```

a new shop with name "My Shop" is created and assigned to the @product, as expected.

However, I can't figure out what happens when shop_attributes contains some id, like:

```<code>params[:product][:shop_attributes] = {"id" => "20", "name" => "My Shop"}
</code>```

I get the following error:

```<code>Couldn't find Shop with ID=20 for Product with ID=
</code>```

Question 1

What does this means ?

Question 2

If this is the case, i.e. the id of the shop is known, and the shop with such id already exist, how should I create the @product such that this shop will be assigned to it ?

答:
I think that you're trying to figure out creating a new associated item vs. associating with an existing item.

For creating a new item, you seem to have it working.
When you passed the id in shop_attributes, it did not work, because it's looking up an association that doesn't exist yet.

If you're trying to associate with an existing item, you should be using the following:

```<code>params[:product][:shop_id] = "20"
</code>```

This will assign the current product's shop to the shop with id 'shop_id'.  (Product should have a 'shop_id' column.)

Body:
Consider the following association:

class Product < ActiveRecord::Base
  belongs_to :shop
  accepts_nested_attributes_for :shop
end

If

params[:product][:shop_attributes] = {"name" => "My Shop"}

and I do:

@product = Product.new(params[:product])
@product.save

a new shop with name "My Shop" is created and assigned to the @product, as expected.

However, I can't figure out what happens when shop_attributes contains some id, like:

params[:product][:shop_attributes] = {"id" => "20", "name" => "My Shop"}

I get the following error:

Couldn't find Shop with ID=20 for Product with ID=

Question 1

What does this means ?

Question 2

If this is the case, i.e. the id of the shop is known, and the shop with such id already exist, how should I create the @product such that this shop will be assigned to it ?

Body:
I think that you're trying to figure out creating a new associated item vs. associating with an existing item.

For creating a new item, you seem to have it working.
When you passed the id in shop_attributes, it did not work, because it's looking up an association that doesn't exist yet.

If you're trying to associate with an existing item, you should be using the following:

params[:product][:shop_id] = "20"

This will assign the current product's shop to the shop with id 'shop_id'.  (Product should have a 'shop_id' column.)

ContentLicense: CC BY-SA 2.5


问:
User Form Multi Page Control - Page Caption Left Alignment
I was searching everywhere on the Net, and couldn't find a result if it is possible to align the Multi-Page Control (on a User Form)  Page Caption to the left (see image below).

I want that all pages caption will be aligned to the left - now it doesn't look so when they are aligned center (visually).

Thanks

答:
You can do this with vbTabat the end of your caption strings. In my example I've used TabFixedWidthproperty with a value of 90. For a shorter caption as for page 3 it's necessary to insert vbTabtwice. For a longer Caption as for page 7 no vbTabis needed.

```<code>mpgBid.Pages.Item("pg1").Caption = "1 Overview" & vbTab
mpgBid.Pages.Item("pg2").Caption = "2 Tables" & vbTab
mpgBid.Pages.Item("pg3").Caption = "3 Forms" & vbTab & vbTab
mpgBid.Pages.Item("pg4").Caption = "4 Databases" & vbTab
mpgBid.Pages.Item("pg5").Caption = "5 Reports" & vbTab
mpgBid.Pages.Item("pg6").Caption = "6 Examples" & vbTab
mpgBid.Pages.Item("pg7").Caption = "7 More Examples"
</code>```

screenshot

Body:
You can do this with vbTabat the end of your caption strings. In my example I've used TabFixedWidthproperty with a value of 90. For a shorter caption as for page 3 it's necessary to insert vbTabtwice. For a longer Caption as for page 7 no vbTabis needed.

mpgBid.Pages.Item("pg1").Caption = "1 Overview" & vbTab
mpgBid.Pages.Item("pg2").Caption = "2 Tables" & vbTab
mpgBid.Pages.Item("pg3").Caption = "3 Forms" & vbTab & vbTab
mpgBid.Pages.Item("pg4").Caption = "4 Databases" & vbTab
mpgBid.Pages.Item("pg5").Caption = "5 Reports" & vbTab
mpgBid.Pages.Item("pg6").Caption = "6 Examples" & vbTab
mpgBid.Pages.Item("pg7").Caption = "7 More Examples"

screenshot


问:
How to retrieve currently logged in username in Windows?
I wish to retrieve the username of the currently logged in user in Windows (preferably some solution that works from Windows XP to W10) in a Delphi 7 project.

I tried both solutions given in this question, but they all give the name of the user, not the actual "username" that is used to log into Windows.

For example, the "username" I use to log into Windows is "joao.victor" (using a local Windows account), or my e-mail when I use a Microsoft account. But when I tried those 2 solutions, the string it returned was "João", which is my first name and the name configured in those accounts.

Does anyone know of a solution where I can retrieve the username that is used to log into Windows instead of the first name of the user?

答:
GetUserNameEx is the most flexible, and offers various user names depending on the context and format you're looking to obtain. I don't know if it works in XP, but it does in Windows 2000 and up (tested up to Windows 7, Server 2008 and Windows Server 2012).

Here's a sample console app that has some type definitions that will help, along with the function declaration and sample code that demonstrates the possibilities. It compiles in both D2007 and Seattle/Berlin.

```<code>program Project1;

{$APPTYPE CONSOLE}

uses
  System.SysUtils, WinAPI.Windows;

type
  EXTENDED_NAME_FORMAT = DWORD;

const
  NameUnknown           = 0;
  NameFullyQualifiedDN  = 1;
  NameSamCompatible     = 2;
  NameDisplay           = 3;
  NameUniqueId          = 6;
  NameCanonical         = 7;
  NameUserPrincipal     = 8;
  NameCanonicalEx       = 9;
  NameServicePrincipal  = 10;
  NameDnsDomain         = 12;

const
  NameFormats: array[0..8] of EXTENDED_NAME_FORMAT = (NameFullyQualifiedDN,
                                                      NameSamCompatible,
                                                      NameDisplay,
                                                      NameUniqueID,
                                                      NameCanonical,
                                                      NameUserPrincipal,
                                                      NameCanonicalEx,
                                                      NameServicePrincipal,
                                                      NameDnsDomain);

function GetUserNameExW(NameFormat: EXTENDED_NAME_FORMAT; lpNameBuffer: LPWSTR;
  var nSize: ULONG): BOOL; stdcall;
    external 'secur32.dll' Name 'GetUserNameExW';

var
  UserName: String;
  Size: ULONG;
  i: Integer;
begin
  for i := Low(NameFormats) to High(NameFormats) do
  begin
    Size := 0;
    GetUserNameExW(NameFormats[i], nil, Size);
    SetLength(UserName, Size);
    if GetUserNameExW(NameFormats[i], PWideChar(UserName), Size) then
      WriteLn(Ord(NameFormats[i]), #32 + UserName);
  end;
  ReadLn;
end.
</code>```

Body:
GetUserNameEx is the most flexible, and offers various user names depending on the context and format you're looking to obtain. I don't know if it works in XP, but it does in Windows 2000 and up (tested up to Windows 7, Server 2008 and Windows Server 2012).

Here's a sample console app that has some type definitions that will help, along with the function declaration and sample code that demonstrates the possibilities. It compiles in both D2007 and Seattle/Berlin.

program Project1;

{$APPTYPE CONSOLE}

uses
  System.SysUtils, WinAPI.Windows;

type
  EXTENDED_NAME_FORMAT = DWORD;

const
  NameUnknown           = 0;
  NameFullyQualifiedDN  = 1;
  NameSamCompatible     = 2;
  NameDisplay           = 3;
  NameUniqueId          = 6;
  NameCanonical         = 7;
  NameUserPrincipal     = 8;
  NameCanonicalEx       = 9;
  NameServicePrincipal  = 10;
  NameDnsDomain         = 12;

const
  NameFormats: array[0..8] of EXTENDED_NAME_FORMAT = (NameFullyQualifiedDN,
                                                      NameSamCompatible,
                                                      NameDisplay,
                                                      NameUniqueID,
                                                      NameCanonical,
                                                      NameUserPrincipal,
                                                      NameCanonicalEx,
                                                      NameServicePrincipal,
                                                      NameDnsDomain);

function GetUserNameExW(NameFormat: EXTENDED_NAME_FORMAT; lpNameBuffer: LPWSTR;
  var nSize: ULONG): BOOL; stdcall;
    external 'secur32.dll' Name 'GetUserNameExW';

var
  UserName: String;
  Size: ULONG;
  i: Integer;
begin
  for i := Low(NameFormats) to High(NameFormats) do
  begin
    Size := 0;
    GetUserNameExW(NameFormats[i], nil, Size);
    SetLength(UserName, Size);
    if GetUserNameExW(NameFormats[i], PWideChar(UserName), Size) then
      WriteLn(Ord(NameFormats[i]), #32 + UserName);
  end;
  ReadLn;
end.