问:
Dynamic created User-Form, with 2 dependent Combo-Boxes
I am trying to create a dynamic User_form, where all the Controls are created at Run-Time.

I have 2 array of Combo-Boxes, first array of Combo-Boxes is "Catgeory" (CatCBArr) , and the second array of Combo-Boxes is "Item" (ItemCBArr).

I want, that once I select a value from the first Combo-Box of "Category", let's say CatCBArr(0), that only the related Items in ItemCBArr(0) will be displayed.

Issue: I can't figure out how to modify the second Combo-box (ItemCBArr(0)) according to the value selected in the first Combo-box (CatCBArr(0))

User_Form Code (relevant section)

```<code>Option Explicit

Dim ItemsNumofRows As Long
Dim QtyTB As MSForms.TextBox
Dim CatCB As MSForms.ComboBox
Dim ItemCB As MSForms.ComboBox

Dim Key As Variant

' dynamic Form controls (related to new Classes)
Dim CatCBArr()                     As New cComboBox
Dim ItemCBArr()                    As New cComboBox
Dim QtyTBArr()                     As New cTextBox

Private Sub UserForm_Initialize()

' reset flags
ItemsNumofRows = 5
TasksNamesUpd = False
TasksColUpd = False

ItemsRows_ControlsInit '<-- upload all Controls at run-time
Check_FormHeight

End Sub

'======================================================

Private Sub ItemsRows_ControlsInit()

For ItemRow = 0 To ItemsNumofRows

    ' add Category Combo-boxes
    Set CatCB = Me.Controls.Add("Forms.ComboBox.1", "Cb" & ItemRow, True)
    With CatCB
        ' loop through Dictionay items (view category)
        For Each Key In Dict.Keys
            .AddItem Key
        Next Key

        .SpecialEffect = fmSpecialEffectSunken
        .Left = 40
        .Width = 100
        .Height = 18
        .Top = 54 + 20 * ItemRow

        ReDim Preserve CatCBArr(0 To ItemRow)
        Set CatCBArr(ItemRow).ComboBoxEvents = CatCB
    End With

    ' add Item Combo-boxes
    Set ItemCB = Me.Controls.Add("Forms.ComboBox.1", "Cb_" & ItemRow, True)
    With ItemCB

        .SpecialEffect = fmSpecialEffectSunken
        .Left = 160
        .Width = 100
        .Height = 18
        .Top = 54 + 20 * ItemRow

        ReDim Preserve ItemCBArr(0 To ItemRow)
        Set ItemCBArr(ItemRow).ComboBoxEvents = ItemCB
    End With
Next ItemRow

End Sub
</code>```

cComboBox Class Code

```<code>Public WithEvents ComboBoxEvents As MSForms.ComboBox

Private Sub ComboBoxEvents_Change()

Dim CBIndex                            As Long

' get for ID number (row number), from third character in String Name.
' e.g "Cb1" will result 1)
CBIndex = CInt(Mid(ComboBoxEvents.Name, 3))

' ??? How do I get the Value, and update the second combo-box Items

Select Case ComboBoxEvents.Value

End Select

End Sub
</code>```

GUI User_Form screen-shot

答:
Alright, here's the basics.
Your class cCombobox I replicated as follows:

```<code>Private WithEvents ComboBoxEvents As MsForms.ComboBox
Private Sub ComboBoxEvents_Change()
    Select Case ComboBoxEvents.value
        Case "1":
            UserForm1.DependentBox.Clear
            UserForm1.DependentBox.AddItem "3"
            UserForm1.DependentBox.AddItem "4"
        Case "2":
            UserForm1.DependentBox.Clear
            UserForm1.DependentBox.AddItem "5"
            UserForm1.DependentBox.AddItem "6"
        Case Default:
            'Do Nothing
    End Select
End Sub
Public Property Let box(value As MsForms.ComboBox)
    Set ComboBoxEvents = value
End Property
Public Property Get box() As MsForms.ComboBox
    Set box = ComboBoxEvents
End Property
</code>```

Next, I created a UserForm1 that adds 2 comboboxes, one of which I add to a local variable of type cComboBox.

```<code>Public DependentBox As MsForms.ComboBox
Private InitialBox As cComboBox
Private Sub UserForm_Initialize()
    Dim cBox As MsForms.ComboBox
    Set InitialBox = New cComboBox

    Set cBox = Me.Controls.Add("Forms.ComboBox.1", "initial", True)
    With cBox
        .Left = 6
        .Width = 100
        .Height = 25
        .Top = 6
        .AddItem "1"
        .AddItem "2"
    End With
    InitialBox.box = cBox

    Set DependentBox = Me.Controls.Add("Forms.ComboBox.1", "dependent", True)
    With DependentBox
        .Top = 6
        .Left = 126
        .Height = 25
        .Width = 100
    End With
End Sub
</code>```

Even though this works, the above approach is not very clean, since your class is not self-contained - It has to be aware of the UserForm. A better way would be to link the boxes in the class already and then just pass them from the Userform when you initialize your arrays of controls.
Then it would be:

cComboBox class:

```<code>Private WithEvents p_ComboBoxEvents As MSForms.ComboBox
Private p_DependBox As MSForms.ComboBox
Private Sub p_ComboBoxEvents_Change()
    Select Case p_ComboBoxEvents.value
        Case "1":
            p_DependBox.Clear
            p_DependBox.AddItem "3"
            p_DependBox.AddItem "4"
        Case "2":
            p_DependBox.Clear
            p_DependBox.AddItem "5"
            p_DependBox.AddItem "6"
        Case Default:
            'Do Nothing
    End Select
End Sub
Public Property Let TriggerBox(value As MSForms.ComboBox)
    Set p_ComboBoxEvents = value
End Property
Public Property Get TriggerBox() As MSForms.ComboBox
    Set TriggerBox = p_ComboBoxEvents
End Property
Public Property Let DependBox(value As MSForms.ComboBox)
    Set p_DependBox = value
End Property
Public Property Get DependBox() As MSForms.ComboBox
    Set DependBox = p_DependBox
End Property
</code>```

Here you see you already link the boxes in a self-contained class.
In the event handler you could create a lookup for the values, etc.
Then in the UserForm1 code you initialize them as follows:

```<code>Option Explicit
Private LinkedComboBox As cComboBox
Private Sub UserForm_Initialize()
    Dim cBox As MSForms.ComboBox
    Set LinkedComboBox = New cComboBox

    Set cBox = Me.Controls.Add("Forms.ComboBox.1", "initial", True)
    With cBox
        .Left = 6
        .Width = 100
        .Height = 25
        .Top = 6
        .AddItem "1"
        .AddItem "2"
    End With
    LinkedComboBox.TriggerBox = cBox

    Set cBox = Me.Controls.Add("Forms.ComboBox.1", "dependent", True)
    With cBox
        .Top = 6
        .Left = 126
        .Height = 25
        .Width = 100
    End With
    LinkedComboBox.DependBox = cBox
End Sub
</code>```

EDIT:
Based on the fact that it needs to be an array, you can amend the userform as follows:

```<code>Option Explicit
Private LinkedComboBox(0 To 4) As cComboBOx
Private Sub UserForm_Initialize()
    Dim cBox As MSForms.ComboBox
    Dim i As Integer

    For i = 0 To 4
        Set LinkedComboBox(i) = New cComboBOx
        Set cBox = Me.Controls.Add("Forms.ComboBox.1", "initial", True)
        With cBox
            .Left = 6
            .Width = 100
            .Height = 25
            .Top = 6 + (i * 25)
            .AddItem "1"
            .AddItem "2"
        End With
        LinkedComboBox(i).TriggerBox = cBox

        Set cBox = Me.Controls.Add("Forms.ComboBox.1", "dependent", True)
        With cBox
            .Top = 6 + (i * 25)
            .Left = 126
            .Height = 25
            .Width = 100
        End With
        LinkedComboBox(i).DependBox = cBox
    Next i

End Sub
</code>```

In the array you can access each box as LinkedComboBox(i).DependBox and LinkedComboBox(i).TriggerBox. You won't need the two seperate arrays anymore, since everything is already contained in this LinkedComboBox array

Body:
I am trying to create a dynamic User_form, where all the Controls are created at Run-Time.

I have 2 array of Combo-Boxes, first array of Combo-Boxes is "Catgeory" (CatCBArr) , and the second array of Combo-Boxes is "Item" (ItemCBArr).

I want, that once I select a value from the first Combo-Box of "Category", let's say CatCBArr(0), that only the related Items in ItemCBArr(0) will be displayed.

Issue: I can't figure out how to modify the second Combo-box (ItemCBArr(0)) according to the value selected in the first Combo-box (CatCBArr(0))

User_Form Code (relevant section)

Option Explicit

Dim ItemsNumofRows As Long
Dim QtyTB As MSForms.TextBox
Dim CatCB As MSForms.ComboBox
Dim ItemCB As MSForms.ComboBox

Dim Key As Variant

' dynamic Form controls (related to new Classes)
Dim CatCBArr()                     As New cComboBox
Dim ItemCBArr()                    As New cComboBox
Dim QtyTBArr()                     As New cTextBox

Private Sub UserForm_Initialize()

' reset flags
ItemsNumofRows = 5
TasksNamesUpd = False
TasksColUpd = False

ItemsRows_ControlsInit '<-- upload all Controls at run-time
Check_FormHeight

End Sub

'======================================================

Private Sub ItemsRows_ControlsInit()

For ItemRow = 0 To ItemsNumofRows

    ' add Category Combo-boxes
    Set CatCB = Me.Controls.Add("Forms.ComboBox.1", "Cb" & ItemRow, True)
    With CatCB
        ' loop through Dictionay items (view category)
        For Each Key In Dict.Keys
            .AddItem Key
        Next Key

        .SpecialEffect = fmSpecialEffectSunken
        .Left = 40
        .Width = 100
        .Height = 18
        .Top = 54 + 20 * ItemRow

        ReDim Preserve CatCBArr(0 To ItemRow)
        Set CatCBArr(ItemRow).ComboBoxEvents = CatCB
    End With

    ' add Item Combo-boxes
    Set ItemCB = Me.Controls.Add("Forms.ComboBox.1", "Cb_" & ItemRow, True)
    With ItemCB

        .SpecialEffect = fmSpecialEffectSunken
        .Left = 160
        .Width = 100
        .Height = 18
        .Top = 54 + 20 * ItemRow

        ReDim Preserve ItemCBArr(0 To ItemRow)
        Set ItemCBArr(ItemRow).ComboBoxEvents = ItemCB
    End With
Next ItemRow

End Sub

cComboBox Class Code

Public WithEvents ComboBoxEvents As MSForms.ComboBox

Private Sub ComboBoxEvents_Change()

Dim CBIndex                            As Long

' get for ID number (row number), from third character in String Name.
' e.g "Cb1" will result 1)
CBIndex = CInt(Mid(ComboBoxEvents.Name, 3))

' ??? How do I get the Value, and update the second combo-box Items

Select Case ComboBoxEvents.Value

End Select

End Sub

GUI User_Form screen-shot

Body:
Alright, here's the basics.
Your class cCombobox I replicated as follows:

Private WithEvents ComboBoxEvents As MsForms.ComboBox
Private Sub ComboBoxEvents_Change()
    Select Case ComboBoxEvents.value
        Case "1":
            UserForm1.DependentBox.Clear
            UserForm1.DependentBox.AddItem "3"
            UserForm1.DependentBox.AddItem "4"
        Case "2":
            UserForm1.DependentBox.Clear
            UserForm1.DependentBox.AddItem "5"
            UserForm1.DependentBox.AddItem "6"
        Case Default:
            'Do Nothing
    End Select
End Sub
Public Property Let box(value As MsForms.ComboBox)
    Set ComboBoxEvents = value
End Property
Public Property Get box() As MsForms.ComboBox
    Set box = ComboBoxEvents
End Property

Next, I created a UserForm1 that adds 2 comboboxes, one of which I add to a local variable of type cComboBox.

Public DependentBox As MsForms.ComboBox
Private InitialBox As cComboBox
Private Sub UserForm_Initialize()
    Dim cBox As MsForms.ComboBox
    Set InitialBox = New cComboBox

    Set cBox = Me.Controls.Add("Forms.ComboBox.1", "initial", True)
    With cBox
        .Left = 6
        .Width = 100
        .Height = 25
        .Top = 6
        .AddItem "1"
        .AddItem "2"
    End With
    InitialBox.box = cBox

    Set DependentBox = Me.Controls.Add("Forms.ComboBox.1", "dependent", True)
    With DependentBox
        .Top = 6
        .Left = 126
        .Height = 25
        .Width = 100
    End With
End Sub

Even though this works, the above approach is not very clean, since your class is not self-contained - It has to be aware of the UserForm. A better way would be to link the boxes in the class already and then just pass them from the Userform when you initialize your arrays of controls.
Then it would be:

cComboBox class:

Private WithEvents p_ComboBoxEvents As MSForms.ComboBox
Private p_DependBox As MSForms.ComboBox
Private Sub p_ComboBoxEvents_Change()
    Select Case p_ComboBoxEvents.value
        Case "1":
            p_DependBox.Clear
            p_DependBox.AddItem "3"
            p_DependBox.AddItem "4"
        Case "2":
            p_DependBox.Clear
            p_DependBox.AddItem "5"
            p_DependBox.AddItem "6"
        Case Default:
            'Do Nothing
    End Select
End Sub
Public Property Let TriggerBox(value As MSForms.ComboBox)
    Set p_ComboBoxEvents = value
End Property
Public Property Get TriggerBox() As MSForms.ComboBox
    Set TriggerBox = p_ComboBoxEvents
End Property
Public Property Let DependBox(value As MSForms.ComboBox)
    Set p_DependBox = value
End Property
Public Property Get DependBox() As MSForms.ComboBox
    Set DependBox = p_DependBox
End Property

Here you see you already link the boxes in a self-contained class.
In the event handler you could create a lookup for the values, etc.
Then in the UserForm1 code you initialize them as follows:

Option Explicit
Private LinkedComboBox As cComboBox
Private Sub UserForm_Initialize()
    Dim cBox As MSForms.ComboBox
    Set LinkedComboBox = New cComboBox

    Set cBox = Me.Controls.Add("Forms.ComboBox.1", "initial", True)
    With cBox
        .Left = 6
        .Width = 100
        .Height = 25
        .Top = 6
        .AddItem "1"
        .AddItem "2"
    End With
    LinkedComboBox.TriggerBox = cBox

    Set cBox = Me.Controls.Add("Forms.ComboBox.1", "dependent", True)
    With cBox
        .Top = 6
        .Left = 126
        .Height = 25
        .Width = 100
    End With
    LinkedComboBox.DependBox = cBox
End Sub

EDIT:
Based on the fact that it needs to be an array, you can amend the userform as follows:

Option Explicit
Private LinkedComboBox(0 To 4) As cComboBOx
Private Sub UserForm_Initialize()
    Dim cBox As MSForms.ComboBox
    Dim i As Integer

    For i = 0 To 4
        Set LinkedComboBox(i) = New cComboBOx
        Set cBox = Me.Controls.Add("Forms.ComboBox.1", "initial", True)
        With cBox
            .Left = 6
            .Width = 100
            .Height = 25
            .Top = 6 + (i * 25)
            .AddItem "1"
            .AddItem "2"
        End With
        LinkedComboBox(i).TriggerBox = cBox

        Set cBox = Me.Controls.Add("Forms.ComboBox.1", "dependent", True)
        With cBox
            .Top = 6 + (i * 25)
            .Left = 126
            .Height = 25
            .Width = 100
        End With
        LinkedComboBox(i).DependBox = cBox
    Next i

End Sub

In the array you can access each box as LinkedComboBox(i).DependBox and LinkedComboBox(i).TriggerBox. You won't need the two seperate arrays anymore, since everything is already contained in this LinkedComboBox array


来源: stackexchange

问:
NSInvalidArgument Exception when click next Button in Walkthrough Screens
I am making IntroScreens for iOS app, Every thing is perfect but when I click next button it shows NSInvalidArgumentException error

pageContentViewController

```<code>- (IBAction)nextButtonTapped:(id)sender {

switch (self.pageIndex) {
    case 0:
    case 1:
        pageViewController  = ((PageViewController *)self.parentViewController);
        [pageViewController forward:self.pageIndex];
        break;
    case 2:

       [self performSegueWithIdentifier:@"LoginScreen" sender:nil];

        break;

    default:
        break;
}
}
</code>```

PageViewController

```<code>-(void)forward:(NSUInteger)index{

    [self.pageViewController  setViewControllers:@[[self viewControllerAtIndexArabic:index +1]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];

  }

reason: '-[UIPageViewController forward:]: unrecognized selector sent to instance 0x7fb2cf009600
</code>```

答:
The issue it with the following code block
 pageViewController  = ((PageViewController *)self.parentViewController);

I guess you have set your pageviewcontroller in storyboard which is an instance of UIPageViewController but in the code you are trying to access PageViewController ( which I guess is a third party controller ).

So you must change the class of your UIPageViewController in storyboard to PageViewController.

ContentLicense: CC BY-SA 3.0

Body:
I am making IntroScreens for iOS app, Every thing is perfect but when I click next button it shows NSInvalidArgumentException error

pageContentViewController

- (IBAction)nextButtonTapped:(id)sender {

switch (self.pageIndex) {
    case 0:
    case 1:
        pageViewController  = ((PageViewController *)self.parentViewController);
        [pageViewController forward:self.pageIndex];
        break;
    case 2:

       [self performSegueWithIdentifier:@"LoginScreen" sender:nil];

        break;

    default:
        break;
}
}

PageViewController

-(void)forward:(NSUInteger)index{

    [self.pageViewController  setViewControllers:@[[self viewControllerAtIndexArabic:index +1]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];

  }

reason: '-[UIPageViewController forward:]: unrecognized selector sent to instance 0x7fb2cf009600


问:
Calculator should accepting all operators
Can u please help on this on this calculator.

答:
```<code>$("#idCalculadoratxtResultado").focus();
    $(function () {
    $("input[id*='idCalculadoratxtResultado']").keyup(function (e) {
        var val = $(this).val();
        if (isNaN(val)) {
            debugger;
            val = val.replace("^[0-9+-*\\-`.+,/\"]*$", '');
            if (val.split('..').length > 1)
                val = val.replace(/\.+$/, ".");
            if (val.split('++').length > 1)
                val = val.replace('++', "+");
            if (val.split('--').length > 1)
                val = val.replace('--', "-");
            if (val.split('**').length > 1)
                val = val.replace('**', "*");
            if (val.split('//').length > 1)
                val = val.replace('//', "/");
        }
        $(this).val(val);
    });
    });
    $("#idCalculadora").on("keydown", function search(e) {

        if (e.keyCode == 13) {
            $(".btn-warning").focus();
        }
    });
    $("#idCalculadora").Calculadora();
});
$("#idCalculadora").dialog({
    autoOpen: false,
    modal: true,
    title: "Calculator",
    overflow: "hidden",
    width: "300",
    //close: function () {
    //    $('#idCalculadora').empty();
    //}
});
$('#Calculator').click(function () {
    debugger;
    $("#idCalculadora").removeClass('hide');
    $("#idCalculadora").dialog("open");
});
</code>```

here I am using this  code and plugins only and not any code for this

Body:
$("#idCalculadoratxtResultado").focus();
    $(function () {
    $("input[id*='idCalculadoratxtResultado']").keyup(function (e) {
        var val = $(this).val();
        if (isNaN(val)) {
            debugger;
            val = val.replace("^[0-9+-*\\-`.+,/\"]*$", '');
            if (val.split('..').length > 1)
                val = val.replace(/\.+$/, ".");
            if (val.split('++').length > 1)
                val = val.replace('++', "+");
            if (val.split('--').length > 1)
                val = val.replace('--', "-");
            if (val.split('**').length > 1)
                val = val.replace('**', "*");
            if (val.split('//').length > 1)
                val = val.replace('//', "/");
        }
        $(this).val(val);
    });
    });
    $("#idCalculadora").on("keydown", function search(e) {

        if (e.keyCode == 13) {
            $(".btn-warning").focus();
        }
    });
    $("#idCalculadora").Calculadora();
});
$("#idCalculadora").dialog({
    autoOpen: false,
    modal: true,
    title: "Calculator",
    overflow: "hidden",
    width: "300",
    //close: function () {
    //    $('#idCalculadora').empty();
    //}
});
$('#Calculator').click(function () {
    debugger;
    $("#idCalculadora").removeClass('hide');
    $("#idCalculadora").dialog("open");
});

here I am using this  code and plugins only and not any code for this


问:
Hangfire Error `Connection string is missing for the SQL error log
I am busy trying to add hangfire to my MVC project. I am following the Quick Start Guide

I have added this to my startup.cs file

```<code>   public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);

        //Hangfire
        GlobalConfiguration.Configuration.UseSqlServerStorage("data source=ip;initial catalog=Name;user id=Hangfire;password=Password;");
        app.UseHangfireDashboard();
        app.UseHangfireServer();
    }
</code>```

However when I run my project I get the following error:  (it highlights the GlobalConfiguration.Configuration.UseSqlServerStorage line in my startup.cs class)

```<code>Connection string is missing for the SQL error log.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Elmah.ApplicationException: Connection string is missing for the SQL error log.
</code>```

答: It turns out the error message had nothing to do with hangfire. I simply did not have a connection string for Elmah in the web config.</p>

Body:
I am busy trying to add hangfire to my MVC project. I am following the Quick Start Guide

I have added this to my startup.cs file

   public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);

        //Hangfire
        GlobalConfiguration.Configuration.UseSqlServerStorage("data source=ip;initial catalog=Name;user id=Hangfire;password=Password;");
        app.UseHangfireDashboard();
        app.UseHangfireServer();
    }

However when I run my project I get the following error:  (it highlights the GlobalConfiguration.Configuration.UseSqlServerStorage line in my startup.cs class)

Connection string is missing for the SQL error log.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Elmah.ApplicationException: Connection string is missing for the SQL error log.


问:
Showing loading image with getJSON
I want to use a loading image while retrieving data through AJAX with getJSON. I have been looking around but haven't yet found a proper way of doing this. What is the best way to do this?</p>

```<code>$.getJSON('file.php', function(json) {
    $.each(json, function() {

    // Retrieving data from json...

    });
});
</code>```

答:
.ajaxStart() documentation says :

As of jQuery 1.9, all the handlers for the jQuery global Ajax events,
  including those added with the .ajaxStart() method, must be attached
  to document.

If $.ajax() or $.ajaxSetup() is called with the global option set to false, the .ajaxStart() method will not fire.

Title: Showing loading image with getJSON

Body:
I want to use a loading image while retrieving data through AJAX with getJSON. I have been looking around but haven't yet found a proper way of doing this. What is the best way to do this?

$.getJSON('file.php', function(json) {
    $.each(json, function() {

    // Retrieving data from json...

    });
});


问:
EF Code First Migration list
I want to see all available of migrations in a project. Command Get-Migrations returns all applied migrations to DB, but I want to see all migration list, including not applied. Reason : I have created one more migration in the project and want to remove it. I removed files of migration, but Visual Studio (solution) remember of this migration and want to apply it.

Where is 201706071156593_AutomaticMigration at all and how to remove it?

答:
Deleting the files should be sufficient - have you built the project since?

You can programmatically access the list of migrations using the DbMigrator class, which has a method GetPendingMigrations() which will return the name of all migrations which it is aware of that have not yet been applied.

Update: Now that you've updated your question with the migration name, it becomes clear that because you have Automatic Migrations enabled (in the constructor of Configuration), this is the cause.  To use explicit migrations only, change AutomaticMigrationsEnabled to false.

Title: EF Code First Migration list


问:
CSS Change background color by User
i'm writing a page for a mobile version of a website and i'd like to insert a checkbox with label Dark Theme, when an user check this box change background color (of entire website) to black and text color to white, i found many part of codes in internet but it doesn't works, i don't know why.

For Example i tried this:

#select1:checked ~ div .wrapper{
 background-color:black;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
<input id="select1" name="check1" type="checkbox" />
<label for="select1">Dark Theme</label>
</div></code>```

Can you help me?
Thank you

答:
Change div background color by using css   </p>

```<code><!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <style type="text/css">
    .wrapper{
        width:50px;
        height:50px;
        background-color:#000;
    }

    #select2:checked ~ .wrapper{
        background-color:#060;
    }

    #select3:checked ~ .wrapper{
        background-color:#0000FF;
    }
    </style>
    </head>

    <body>
            <input id="select1" name="check1" type="checkbox" checked />
            <label for="select1">Dark Theme</label>
        <input id="select2" name="check1" type="checkbox" />
            <label for="select2">Green Theme</label>
        <input id="select3" name="check1" type="checkbox" />
            <label for="select3">Blue Theme</label>

        <div class="wrapper"></div>

    </body>
    </html>
</code>```

Title: CSS Change background color by User

Body:
i'm writing a page for a mobile version of a website and i'd like to insert a checkbox with label Dark Theme, when an user check this box change background color (of entire website) to black and text color to white, i found many part of codes in internet but it doesn't works, i don't know why.

For Example i tried this:

#select1:checked ~ div .wrapper{
 background-color:black;
  color: white;
}

<input id="select1" name="check1" type="checkbox" />
Dark Theme

Can you help me?
Thank you

Body:
Change div background color by using css

<!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <style type="text/css">
    .wrapper{
        width:50px;
        height:50px;
        background-color:#000;
    }

    #select2:checked ~ .wrapper{
        background-color:#060;
    }

    #select3:checked ~ .wrapper{
        background-color:#0000FF;
    }
    </style>
    </head>

    <body>
            <input id="select1" name="check1" type="checkbox" checked />
            <label for="select1">Dark Theme</label>
        <input id="select2" name="check1" type="checkbox" />
            <label for="select2">Green Theme</label>
        <input id="select3" name="check1" type="checkbox" />
            <label for="select3">Blue Theme</label>

        <div class="wrapper"></div>

    </body>
    </html>


答:
np.argsort(arr[:, -1]) will give you the permutation so that elements of the last column of arr are ordered.

Then, arr[np.argsort(arr[:, -1])] reorders the rows of arr according to this permutation.

Beware that the lexicographic order is used since your data consists of string, so 0_10 comes before 0_2. If this is not what you want, you should split the last column, and I advise you to use a pandas.DataFrame:

```<code>import pandas as pd
df = pd.DataFrame(arr)
df['Cell'], df['CellIndex'] = df[df.columns[-1]].str.split('_', 1).str
df['Cell'] = df['Cell'].astype(int)
df['CellIndex'] = df['CellIndex'].astype(int)
df.sort_values(['Cell', 'CellIndex'])
</code>```

pandas is really the way to go to manipulate this kind of data.

Title: How to sort a NumPy array of strings by the last column

Body:
Is there a way to sort the rows of an array by the last element, in this case the cell ids. The cell id is build as follows : "CellID_NumberOfCell

arr =np.array([['65.0','30.0','20.0','0.0','0_0'],
 ['2.0','29.0','24.0','0.0','1_0'],
 ['0.0','18.0','4.0','0.0','2_0'],
 ['16.0','9.0','0.0','9990.0','7_203'],
 ['16.0','9.0','0.0','9990.0','0_203'],
 ['20.0','23.0','31.0','9990.0','8_158'],
 ['65.0','30.0','20.0','0.0','0_10']])

So after sorting it should look like:

arr =np.array([['65.0','30.0','20.0','0.0','0_0'],
 ['65.0','30.0','20.0','0.0','0_10'],
 ['16.0','9.0','0.0','9990.0','0_203'],
 ['2.0','29.0','24.0','0.0','1_0'],
 ['0.0','18.0','4.0','0.0','2_0'],
 ['16.0','9.0','0.0','9990.0','7_203'],
 ['20.0','23.0','31.0','9990.0','8_158']])

EDIT:

Is it also possible to delete the numbers after the underscore after sorting?. So that i just have the ID. Instead of 0_0 just 0.

EDIT2

After sorting the ID, it should also sort after time, so that every ID with 0 for example should also be sorted after time 0,1...9999 etc.

Body:
np.argsort(arr[:, -1]) will give you the permutation so that elements of the last column of arr are ordered.

Then, arr[np.argsort(arr[:, -1])] reorders the rows of arr according to this permutation.

Beware that the lexicographic order is used since your data consists of string, so 0_10 comes before 0_2. If this is not what you want, you should split the last column, and I advise you to use a pandas.DataFrame:

import pandas as pd
df = pd.DataFrame(arr)
df['Cell'], df['CellIndex'] = df[df.columns[-1]].str.split('_', 1).str
df['Cell'] = df['Cell'].astype(int)
df['CellIndex'] = df['CellIndex'].astype(int)
df.sort_values(['Cell', 'CellIndex'])

pandas is really the way to go to manipulate this kind of data.


问:
MVC4 - Custom Controller for all calls (including WebAPI)
I am building an MVC4 application, where I have the normal MVC views and I have added a few WebAPI controllers.
I know that the corresponding controllers exist in different namespaces (System.Web.Mvc and System.Web.Http).

So, I want to create a custom controller which will capture all incoming calls (to webpages and to WebAPI), register the call and perform authorisation, all in one class for consistency.

Is there a MVC way to do that?
If this cannot be done with 1 custom controller, is there any other approach to this? Would a HttpModule be a good idea for an MVC application?

Right now, I have created 2 similar classes which derive from:
System.Web.Http.ApiController and
System.Web.Mvc.Controller
but does not seem like a good idea, as I almost duplicate the code.

答:
I think that for this pourpose is better to use global filters.
But you will need slightly different implementations for Mvc and WebApi

See some examples here:
How to add global ASP.Net Web Api Filters?


问:
Linq to many objects using MVC
I am trying to use Linq to create an object which itself contains 2 data objects. From the Linq expression I am trying to set up the objects directly rather than having an inbetween function in the containing class.

The containing class looks like this:

```<code>public class SupplierCategories
{

    public  category _category;
    public category_sub _category_sub;
    private bool _IsActive;
    private int? _SupplierID;

    public SupplierCategories()
    {

    }

    public bool IsActive
    {
        get
        {
            return _IsActive;
        }
        set
        {
            _IsActive = value;
        }
    }

    public int? SupplierID
    {
        get
        {
            return _SupplierID;
        }
        set
        {
            _SupplierID = value;
            if (_SupplierID != null) // The county is active if there is a supplier ID matching
            {
                _IsActive = true;
            }
        }

    }
}
</code>```

Note: category and category_sub objects are all set up through the Entity Framework.

My link expression has 2 tables and looks like this:

```<code>    public IEnumerable<SupplierCategories> GetAllOrdered()
    {
        IEnumerable<SupplierCategories> areaList;

        var results = from cat in dbContext.categories
                      join sub in dbContext.category_sub on cat.id equals sub.categoryid
                      orderby cat.id ascending, sub.name ascending
                      select new SupplierCategories
                      {
                          _category = { new category { cat.id, cat.name } },
                          _category_sub = { new category_sub { sub.id, sub.categoryid, sub.name } }
                      };

        areaList = results.ToList();

        return areaList;
    }
</code>```

Hopefully you can see that I am trying to create the "_category" and "_category_sub" objects directly.

The error I get is:

Error 5 Cannot initialize type
  'Essential_Collections.Models.category'
  with a collection initializer because
  it does not implement
  'System.Collections.IEnumerable'
  D:\Websites\Essential
  Collections\development\build\Essential
  Collections\Models\SupplierCategories\SupplierCategoriesRepository.cs
  51 37 Essential Collections

Any solutions or possibly other approaches would be gratefully received

答:
You missed the parantheses on the constructor call:</p>

```<code>select new SupplierCategories()
{
</code>```

ContentLicense: CC BY-SA 2.5

Title: Linq to many objects using MVC

Body:
I am trying to use Linq to create an object which itself contains 2 data objects. From the Linq expression I am trying to set up the objects directly rather than having an inbetween function in the containing class.

The containing class looks like this:

public class SupplierCategories
{

    public  category _category;
    public category_sub _category_sub;
    private bool _IsActive;
    private int? _SupplierID;

    public SupplierCategories()
    {

    }

    public bool IsActive
    {
        get
        {
            return _IsActive;
        }
        set
        {
            _IsActive = value;
        }
    }

    public int? SupplierID
    {
        get
        {
            return _SupplierID;
        }
        set
        {
            _SupplierID = value;
            if (_SupplierID != null) // The county is active if there is a supplier ID matching
            {
                _IsActive = true;
            }
        }

    }
}

Note: category and category_sub objects are all set up through the Entity Framework.

My link expression has 2 tables and looks like this:

    public IEnumerable<SupplierCategories> GetAllOrdered()
    {
        IEnumerable<SupplierCategories> areaList;

        var results = from cat in dbContext.categories
                      join sub in dbContext.category_sub on cat.id equals sub.categoryid
                      orderby cat.id ascending, sub.name ascending
                      select new SupplierCategories
                      {
                          _category = { new category { cat.id, cat.name } },
                          _category_sub = { new category_sub { sub.id, sub.categoryid, sub.name } }
                      };

        areaList = results.ToList();

        return areaList;
    }

Hopefully you can see that I am trying to create the "_category" and "_category_sub" objects directly.

The error I get is:

Error 5 Cannot initialize type
  'Essential_Collections.Models.category'
  with a collection initializer because
  it does not implement
  'System.Collections.IEnumerable'
  D:\Websites\Essential
  Collections\development\build\Essential
  Collections\Models\SupplierCategories\SupplierCategoriesRepository.cs
  51 37 Essential Collections

Any solutions or possibly other approaches would be gratefully received

Body:
You missed the parantheses on the constructor call:

select new SupplierCategories()
{


问:
How to prevent Soft Keyboard hiding button in custom dialog?
I have a custom dialog like following

When soft keyboard comes it hides the Button like below.

my code

https://mcaf.ee/9qhnef

How to avoid Submit button being hide?  i have added autoresize and auto pan but no luck so far.

答:
You can try this :

```<code>dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
</code>```

or in XML you can change this:

```<code>android:focusable="true"
android:focusableInTouchMode="true"
</code>```

Body:
You can try this :

dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

or in XML you can change this:

android:focusable="true"
android:focusableInTouchMode="true"

ContentLicense: CC BY-SA 4.0


问:
"Could not load type [Namespace].Global" causing me grief
In my .Net 2.0 Asp.net WebForms app, I have my Global.asax containing the following code:

```<code><%@ Application CodeBehind="Global.asax.cs" Inherits="MyNamespace.Global" Language="C#" %>
</code>```

However when I build I get an error stating-

Could not load type 'MyNamespace.Global'.

This seems to be because the MyNamespace namespace (defined in the code behind file Global.asax.cs) is not seen by the compiler in the Global.asax file (does not show in R# intellisence..).
This turned out to be a very hard nut to crack... any help will be appreciated!

Note: The Global.asax and the Global.asax.cs are located in the same folder.

Note2: When compiling from the vs prompt with csc it compiles o.k.

答: If you are using Visual Studio, You probably are trying to execute the application in the Release Mode, try changing it to the Debug Mode.</p>

Body:
In my .Net 2.0 Asp.net WebForms app, I have my Global.asax containing the following code:

<%@ Application CodeBehind="Global.asax.cs" Inherits="MyNamespace.Global" Language="C#" %>

However when I build I get an error stating-

Could not load type 'MyNamespace.Global'.

This seems to be because the MyNamespace namespace (defined in the code behind file Global.asax.cs) is not seen by the compiler in the Global.asax file (does not show in R# intellisence..).
This turned out to be a very hard nut to crack... any help will be appreciated!

Note: The Global.asax and the Global.asax.cs are located in the same folder.

Note2: When compiling from the vs prompt with csc it compiles o.k.


问:
Conditional assignment in if clause
I have a code which I do not want to duplicate too much, it looks something like this:

```<code>myEnum setting;

if (((input == "Enum0") && ((setting = myEnum_0) == setting)) ||
    ((input == "Enum1") && ((setting = myEnum_1) == setting)) ||
    ((input == "Enum2") && ((setting = myEnum_2) == setting)))
{
    doActionWith(setting);
}
</code>```

This way I don't have to check if the input was something totally different (if I just assigned with

```<code>if (input=="Enum0")
    setting = myEnum_0;
</code>```

the code wouldn't know if the enum was actually set, or not.

Now I wonder, is there a more elegant solution for the thing at the end?

The && ((setting = myEnum_x) == setting) ?

答:
I'd go with this:

```<code>//in the part of the code where you declare myEnum,
//if in a header, you might want to declare this inline
myEnum toMyEnum(const string input){
    if(input == "Enum0")
        return myEnum_0;
    ...
    return undefinedMyEnum;
}
</code>```

and then you go with

```<code>myEnum setting = toMyEnum(input);
if(setting != undefinedMyEnum){
    doActionWith(setting);
}
</code>```

This way, you have clear responsibilities. You simply take a string and transform it into your enumeration. Your code with the side effect is difficult to read, avoid such "tricks".

edit: on a second thought, right now my code produces a silent error, that is most likely not that good. You might want to replace return undefinedMyEnum; with something such as an EXIT or throw error or an apropriate assert.

Title: Conditional assignment in if clause

Body:
I have a code which I do not want to duplicate too much, it looks something like this:

myEnum setting;

if (((input == "Enum0") && ((setting = myEnum_0) == setting)) ||
    ((input == "Enum1") && ((setting = myEnum_1) == setting)) ||
    ((input == "Enum2") && ((setting = myEnum_2) == setting)))
{
    doActionWith(setting);
}

This way I don't have to check if the input was something totally different (if I just assigned with

if (input=="Enum0")
    setting = myEnum_0;

the code wouldn't know if the enum was actually set, or not.

Now I wonder, is there a more elegant solution for the thing at the end?

The && ((setting = myEnum_x) == setting) ?

Body:
I'd go with this:

//in the part of the code where you declare myEnum,
//if in a header, you might want to declare this inline
myEnum toMyEnum(const string input){
    if(input == "Enum0")
        return myEnum_0;
    ...
    return undefinedMyEnum;
}

and then you go with

myEnum setting = toMyEnum(input);
if(setting != undefinedMyEnum){
    doActionWith(setting);
}

This way, you have clear responsibilities. You simply take a string and transform it into your enumeration. Your code with the side effect is difficult to read, avoid such "tricks".

edit: on a second thought, right now my code produces a silent error, that is most likely not that good. You might want to replace return undefinedMyEnum; with something such as an EXIT or throw error or an apropriate assert.


问:
angular-cli server - how to proxy API requests to another server?
With the angular-cli ng serve local dev server, it's serving all the static files from my project directory.

How can I proxy my AJAX calls to a different server?

答:
We can find the proxy documentation for Angular-CLI over here:

https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

After setting up a file called proxy.conf.json in your root folder, edit your package.json to include the proxy config on ng start. After adding     "start": "ng serve --proxy-config proxy.conf.json" to your scripts, run npm start and not ng serve, because that will ignore the flag setup in your package.json.

current version of angular-cli: 1.1.0


问:
How to modify Windows C# code to read from a serial port in mono in Linux?
I am trying to port a service written for Windows systems in C# onto Linux, with the aim of replacing Windows altogether. The hardware remains identical in both Windows and Linux environments.

So far this has gone great - I've installed Mono-complete, modified those bits that need modifying to stop it looking for Nuget, compiled the software with only cosmetic errors, run it with mono-service and have established communication with the Serial Port.

That's where things start going wrong.

I am able to open the port, and I am able to send a message to the port which results in the proper response.

By running 'cat /dev/ttyUSB0' I am seeing the proper response from the port -  the symbol @

However the symbol is simply not being read by the software and I'm hitting a timeout every time.

I have changed nothing in the code except to open port '/dev/ttyUSB0' instead of 'COM1' (or whatever port it needs).

Why then can I write to, but not read from, the serial port?

I have tried messing with the Encoding of the returning bits, I thought it might be a big-endian / little endian issue but it is correctly sending the signal to the device ("M2" - no quotation marks).

Return communication also looks good - cat /dev/ttyUSB0 shows a series of '@' symbols being returned, each on a new line.

What is not happening though is the software then reading this, instead it is hitting the timeout waiting for the response.

I wondered if it might be a newline issue - but then why would it work as-is on the Windows system, and why would it send perfectly happily (newline currently is explicitly set to '\r\n')

Is there something specific to Linux that I am missing?

答:
I know this is a while late, but I'd left the project to one side for a while and have only just picked it back up.

It turns out that the problem lies with mono not firing DataReceivedEvents, so when the code ported from Windows .Net came across listening for them they weren't being picked up because they weren't being fired.

I overcame this by spawning a new thread whose sole purpose was to listen on the port, and when serialPort.BytesToRead was greater than 0 run whatever code would have been run on the event firing.


问:
How does a web server know what linked to it?
I use photobucket to post images to various user forums.  The forums I post to allow the embedding of a direct link to the image.

One of the services photobucket provides is a view history which includes not only number of hits but also information on which sites viewed the page.  I can't figure out how they do that -- can anyone fill me in on the details?

I would like to add that ability to my own server, but isn't this a security hole in the HTTP protocol of sorts?

答: It's usually information pulled from the HTTP_Referrer. It can be removed/changed so it's not a foolproof thing for security but the very basic usage is to compare this and check where it came from. When you embed an image/object from elsewhere, the term is Hot Linking and this is what the technique will usually prevent.</p>


问:
Get the names of all schemas with Psycopg2
I'm trying to iterate all tables of a Postgresql DB in Python, to execute a query in each of them. I need to get the schema and table name of each of them in order to execute the queries, so I'd like to get a list of strings like this: "schema.tablename".

I've used this, but it only lists the names of tables, so it is of no help.

```<code>select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';
</code>```

I'm sure there must be a more simple way, but I have been looking for something with no success...

Any help appreciated, thanks!!

答:
```<code>select
  relname,
  oid::regclass as full_name,
  relnamespace::regnamespace as schema_name
from pg_class
where relkind='r';
</code>```

Note that it does not append schema name to tables which available by search_path parameter so you could to use the schema_name column from the query above.

Body:
I'm trying to iterate all tables of a Postgresql DB in Python, to execute a query in each of them. I need to get the schema and table name of each of them in order to execute the queries, so I'd like to get a list of strings like this: "schema.tablename".

I've used this, but it only lists the names of tables, so it is of no help.

select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';

I'm sure there must be a more simple way, but I have been looking for something with no success...

Any help appreciated, thanks!!

Body:
select
  relname,
  oid::regclass as full_name,
  relnamespace::regnamespace as schema_name
from pg_class
where relkind='r';

Note that it does not append schema name to tables which available by search_path parameter so you could to use the schema_name column from the query above.


问:
Different CURRENT_TIMESTAMP and SYSDATE in oracle
After executing this SQL in oracle 10g:

```<code>SELECT SYSDATE, CURRENT_TIMESTAMP  FROM DUAL
</code>```

I receive this strange output:

What is cause of the difference in time?
The server time is equal of SYSDATE value

答:
SYSDATE, systimestamp return datetime of server where database is installed. SYSDATE - returns only date, i.e., "yyyy-mm-dd". systimestamp returns date with time and zone, i.e., "yyyy-mm-dd hh:mm:ss:ms timezone"

now() returns datetime at the time statement execution, i.e., "yyyy-mm-dd hh:mm:ss"

CURRENT_DATE - "yyyy-mm-dd", CURRENT_TIME - "hh:mm:ss", CURRENT_TIMESTAMP - "yyyy-mm-dd hh:mm:ss timezone". These are related to a record insertion time.

Body:
After executing this SQL in oracle 10g:

SELECT SYSDATE, CURRENT_TIMESTAMP  FROM DUAL

I receive this strange output:

What is cause of the difference in time?
The server time is equal of SYSDATE value


问:
How to call simulink model(.slx) from script
I'm a super beginner in Simulink models and control systems.
I have .slx Simulink model for drone dynamics system.
It takes in two inputs (roll cmd, pitch cmd) and outputs velocity x, velocity y, position x, and position y.

From here, it seems like I can open the system by calling

```<code>open_system('myModel.slx', 'loadable');
</code>```

But how do I put inputs and get output values?
Is there a way I can do this in a gui?

EDIT:
Here is the full layout of my model:

When I did

```<code>roll_CMD=10;
pitch_CMD=20;
</code>```

I got a warning saying:

```<code>Input port 1 of 'SimpleDroneDynamics/...' is not connected.
</code>```

How do I feed inputs using port numbers?

How do I get outputs with port numbers? I tried

[vx, vy, px, py] = sim('SimpleDroneDynamics.slx');

and got an error saying

```<code>Number of left-hand side argument doesn't match block diagram...
</code>```

Is there a way to continuously feed inputs at every time step? This being controller module, I think I'm supposed to feed in different values based on output position and velocity.

EDIT2:
I'm using Matlab2017a

答:
About the first two points of your question:

In simulink:

For the inputs you can use a constant block and when you double click the input block you can assign a value, which can be a workspace variable.

To get the outputs to your workspace you can use the simout block (make sure to put Save format to array).

Connect inputs to your simulink model

Connect outputs of your simulink model to the simout blocks.

MATLAB script

```<code>   clc;
   clear all;

   roll = 10;
   pitch = 20;

   sim('/path_to_simulinkmodel.slx')

   time = simout(:,1);
   velocity_X = simout(:,2);
   velocity_Y = simout(:,3);
   position_X = simout(:,4);
   position_Y = simout(:,5);
</code>```

About the third point of your question

You can define the duration of your simulation in the block diagram editor. You can put a variable which is defined in the calling script. There are multiple ways of achieving time dependent input variables:

One option I personally don't recommend is using a for-loop and calling the simulink model with a different value of roll and pitch

```<code> for i = 1:numberOfTimesteps
    roll = ...
    ...
    sim('simulinkModel.slx')
 end
</code>```

A second and more efficient approach is changing the constant blocks to other source blocks like ramp signals or sinusoid signals

Body:
I'm a super beginner in Simulink models and control systems.
I have .slx Simulink model for drone dynamics system.
It takes in two inputs (roll cmd, pitch cmd) and outputs velocity x, velocity y, position x, and position y.

From here, it seems like I can open the system by calling

open_system('myModel.slx', 'loadable');

But how do I put inputs and get output values?
Is there a way I can do this in a gui?

EDIT:
Here is the full layout of my model:

When I did

roll_CMD=10;
pitch_CMD=20;

I got a warning saying:

Input port 1 of 'SimpleDroneDynamics/...' is not connected.

How do I feed inputs using port numbers?

How do I get outputs with port numbers? I tried

[vx, vy, px, py] = sim('SimpleDroneDynamics.slx');

and got an error saying

Number of left-hand side argument doesn't match block diagram...

Is there a way to continuously feed inputs at every time step? This being controller module, I think I'm supposed to feed in different values based on output position and velocity.

EDIT2:
I'm using Matlab2017a

Body:
About the first two points of your question:

In simulink:

For the inputs you can use a constant block and when you double click the input block you can assign a value, which can be a workspace variable.

To get the outputs to your workspace you can use the simout block (make sure to put Save format to array).

Connect inputs to your simulink model

Connect outputs of your simulink model to the simout blocks.

MATLAB script

   clc;
   clear all;

   roll = 10;
   pitch = 20;

   sim('/path_to_simulinkmodel.slx')

   time = simout(:,1);
   velocity_X = simout(:,2);
   velocity_Y = simout(:,3);
   position_X = simout(:,4);
   position_Y = simout(:,5);

About the third point of your question

You can define the duration of your simulation in the block diagram editor. You can put a variable which is defined in the calling script. There are multiple ways of achieving time dependent input variables:

One option I personally don't recommend is using a for-loop and calling the simulink model with a different value of roll and pitch

 for i = 1:numberOfTimesteps
    roll = ...
    ...
    sim('simulinkModel.slx')
 end

A second and more efficient approach is changing the constant blocks to other source blocks like ramp signals or sinusoid signals


问:
I want to read and confirm data from a dictionary
I want to write a simple login script for existing users, I've created a dictionary for it but my code doesn't work.

I've tried the following:

```<code>d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}
print "Please enter your username: "
user_name = raw_input()
print "Please enter your password: "
password = raw_input
for user_name,password in d:
    if user_name in d and password in d:
        print "great"
    else:
        print "Password incorrect!"
</code>```

The code doesn't work, I always get incorrect password.

答:
There're some things that you're doing wrong:

you're not calling raw_input() on password

you're storing the password in plain-text

raw_string() can take a string as parameter so you can get rid off your print statements

you're checking if user_name / password are in d but you should actually look for username in key and for password in value. More user_name and password are already defined above the for loop and that makes your for loop completely wrong.

So, a simple solution would be:

```<code>d = {'apple': 'red', 'green': 'lettuce', 'yellow': 'lemon', 'orange': 'orange'}

user_name = raw_input("Please enter your username: ")
password = raw_input("Please enter your password: ")

if password == d.get(user_name):
  print True
else:
  print False
</code>```

Body:
I want to write a simple login script for existing users, I've created a dictionary for it but my code doesn't work.

I've tried the following:

d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}
print "Please enter your username: "
user_name = raw_input()
print "Please enter your password: "
password = raw_input
for user_name,password in d:
    if user_name in d and password in d:
        print "great"
    else:
        print "Password incorrect!"

The code doesn't work, I always get incorrect password.

Body:
There're some things that you're doing wrong:

you're not calling raw_input() on password

you're storing the password in plain-text

raw_string() can take a string as parameter so you can get rid off your print statements

you're checking if user_name / password are in d but you should actually look for username in key and for password in value. More user_name and password are already defined above the for loop and that makes your for loop completely wrong.

So, a simple solution would be:

d = {'apple': 'red', 'green': 'lettuce', 'yellow': 'lemon', 'orange': 'orange'}

user_name = raw_input("Please enter your username: ")
password = raw_input("Please enter your password: ")

if password == d.get(user_name):
  print True
else:
  print False


问:
VSCode debugging with libvala-0.36 needs debug symbols?
Developing a Vala (libvala) program using --pkg libvala-0.36 on VSCode 1.12.2/Linux Mint 18. Running an F5 Debug session, I'm able to set breakpoints and see local variable values. But I can't seem to get Vala objects to display class data instead of just an address. For example:

```<code>foreach (Vala.SourceFile src in context.get_source_files ()) {
                   var source = find_source_file (src.filename) ;
</code>```

The Debug window (and mouse hover) displays src:Object@#*0x660aa0 instead of a Vala.SourceFile class object.  I'm guessing there is no libvala symbol table loaded? "apt search" shows libvala-0.36-0-dbg and libvala-0.36-dev packages installed, but not sure how to use them.

Googling, I found a reference to "valac-dbgsym". So I tried...

```<code>sudo apt-get install valac-dbgsym
E: Unable to locate package valac-dbgsym
</code>```

Appreciate your help/insight on what i'm doing wrong. My objective is to Run Debug and display Vala.??? class object data in Debug window.
Thanks for your help!

```<code>george@george-KT369AA-ABA-a6512p ~ $ sudo apt search libvala
p   libvala-0.30-0                  - C# like language for the GObject system -
p   libvala-0.30-0:i386             - C# like language for the GObject system -
p   libvala-0.30-0-dbg              - C# like language for the GObject system -
p   libvala-0.30-0-dbg:i386         - C# like language for the GObject system -
p   libvala-0.30-dev                - C# like language for the GObject system -
p   libvala-0.30-dev:i386           - C# like language for the GObject system -
p   libvala-0.34-0                  - C# like language for the GObject system -
p   libvala-0.34-0:i386             - C# like language for the GObject system -
p   libvala-0.34-0-dbg              - C# like language for the GObject system -
p   libvala-0.34-0-dbg:i386         - C# like language for the GObject system -
p   libvala-0.34-dev                - C# like language for the GObject system -
p   libvala-0.34-dev:i386           - C# like language for the GObject system -
i   libvala-0.36-0                  - C# like language for the GObject system -
p   libvala-0.36-0:i386             - C# like language for the GObject system -
i   libvala-0.36-0-dbg              - C# like language for the GObject system -
p   libvala-0.36-0-dbg:i386         - C# like language for the GObject system -
i   libvala-0.36-dev                - C# like language for the GObject system -
p   libvala-0.36-dev:i386           - C# like language for the GObject system -
v   libvala-dev                     -
v   libvala-dev:i386                -
p   libvaladoc-data                 - API documentation generator for vala (data
v   libvaladoc-data:i386            -
p   libvaladoc-dev                  - API documentation generator for vala (deve
p   libvaladoc-dev:i386             - API documentation generator for vala (deve
p   libvaladoc3                     - API documentation generator for vala (libr
p   libvaladoc3:i386                - API documentation generator for vala (libr

===========================================================================
----------building CSharp2Vala.exe
===========================================================================
valac -X -I/media/george/SharedData/Projects/Vala/vala-extra-vapis/ --verbose --vapidir=/media/george/SharedData/P
rojects/Vala/osslibs/ --girdir=/media/george/SharedData/Projects/Vala/osslibs/ --pkg gio-2.0 --define=DEBUG --save
-temps -g -X -w \
        --pkg libvala-0.36  \
        --pkg gee-0.8 \
        -X -DGETTEXT_PACKAGE="..." \
        -X -I/media/george/SharedData/Projects/Vala/CSharp2Vala/Echo-src/lib \
        -X /media/george/SharedData/Projects/Vala/CSharp2Vala/Echo-src/lib/libecho.so \
        /media/george/SharedData/Projects/Vala/CSharp2Vala/Echo-src/lib/libecho.vapi \
        /media/george/SharedData/Projects/Vala/CSharp2Vala/CSharp2Vala.vala \        -o /media/george/SharedData/Projects/Vala/CSharp2Vala/CSharp2Vala.exe
Loaded package `/usr/share/vala-0.36/vapi/glib-2.0.vapi'
Loaded package `/usr/share/vala-0.36/vapi/gobject-2.0.vapi'
Loaded package `/usr/share/vala-0.36/vapi/gio-2.0.vapi'
Loaded package `/usr/share/vala-0.36/vapi/libvala-0.36.vapi'
Loaded package `/usr/share/vala/vapi/gee-0.8.vapi'

cc -g -o '/media/george/SharedData/Projects/Vala/CSharp2Vala/CSharp2Vala.exe' '/media/george/SharedData/Projects/V
    ala/CSharp2Vala/CSharp2Vala.c' -pthread -I/usr/include/vala-0.36 -I/usr/include/gee-0.8 -I/usr/include/glib-2.0 -I
    /usr/lib/x86_64-linux-gnu/glib-2.0/include -lgio-2.0 -lvala-0.36 -lgee-0.8 -lgobject-2.0 -lglib-2.0 '-I/media/geor
    ge/SharedData/Projects/Vala/vala-extra-vapis/' '-w' '-DGETTEXT_PACKAGE=...' '-I/media/george/SharedData/Projects/V
    ala/CSharp2Vala/Echo-src/lib' '/media/george/SharedData/Projects/Vala/CSharp2Vala/Echo-src/lib/libecho.so'
    Compilation succeeded - 3 warning(s)
</code>```

答:
You should be aware that libvala is an internal API used by clients such as valac and vapigen. Both of those clients are developed in the main source and so are kept in sync with the libvala API. The API isn't changing much, but for example, with the upcoming 0.38 release commit c9aa47 removes the CCode and Codegen symbols from the API, making them private to libvala only. Also commit     e1b399 will add an optional parameter to Report.set_colors. Over the years, however, a number of IDE tools have started to use libvala directly. So the pragmatic advice would be to avoid the libvala API if you can and to use as little of the API as possible if you have to. Typically use the part of the API that is used by existing tools.

If you are looking to develop libvala itself then you can build Vala with the --enable-coverage when you configure the Autotools build. This will add line numbers for Vala source files in libvala and so show the Vala source and line number in backtraces. You will also want to install GLib debug symbols. I think this is libglib2.0-0-dbgsym in Ubuntu.

If you are looking to debug Vala programs. Then the --debug switch for valac will add the source file and line number to the final binary. BTW --debug is the default when using Meson build with Vala. The type system in Vala is based on GLib so will want the GLib2 debug symbols installed as well.

Body:
Developing a Vala (libvala) program using --pkg libvala-0.36 on VSCode 1.12.2/Linux Mint 18. Running an F5 Debug session, I'm able to set breakpoints and see local variable values. But I can't seem to get Vala objects to display class data instead of just an address. For example:

foreach (Vala.SourceFile src in context.get_source_files ()) {
                   var source = find_source_file (src.filename) ;

The Debug window (and mouse hover) displays src:Object@#*0x660aa0 instead of a Vala.SourceFile class object.  I'm guessing there is no libvala symbol table loaded? "apt search" shows libvala-0.36-0-dbg and libvala-0.36-dev packages installed, but not sure how to use them.

Googling, I found a reference to "valac-dbgsym". So I tried...

sudo apt-get install valac-dbgsym
E: Unable to locate package valac-dbgsym

Appreciate your help/insight on what i'm doing wrong. My objective is to Run Debug and display Vala.??? class object data in Debug window.
Thanks for your help!

george@george-KT369AA-ABA-a6512p ~ $ sudo apt search libvala
p   libvala-0.30-0                  - C# like language for the GObject system -
p   libvala-0.30-0:i386             - C# like language for the GObject system -
p   libvala-0.30-0-dbg              - C# like language for the GObject system -
p   libvala-0.30-0-dbg:i386         - C# like language for the GObject system -
p   libvala-0.30-dev                - C# like language for the GObject system -
p   libvala-0.30-dev:i386           - C# like language for the GObject system -
p   libvala-0.34-0                  - C# like language for the GObject system -
p   libvala-0.34-0:i386             - C# like language for the GObject system -
p   libvala-0.34-0-dbg              - C# like language for the GObject system -
p   libvala-0.34-0-dbg:i386         - C# like language for the GObject system -
p   libvala-0.34-dev                - C# like language for the GObject system -
p   libvala-0.34-dev:i386           - C# like language for the GObject system -
i   libvala-0.36-0                  - C# like language for the GObject system -
p   libvala-0.36-0:i386             - C# like language for the GObject system -
i   libvala-0.36-0-dbg              - C# like language for the GObject system -
p   libvala-0.36-0-dbg:i386         - C# like language for the GObject system -
i   libvala-0.36-dev                - C# like language for the GObject system -
p   libvala-0.36-dev:i386           - C# like language for the GObject system -
v   libvala-dev                     -
v   libvala-dev:i386                -
p   libvaladoc-data                 - API documentation generator for vala (data
v   libvaladoc-data:i386            -
p   libvaladoc-dev                  - API documentation generator for vala (deve
p   libvaladoc-dev:i386             - API documentation generator for vala (deve
p   libvaladoc3                     - API documentation generator for vala (libr
p   libvaladoc3:i386                - API documentation generator for vala (libr

===========================================================================
----------building CSharp2Vala.exe
===========================================================================
valac -X -I/media/george/SharedData/Projects/Vala/vala-extra-vapis/ --verbose --vapidir=/media/george/SharedData/P
rojects/Vala/osslibs/ --girdir=/media/george/SharedData/Projects/Vala/osslibs/ --pkg gio-2.0 --define=DEBUG --save
-temps -g -X -w \
        --pkg libvala-0.36  \
        --pkg gee-0.8 \
        -X -DGETTEXT_PACKAGE="..." \
        -X -I/media/george/SharedData/Projects/Vala/CSharp2Vala/Echo-src/lib \
        -X /media/george/SharedData/Projects/Vala/CSharp2Vala/Echo-src/lib/libecho.so \
        /media/george/SharedData/Projects/Vala/CSharp2Vala/Echo-src/lib/libecho.vapi \
        /media/george/SharedData/Projects/Vala/CSharp2Vala/CSharp2Vala.vala \        -o /media/george/SharedData/Projects/Vala/CSharp2Vala/CSharp2Vala.exe
Loaded package `/usr/share/vala-0.36/vapi/glib-2.0.vapi'
Loaded package `/usr/share/vala-0.36/vapi/gobject-2.0.vapi'
Loaded package `/usr/share/vala-0.36/vapi/gio-2.0.vapi'
Loaded package `/usr/share/vala-0.36/vapi/libvala-0.36.vapi'
Loaded package `/usr/share/vala/vapi/gee-0.8.vapi'

cc -g -o '/media/george/SharedData/Projects/Vala/CSharp2Vala/CSharp2Vala.exe' '/media/george/SharedData/Projects/V
    ala/CSharp2Vala/CSharp2Vala.c' -pthread -I/usr/include/vala-0.36 -I/usr/include/gee-0.8 -I/usr/include/glib-2.0 -I
    /usr/lib/x86_64-linux-gnu/glib-2.0/include -lgio-2.0 -lvala-0.36 -lgee-0.8 -lgobject-2.0 -lglib-2.0 '-I/media/geor
    ge/SharedData/Projects/Vala/vala-extra-vapis/' '-w' '-DGETTEXT_PACKAGE=...' '-I/media/george/SharedData/Projects/V
    ala/CSharp2Vala/Echo-src/lib' '/media/george/SharedData/Projects/Vala/CSharp2Vala/Echo-src/lib/libecho.so'
    Compilation succeeded - 3 warning(s)


问:
php is not adding data to mysql
```<code>$date = date('Y-m-d H:i:s');
        $qry = "INSERT INTO `guest` (`name`, `pincode`, `address`, `phone`, `date`) VALUES ('".$_SESSION['name']."', '".$_SESSION['pincode']."', '".$_SESSION['address']."', '".$_SESSION['phone']."', '".$date."');";
        $result = $conn->query($qry);
        //echo $qry;
        $qry = "select guest_id from guest where name = '".$_SESSION['name']."' and pincode = '".$_SESSION['pincode']."' and address= '".$_SESSION['address']."' and phone= '".$_SESSION['phone']."' and date= '".$date."';";
        //echo $qry;
        $result = $conn->query($qry);
        $row = $result -> fetch_assoc();
        //echo $row['guest_id'];
        $guest_id = $row['guest_id'];
        $date = date('Y-m-d H:i:s');
        //$qry1 = "INSERT INTO order (`order_date`, `payment_type`, `payment_status`, `order_status`, `order_type`, `amount`, `cust_id`) VALUES ('".$date."', 'cod', 'yes', 'Pending', 'yes', ".$_SESSION['total'].", '".$guest_id."');";
        $qry1 = "INSERT INTO `grocery`.`order` (`order_date`, `payment_type`, `payment_status`, `order_status`, `delivery_slot`, `order_type`, `amount`, `deliver_date`, `cust_id`) VALUES ('sd', 'asd', 'sdf', 'sd', '4', 'sf', '23', '2017-04-19', 'sdfs');";

        $result1 = $conn->query($qry1);
        echo $qry1;
</code>```

The first 2 queries are getting executed and data is added to db.. But the last statement is not adding the data to db. Please help me out

答:
I'm going to assume $conn is a PDO object.

I have a few recommendations:

1) Use a higher level database abstraction. DBAL is really nice.

2) If you're going to use PDO, you have to check the return value of $conn->query() for  false to know if an error occurred, then call $conn->errorInfo and $conn->errorCode to know what that error was. You should always handle error conditions in function calls.

3) Instead of handling error conditions, PDO can be configured to throw exceptions by using:

```<code>$conn->setAttribute("PDO::ATTR_ERRMODE", PDO::ERRMODE_EXCEPTION);
</code>```

This means you have less error handling code to write if you simply want to abort on DB errors.

Title: php is not adding data to mysql

Body:
$date = date('Y-m-d H:i:s');
        $qry = "INSERT INTO `guest` (`name`, `pincode`, `address`, `phone`, `date`) VALUES ('".$_SESSION['name']."', '".$_SESSION['pincode']."', '".$_SESSION['address']."', '".$_SESSION['phone']."', '".$date."');";
        $result = $conn->query($qry);
        //echo $qry;
        $qry = "select guest_id from guest where name = '".$_SESSION['name']."' and pincode = '".$_SESSION['pincode']."' and address= '".$_SESSION['address']."' and phone= '".$_SESSION['phone']."' and date= '".$date."';";
        //echo $qry;
        $result = $conn->query($qry);
        $row = $result -> fetch_assoc();
        //echo $row['guest_id'];
        $guest_id = $row['guest_id'];
        $date = date('Y-m-d H:i:s');
        //$qry1 = "INSERT INTO order (`order_date`, `payment_type`, `payment_status`, `order_status`, `order_type`, `amount`, `cust_id`) VALUES ('".$date."', 'cod', 'yes', 'Pending', 'yes', ".$_SESSION['total'].", '".$guest_id."');";
        $qry1 = "INSERT INTO `grocery`.`order` (`order_date`, `payment_type`, `payment_status`, `order_status`, `delivery_slot`, `order_type`, `amount`, `deliver_date`, `cust_id`) VALUES ('sd', 'asd', 'sdf', 'sd', '4', 'sf', '23', '2017-04-19', 'sdfs');";

        $result1 = $conn->query($qry1);
        echo $qry1;

The first 2 queries are getting executed and data is added to db.. But the last statement is not adding the data to db. Please help me out

Body:
I'm going to assume $conn is a PDO object.

I have a few recommendations:

1) Use a higher level database abstraction. DBAL is really nice.

2) If you're going to use PDO, you have to check the return value of $conn->query() for  false to know if an error occurred, then call $conn->errorInfo and $conn->errorCode to know what that error was. You should always handle error conditions in function calls.

3) Instead of handling error conditions, PDO can be configured to throw exceptions by using:

$conn->setAttribute("PDO::ATTR_ERRMODE", PDO::ERRMODE_EXCEPTION);

This means you have less error handling code to write if you simply want to abort on DB errors.


问:
Avoid dropdown menu close on click inside
I have a Twitter Bootstrap dropdown menu. As all Twitter Bootstrap users know, the dropdown menu closes on click (even clicking inside it).

To avoid this, I can easily attach a click event handler on the dropdown menu and simply add the famous event.stopPropagation().

```<code><ul class="nav navbar-nav">
  <li class="dropdown mega-dropdown">
    <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown">
      <i class="fa fa-list-alt"></i> Menu item 1
      <span class="fa fa-chevron-down pull-right"></span>
    </a>
    <ul class="dropdown-menu mega-dropdown-menu">
      <li>
        <div id="carousel" class="carousel slide" data-ride="carousel">
          <ol class="carousel-indicators">
            <li data-slide-to="0" data-target="#carousel"></li>
            <li class="active" data-slide-to="1" data-target="#carousel"></li>
          </ol>
          <div class="carousel-inner">
            <div class="item">
              <img alt="" class="img-rounded" src="img1.jpg">
            </div>
            <div class="item active">
              <img alt="" class="img-rounded" src="img2.jpg">
            </div>
          </div>
          <a data-slide="prev" role="button" href="#carousel"
             class="left carousel-control">
            <span class="glyphicon glyphicon-chevron-left"></span>
          </a>
          <a data-slide="next" role="button" href="#carousel"
             class="right carousel-control">
            <span class="glyphicon glyphicon-chevron-right"></span>
          </a>
        </div>
      </li>
    </ul>
  </li>
</ul>
</code>```

This looks easy and a very common behavior, however, and since carousel-controls (as well as carousel indicators) event handlers are delegated to the document object, the click event on these elements (prev/next controls, ...) will be “ignored”.

```<code>$('ul.dropdown-menu.mega-dropdown-menu').on('click', function(event){
    // The event won't be propagated up to the document NODE and
    // therefore delegated events won't be fired
    event.stopPropagation();
});
</code>```

Relying on Twitter Bootstrap dropdown hide/hidden events is not a solution for the following reasons:

The provided event object for both event handlers does not give reference to the clicked element

I don't have control over the dropdown menu content so adding a flag class or attribute is not possible

This fiddle is the normal behavior and this fiddle is with event.stopPropagation() added.

Update

Thanks to Roman for his answer. I also found an answer that you can find below.

答:
Instead of writing some javascript or jquery code(reinventing the wheel). The above scenario can be managed by bootstrap auto-close option.
You can provide either of the values to auto-close:

always - (Default) automatically closes the dropdown when any of its elements is clicked.

outsideClick - closes the dropdown automatically only when the user clicks any element outside the dropdown.

disabled - disables the auto close

Take a look at the following plunkr :

http://plnkr.co/edit/gnU8M2fqlE0GscUQtCWa?p=preview

Set

```<code>uib-dropdown auto-close="disabled"
</code>```

Hope this helps :)

Body:
I have a Twitter Bootstrap dropdown menu. As all Twitter Bootstrap users know, the dropdown menu closes on click (even clicking inside it).

To avoid this, I can easily attach a click event handler on the dropdown menu and simply add the famous event.stopPropagation().

       Menu item 1

This looks easy and a very common behavior, however, and since carousel-controls (as well as carousel indicators) event handlers are delegated to the document object, the click event on these elements (prev/next controls, ...) will be “ignored”.

$('ul.dropdown-menu.mega-dropdown-menu').on('click', function(event){
    // The event won't be propagated up to the document NODE and
    // therefore delegated events won't be fired
    event.stopPropagation();
});

Relying on Twitter Bootstrap dropdown hide/hidden events is not a solution for the following reasons:

The provided event object for both event handlers does not give reference to the clicked element

I don't have control over the dropdown menu content so adding a flag class or attribute is not possible

This fiddle is the normal behavior and this fiddle is with event.stopPropagation() added.

Update

Thanks to Roman for his answer. I also found an answer that you can find below.

Body:
Instead of writing some javascript or jquery code(reinventing the wheel). The above scenario can be managed by bootstrap auto-close option.
You can provide either of the values to auto-close:

always - (Default) automatically closes the dropdown when any of its elements is clicked.

outsideClick - closes the dropdown automatically only when the user clicks any element outside the dropdown.

disabled - disables the auto close

Take a look at the following plunkr :

http://plnkr.co/edit/gnU8M2fqlE0GscUQtCWa?p=preview

Set

uib-dropdown auto-close="disabled"

Hope this helps :)


问:
How do I do a basic import/include of a function from one module to another in Rust 2015?
I can't find how to include (or import, inject, or some other word) a function from one file (module) to another.

I start a new project with

$ cd ~/projects
$ cargo new proj --bin
$ cd proj
$ tree
.
|
-- Cargo.toml
-- src
   |
   -- main.rs
```

<p>I modify <code>main.rs</code> and create a new file <code>a.rs</code> (inside the <code>src</code> dir) with the following code:</p>

<p><strong>main.rs</strong></p>

```fn main() {
    println!("{}", a::foo());
}
```

<p><strong>a.rs</strong></p>

```pub fn foo() -> i32 { 42 }
```

<p>I run the project with <code>cargo run</code> and get the error:</p>

<pre class="lang-none prettyprint-override"><code>error[E0433]: failed to resolve: use of undeclared type or module `a`
 --> src/main.rs:2:20
  |
2 |     println!("{}", a::foo());
  |                    ^ use of undeclared type or module `a`
</code>```

It seems that I need to import the a somehow. I tried to add following things as a first line to main.rs

use a;

error[E0432]: unresolved import `a`
 --> src/main.rs:1:5
  |
1 | use a;
  |     ^ no `a` in the root
```</li>
<li><p><code>use a::*;</code></p>

<pre class="lang-none prettyprint-override"><code>error[E0432]: unresolved import `a`
 --> src/main.rs:1:5
  |
1 | use a::*;
  |     ^ maybe a missing `extern crate a;`?

error[E0433]: failed to resolve: use of undeclared type or module `a`
 --> src/main.rs:4:20
  |
4 |     println!("{}", a::foo());
  |                    ^ use of undeclared type or module `a`
</code>```

use a::foo;

error[E0432]: unresolved import `a`
 --> src/main.rs:1:5
  |
1 | use a::foo;
  |     ^ maybe a missing `extern crate a;`?

error[E0433]: failed to resolve: use of undeclared type or module `a`
 --> src/main.rs:4:20
  |
4 |     println!("{}", a::foo());
  |                    ^ use of undeclared type or module `a`
```</li>
<li><p><code>extern crate a; use a::foo;</code> </p>

<pre class="lang-none prettyprint-override"><code>error[E0463]: can't find crate for `a`
 --> src/main.rs:1:1
  |
1 | extern crate a;
  | ^^^^^^^^^^^^^^^ can't find crate
</code>```

extern crate proj; use proj::a::foo;

error[E0463]: can't find crate for `proj`
 --> src/main.rs:1:1
  |
1 | extern crate proj;
  | ^^^^^^^^^^^^^^^^^^ can't find crate
```

I have read the guide but still cannot figure out how to do imports.

答:
In Rust, there are some keywords to deal with modules:

mod

mod has two forms:

when used with curly braces it declares a module (namespace).

when used with just a name, it will look for the module in the local filesystem.

A module can be:

a file with extension .rs, or

a folder with a file named mod.rs

use

use imports a name into the current module's namespace. We can use any function, struct, enum, type alias, trait, or (sub)module. The use clause is pretty strict, if we state use module1::moduleA; no other name from module1 will be available but moduleA. An asterisk (*) can be used to use everything within a module: use module1::*;. Sets can be used as well: use module1::{moduleA, moduleB};

An example:

| main.rs
|- module1
      |- mod.rs
      |- moduleA.rs
      |- moduleB.rs
```
<p>mod.rs contains:</p>
```pub mod moduleA; // declare a child module
pub mod moduleB; // declare a child module
```
<p>main.rs contains:</p>
```// use what Cargo downloaded (not necessary in Rust 2018)
//extern crate that_one_thing_i_need;

///  ======

mod module1; // declare a child module

// some local stuff I want to scope
mod local {
    pub fn my_function() {}
}

//   ======

// make the symbols locally available:
use module1::moduleA::*;
use module1::moduleB::{functionX, moduleY, typeZ};

// To avoid having to write `that_one_thing_i_need::` a lot,
// we can make local aliases that will be valid in the current module.
use that_one_thing_i_need::fancy_stuff as fs;

///  ======

fn main() {
    // we can use anything here from the namespaces we are using:
    //      moduleA
    //      functionX
    //      moduleY
    //      typeZ
    //      fs

    // We can access stuff by navigating from the outermost visible
    // module name
    local::my_function();
}
```

Symbols are only usable from within the module. If you want to cross this barrier (even on a locally declared module) we need to make them public using the keyword pub.

extern crate

extern crate fills the gap between Cargo and Rust. We write code in a .rs file, this file can be compiled with rustc. Cargo will manage external dependencies and call rustc. The extern crate ... line tells the compiler to look for this namespace, so it is unambiguous.

Editor's note — extern crate is not required in many cases if you are using the Rust 2018 edition.

Body:
I can't find how to include (or import, inject, or some other word) a function from one file (module) to another.

I start a new project with

$ cd ~/projects
$ cargo new proj --bin
$ cd proj
$ tree
.
|
-- Cargo.toml
-- src
   |
   -- main.rs

I modify main.rs and create a new file a.rs (inside the src dir) with the following code:

main.rs

fn main() {
    println!("{}", a::foo());
}

a.rs

pub fn foo() -> i32 { 42 }

I run the project with cargo run and get the error:

error[E0433]: failed to resolve: use of undeclared type or module `a`
 --> src/main.rs:2:20
  |
2 |     println!("{}", a::foo());
  |                    ^ use of undeclared type or module `a`

It seems that I need to import the a somehow. I tried to add following things as a first line to main.rs

use a;

error[E0432]: unresolved import `a`
 --> src/main.rs:1:5
  |
1 | use a;
  |     ^ no `a` in the root

use a::*;

error[E0432]: unresolved import `a`
 --> src/main.rs:1:5
  |
1 | use a::*;
  |     ^ maybe a missing `extern crate a;`?

error[E0433]: failed to resolve: use of undeclared type or module `a`
 --> src/main.rs:4:20
  |
4 |     println!("{}", a::foo());
  |                    ^ use of undeclared type or module `a`

use a::foo;

error[E0432]: unresolved import `a`
 --> src/main.rs:1:5
  |
1 | use a::foo;
  |     ^ maybe a missing `extern crate a;`?

error[E0433]: failed to resolve: use of undeclared type or module `a`
 --> src/main.rs:4:20
  |
4 |     println!("{}", a::foo());
  |                    ^ use of undeclared type or module `a`

extern crate a; use a::foo;

error[E0463]: can't find crate for `a`
 --> src/main.rs:1:1
  |
1 | extern crate a;
  | ^^^^^^^^^^^^^^^ can't find crate

extern crate proj; use proj::a::foo;

error[E0463]: can't find crate for `proj`
 --> src/main.rs:1:1
  |
1 | extern crate proj;
  | ^^^^^^^^^^^^^^^^^^ can't find crate

I have read the guide but still cannot figure out how to do imports.

Body:
In Rust, there are some keywords to deal with modules:

mod

mod has two forms:

when used with curly braces it declares a module (namespace).

when used with just a name, it will look for the module in the local filesystem.

A module can be:

a file with extension .rs, or

a folder with a file named mod.rs

use

use imports a name into the current module's namespace. We can use any function, struct, enum, type alias, trait, or (sub)module. The use clause is pretty strict, if we state use module1::moduleA; no other name from module1 will be available but moduleA. An asterisk (*) can be used to use everything within a module: use module1::*;. Sets can be used as well: use module1::{moduleA, moduleB};

An example:

| main.rs
|- module1
      |- mod.rs
      |- moduleA.rs
      |- moduleB.rs

mod.rs contains:

pub mod moduleA; // declare a child module
pub mod moduleB; // declare a child module

main.rs contains:

// use what Cargo downloaded (not necessary in Rust 2018)
//extern crate that_one_thing_i_need;

///  ======

mod module1; // declare a child module

// some local stuff I want to scope
mod local {
    pub fn my_function() {}
}

//   ======

// make the symbols locally available:
use module1::moduleA::*;
use module1::moduleB::{functionX, moduleY, typeZ};

// To avoid having to write `that_one_thing_i_need::` a lot,
// we can make local aliases that will be valid in the current module.
use that_one_thing_i_need::fancy_stuff as fs;

///  ======

fn main() {
    // we can use anything here from the namespaces we are using:
    //      moduleA
    //      functionX
    //      moduleY
    //      typeZ
    //      fs

    // We can access stuff by navigating from the outermost visible
    // module name
    local::my_function();
}

Symbols are only usable from within the module. If you want to cross this barrier (even on a locally declared module) we need to make them public using the keyword pub.

extern crate

extern crate fills the gap between Cargo and Rust. We write code in a .rs file, this file can be compiled with rustc. Cargo will manage external dependencies and call rustc. The extern crate ... line tells the compiler to look for this namespace, so it is unambiguous.

Editor's note — extern crate is not required in many cases if you are using the Rust 2018 edition.


问:
Why this c program fall into infinity loop?
```<code>#include <stdio.h>

int main()
{
  int sum=0;
  char s[10];

  while(scanf("%[^\n]s", s)!=EOF)
  {
    printf("%s", s);

  }

  return 0;
}
</code>```

This while loop fall into infinity loop for any string input.

答:
```<code>int main()
{
    int sum = 0;
    char s[10];

    int ret = scanf("%[^\n]s", s);
    while (ret != EOF)
    {
        printf("%s", s);
        memset(s,0,10);
        ret = scanf("%[^\n]s", s);
    }

    return 0;
}
</code>```

with the debug, you can see the second ret value in the while block is 0, that's , and not equal EOF, so infinity loop.

man scanf:

RETURN VALUE

Upon  successful  completion,  these  functions  shall  return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure.

That mean the other scanf is matching failure, except the first one.

But why?

The stdio has cache, and the matching only read "\n" from the stdin, but when you input the "Enter", it input "\n\r", so, the "\r" will in the stdin cache and become the input value for other scanf, but cannot match the input, so matching failure. And scanf return 0, and goto infinity loop.

But if you only input "\n" for each input, it's OK!

You can press "Alt" and at same time press "0" + "1" + "0", and the release the "Alt", the console will input "\n" only and you will get the right result , and the program will be OK, not into infinity loop!

And this's my test result:enter image description here

Body:
#include <stdio.h>

int main()
{
  int sum=0;
  char s[10];

  while(scanf("%[^\n]s", s)!=EOF)
  {
    printf("%s", s);

  }

  return 0;
}

This while loop fall into infinity loop for any string input.

Body:
int main()
{
    int sum = 0;
    char s[10];

    int ret = scanf("%[^\n]s", s);
    while (ret != EOF)
    {
        printf("%s", s);
        memset(s,0,10);
        ret = scanf("%[^\n]s", s);
    }

    return 0;
}

with the debug, you can see the second ret value in the while block is 0, that's , and not equal EOF, so infinity loop.

man scanf:

RETURN VALUE

Upon  successful  completion,  these  functions  shall  return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure.

That mean the other scanf is matching failure, except the first one.

But why?

The stdio has cache, and the matching only read "\n" from the stdin, but when you input the "Enter", it input "\n\r", so, the "\r" will in the stdin cache and become the input value for other scanf, but cannot match the input, so matching failure. And scanf return 0, and goto infinity loop.

But if you only input "\n" for each input, it's OK!

You can press "Alt" and at same time press "0" + "1" + "0", and the release the "Alt", the console will input "\n" only and you will get the right result , and the program will be OK, not into infinity loop!

And this's my test result:enter image description here


问:
PHP: Change only a portion of a URL string?
I’m working on a small hoppy project where I want to replace a specific page on a URL. Let me explain:

I’ve got the URL

http://www.example.com/article/paragraph/low/

I want to keep the URL but replace the last segment /low/ with /high/ so the new URL is:

http://www.example.com/article/paragraph/high/

I’ve tried different explode, split and splice but I just can’t seem to wrap my head around it and make it work. I can change the entire URL but not just the last segment and save it in a new variable.

I’m pretty confidence that it is a pretty straight forward case but I’ve never worked that much with arrays / string-manipulation in PHP so I’m pretty lost.

I guess that I have to first split the URL up in segments, using the "\" to separate it (I tried that but have problems by using explode("\", $string)) and then replace the last \low\ with \high\

Hope someone could help or point me in the right direction to what methods to use for doing this.

Sincere

Mestika

答:
```<code><?php

class TestURL extends PHPUnit_Framework_TestCase {
    public function testURL() {
        $URL =  'http://www.mydomain.com/article/paragraph/low/';
        $explode = explode('/', $URL);
        $explode[5] = 'high';
        $expected = 'http://www.mydomain.com/article/paragraph/high/';
        $actual = implode('/', $explode);
        $this->assertEquals($expected, $actual);
    }
}
</code>```

<p>--</p>

```<code>phpunit simple-test.php
PHPUnit 3.4.13 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 4.75Mb

OK (1 test, 1 assertion)
</code>```

Body:
<?php

class TestURL extends PHPUnit_Framework_TestCase {
    public function testURL() {
        $URL =  'http://www.mydomain.com/article/paragraph/low/';
        $explode = explode('/', $URL);
        $explode[5] = 'high';
        $expected = 'http://www.mydomain.com/article/paragraph/high/';
        $actual = implode('/', $explode);
        $this->assertEquals($expected, $actual);
    }
}

--

phpunit simple-test.php
PHPUnit 3.4.13 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 4.75Mb

OK (1 test, 1 assertion)


问:
How to include custom JS files in to React create app
I had js files under public folder i want to include these js files in to react components which are under src component folder in react create application?</p>

答:
Please read Using the public Folder.

In general we recommend installing packages from npm and using import to access them from the source. But if you must use a prebuilt JS file that you don’t want to import, you can add it to the public folder (for example, public/mylib.js) and then add this to public/index.html:

```<code><script src="%PUBLIC_URL%/mylib.js"></script>
</code>```

Then you can access the global variable from your app, for example:

```<code>const mylib = window.mylib;
</code>```

And then use it.

Hope this helps!

Body:
Please read Using the public Folder.

In general we recommend installing packages from npm and using import to access them from the source. But if you must use a prebuilt JS file that you don’t want to import, you can add it to the public folder (for example, public/mylib.js) and then add this to public/index.html:

<script src="%PUBLIC_URL%/mylib.js"></script>

Then you can access the global variable from your app, for example:

const mylib = window.mylib;

And then use it.

Hope this helps!


问:
How to use import with absolute paths with Expo and React Native?
I'm trying to use absolute import paths instead of relative paths with Expo and React Native.

I looked on the expo docs and couldn't find an answer... Searching for the subject in react community I found babel-plugin-module-resolver but it seems that Expo is already using it so I've changed my .babelrc to create some aliases:

{
  "presets": ["babel-preset-expo"],
  "env": {
    "development": {
      "plugins": [
        "transform-react-jsx-source",
        ["module-resolver", {
          "root": ["./app"],
          "alias": {
            "Components": "./app/components",
          }
        }]
      ]
    }
  }
}
```
<p>But I got the following error:</p>
<pre class="lang-bash prettyprint-override"><code>    Unable to resolve module '@expo/vector-icons/glyphmaps/Entypo.json'
    from '/Users/eduardoleal/Code/lua/rook/node_modules/@expo/vector-icons/Entypo.js':
    Module does not exist in the module map or in these directories:   /Users/eduardoleal/Code/lua/rook/node_modules/@expo/vector-icons/node_modules/@expo/vector-icons/glyphmaps ,   /Users/eduardoleal/Code/lua/rook/node_modules/@expo/vector-icons/glyphmaps  This might be related to https://github.com/facebook/react-native/issues/4968 To resolve try the following:
    1. Clear watchman watches: 'watchman watch-del-all'.
    2. Delete the 'node_modules' folder: 'rm -rf node_modules && npm install'.
    3. Reset packager cache: 'rm -fr $TMPDIR/react-*' or 'npm start --reset-cache'.
    ABI16_0_0RCTFatal -[ABI16_0_0RCTBatchedBridge stopLoadingWithError:] __34-[ABI16_0_0RCTBatchedBridge start]_block_invoke_2 _dispatch_call_block_and_release _dispatch_client_callout _dispatch_main_queue_callback_4CF __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ __CFRunLoopRun CFRunLoopRunSpecific GSEventRunModal UIApplicationMain main start 0x0
</code>```

Is there any easy way to import absolute paths?

答:
Update: Expo v32.0.0 and up

Expo init is creating a babel.config.js for you. Just add the plugins key to your babel.config.js file and add your alias. The env key is not needed anymore.

module.exports = function(api) {
  api.cache(true)

  return {
    presets: ['babel-preset-expo'],
    plugins: [
      [
        'module-resolver',
        {
          alias: {
            assets: './assets',
            components: './src/components',
            modules: './src/modules',
            lib: './src/lib',
            types: './src/types',
            constants: './src/constants',
          },
        },
      ],
    ],
  }
}
```
<blockquote>
<p>Update: Changes for Expo.io SDK v20.0.0</p>
</blockquote>
<p>Since SDK v20.0.0 you can use the normal Babel Expo presets</p>
```{
  "presets": ["babel-preset-expo"],
  "env": {
    "development": {
      "plugins": ["transform-react-jsx-source"]
    }
  },
  "plugins": [
    ["module-resolver", {
      "alias": {
        "alias-name": "./app",
      }
    }]
  ]
}
```
<blockquote>
<p>Expo.io SDK v19.0.0 and before</p>
</blockquote>
<p>Without the <code>root</code>-element, separating <code>plugins</code> and changing <code>presets</code> to <code>babel-preset-react-native-stage-0/decorator-support</code>, an alias work for me.</p>
<p>Using Expo.io on Version 16.0.0
<br>Found this in the Expo Forums here: https://forums.expo.io/t/relative-paths-with-expo/654/3</p>
<p>Can you verify that this works on your case too?</p>
```{
  "presets": ["babel-preset-react-native-stage-0/decorator-support"],
  "env": {
    "development": {
      "plugins": ["transform-react-jsx-source"]
    }
  },
  "plugins": [
    ["module-resolver", {
      "alias": {
        "alias-name": "./app",
      }
    }]
  ]
}
```

Body:
I'm trying to use absolute import paths instead of relative paths with Expo and React Native.

I looked on the expo docs and couldn't find an answer... Searching for the subject in react community I found babel-plugin-module-resolver but it seems that Expo is already using it so I've changed my .babelrc to create some aliases:

{
  "presets": ["babel-preset-expo"],
  "env": {
    "development": {
      "plugins": [
        "transform-react-jsx-source",
        ["module-resolver", {
          "root": ["./app"],
          "alias": {
            "Components": "./app/components",
          }
        }]
      ]
    }
  }
}

But I got the following error:

    Unable to resolve module '@expo/vector-icons/glyphmaps/Entypo.json'
    from '/Users/eduardoleal/Code/lua/rook/node_modules/@expo/vector-icons/Entypo.js':
    Module does not exist in the module map or in these directories:   /Users/eduardoleal/Code/lua/rook/node_modules/@expo/vector-icons/node_modules/@expo/vector-icons/glyphmaps ,   /Users/eduardoleal/Code/lua/rook/node_modules/@expo/vector-icons/glyphmaps  This might be related to https://github.com/facebook/react-native/issues/4968 To resolve try the following:
    1. Clear watchman watches: 'watchman watch-del-all'.
    2. Delete the 'node_modules' folder: 'rm -rf node_modules && npm install'.
    3. Reset packager cache: 'rm -fr $TMPDIR/react-*' or 'npm start --reset-cache'.
    ABI16_0_0RCTFatal -[ABI16_0_0RCTBatchedBridge stopLoadingWithError:] __34-[ABI16_0_0RCTBatchedBridge start]_block_invoke_2 _dispatch_call_block_and_release _dispatch_client_callout _dispatch_main_queue_callback_4CF __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ __CFRunLoopRun CFRunLoopRunSpecific GSEventRunModal UIApplicationMain main start 0x0

Is there any easy way to import absolute paths?

Body:
Update: Expo v32.0.0 and up

Expo init is creating a babel.config.js for you. Just add the plugins key to your babel.config.js file and add your alias. The env key is not needed anymore.

module.exports = function(api) {
  api.cache(true)

  return {
    presets: ['babel-preset-expo'],
    plugins: [
      [
        'module-resolver',
        {
          alias: {
            assets: './assets',
            components: './src/components',
            modules: './src/modules',
            lib: './src/lib',
            types: './src/types',
            constants: './src/constants',
          },
        },
      ],
    ],
  }
}

Update: Changes for Expo.io SDK v20.0.0

Since SDK v20.0.0 you can use the normal Babel Expo presets

{
  "presets": ["babel-preset-expo"],
  "env": {
    "development": {
      "plugins": ["transform-react-jsx-source"]
    }
  },
  "plugins": [
    ["module-resolver", {
      "alias": {
        "alias-name": "./app",
      }
    }]
  ]
}

Expo.io SDK v19.0.0 and before

Without the root-element, separating plugins and changing presets to babel-preset-react-native-stage-0/decorator-support, an alias work for me.

Using Expo.io on Version 16.0.0

Found this in the Expo Forums here: https://forums.expo.io/t/relative-paths-with-expo/654/3

Can you verify that this works on your case too?

{
  "presets": ["babel-preset-react-native-stage-0/decorator-support"],
  "env": {
    "development": {
      "plugins": ["transform-react-jsx-source"]
    }
  },
  "plugins": [
    ["module-resolver", {
      "alias": {
        "alias-name": "./app",
      }
    }]
  ]
}