问:
How to continue code on next line (code too long)
How do I continue code (record insertion) on the next line?  In the example below I tried using underscore to end a line, then & to begin the next due to suggestions online, but it still doesn't compile.  Any thoughts?

Code Line:

```<code>CurrentDb.Execute "INSERT INTO AIP&BOP (PlanTitle, FileLocation, YearsofData, AnnualImprovedCML, AIP1, AIP1BOP1, AIP2, AIP1BOP2, AIP3, AIP1BOP3, AIP4, AIP1BOP4, AIP5, AIP1BOP5, AIP6, AIP1BOP6, AIP7, AIP1BOP7, AIP8, AIP1BOP8, AIP9, AIP1BOP9, AIP10, AIP1BOP10, AIP11, AIP1BOP11, AIP12, AIP1BOP12, AIP13, AIP1BOP13, AIP14, AIP1BOP14, AIP15, AIP1BOP15, AIP16, AIP1BOP16, AIP17, AIP1BOP17, AIP18, AIP1BOP18, AIP19, AIP1BOP19, AIP20, AIP1BOP20, AIP21, AIP1BOP21, AIP22, AIP1BOP22, AIP23, AIP1BOP23, AIP24, AIP1BOP24) Values ('" & RWPSheetvalues(71) & "', '" & RWPSheetvalues(72) & "', '" & RWPSheetvalues(73) & "', '" & RWPSheetvalues(74) & "','" & RWPSheetvalues(1) & "','" & RWPSheetvalues(2) & "', '" & RWPSheetvalues(3) & "', '" & RWPSheetvalues(4) & "','" & RWPSheetvalues(5) & "','" & RWPSheetvalues(6) & "', '" & RWPSheetvalues(7) & "', '" & RWPSheetvalues(8) & "','" & RWPSheetvalues(9) & "', _
& '" & RWPSheetvalues(10) & "', '" & RWPSheetvalues(11) & "', '" & RWPSheetvalues(12) & "','" & RWPSheetvalues(13) & "','" & RWPSheetvalues(14) & "', '" & RWPSheetvalues(15) & "', '" & RWPSheetvalues(16) & "','" & RWPSheetvalues(17) & "','" & RWPSheetvalues(18) & "', '" & RWPSheetvalues(19) & "', '" & RWPSheetvalues(20) & "','" & RWPSheetvalues(21) & "','" & RWPSheetvalues(22) & "', '" & RWPSheetvalues(23) & "', '" & RWPSheetvalues(24) & "','" & RWPSheetvalues(25) & "','" & RWPSheetvalues(26) & "', '" & RWPSheetvalues(27) & "', '" & RWPSheetvalues(28) & "','" & RWPSheetvalues(29) & "','" & RWPSheetvalues(30) & "', '" & RWPSheetvalues(31) & "', '" & RWPSheetvalues(32) & "','" & RWPSheetvalues(33) & "','" & RWPSheetvalues(34) & "', '" & RWPSheetvalues(35) & "', '" & RWPSheetvalues(36) & "','" & RWPSheetvalues(37) & "','" & RWPSheetvalues(38) & "', '" & RWPSheetvalues(39) & "', '" & RWPSheetvalues(40) & "','" & RWPSheetvalues(41) & "', _
& '" & RWPSheetvalues(42) & "', '" & RWPSheetvalues(43) & "', '" & RWPSheetvalues(44) & "','" & RWPSheetvalues(45) & "','" & RWPSheetvalues(46) & "', '" & RWPSheetvalues(47) & "', '" & RWPSheetvalues(48) & "','" & RWPSheetvalues(49) & "','" & RWPSheetvalues(50) & "', '" & RWPSheetvalues(51) & "', '" & RWPSheetvalues(52) & "','" & RWPSheetvalues(53) & "','" & RWPSheetvalues(54) & "', '" & RWPSheetvalues(55) & "', '" & RWPSheetvalues(56) & "','" & RWPSheetvalues(57) & "','" & RWPSheetvalues(58) & "', '" & RWPSheetvalues(59) & "', '" & RWPSheetvalues(60) & "','" & RWPSheetvalues(61) & "','" & RWPSheetvalues(62) & "', '" & RWPSheetvalues(63) & "', '" & RWPSheetvalues(64) & "','" & RWPSheetvalues(65) & "','" & RWPSheetvalues(66) & "', '" & RWPSheetvalues(67) & "', '" & RWPSheetvalues(68) & "','" & RWPSheetvalues(69) & "','" & RWPSheetvalues(70) & "')"
</code>```

答:
You have ended your line this way: "','" & RWPSheetvalues(9) & "', _, putting the underscore inside the String. The interpreter interpreted the underscore as a character in the String, rather than a line connector, and the String to be endless. The String in the next line is interpreted as not started.

Just end the string a the end of the line:

"','" & RWPSheetvalues(9) & "', " _

and begin a concatenated String at the beginning of the next line:

& "'" & RWPSheetvalues(10)

I would also highly recommend you add more underscores, and make the code more readable.

Body:
How do I continue code (record insertion) on the next line?  In the example below I tried using underscore to end a line, then & to begin the next due to suggestions online, but it still doesn't compile.  Any thoughts?

Code Line:

CurrentDb.Execute "INSERT INTO AIP&BOP (PlanTitle, FileLocation, YearsofData, AnnualImprovedCML, AIP1, AIP1BOP1, AIP2, AIP1BOP2, AIP3, AIP1BOP3, AIP4, AIP1BOP4, AIP5, AIP1BOP5, AIP6, AIP1BOP6, AIP7, AIP1BOP7, AIP8, AIP1BOP8, AIP9, AIP1BOP9, AIP10, AIP1BOP10, AIP11, AIP1BOP11, AIP12, AIP1BOP12, AIP13, AIP1BOP13, AIP14, AIP1BOP14, AIP15, AIP1BOP15, AIP16, AIP1BOP16, AIP17, AIP1BOP17, AIP18, AIP1BOP18, AIP19, AIP1BOP19, AIP20, AIP1BOP20, AIP21, AIP1BOP21, AIP22, AIP1BOP22, AIP23, AIP1BOP23, AIP24, AIP1BOP24) Values ('" & RWPSheetvalues(71) & "', '" & RWPSheetvalues(72) & "', '" & RWPSheetvalues(73) & "', '" & RWPSheetvalues(74) & "','" & RWPSheetvalues(1) & "','" & RWPSheetvalues(2) & "', '" & RWPSheetvalues(3) & "', '" & RWPSheetvalues(4) & "','" & RWPSheetvalues(5) & "','" & RWPSheetvalues(6) & "', '" & RWPSheetvalues(7) & "', '" & RWPSheetvalues(8) & "','" & RWPSheetvalues(9) & "', _
& '" & RWPSheetvalues(10) & "', '" & RWPSheetvalues(11) & "', '" & RWPSheetvalues(12) & "','" & RWPSheetvalues(13) & "','" & RWPSheetvalues(14) & "', '" & RWPSheetvalues(15) & "', '" & RWPSheetvalues(16) & "','" & RWPSheetvalues(17) & "','" & RWPSheetvalues(18) & "', '" & RWPSheetvalues(19) & "', '" & RWPSheetvalues(20) & "','" & RWPSheetvalues(21) & "','" & RWPSheetvalues(22) & "', '" & RWPSheetvalues(23) & "', '" & RWPSheetvalues(24) & "','" & RWPSheetvalues(25) & "','" & RWPSheetvalues(26) & "', '" & RWPSheetvalues(27) & "', '" & RWPSheetvalues(28) & "','" & RWPSheetvalues(29) & "','" & RWPSheetvalues(30) & "', '" & RWPSheetvalues(31) & "', '" & RWPSheetvalues(32) & "','" & RWPSheetvalues(33) & "','" & RWPSheetvalues(34) & "', '" & RWPSheetvalues(35) & "', '" & RWPSheetvalues(36) & "','" & RWPSheetvalues(37) & "','" & RWPSheetvalues(38) & "', '" & RWPSheetvalues(39) & "', '" & RWPSheetvalues(40) & "','" & RWPSheetvalues(41) & "', _
& '" & RWPSheetvalues(42) & "', '" & RWPSheetvalues(43) & "', '" & RWPSheetvalues(44) & "','" & RWPSheetvalues(45) & "','" & RWPSheetvalues(46) & "', '" & RWPSheetvalues(47) & "', '" & RWPSheetvalues(48) & "','" & RWPSheetvalues(49) & "','" & RWPSheetvalues(50) & "', '" & RWPSheetvalues(51) & "', '" & RWPSheetvalues(52) & "','" & RWPSheetvalues(53) & "','" & RWPSheetvalues(54) & "', '" & RWPSheetvalues(55) & "', '" & RWPSheetvalues(56) & "','" & RWPSheetvalues(57) & "','" & RWPSheetvalues(58) & "', '" & RWPSheetvalues(59) & "', '" & RWPSheetvalues(60) & "','" & RWPSheetvalues(61) & "','" & RWPSheetvalues(62) & "', '" & RWPSheetvalues(63) & "', '" & RWPSheetvalues(64) & "','" & RWPSheetvalues(65) & "','" & RWPSheetvalues(66) & "', '" & RWPSheetvalues(67) & "', '" & RWPSheetvalues(68) & "','" & RWPSheetvalues(69) & "','" & RWPSheetvalues(70) & "')"


来源: stackexchange

问:
Android in-app billing crashing sometimes/working sometimes
I'm trying to setup in-app billing for my app and I just edit the TrivialDrive's (only needed gas purchase so i delete other purchase codes). so the first time i run it it worked perfectly and I even done the purchase. but the next time i run it (i'm 100% sure i didn't change any code) when i select purchase button the app just crashes!

i tried: invalidate and restart android studio-restarting my phone but nothing changes.

```<code>>     java.lang.IllegalStateException: Could not execute method of the activity
>                                                                                at android.view.View$1.onClick(View.java:3688)
>                                                                                at android.view.View.performClick(View.java:4293)
>                                                                                at android.view.View$PerformClick.run(View.java:17535)
>                                                                                at android.os.Handler.handleCallback(Handler.java:725)
>                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
>                                                                                at android.os.Looper.loop(Looper.java:153)
>                                                                                at android.app.ActivityThread.main(ActivityThread.java:5299)
>                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
>                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
>                                                                                at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
>                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
>                                                                                at dalvik.system.NativeStart.main(Native Method)
>                                                                              Caused by: java.lang.reflect.InvocationTargetException
>                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
>                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
>                                                                                at android.view.View$1.onClick(View.java:3683)
>                                                                                at android.view.View.performClick(View.java:4293)
>                                                                                at android.view.View$PerformClick.run(View.java:17535)
>                                                                                at android.os.Handler.handleCallback(Handler.java:725)
>                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
>                                                                                at android.os.Looper.loop(Looper.java:153)
>                                                                                at android.app.ActivityThread.main(ActivityThread.java:5299)
>                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
>                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
>                                                                                at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
>                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
>                                                                                at dalvik.system.NativeStart.main(Native Method)
>                                                                              Caused by: java.lang.IllegalStateException: Can't start async
> operation (launchPurchaseFlow) because another async operation(refresh
> inventory) is in progress.
>                                                                                at util.IabHelper.flagStartAsync(IabHelper.java:819)
>                                                                                at util.IabHelper.launchPurchaseFlow(IabHelper.java:373)
>                                                                                at util.IabHelper.launchPurchaseFlow(IabHelper.java:338)
>                                                                                at
> kalamat.fun4ever.com.word2.buying.onBuyGasButtonClicked(buying.java:209)
>                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
>                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
>                                                                                at android.view.View$1.onClick(View.java:3683)
>                                                                                at android.view.View.performClick(View.java:4293)
>                                                                                at android.view.View$PerformClick.run(View.java:17535)
>                                                                                at android.os.Handler.handleCallback(Handler.java:725)
>                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
>                                                                                at android.os.Looper.loop(Looper.java:153)
>                                                                                at android.app.ActivityThread.main(ActivityThread.java:5299)
>                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
>                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
>                                                                                at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
>                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
>                                                                                at dalvik.system.NativeStart.main(Native Method)  12-01 21:15:29.052
> 27771-27777/kalamat.fun4ever.com.word2 D/jdwp: processIncoming
</code>```

this is 'buying.java:209'  :

```<code>  mHelper.launchPurchaseFlow(this, SKU_GAS, RC_REQUEST,
                mPurchaseFinishedListener, payload);
</code>```

答: because another operation not finished,maybe you have disconnected with google servers.check if the mservices is null,when the crash happened.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to setup in-app billing for my app and I just edit the TrivialDrive's (only needed gas purchase so i delete other purchase codes). so the first time i run it it worked perfectly and I even done the purchase. but the next time i run it (i'm 100% sure i didn't change any code) when i select purchase button the app just crashes!

i tried: invalidate and restart android studio-restarting my phone but nothing changes.

>     java.lang.IllegalStateException: Could not execute method of the activity
>                                                                                at android.view.View$1.onClick(View.java:3688)
>                                                                                at android.view.View.performClick(View.java:4293)
>                                                                                at android.view.View$PerformClick.run(View.java:17535)
>                                                                                at android.os.Handler.handleCallback(Handler.java:725)
>                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
>                                                                                at android.os.Looper.loop(Looper.java:153)
>                                                                                at android.app.ActivityThread.main(ActivityThread.java:5299)
>                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
>                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
>                                                                                at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
>                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
>                                                                                at dalvik.system.NativeStart.main(Native Method)
>                                                                              Caused by: java.lang.reflect.InvocationTargetException
>                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
>                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
>                                                                                at android.view.View$1.onClick(View.java:3683)
>                                                                                at android.view.View.performClick(View.java:4293)
>                                                                                at android.view.View$PerformClick.run(View.java:17535)
>                                                                                at android.os.Handler.handleCallback(Handler.java:725)
>                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
>                                                                                at android.os.Looper.loop(Looper.java:153)
>                                                                                at android.app.ActivityThread.main(ActivityThread.java:5299)
>                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
>                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
>                                                                                at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
>                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
>                                                                                at dalvik.system.NativeStart.main(Native Method)
>                                                                              Caused by: java.lang.IllegalStateException: Can't start async
> operation (launchPurchaseFlow) because another async operation(refresh
> inventory) is in progress.
>                                                                                at util.IabHelper.flagStartAsync(IabHelper.java:819)
>                                                                                at util.IabHelper.launchPurchaseFlow(IabHelper.java:373)
>                                                                                at util.IabHelper.launchPurchaseFlow(IabHelper.java:338)
>                                                                                at
> kalamat.fun4ever.com.word2.buying.onBuyGasButtonClicked(buying.java:209)
>                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
>                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
>                                                                                at android.view.View$1.onClick(View.java:3683)
>                                                                                at android.view.View.performClick(View.java:4293)
>                                                                                at android.view.View$PerformClick.run(View.java:17535)
>                                                                                at android.os.Handler.handleCallback(Handler.java:725)
>                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
>                                                                                at android.os.Looper.loop(Looper.java:153)
>                                                                                at android.app.ActivityThread.main(ActivityThread.java:5299)
>                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
>                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
>                                                                                at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
>                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
>                                                                                at dalvik.system.NativeStart.main(Native Method)  12-01 21:15:29.052
> 27771-27777/kalamat.fun4ever.com.word2 D/jdwp: processIncoming

this is 'buying.java:209'  :

  mHelper.launchPurchaseFlow(this, SKU_GAS, RC_REQUEST,
                mPurchaseFinishedListener, payload);


问:
How to hide groupbox by conditions in xaml
I have this piece of code:

```<code> <GroupBox Header="Varování" Grid.Column="0" VerticalAlignment="Top"  Grid.ColumnSpan="2" Height="Auto" Margin="0,75,0,-6" >

            <StackPanel Orientation="Horizontal" VerticalAlignment="Top" Height="Auto">
                <checks:UCWeighingRecordCheck x:Name="weighingRecordCheck" DataContext="{Binding EntityNotifiedTruck.WeighingRecordCheck}"  VerticalAlignment="Top" />
            </StackPanel>
        </GroupBox>
</code>```

What i want to do is: I want to hide this groupbox if UCWeighingRecordChecks is null. Any tips how to do it?

答:
You can also use DataTrigger:

```<code><GroupBox Header="Varování" Grid.Column="0" VerticalAlignment="Top"  Grid.ColumnSpan="2" Height="Auto" Margin="0,75,0,-6" >
    <StackPanel Orientation="Horizontal" VerticalAlignment="Top" Height="Auto">
       <checks:UCWeighingRecordCheck x:Name="weighingRecordCheck" DataContext="{Binding EntityNotifiedTruck.WeighingRecordCheck}"  VerticalAlignment="Top" />
   </StackPanel>
   <GroupBox.Style>
     <Style TargetType="GroupBox">
       <Style.Triggers>
          <DataTrigger Binding="{Binding UCWeighingRecordChecks }" Value="{x:Null}">
             <Setter Property="Visibility" Value="Collapsed"/>
          </DataTrigger>
        </Style.Triggers>
    </Style>
  </GroupBox.Style>
</GroupBox>
</code>```

Body:
I have this piece of code:

 <GroupBox Header="Varování" Grid.Column="0" VerticalAlignment="Top"  Grid.ColumnSpan="2" Height="Auto" Margin="0,75,0,-6" >

            <StackPanel Orientation="Horizontal" VerticalAlignment="Top" Height="Auto">
                <checks:UCWeighingRecordCheck x:Name="weighingRecordCheck" DataContext="{Binding EntityNotifiedTruck.WeighingRecordCheck}"  VerticalAlignment="Top" />
            </StackPanel>
        </GroupBox>

What i want to do is: I want to hide this groupbox if UCWeighingRecordChecks is null. Any tips how to do it?

Body:
You can also use DataTrigger:

<GroupBox Header="Varování" Grid.Column="0" VerticalAlignment="Top"  Grid.ColumnSpan="2" Height="Auto" Margin="0,75,0,-6" >
    <StackPanel Orientation="Horizontal" VerticalAlignment="Top" Height="Auto">
       <checks:UCWeighingRecordCheck x:Name="weighingRecordCheck" DataContext="{Binding EntityNotifiedTruck.WeighingRecordCheck}"  VerticalAlignment="Top" />
   </StackPanel>
   <GroupBox.Style>
     <Style TargetType="GroupBox">
       <Style.Triggers>
          <DataTrigger Binding="{Binding UCWeighingRecordChecks }" Value="{x:Null}">
             <Setter Property="Visibility" Value="Collapsed"/>
          </DataTrigger>
        </Style.Triggers>
    </Style>
  </GroupBox.Style>
</GroupBox>


问:
Using NSNumberFormatter to get a decimal value from an international currency string
It seems that the NSNumberFormatter can't parse Euro (and probably other) currency strings into a numerical type. Can someone please prove me wrong.

I'm attempting to use the following to get a numeric amount from a currency string:

```<code>NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *currencyNumber = [currencyFormatter numberFromString:currencyString];
</code>```

This works fine for UK and US currency amounts. It even deals with $ and £ and thousands separators with no problems.

However, when I use it with euro currency amounts (with the Region Format set to France or Germany in the settings app) it returns an empty string. All of the following strings fail:

```<code>12,34 €
12,34
12.345,67 €
12.345,67
</code>```

It's worth noting that these strings match exactly what comes out of the NSNumberFormatter's stringFromNumber method when using the corresponding locale.

Setting the Region Format to France in the settings app, then setting currencyNumber to 12.34 in the following code, results in currencyString being set to '12,34 €' :

```<code>NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *currencyString = [currencyFormatter stringFromNumber:currencyNumber];
</code>```

It would obviously be fairly easy to hack around this problem specifically for the Euro but I'm hoping to sell this app in as many countries as possible and I'm thinking that a similar situation is bound to occur with other locales.

Does anyone have an answer?

TIA, Duncan

答:
Its working code in Swift..

```<code>    let formatter = NumberFormatter()
    formatter.usesGroupingSeparator = true
    formatter.locale = Locale(identifier: "de_DE")
    formatter.numberStyle = NumberFormatter.Style.currency
    formatter.string(from: NSNumber(floatLiteral: InputAsDoubleValue))!
</code>```

Identifiers:

for German - "de_DE"

for US - "en_US"

for France - "fr_FR"

The formatted value would also be returned with the respective currency symbol.

ContentLicense: CC BY-SA 2.5

Body:
It seems that the NSNumberFormatter can't parse Euro (and probably other) currency strings into a numerical type. Can someone please prove me wrong.

I'm attempting to use the following to get a numeric amount from a currency string:

NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *currencyNumber = [currencyFormatter numberFromString:currencyString];

This works fine for UK and US currency amounts. It even deals with $ and £ and thousands separators with no problems.

However, when I use it with euro currency amounts (with the Region Format set to France or Germany in the settings app) it returns an empty string. All of the following strings fail:

12,34 €
12,34
12.345,67 €
12.345,67

It's worth noting that these strings match exactly what comes out of the NSNumberFormatter's stringFromNumber method when using the corresponding locale.

Setting the Region Format to France in the settings app, then setting currencyNumber to 12.34 in the following code, results in currencyString being set to '12,34 €' :

NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *currencyString = [currencyFormatter stringFromNumber:currencyNumber];

It would obviously be fairly easy to hack around this problem specifically for the Euro but I'm hoping to sell this app in as many countries as possible and I'm thinking that a similar situation is bound to occur with other locales.

Does anyone have an answer?

TIA, Duncan

Body:
Its working code in Swift..

    let formatter = NumberFormatter()
    formatter.usesGroupingSeparator = true
    formatter.locale = Locale(identifier: "de_DE")
    formatter.numberStyle = NumberFormatter.Style.currency
    formatter.string(from: NSNumber(floatLiteral: InputAsDoubleValue))!

Identifiers:

for German - "de_DE"

for US - "en_US"

for France - "fr_FR"

The formatted value would also be returned with the respective currency symbol.


问:
How can I rename a field for all documents in MongoDB?
Assuming I have a collection in MongoDB with 5000 records, each containing something similar to:

```<code>{
"occupation":"Doctor",
"name": {
   "first":"Jimmy",
   "additional":"Smith"
}
</code>```

Is there an easy way to rename the field "additional" to "last" in all documents? I saw the $rename operator in the documentation but I'm not really clear on how to specify a subfield.

答:
I am using ,Mongo 3.4.0

The $rename operator updates the name of a field and has the following form:

```<code>{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }
</code>```

for e.g

```<code>db.getCollection('user').update( { _id: 1 }, { $rename: { 'fname': 'FirstName', 'lname': 'LastName' } } )
</code>```

The new field name must differ from the existing field name. To specify a  in an embedded document, use dot notation.

This operation renames the field nmae to name for all documents in the collection:

```<code>db.getCollection('user').updateMany( {}, { $rename: { "add": "Address" } } )

db.getCollection('user').update({}, {$rename:{"name.first":"name.FirstName"}}, false, true);
</code>```

In the method above  false, true are: { upsert:false, multi:true }.To update all your records, You need the multi:true.

Rename a Field in an Embedded Document

```<code>db.getCollection('user').update( { _id: 1 }, { $rename: { "name.first": "name.fname" } } )
</code>```

use link : https://docs.mongodb.com/manual/reference/operator/update/rename/

Body:
Assuming I have a collection in MongoDB with 5000 records, each containing something similar to:

{
"occupation":"Doctor",
"name": {
   "first":"Jimmy",
   "additional":"Smith"
}

Is there an easy way to rename the field "additional" to "last" in all documents? I saw the $rename operator in the documentation but I'm not really clear on how to specify a subfield.

Body:
I am using ,Mongo 3.4.0

The $rename operator updates the name of a field and has the following form:

{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }

for e.g

db.getCollection('user').update( { _id: 1 }, { $rename: { 'fname': 'FirstName', 'lname': 'LastName' } } )

The new field name must differ from the existing field name. To specify a  in an embedded document, use dot notation.

This operation renames the field nmae to name for all documents in the collection:

db.getCollection('user').updateMany( {}, { $rename: { "add": "Address" } } )

db.getCollection('user').update({}, {$rename:{"name.first":"name.FirstName"}}, false, true);

In the method above  false, true are: { upsert:false, multi:true }.To update all your records, You need the multi:true.

Rename a Field in an Embedded Document

db.getCollection('user').update( { _id: 1 }, { $rename: { "name.first": "name.fname" } } )

use link : https://docs.mongodb.com/manual/reference/operator/update/rename/


问:
Unexpected behavior in the following Prolog program
I am trying to understand how recursion works in Prolog. Consider the following program.

```<code>edge(a,b).
edge(b,c).
edge(c,d).
edge(a,d).
edge(c,e).
path(d).
path(Vertex) :-  edge(Vertex, Next), write(Next), path(Next).
</code>```

Run path(a).

output:

```<code>?- path(a).
bcd
true ;
ed
true;
false
</code>```

What I don't quiet understand is the loop part of this program. So we start at a and then we go to b,c and d. Once we see d we stop. I can't understand the output 'ed' in the forth line. Why is it going to e,d and then returning true.  I also don't understand how the operator ';' works when querying another result. Does it mean get next possible result?

Another example: The following program writes all possible paths from one node to another node. I don't understand how loops work in this program to display different lists of paths.

```<code> link( a, b ).
    link( a, d ).
    link( b, c ).
    link( d, e ).
    link( e, c ).
    link( e, f ).
    link( f, a ).
    link( f, g ).
    link( f, j ).
    link( g, h ).
    link( h, i ).
    link( i, j ).

not( X ) :- X, !, fail.
not( _ ).

writeallpaths( Node, Node ) :-
   write( Node ), write( ' is ' ), write( Node ), nl.
writeallpaths( Node, Next ) :-
   listpath( Node, Next, [Node], List ),
   write( Node ), write( ' to ' ), write( Next ), write( ' is ' ),
   writepath( List ),
   fail.

writepath( [] ) :-
   nl.
writepath( [Head|Tail] ) :-
   write( ' ' ), write( Head ), writepath( Tail ).

listpath( Node, End, Outlist ) :-
   listpath( Node, End, [Node], Outlist ).

listpath( Node, Node, _, [Node] ).
listpath( Node, End, Tried, [Node|List] ) :-
   link( Node, Next ),
   not( member( Next, Tried )),
   listpath( Next, End, [Next|Tried], List ).
</code>```

答:
I also don't understand how the operator ';' works when querying another result. Does it mean get next possible result?

Yes. What happens is that when you enter ; after finding the solution "bcd", Prolog tries to find alternative solution. In your case, it "goes back" (backtracks) to "c" because it has alternative path to "e" and continues search from there, until it reaches "d". Obviously, it doesn't print you the entire solution "bced", because Prolog does not go back to the very beginning, but rather only to "c", so only nodes after "c" are printed.

Also, you can always use trace/0 predicate which allows you to see in detail how Prolog executes your code.

Body:
I am trying to understand how recursion works in Prolog. Consider the following program.

edge(a,b).
edge(b,c).
edge(c,d).
edge(a,d).
edge(c,e).
path(d).
path(Vertex) :-  edge(Vertex, Next), write(Next), path(Next).

Run path(a).

output:

?- path(a).
bcd
true ;
ed
true;
false

What I don't quiet understand is the loop part of this program. So we start at a and then we go to b,c and d. Once we see d we stop. I can't understand the output 'ed' in the forth line. Why is it going to e,d and then returning true.  I also don't understand how the operator ';' works when querying another result. Does it mean get next possible result?

Another example: The following program writes all possible paths from one node to another node. I don't understand how loops work in this program to display different lists of paths.

 link( a, b ).
    link( a, d ).
    link( b, c ).
    link( d, e ).
    link( e, c ).
    link( e, f ).
    link( f, a ).
    link( f, g ).
    link( f, j ).
    link( g, h ).
    link( h, i ).
    link( i, j ).

not( X ) :- X, !, fail.
not( _ ).

writeallpaths( Node, Node ) :-
   write( Node ), write( ' is ' ), write( Node ), nl.
writeallpaths( Node, Next ) :-
   listpath( Node, Next, [Node], List ),
   write( Node ), write( ' to ' ), write( Next ), write( ' is ' ),
   writepath( List ),
   fail.

writepath( [] ) :-
   nl.
writepath( [Head|Tail] ) :-
   write( ' ' ), write( Head ), writepath( Tail ).

listpath( Node, End, Outlist ) :-
   listpath( Node, End, [Node], Outlist ).

listpath( Node, Node, _, [Node] ).
listpath( Node, End, Tried, [Node|List] ) :-
   link( Node, Next ),
   not( member( Next, Tried )),
   listpath( Next, End, [Next|Tried], List ).


问:
Set Location in PowerShell that contains a ampersand (&)
How do i set my directory using PowerShell to the below location ?

```<code>W:\B&M\Store Segmentation\Pete\Python
</code>```

I tried using:

```<code>PS > Set-Location -Path W:\B"&"M\Store Segmentation\Pete\Python
</code>```

答:
Use " double quotes or ' apostrophes as follows:

```<code>Set-Location -Path "W:\B&M\Store Segmentation\Pete\Python"
</code>```

or

```<code>Set-Location -Path 'W:\B&M\Store Segmentation\Pete\Python'
</code>```

Read About Quoting Rules for explanation.

Body:
How do i set my directory using PowerShell to the below location ?

W:\B&M\Store Segmentation\Pete\Python

I tried using:

PS > Set-Location -Path W:\B"&"M\Store Segmentation\Pete\Python

Body:
Use " double quotes or ' apostrophes as follows:

Set-Location -Path "W:\B&M\Store Segmentation\Pete\Python"

or

Set-Location -Path 'W:\B&M\Store Segmentation\Pete\Python'

Read About Quoting Rules for explanation.


问:
Uncaught ReferenceError: controller is not defined in react js
This is the second tutorial that I am following due to failure in versions and dependencies in the earlier. As you can guess I am just trying to get started with react here.

I created a controller called Appointments. This is my controller jsx inside the components folder.

app/assets/js/components/appointments.jsx

```<code>var Appointments = React.Component({
    render: function() {
        return (
         <h1>React calender</h1>
        )
    }
});
</code>```

appointments/index.html.erb

```<code><%= react_component 'Appointments' %>
</code>```

And I restarted rails server. All I see is a blank browser and console showing this

```<code>Uncaught ReferenceError: Appointments is not defined
</code>```

答:
What you most probably meant to do is this

```<code>const Appointments = React.createClass({
    // ...
    render() {
    return <div>{this.state.hello}</div>;
  }
});
</code>```

Which is not a very good thing if you plan to or have internal state and/or refs

It is recommended to rather do it like this

```<code>class Appointments extends React.Component {
   // ...
  render() {
    return <div>{this.state.hello}</div>;
  }
}
</code>```

So in your case your component should change from:

```<code>var Appointments = React.Component({
  render: function() {
    return (
     <h1>React calender</h1>
    )
  }
});
</code>```

to this:

```<code>class Appointments extends React.Component {
  render() {
    return (
     <h1>React calender</h1>
    )
  }
}
</code>```

Body:
This is the second tutorial that I am following due to failure in versions and dependencies in the earlier. As you can guess I am just trying to get started with react here.

I created a controller called Appointments. This is my controller jsx inside the components folder.

app/assets/js/components/appointments.jsx

var Appointments = React.Component({
    render: function() {
        return (

React calender

        )
    }
});

appointments/index.html.erb

<%= react_component 'Appointments' %>

And I restarted rails server. All I see is a blank browser and console showing this

Uncaught ReferenceError: Appointments is not defined

Body:
What you most probably meant to do is this

const Appointments = React.createClass({
    // ...
    render() {
    return <div>{this.state.hello}</div>;
  }
});

Which is not a very good thing if you plan to or have internal state and/or refs

It is recommended to rather do it like this

class Appointments extends React.Component {
   // ...
  render() {
    return <div>{this.state.hello}</div>;
  }
}

So in your case your component should change from:

var Appointments = React.Component({
  render: function() {
    return (
     <h1>React calender</h1>
    )
  }
});

to this:

class Appointments extends React.Component {
  render() {
    return (
     <h1>React calender</h1>
    )
  }
}


问:
Distinct Values using Set
I have been using

```<code>      <FormGroup>
        <Campaign
          campaignName={this.campaignName.bind(this)}
          campaignOptions={[...new Set(this.props.records.map(options => options.campaign))]}/>
      </FormGroup>
</code>```

to get a unique array for a dropdown option, however I now need to pass an array with each object in it having a label and a value.

I have refactored the code as follows,

```<code>   <FormGroup>
        <Campaign
          campaignName={this.campaignName.bind(this)}
          campaignOptions={[...new Set(this.props.records.map(options => {
            return {value: options.campaign, label: options.campaign };
          }))]}/>
      </FormGroup>
</code>```

...but the unique element is now not working (see below with duplicates). What am I doing wrong please?

The input array looks like...

```<code>    [
    1. 0:{_id: "zWTiLEjqrCKdxTvze", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "newevent", …}
    2. 1:{_id: "SkZzDMAWokFFYEycp", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "instagramlaunch", …}
    3. 2:{_id: "p4pychanC5Zw8iWAQ", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "stuffinhere", …}
       … more in here including more than 1 object with instagram launch for example
    ]
</code>```

Original approach resulted in Array of...

```<code>    0:"newevent"
    1:"sheffieldevent"
    2:"stuffinhere"
    3:”instagramlaunch"
    4:”anothertest"
    5:”yetanother"
</code>```

now results in...

```<code>    0:{value: "newevent", label: "newevent"}
    1:{value: "sheffieldevent", label: "sheffieldevent"}
    2:{value: "stuffinhere", label: "stuffinhere"}
    3:{value: "instagramlaunch", label: "instagramlaunch"}
    4:{value: "instagramlaunch", label: "instagramlaunch"}
    5:{value: "instagramlaunch", label: "instagramlaunch”}
    6:{value: "anothertest", label: "anothertest”}
    7:{value: "yetanother", label: "yetanother"}
</code>```

答:
```<code>new Set(this.props.records.map(options => {
    return {value: options.campaign, label: options.campaign };
}))
</code>```

Does not work, because every new object is a unique object and Set works with all types. As result, you get all options, but not unique options.

If you have the same pattern as you want, you could render the set after collecting all values and build a new objects array out of the set.

```<code>var optionsSet = new Set(array.map(option => option.campaign)),
    options = Array.from(optionsSet, v => ({ value: v, label: v }));
</code>```

Title: Distinct Values using Set

Body:
I have been using

      <FormGroup>
        <Campaign
          campaignName={this.campaignName.bind(this)}
          campaignOptions={[...new Set(this.props.records.map(options => options.campaign))]}/>
      </FormGroup>

to get a unique array for a dropdown option, however I now need to pass an array with each object in it having a label and a value.

I have refactored the code as follows,

   <FormGroup>
        <Campaign
          campaignName={this.campaignName.bind(this)}
          campaignOptions={[...new Set(this.props.records.map(options => {
            return {value: options.campaign, label: options.campaign };
          }))]}/>
      </FormGroup>

...but the unique element is now not working (see below with duplicates). What am I doing wrong please?

The input array looks like...

    [
    1. 0:{_id: "zWTiLEjqrCKdxTvze", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "newevent", …}
    2. 1:{_id: "SkZzDMAWokFFYEycp", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "instagramlaunch", …}
    3. 2:{_id: "p4pychanC5Zw8iWAQ", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "stuffinhere", …}
       … more in here including more than 1 object with instagram launch for example
    ]

Original approach resulted in Array of...

    0:"newevent"
    1:"sheffieldevent"
    2:"stuffinhere"
    3:”instagramlaunch"
    4:”anothertest"
    5:”yetanother"

now results in...

    0:{value: "newevent", label: "newevent"}
    1:{value: "sheffieldevent", label: "sheffieldevent"}
    2:{value: "stuffinhere", label: "stuffinhere"}
    3:{value: "instagramlaunch", label: "instagramlaunch"}
    4:{value: "instagramlaunch", label: "instagramlaunch"}
    5:{value: "instagramlaunch", label: "instagramlaunch”}
    6:{value: "anothertest", label: "anothertest”}
    7:{value: "yetanother", label: "yetanother"}

Body:
new Set(this.props.records.map(options => {
    return {value: options.campaign, label: options.campaign };
}))

Does not work, because every new object is a unique object and Set works with all types. As result, you get all options, but not unique options.

If you have the same pattern as you want, you could render the set after collecting all values and build a new objects array out of the set.

var optionsSet = new Set(array.map(option => option.campaign)),
    options = Array.from(optionsSet, v => ({ value: v, label: v }));


问:
How to create a solution folder for a solution in visual studio dynamically?
I want to create a new Solution Folder dynamically in Visual Studio using PowerShell script.

I know how to create a solution folder for an existing solution in Visual Studio manually but is there a way we can automate it using PowerShell?

答:
To add a Solution Folder, you should add a Project entry. The Guid for the Project Type for a solution folder should be : "{2150E333-8FDC-42A3-9474-1A3956D46DE8}" and for the project Guid, you should use a new Guid.

Here is a function which adds a folder to a solution file:

```<code>Function AddFolderToSolution($folderName, $solutionFile)
{
   $solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}"
   $content = [System.IO.File]::ReadLines($solutionFile)
   $lines = New-Object System.Collections.Generic.List[string]
   $lines.AddRange($content)
   $index = $lines.IndexOf("Global")
   $guid = [System.Guid]::NewGuid().ToString().ToUpper()
   $txt = "Project(`"$solutionFolderGuid`") = `"$folderName`", `"$folderName`", `"$guid`""
   $lines.Insert($index, $txt)
   $lines.Insert($index+1, "EndProject")
   [System.IO.File]::WriteAllLines($solutionFile, $lines)
}
</code>```

And here is the usage:

```<code>AddFolderToSolution "NewFolder10" "D:\Solution1.sln"
</code>```

Body:
To add a Solution Folder, you should add a Project entry. The Guid for the Project Type for a solution folder should be : "{2150E333-8FDC-42A3-9474-1A3956D46DE8}" and for the project Guid, you should use a new Guid.

Here is a function which adds a folder to a solution file:

Function AddFolderToSolution($folderName, $solutionFile)
{
   $solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}"
   $content = [System.IO.File]::ReadLines($solutionFile)
   $lines = New-Object System.Collections.Generic.List[string]
   $lines.AddRange($content)
   $index = $lines.IndexOf("Global")
   $guid = [System.Guid]::NewGuid().ToString().ToUpper()
   $txt = "Project(`"$solutionFolderGuid`") = `"$folderName`", `"$folderName`", `"$guid`""
   $lines.Insert($index, $txt)
   $lines.Insert($index+1, "EndProject")
   [System.IO.File]::WriteAllLines($solutionFile, $lines)
}

And here is the usage:

AddFolderToSolution "NewFolder10" "D:\Solution1.sln"


问:
.htaccess 301 from w/o subdirectory to subdirectory
Maybe this is a simple thing but I really don't get it.

I have some URLs with this structure
https://www.somedomain.com/this-is-a-slug-for-page-1/123456789/

I want to to a 301 for every URL with this pattern to
https://www.somedomain.com/product/this-is-a-slug-for-page-1/123456789/

I thought, I could make it like this but I does not work correctly:
RewriteRule ^(.+)/[0-9]+?$ $1/product$2 [R=301,L]

Hope you can help me solving this issue with a little bit of explanation for a better understanding.

Thanks

答:
Your pattern is not capturing 2 groups. You can use this rule as your first rule:

```<code>RewriteRule ^(?!product/).+/\d+/?$ /product/$0 [R=301,L,NE,NC]
</code>```

(?!product/) is a negative lookhead that will skip this rule if URI is already starting with /product/

Body:
Your pattern is not capturing 2 groups. You can use this rule as your first rule:

RewriteRule ^(?!product/).+/\d+/?$ /product/$0 [R=301,L,NE,NC]

(?!product/) is a negative lookhead that will skip this rule if URI is already starting with /product/


问:
Turn on specific LED using NeoPixel module for Espruino?
I am trying to turn on a specific LED using the NeoPixel module. How it works is really easy: Parse it a 2D array of RGB colors. Here's an example:

```<code>require("neopixel").write(NodeMCU.B2, [[255, 0, 0], [0, 255, 0], [0, 0, 255]]);
</code>```

That will turn on the first three LEDs with red, green, and blue. I want to have a function, where I can do something like:

```<code>function single(number, color) {
    require("neopixel").write(NodeMCU.B2, number, color);
}

single(0, [255, 0, 0]);
single(1, [0, 255, 0]);
single(2, [0, 0, 255]);
</code>```

Which would do the exact same as above. Now you might ask: Why would you want that? Well:

I want it to remember the last "configuration" of LEDs, so I can update it over time

If I want to turn off all my 100+ LEDs and just turn on the last few (or the ones in the middle), I wouldn't have to parse the write() function 100+ LEDs, where most of them are black

Is something like that possible, or would I have to do some magic in order to remember the last LED configuration?

答:
Yes, totally - it's worth looking at the neopixel docs at http://www.espruino.com/WS2811 as they suggest you use an array to
store the current state.

Once you have that array - called arr here - you can use the .set method to set the 3 elements at the right position (3x the number, because RGB), and then can resend the whole array.

```<code>var arr = new Uint8ClampedArray(NUM_OF_LEDS*3);

function single(number, color) {
  arr.set(color, number*3);
  require("neopixel").write(NodeMCU.B2, arr);
}
</code>```

Body:
I am trying to turn on a specific LED using the NeoPixel module. How it works is really easy: Parse it a 2D array of RGB colors. Here's an example:

require("neopixel").write(NodeMCU.B2, [[255, 0, 0], [0, 255, 0], [0, 0, 255]]);

That will turn on the first three LEDs with red, green, and blue. I want to have a function, where I can do something like:

function single(number, color) {
    require("neopixel").write(NodeMCU.B2, number, color);
}

single(0, [255, 0, 0]);
single(1, [0, 255, 0]);
single(2, [0, 0, 255]);

Which would do the exact same as above. Now you might ask: Why would you want that? Well:

I want it to remember the last "configuration" of LEDs, so I can update it over time

If I want to turn off all my 100+ LEDs and just turn on the last few (or the ones in the middle), I wouldn't have to parse the write() function 100+ LEDs, where most of them are black

Is something like that possible, or would I have to do some magic in order to remember the last LED configuration?

Body:
Yes, totally - it's worth looking at the neopixel docs at http://www.espruino.com/WS2811 as they suggest you use an array to
store the current state.

Once you have that array - called arr here - you can use the .set method to set the 3 elements at the right position (3x the number, because RGB), and then can resend the whole array.

var arr = new Uint8ClampedArray(NUM_OF_LEDS*3);

function single(number, color) {
  arr.set(color, number*3);
  require("neopixel").write(NodeMCU.B2, arr);
}


问:
Yii2: How create an route to common
I want create an "errorAction" in "common". So that when a page does not exist, be redirected to action "index" in "common/controllers/ErrorController".

I have this:

common\main.php

```<code><?php
return [
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'errorHandler' => [
            'errorAction' => 'error/index',
        ],
    ],
];
</code>```

And this structure:

```<code>common
 - controllers
 - - ErrorController.php
 - views
 - - error
 - - - index.php
</code>```

But I want it to redirect there even when there is no "frontend" folder on the server (it does not exist temporarily because of maintenance).

I use the extension "Yii2 Maintenance mode component", and it redirects correctly to the view I created in the "common" folder.
The problem is that when I have deleted both the "backend" and "frontend" folder from the server, it does not redirect to the maintenance page, and it shows the default page of the Apache "404 Not Found".

common\main-local.php

```<code>...
        'maintenanceMode' => [
            'class' => 'brussens\maintenance\MaintenanceMode',
            'layoutPath' => '@common/views/layouts/maintenance',
            'viewPath' => '@common/views/maintenance/index',
            'roles' => [
                'administrator',
            ],
            'urls' => [
                'site/login',
            ],
        ],
...
</code>```

答:
You can achive this adding a .htaccess file in your document root. With this configuration you have been redirected on common page when a folder/file not exist instead of a 404 error.

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . route/to/your/common/handler [L]
</code>```

Title: Yii2: How create an route to common

Body:
I want create an "errorAction" in "common". So that when a page does not exist, be redirected to action "index" in "common/controllers/ErrorController".

I have this:

common\main.php

<?php
return [
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'errorHandler' => [
            'errorAction' => 'error/index',
        ],
    ],
];

And this structure:

common
 - controllers
 - - ErrorController.php
 - views
 - - error
 - - - index.php

But I want it to redirect there even when there is no "frontend" folder on the server (it does not exist temporarily because of maintenance).

I use the extension "Yii2 Maintenance mode component", and it redirects correctly to the view I created in the "common" folder.
The problem is that when I have deleted both the "backend" and "frontend" folder from the server, it does not redirect to the maintenance page, and it shows the default page of the Apache "404 Not Found".

common\main-local.php

...
        'maintenanceMode' => [
            'class' => 'brussens\maintenance\MaintenanceMode',
            'layoutPath' => '@common/views/layouts/maintenance',
            'viewPath' => '@common/views/maintenance/index',
            'roles' => [
                'administrator',
            ],
            'urls' => [
                'site/login',
            ],
        ],
...

Body:
You can achive this adding a .htaccess file in your document root. With this configuration you have been redirected on common page when a folder/file not exist instead of a 404 error.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . route/to/your/common/handler [L]


问:
Best way to get values from a dictionary in Python
Apologies for the potentially noobish question.

I have this dict:

```<code>info = {'a': [u'option1'], 'b': [u'option2', u'option3'], 'c': [], 'd': [], 'e': [], 'f': [u'option4', u'option5', u'option6', u'option7', u'option8', u'option9', u'option10', u'option11'], 'g': [], 'h': []}
</code>```

I need to make a query with each value.
In Python what is the best way to get the values?

I currently do this:

```<code>keys = info.keys ()
for i in keys:
    for j in info [i]:
        # Make query with j
</code>```

I think it can be done better.
Thank you very much!

答:
```<code>for key, value in info.items():
    #do something with either the key, value or both
</code>```

Body:
Apologies for the potentially noobish question.

I have this dict:

info = {'a': [u'option1'], 'b': [u'option2', u'option3'], 'c': [], 'd': [], 'e': [], 'f': [u'option4', u'option5', u'option6', u'option7', u'option8', u'option9', u'option10', u'option11'], 'g': [], 'h': []}

I need to make a query with each value.
In Python what is the best way to get the values?

I currently do this:

keys = info.keys ()
for i in keys:
    for j in info [i]:
        # Make query with j

I think it can be done better.
Thank you very much!


问:
How do I exclude a specific row in Laravel?
I'm trying to return information from my database but I would like to output last news a litlle differend than other.

I managed to get last news with the following code

```<code>$finalNews = News::find(DB::table('news')->max('id'));
</code>```

But than I have another variable which return all the rows from News table with the following code

```<code>$news = News::orderBy('id','desc')->get();
</code>```

I want to exclude the news row which is equal to $finalNews
at the end of controller I return view with following data

```<code>return view('news', ['news' => $news, 'finalNews' => $finalNews]);
</code>```

How can I exclude the last news? I am using Laravel and MySQL.

答:
Try to use following code</p>

```<code>$finalNews = News::find(DB::table('news')->max('id'));

$news = News::where('id','<>',$finalNews->id)->orderBy('id','desc')->get();
</code>```

Body:
I'm trying to return information from my database but I would like to output last news a litlle differend than other.

I managed to get last news with the following code

$finalNews = News::find(DB::table('news')->max('id'));

But than I have another variable which return all the rows from News table with the following code

$news = News::orderBy('id','desc')->get();

I want to exclude the news row which is equal to $finalNews
at the end of controller I return view with following data

return view('news', ['news' => $news, 'finalNews' => $finalNews]);

How can I exclude the last news? I am using Laravel and MySQL.

Body:
Try to use following code

$finalNews = News::find(DB::table('news')->max('id'));

$news = News::where('id','<>',$finalNews->id)->orderBy('id','desc')->get();


答:
You can iterate through the keys and values of a dict using items().

```<code>for i, js in info.items():
    for j in js:
        # Make query with j
</code>```

(In Python 2 you might prefer to use iteritems() instead of items().)

If you don't need to make use of the keys at all, you could just use values (or itervalues for Python 2).

```<code>for js in info.values():
    for j in js:
        # Make query with j
</code>```

Maybe a list comprehension would work for you; it is impossible to tell without knowing what "Make query with j" entails.

Title: Best way to get values from a dictionary in Python

Body:
You can iterate through the keys and values of a dict using items().

for i, js in info.items():
    for j in js:
        # Make query with j

(In Python 2 you might prefer to use iteritems() instead of items().)

If you don't need to make use of the keys at all, you could just use values (or itervalues for Python 2).

for js in info.values():
    for j in js:
        # Make query with j

Maybe a list comprehension would work for you; it is impossible to tell without knowing what "Make query with j" entails.


问:
Your organization's policies are preventing us from completing this action - Microsoft Office
When I try to open hyperlinks in a Microsoft Office program like Excel or Outlook the following message is shown:

Your organization's policies are preventing us from completing this action for you. For more info, please contact your help desk.

How can I resolve this so it opens Hyperlinks with my default browser?

答:
Method 3 - Step 3 from Microsoft support page Hyperlinks are not working in Outlook:

Verify that the String (Default) value of the "HKEY_CLASSES_ROOT .html" key is "htmlfile"

Select Start > Run.

In the Open box, type regedit, and then select OK.

Locate, and then click the following registry subkey:HKEY_CLASSES_ROOT .html

Make sure that the value of the String (Default) is "htmlfile". If it's not "htmlfile", right-click (Default), select Modify, input htmlfile in the Value data box, and then select OK.

Exit Registry Editor.

In my case .html default value was incorrectly set to to FirefoxHTML.

ContentLicense: CC BY-SA 4.0


问:
Why does Set.of() throw an IllegalArgumentException if the elements are duplicates?
In Java 9 new static factory methods were introduced on the Set interface, called of(), which accept multiple elements, or even an array of elements.

I wanted to turn a list into a set to remove any duplicate entries in the set, which can be done (prior to Java 9) using:

```<code>Set<String> set = new HashSet<>();
set.addAll(list);
</code>```

But I thought it would be cool to use this new Java 9 static factory method doing:

```<code>Set.of(list.toArray())
</code>```

where the list is a List of Strings, previously defined.

But alas, java threw an IllegalArgumentException when the elements were duplicates, also stated in the Javadoc of the method. Why is this?

Edit: this question is not a duplicate of another question about a conceptually equivalent topic, the Map.of() method, but distinctly different. Not all static factory of() methods behave the same. In other words, when I am asking something about the Set.of() method I would not click on a question dealing with the Map.of() method.

答:
Set.of() is a short way of creating manually a small Set. In this case it would be a flagrant programming error if you gave it duplicate values, as you're supposed to write out the elements yourself. I.e. Set.of("foo", "bar", "baz", "foo"); is clearly an error on the programmer's part.

Your cool way is actually a really bad way. If you want to convert a List to a Set, you can do it with Set<Foo> foo = new HashSet<>(myList);, or any other way you wish (such as with streams and collecting toSet()). Advantages include not doing a useless toArray(), the choice of your own Set (you might want a LinkedHashSet to preserve order) etc. Disadvantages include having to type out a few more characters of code.

The original design idea behind the Set.of(), List.of() and Map.of() methods (and their numerous overloads) is explained here What is the point of overloaded Convenience Factory Methods for Collections in Java 9 and here, where it's mentioned that The focus is on small collections, which is something very common all around the internal API, so performance advantages can be had. Although currently the methods delegate to the varargs method offering no performance advantage, this can be easily changed (not sure what the hold-up is on that though).

Body:
In Java 9 new static factory methods were introduced on the Set interface, called of(), which accept multiple elements, or even an array of elements.

I wanted to turn a list into a set to remove any duplicate entries in the set, which can be done (prior to Java 9) using:

Set<String> set = new HashSet<>();
set.addAll(list);

But I thought it would be cool to use this new Java 9 static factory method doing:

Set.of(list.toArray())

where the list is a List of Strings, previously defined.

But alas, java threw an IllegalArgumentException when the elements were duplicates, also stated in the Javadoc of the method. Why is this?

Edit: this question is not a duplicate of another question about a conceptually equivalent topic, the Map.of() method, but distinctly different. Not all static factory of() methods behave the same. In other words, when I am asking something about the Set.of() method I would not click on a question dealing with the Map.of() method.


问:
Disabling inline_styles on TinyMCE for Wordpress
I would like to force TinyMCE for wordpress to stop adding inline CSS for everything I do during edition.

I found this page that says that I should add this snippet

```<code>tinyMCE.init({
        ...
        inline_styles : false
});
</code>```

add to where? The page, and by the way, the entire TinyMCE documentation fails to tell where we should add the valuable snippets they mention.

Any ideas?

答:
I'm not entirely sure that you can disable the inline-styles via TinyMCE, however the filter used to change default TinyMCE settings is: tiny_mce_before_init, so assuming that inline_styles is still a valid option that can be overwritten, you could theoretically do it like this.

```<code>function my_format_TinyMCE( $init ) {
    $init['inline_styles'] = false;
    return $init;
}
add_filter( 'tiny_mce_before_init', 'my_format_TinyMCE' );
</code>```

There is a note about it in the source code and a bit of documentation here

Body:
I would like to force TinyMCE for wordpress to stop adding inline CSS for everything I do during edition.

I found this page that says that I should add this snippet

tinyMCE.init({
        ...
        inline_styles : false
});

add to where? The page, and by the way, the entire TinyMCE documentation fails to tell where we should add the valuable snippets they mention.

Any ideas?

Body:
I'm not entirely sure that you can disable the inline-styles via TinyMCE, however the filter used to change default TinyMCE settings is: tiny_mce_before_init, so assuming that inline_styles is still a valid option that can be overwritten, you could theoretically do it like this.

function my_format_TinyMCE( $init ) {
    $init['inline_styles'] = false;
    return $init;
}
add_filter( 'tiny_mce_before_init', 'my_format_TinyMCE' );

There is a note about it in the source code and a bit of documentation here


问:
Determine which the link is hashtag
I'm a beginner with using jQuery and am experiencing a question.

I made a gallery and the gallery links are added to facilitate the hashtags user. For example, if you add a favorite link, to access the page will see the right image, because the hash tag is present in the link.

The gallery is almost working, actually I just wanted to add a class to make the selected image set.

```<code>$gallery = window.location.hash;

//If have no hashtag, adds the class on the first image
if( $gallery == '')
    jQuery('.gallery-nav ul li').children('a').first().addClass('current');
else
{
    jQuery('.gallery-nav ul li').each(function($i){
        $link_hash = jQuery(this).find('a').attr('href');

        if( $link_hash == $gallery)
        {
            alert ( $link_hash );
        }
    });
}
</code>```

Until the first part, "If have no hashtag, adds the class on the first image" is working right, but then I do not know how. For example, if the the link is: http://example.net/gallery.php#3, I want to add the class on the third link.

In the above function, it shows the alert correctly. When it reaches the selected link it shows the alert. But I do not know how to add the class in the link.

Could anyone help me?
Thanks.

答:
You could just select that element directly using the attribute-ends-with-selector(docs) to choose the element where the href ends with the value of $gallery. (I assume there are fewer than ten.)

As you can see, the $gallery is concatenated into the selector string.

```<code>else {
    jQuery('.gallery-nav ul li a[href$=' + $gallery + ']').addClass('current');
}
</code>```

Title: Determine which the link is hashtag

Body:
I'm a beginner with using jQuery and am experiencing a question.

I made a gallery and the gallery links are added to facilitate the hashtags user. For example, if you add a favorite link, to access the page will see the right image, because the hash tag is present in the link.

The gallery is almost working, actually I just wanted to add a class to make the selected image set.

$gallery = window.location.hash;

//If have no hashtag, adds the class on the first image
if( $gallery == '')
    jQuery('.gallery-nav ul li').children('a').first().addClass('current');
else
{
    jQuery('.gallery-nav ul li').each(function($i){
        $link_hash = jQuery(this).find('a').attr('href');

        if( $link_hash == $gallery)
        {
            alert ( $link_hash );
        }
    });
}

Until the first part, "If have no hashtag, adds the class on the first image" is working right, but then I do not know how. For example, if the the link is: http://example.net/gallery.php#3, I want to add the class on the third link.

In the above function, it shows the alert correctly. When it reaches the selected link it shows the alert. But I do not know how to add the class in the link.

Could anyone help me?
Thanks.

Body:
You could just select that element directly using the attribute-ends-with-selector(docs) to choose the element where the href ends with the value of $gallery. (I assume there are fewer than ten.)

As you can see, the $gallery is concatenated into the selector string.

else {
    jQuery('.gallery-nav ul li a[href$=' + $gallery + ']').addClass('current');
}


问:
How can I print each value in a list without shortening the list in python?
What I am trying to do is this:

```<code>Str = "yes"
lst = ["e1", "e2", "e3", "y1", "y2", "y3", "s1", "s2", "s3"]
</code>```

I want to be able to print out each item in the list that has a character in Str. So for example I want it to return this:

```<code>["y1", "y2", "y3", "e1", "e2", "e3", "s1", "s2", "s3"]
</code>```

Since that is the order of Str. I have this so far:

```<code>newlst = []
while lst != []:
if Str[0] in text[0]:
    newlst += text[0]
    lst = lst[1:]
    Str = Str[1:]
else:
   lst = lst[1:]
</code>```

My problem is that it only gives me:

```<code>["y1", "y2", "y3"]
</code>```

It's because the list is now []. Is there any way to do this without shortening the list? So keeping it the same but just extracting the values in list that contain Str[n]?

答:
You can sort your initial list based on where the letters are in my_str like so:

```<code>my_str = "yes"
my_list = ['e1', 'e2', 'e3', 'y1', 'y2', 'y3', 's1', 's2', 's3']

res = sorted(my_list, key= lambda x: my_str.find(x[0]))
print(res)  # -> ['y1', 'y2', 'y3', 'e1', 'e2', 'e3', 's1', 's2', 's3']
</code>```

NOTES

'y2' appears after 'y1' only because that is the order in the original list (my_list). If you want the numbers to act as tie-brakers, the code would have to be modified a bit.

Do not use Python built-in names like str and list. You are overriding functions that you might need later on.

```<code>print('yes'.find('y'))   # -> 0  |
print('yes'.find('e'))   # -> 1  | -> values used by the sorting (smallest to largest)!
print('yes'.find('s'))   # -> 2  |
</code>```

Body:
What I am trying to do is this:

Str = "yes"
lst = ["e1", "e2", "e3", "y1", "y2", "y3", "s1", "s2", "s3"]

I want to be able to print out each item in the list that has a character in Str. So for example I want it to return this:

["y1", "y2", "y3", "e1", "e2", "e3", "s1", "s2", "s3"]

Since that is the order of Str. I have this so far:

newlst = []
while lst != []:
if Str[0] in text[0]:
    newlst += text[0]
    lst = lst[1:]
    Str = Str[1:]
else:
   lst = lst[1:]

My problem is that it only gives me:

["y1", "y2", "y3"]

It's because the list is now []. Is there any way to do this without shortening the list? So keeping it the same but just extracting the values in list that contain Str[n]?

Body:
You can sort your initial list based on where the letters are in my_str like so:

my_str = "yes"
my_list = ['e1', 'e2', 'e3', 'y1', 'y2', 'y3', 's1', 's2', 's3']

res = sorted(my_list, key= lambda x: my_str.find(x[0]))
print(res)  # -> ['y1', 'y2', 'y3', 'e1', 'e2', 'e3', 's1', 's2', 's3']

NOTES

'y2' appears after 'y1' only because that is the order in the original list (my_list). If you want the numbers to act as tie-brakers, the code would have to be modified a bit.

Do not use Python built-in names like str and list. You are overriding functions that you might need later on.

print('yes'.find('y'))   # -> 0  |
print('yes'.find('e'))   # -> 1  | -> values used by the sorting (smallest to largest)!
print('yes'.find('s'))   # -> 2  |


答:
Set.of(E... elements)

The element type of the resulting set will be the component type of the array, and the size of the set will be equal to the length of the array.

Throws:

```<code>IllegalArgumentException - if there are any duplicate elements
</code>```

This is clear that this is not doing any duplicate test since the size of the Set will be the length of the array.

The method is just here to be able to get a populated Set in a one line

```<code>Set.of("A","B","C");
</code>```

But you have to be careful on the duplicate yourself. (This will simply iterate the varargs and add them in the new Set.

Title: Why does Set.of() throw an IllegalArgumentException if the elements are duplicates?

Body:
Set.of(E... elements)

The element type of the resulting set will be the component type of the array, and the size of the set will be equal to the length of the array.

Throws:

IllegalArgumentException - if there are any duplicate elements

This is clear that this is not doing any duplicate test since the size of the Set will be the length of the array.

The method is just here to be able to get a populated Set in a one line

Set.of("A","B","C");

But you have to be careful on the duplicate yourself. (This will simply iterate the varargs and add them in the new Set.


问:
How to get rid of a vertical line in the editor pane of IntelliJ Idea?
recently a gray vertical line appeared in about the middle of the editor pane of my IntelliJIdea Community Edition 13.1.4 probably due to some manipulations with the settings that I cannot remember. I cannot find how to get rid of it, which is annoying. Who can help?

Thanks.

答:
It is called 'Show hard wrap guide' now,
located in Editor > General > Appearance

 Editor > General > Appearance">


问:
Replace "bad words" partly with asteriks, ignoring the case and retaining the old case
I have a bad words replace script for VB.net that has caused many issues. After many trial and error, the current code works but will not filter out words that have caps.

```<code>    Private Function CheckForBadWords(ByVal InputString As String) As String
        Dim r As Regex
        Dim element As String
        Dim eLength As Integer
        Dim x As Integer
        Dim AttachtoEnd As String
        For Each element In alWordList
            r = New Regex("\b" & element)
            eLength = element.Length
            For x = 3 To eLength - 1
                AttachtoEnd = AttachtoEnd & "*"
            Next
            InputString = r.Replace(InputString, element, Left(element, 3) & AttachtoEnd)
            AttachtoEnd = ""
        Next
        Return InputString
    End Function
</code>```

How do I make it check for words with caps in them? For example: phuck will get check where as Phuck or PHUCK will not get checked.

I tried following this tutorial but it's in C# and I barely know VB.net:
http://www.dreamincode.net/forums/topic/67129-creating-a-bad-word-filter-functionality-in-aspnet-wc%23/

Adding more detail: with some help this seemed to work after multiple tweaks, but the errors remain, specifically quotes and double quotes or
s.

```<code>    Private Function CheckForBadWords(ByVal InputString As String) As String
        Dim starPosition As Integer = 0
        Dim element As String
        Dim eLength As Integer
        Dim x As Integer
        Dim AttachtoEnd As String
        Dim strArray = InputString.Split(" ")
        Dim specialChars As New List(Of String)(New String() {"@", "!", ".", ",", "(", ")", "/", "#", "$", "&", "+", "-", "_", "=", ":", "'", "*", "^", "`", "<", ">", "[", "]", "{", "}", "\", "|", ControlChars.Quote})
        Dim firstChars As String = ""
        Dim LastChars As String = ""
        InputString = String.Empty
        For Each item As String In strArray
            Dim str As String = item
            firstChars = String.Empty
            LastChars = String.Empty
            For Each ch As Char In str
                If Not specialChars.Contains(ch) Then
                    Exit For
                Else
                    firstChars += ch
                End If
            Next
            For Each spChar As Char In firstChars.ToCharArray()
                str = str.Trim(spChar)
            Next
            For i As Integer = str.Length - 1 To 0 Step -1
                If Not specialChars.Contains(str(i)) Then
                    Exit For
                Else
                    LastChars = str(i) + LastChars
                End If
            Next
            For Each spChar As String In specialChars
                str = str.Trim(spChar)
            Next
            If Not String.IsNullOrWhiteSpace(str) Then
                For Each element In alWordList
                    If element.ToLower = str.ToLower Then
                        str = str.Trim()
                        eLength = element.Length
                        For x = 3 To eLength - 1
                            AttachtoEnd = AttachtoEnd & "*"
                            starPosition += 1
                        Next
                        str = str.Substring(0, str.Length - starPosition) & AttachtoEnd
                    End If
                    AttachtoEnd = ""
                    starPosition = 0
                Next
            End If
            InputString += firstChars + str + LastChars & " "
        Next
        Return InputString
    End Function
</code>```

So now I think it is best to go back to regex, which works really well just need it too handle caps.

A final note... the words to be checked are coming in as an arraylist.

答:
If you want to replace all "bad words"words in the string with in a way that the first 3 letters remain and rest is replaced with asterisks like phu*** and you want to compare in a case-insensitive manner;  there is no built-in method. You could use

Regex.Replace with RegexOptions.IgnoreCase or

Microsoft.VisualBasic.Strings.Replace with CompareMethod.Text.

But both have the disadvantage that they will replace the old-value with a new-value where the new-value is not keeping the old case. If the word was PHUCK and your "bad-word" in the list is Phuck it will be replaced with Ph*** not PH***.

Since you have commented that this is important, the only way is to write a custom method:

```<code>Module StringExtensions

    <Extension()>
    Public Function ReplaceBadWords(ByVal str As String, ByVal badWords As IEnumerable(Of String), ByVal comparison As StringComparison, ByVal Optional showClearTextLength As Integer = 3, ByVal Optional obfuscateChar As Char = "*"c) As String
        Dim sb As StringBuilder = New StringBuilder(str)
        For Each badWord As String In badWords
            Dim index As Integer = str.IndexOf(badWord, comparison)
            While index <> -1
                Dim oldValue As String = str.Substring(index, badWord.Length)
                Dim newValue As String
                If badWord.Length > showClearTextLength Then
                    newValue = oldValue.Remove(showClearTextLength) & New String(obfuscateChar, oldValue.Length - showClearTextLength)
                Else
                    newValue = New String(obfuscateChar, oldValue.Length)
                End If

                For i As Integer = index To index + newValue.Length - 1
                    sb(i) = newValue(i - index)
                Next

                index += newValue.Length
                index = str.IndexOf(badWord, index, comparison)
            End While
        Next

        Return sb.ToString()
    End Function

End Module
</code>```

With your (silly) sample:

```<code>Dim replaced = "phuck will get check where as Phuck or PHUCK".
    ReplaceBadWords({ "Phuck", "ILL" }, StringComparison.CurrentCultureIgnoreCase)
</code>```

Result:

```<code>phu** w*** get check where as Phu** or PHU**
</code>```

A parallel version if you have a huge amount of "bad-words":

```<code><Extension()>
Public Function ReplaceBadWordsParallel(ByVal str As String, ByVal badWords As IEnumerable(Of String), ByVal comparison As StringComparison, ByVal Optional showClearTextLength As Integer = 3, ByVal Optional obfuscateChar As Char = "*"c) As String
    Dim sb As StringBuilder = New StringBuilder(str)

    Parallel.ForEach(badWords,
        Sub(badWord)
            Dim index As Integer = str.IndexOf(badWord, comparison)
            While index <> -1
                Dim oldValue As String = str.Substring(index, badWord.Length)
                Dim newValue As String
                If badWord.Length > showClearTextLength Then
                    newValue = oldValue.Remove(showClearTextLength) & New String(obfuscateChar, oldValue.Length - showClearTextLength)
                Else
                    newValue = New String(obfuscateChar, oldValue.Length)
                End If

                For i As Integer = index To index + newValue.Length - 1
                    sb(i) = newValue(i - index)
                Next

                index += newValue.Length
                index = str.IndexOf(badWord, index, comparison)
            End While
        End Sub)

    Return sb.ToString()
End Function
</code>```

Note that i've yet not checked if the parallel version is thread-safe at all.

C# Version if someone is interested:

```<code>public static string ReplaceBadWords(this string str, IEnumerable<string> badWords, StringComparison comparison, int showClearTextLength = 3, char obfuscateChar = '*')
{
    StringBuilder sb = new StringBuilder(str);

    foreach (string badWord in badWords)
    {
        int index = str.IndexOf(badWord, comparison);
        while (index != -1)
        {
            string oldValue = str.Substring(index, badWord.Length);
            string newValue;
            if (badWord.Length > showClearTextLength)
            {
                newValue = oldValue.Remove(showClearTextLength) + new string(obfuscateChar, oldValue.Length - showClearTextLength);
            }
            else
            {
                newValue = new string(obfuscateChar, oldValue.Length);
            }
            for (int i = index; i < index + newValue.Length; i++)
                sb[i] = newValue[i - index];

            index += newValue.Length;
            index = str.IndexOf(badWord, index, comparison);
        }
    }

    return sb.ToString();
}
</code>```

Body:
I have a bad words replace script for VB.net that has caused many issues. After many trial and error, the current code works but will not filter out words that have caps.

    Private Function CheckForBadWords(ByVal InputString As String) As String
        Dim r As Regex
        Dim element As String
        Dim eLength As Integer
        Dim x As Integer
        Dim AttachtoEnd As String
        For Each element In alWordList
            r = New Regex("\b" & element)
            eLength = element.Length
            For x = 3 To eLength - 1
                AttachtoEnd = AttachtoEnd & "*"
            Next
            InputString = r.Replace(InputString, element, Left(element, 3) & AttachtoEnd)
            AttachtoEnd = ""
        Next
        Return InputString
    End Function

How do I make it check for words with caps in them? For example: phuck will get check where as Phuck or PHUCK will not get checked.

I tried following this tutorial but it's in C# and I barely know VB.net:
http://www.dreamincode.net/forums/topic/67129-creating-a-bad-word-filter-functionality-in-aspnet-wc%23/

Adding more detail: with some help this seemed to work after multiple tweaks, but the errors remain, specifically quotes and double quotes or
s.

    Private Function CheckForBadWords(ByVal InputString As String) As String
        Dim starPosition As Integer = 0
        Dim element As String
        Dim eLength As Integer
        Dim x As Integer
        Dim AttachtoEnd As String
        Dim strArray = InputString.Split(" ")
        Dim specialChars As New List(Of String)(New String() {"@", "!", ".", ",", "(", ")", "/", "#", "$", "&", "+", "-", "_", "=", ":", "'", "*", "^", "`", "<", ">", "[", "]", "{", "}", "\", "|", ControlChars.Quote})
        Dim firstChars As String = ""
        Dim LastChars As String = ""
        InputString = String.Empty
        For Each item As String In strArray
            Dim str As String = item
            firstChars = String.Empty
            LastChars = String.Empty
            For Each ch As Char In str
                If Not specialChars.Contains(ch) Then
                    Exit For
                Else
                    firstChars += ch
                End If
            Next
            For Each spChar As Char In firstChars.ToCharArray()
                str = str.Trim(spChar)
            Next
            For i As Integer = str.Length - 1 To 0 Step -1
                If Not specialChars.Contains(str(i)) Then
                    Exit For
                Else
                    LastChars = str(i) + LastChars
                End If
            Next
            For Each spChar As String In specialChars
                str = str.Trim(spChar)
            Next
            If Not String.IsNullOrWhiteSpace(str) Then
                For Each element In alWordList
                    If element.ToLower = str.ToLower Then
                        str = str.Trim()
                        eLength = element.Length
                        For x = 3 To eLength - 1
                            AttachtoEnd = AttachtoEnd & "*"
                            starPosition += 1
                        Next
                        str = str.Substring(0, str.Length - starPosition) & AttachtoEnd
                    End If
                    AttachtoEnd = ""
                    starPosition = 0
                Next
            End If
            InputString += firstChars + str + LastChars & " "
        Next
        Return InputString
    End Function

So now I think it is best to go back to regex, which works really well just need it too handle caps.

A final note... the words to be checked are coming in as an arraylist.

Body:
If you want to replace all "bad words"words in the string with in a way that the first 3 letters remain and rest is replaced with asterisks like phu*** and you want to compare in a case-insensitive manner;  there is no built-in method. You could use

Regex.Replace with RegexOptions.IgnoreCase or

Microsoft.VisualBasic.Strings.Replace with CompareMethod.Text.

But both have the disadvantage that they will replace the old-value with a new-value where the new-value is not keeping the old case. If the word was PHUCK and your "bad-word" in the list is Phuck it will be replaced with Ph*** not PH***.

Since you have commented that this is important, the only way is to write a custom method:

Module StringExtensions

    <Extension()>
    Public Function ReplaceBadWords(ByVal str As String, ByVal badWords As IEnumerable(Of String), ByVal comparison As StringComparison, ByVal Optional showClearTextLength As Integer = 3, ByVal Optional obfuscateChar As Char = "*"c) As String
        Dim sb As StringBuilder = New StringBuilder(str)
        For Each badWord As String In badWords
            Dim index As Integer = str.IndexOf(badWord, comparison)
            While index <> -1
                Dim oldValue As String = str.Substring(index, badWord.Length)
                Dim newValue As String
                If badWord.Length > showClearTextLength Then
                    newValue = oldValue.Remove(showClearTextLength) & New String(obfuscateChar, oldValue.Length - showClearTextLength)
                Else
                    newValue = New String(obfuscateChar, oldValue.Length)
                End If

                For i As Integer = index To index + newValue.Length - 1
                    sb(i) = newValue(i - index)
                Next

                index += newValue.Length
                index = str.IndexOf(badWord, index, comparison)
            End While
        Next

        Return sb.ToString()
    End Function

End Module

With your (silly) sample:

Dim replaced = "phuck will get check where as Phuck or PHUCK".
    ReplaceBadWords({ "Phuck", "ILL" }, StringComparison.CurrentCultureIgnoreCase)

Result:

phu** w*** get check where as Phu** or PHU**

A parallel version if you have a huge amount of "bad-words":

<Extension()>
Public Function ReplaceBadWordsParallel(ByVal str As String, ByVal badWords As IEnumerable(Of String), ByVal comparison As StringComparison, ByVal Optional showClearTextLength As Integer = 3, ByVal Optional obfuscateChar As Char = "*"c) As String
    Dim sb As StringBuilder = New StringBuilder(str)

    Parallel.ForEach(badWords,
        Sub(badWord)
            Dim index As Integer = str.IndexOf(badWord, comparison)
            While index <> -1
                Dim oldValue As String = str.Substring(index, badWord.Length)
                Dim newValue As String
                If badWord.Length > showClearTextLength Then
                    newValue = oldValue.Remove(showClearTextLength) & New String(obfuscateChar, oldValue.Length - showClearTextLength)
                Else
                    newValue = New String(obfuscateChar, oldValue.Length)
                End If

                For i As Integer = index To index + newValue.Length - 1
                    sb(i) = newValue(i - index)
                Next

                index += newValue.Length
                index = str.IndexOf(badWord, index, comparison)
            End While
        End Sub)

    Return sb.ToString()
End Function

Note that i've yet not checked if the parallel version is thread-safe at all.

C# Version if someone is interested:

public static string ReplaceBadWords(this string str, IEnumerable<string> badWords, StringComparison comparison, int showClearTextLength = 3, char obfuscateChar = '*')
{
    StringBuilder sb = new StringBuilder(str);

    foreach (string badWord in badWords)
    {
        int index = str.IndexOf(badWord, comparison);
        while (index != -1)
        {
            string oldValue = str.Substring(index, badWord.Length);
            string newValue;
            if (badWord.Length > showClearTextLength)
            {
                newValue = oldValue.Remove(showClearTextLength) + new string(obfuscateChar, oldValue.Length - showClearTextLength);
            }
            else
            {
                newValue = new string(obfuscateChar, oldValue.Length);
            }
            for (int i = index; i < index + newValue.Length; i++)
                sb[i] = newValue[i - index];

            index += newValue.Length;
            index = str.IndexOf(badWord, index, comparison);
        }
    }

    return sb.ToString();
}


问:
JSON URL specific item to DIV
```<code><html>
<script>
function gettodo()
{
    var TODOS ='https://jsonplaceholder.typicode.com/todos';
    $.ajax({
        cache: false,
        dataType: "json",
        url: TODOS,
        success: todos1
    });
}
setInterval(gettodo(),1000);
</script>

<div id="3rd_title_here"></div>
</html>
</code>```

how do i display the 3rd title on the json url to the div

the title on the 3rd row is "fugiat veniam minus"

i want it to have like this when i execute the html

```<code><div id="3rd_title_here">fugiat veniam minus</div>
</code>```

to any ones curiousity this is what the JSON structure looks like if u view the URL link

```<code>{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "fugiat veniam minus",
"completed": false
},
{
"userId": 1,
"id": 4,
"title": "et porro tempora",
"completed": true
}
</code>```

答:
You can write like the following

```<code>$(document).ready(function(){
function gettodo()
{
    var TODOS ='https://jsonplaceholder.typicode.com/todos';
    $.ajax({
        cache: false,
        dataType: "json",
        url: TODOS,
        success: todos1
    });
}
setInterval(gettodo(),1000);

function todos1(data){
for (var i in data){
$('#titles').append('<div id="title_"'+i+'>'+data[i].title+'</div>');
}
}
});
</code>```

And the HTML code will be like

```<code><body>
<div id='titles'>
</div>
</body>
</code>```

Title: JSON URL specific item to DIV

Body:
how do i display the 3rd title on the json url to the div

the title on the 3rd row is "fugiat veniam minus"

i want it to have like this when i execute the html

fugiat veniam minus

to any ones curiousity this is what the JSON structure looks like if u view the URL link

{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "fugiat veniam minus",
"completed": false
},
{
"userId": 1,
"id": 4,
"title": "et porro tempora",
"completed": true
}

Body:
You can write like the following

$(document).ready(function(){
function gettodo()
{
    var TODOS ='https://jsonplaceholder.typicode.com/todos';
    $.ajax({
        cache: false,
        dataType: "json",
        url: TODOS,
        success: todos1
    });
}
setInterval(gettodo(),1000);

function todos1(data){
for (var i in data){
$('#titles').append('<div id="title_"'+i+'>'+data[i].title+'</div>');
}
}
});

And the HTML code will be like

<body>
<div id='titles'>
</div>
</body>


问:
404 page not found - codeigniter Login
Am beginner in codeigniter, and am trying to do a simple login form by referring some online vedios. i did everything . but when i try to login its showing me 404 page not found. Please help me to finsh this

autoload.php

```<code>$autoload['libraries'] = array('database','session');
</code>```

routes.php

```<code>$route['default_controller'] = 'welcome';
</code>```

controllers

welcome.php

```<code><?php defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {

public function __construct(){

    parent::__construct();
        $this->load->helper('url');
        $this->load->model('main_model');
        $this->load->library('session');
        $this->load->library('form_validation');}
public function index()
{
            $this->load->view('welcome_message');
}

function login_user(){
            $this->load->view('welcome_message');

}  function login_validation(){

            $this->load->library('form_validation');
            $this->form_validation->set_rules('username','Username','required');
            $this->form_validation->set_rules('password','Password','required');

            if($this->form_validation->run()){
                // true

                $username = $this->input->post('username');
                $password = $this->input->post('password');

                // model function
                $this->load->model('main_model');

                if($this->main_model->can_login($username, $password)){
                    $session_date = array(
                        'username'=> $username);

                    $this->session->set_userdata($session_date);

                    redirect(base_url() . 'main/enter');
                }else{
                    $this->session->set_flashdata('error','Invalid Username and Password');
                                 redirect(base_url() . 'main/login_user');

                }
            } else{
                //false

                $this->login_user();
            }}function enter(){
if($this->session->userdata('username') !=''){
echo '<h2> Welcome - '.$this->session->userdata('username').'/<h2>';

} else{redirect(base_url() . 'main/login_user');}}}
</code>```

model class

```<code>function can_login($username,$password){
$this->db->where('UserName',$username);
$this->db->where('Password',$password);
  $query=$this->db->get('User');

  if($query->num_rows() > 0){

    return true;

  } else{
   return false;
  }}
</code>```

Whenever i try to login its showing be 404 page not found

login.php

```<code><form method="post" action="<?php echo base_url(); ?>main/login_validation">
            <div class="form-group">
                 <label>Enter Username</label>
                 <input type="text" name="username" class="form-control" />
                 <span class="text-danger"><?php echo form_error('username'); ?></span>
            </div>
            <div class="form-group">
                 <label>Enter Password</label>
                 <input type="password" name="password" class="form-control" />
                 <span class="text-danger"><?php echo form_error('password'); ?></span>
            </div>
            <div class="form-group">
                 <input type="submit" name="insert" value="Login" class="btn btn-info" />
                 <?php
                      echo '<label class="text-danger">'.$this->session->flashdata("error").'</label>';
                 ?>
            </div>
       </form>
</code>```

答:
Your login_validation() method is in your Welcome controller. So your form's action should be welcome/login_validation and not main/login_validation.

If you want to know more, you may want to read about URLs in Codeigniter.

Title: 404 page not found - codeigniter Login

Body:
Am beginner in codeigniter, and am trying to do a simple login form by referring some online vedios. i did everything . but when i try to login its showing me 404 page not found. Please help me to finsh this

autoload.php

$autoload['libraries'] = array('database','session');

routes.php

$route['default_controller'] = 'welcome';

controllers

welcome.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {

public function __construct(){

    parent::__construct();
        $this->load->helper('url');
        $this->load->model('main_model');
        $this->load->library('session');
        $this->load->library('form_validation');}
public function index()
{
            $this->load->view('welcome_message');
}

function login_user(){
            $this->load->view('welcome_message');

}  function login_validation(){

            $this->load->library('form_validation');
            $this->form_validation->set_rules('username','Username','required');
            $this->form_validation->set_rules('password','Password','required');

            if($this->form_validation->run()){
                // true

                $username = $this->input->post('username');
                $password = $this->input->post('password');

                // model function
                $this->load->model('main_model');

                if($this->main_model->can_login($username, $password)){
                    $session_date = array(
                        'username'=> $username);

                    $this->session->set_userdata($session_date);

                    redirect(base_url() . 'main/enter');
                }else{
                    $this->session->set_flashdata('error','Invalid Username and Password');
                                 redirect(base_url() . 'main/login_user');

                }
            } else{
                //false

                $this->login_user();
            }}function enter(){
if($this->session->userdata('username') !=''){
echo '
 Welcome - '.$this->session->userdata('username').'/
';

} else{redirect(base_url() . 'main/login_user');}}}

model class

function can_login($username,$password){
$this->db->where('UserName',$username);
$this->db->where('Password',$password);
  $query=$this->db->get('User');

  if($query->num_rows() > 0){

    return true;

  } else{
   return false;
  }}

Whenever i try to login its showing be 404 page not found

login.php

<form method="post" action="<?php echo base_url(); ?>main/login_validation">

                 Enter Username
                 <input type="text" name="username" class="form-control" />
                 <?php echo form_error('username'); ?>

                 Enter Password
                 <input type="password" name="password" class="form-control" />
                 <?php echo form_error('password'); ?>

                 <input type="submit" name="insert" value="Login" class="btn btn-info" />
                 <?php
                      echo ''.$this->session->flashdata("error").'';
                 ?>

       </form>