问:
FirebaseApp.initializeApp(Context); Android error;
I've spent about three days now trying to solve a java error that's stopping me from finishing my chat app! And of course it's a firebase error! I'm new to Android Developing so when you answer, if you could explain it using simple terms, it'll help a lot! -

```<code>    Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.teo.myapplication. Make sure to call FirebaseApp.initializeApp(Context) first.
                                                                               at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
                                                                               at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
                                                                               at com.example.teo.myapplication.MainActivity.onCreate(MainActivity.java:52)
</code>```

my actual code for the problem looks like this (lines 51 and 52):

```<code>    FirebaseApp.initializeApp(Context);
    dataBase = FirebaseDatabase.getInstance();
</code>```

It looks like it should work, but Context get's an error! It's the old expression expected error and I've tried everything to fix it.
i've tried the following plus some more:

```<code>FirebaseApp.initializeApp(this)

FirebaseApp.initializeApp(this.context)

FirebaseApp.initializeApp(context)

FirebaseApp.initializeApp(many other things)
</code>```

And nothing works! The only thing I can find to work is just (Context) except there's an error on Context... UGH.

I've tried calling it in both MainActivity and ChatActivity but there's an error for both. Please help me!

these are my dependencies:

```<code>  dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.google.firebase:firebase-storage:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.google.firebase:firebase-core:10.2.1'
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'com.google.code.gson:gson:2.8.1'
    compile 'com.google.firebase:firebase-messaging:11.0.4'
    compile 'com.firebase:firebase-client-android:2.5.0'

    testCompile 'junit:junit:4.12'

}
</code>```

I've tried to use the actual code that works

example:

```<code>    FirebaseApp.initializeApp(this);
  dataBase = FirebaseDatabase.getInstance();
</code>```

But even though it doesn't say there's any errors, when I run my app, it closes right away and the same error pops up.

Thanks!

EDIT:

ChatActivity onCreate method code:

```<code>  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat_activity);

    Intent intent = getIntent();
    username = intent.getStringExtra("username");
    chatroomName = intent.getStringExtra("Chat_room_name");
    Incognito = intent.getBooleanExtra("Incognito", false);

    listview = (ListView) findViewById(R.id.list_view);
    chatsend = (EditText) findViewById(R.id.chat_function);
    final ArrayList<String> listArray = new ArrayList<String>();
    MyListAdapter adapter = new MyListAdapter(getApplicationContext(), listArray, ChatActivity.this);
    listview.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    context = this;
    FirebaseApp.initializeApp(this);
  dataBase = FirebaseDatabase.getInstance();
     ref = dataBase.getReference();

    // listArray.add(chatsend);

}
</code>```

Thanks! This code was altered after trying to fix a attempts from comments although none worked as whenever, like said before, I put (this) or anything that isn't (Context), it just asks for (Context) instead.

Edit including the manifest File:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.teo.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ChatActivity"/>
    </application>

</manifest>
</code>```

Thanks!

答:
You are using both the current Firebase SDK and the legacy SDK, com.firebase:firebase-client-android:2.5.0, which has been deprecated for more than a year.  For new development, there is no reason to use the legacy SDK.  Follow the steps the Upgrade Guide to eliminate use of the legacy SDK.

It's also important to use the same version number for all Firebase and Google Play libraries.  You have 10.2.0, 10.2.1 and 11.0.4.

Body:
I've spent about three days now trying to solve a java error that's stopping me from finishing my chat app! And of course it's a firebase error! I'm new to Android Developing so when you answer, if you could explain it using simple terms, it'll help a lot! -

    Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.teo.myapplication. Make sure to call FirebaseApp.initializeApp(Context) first.
                                                                               at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
                                                                               at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
                                                                               at com.example.teo.myapplication.MainActivity.onCreate(MainActivity.java:52)

my actual code for the problem looks like this (lines 51 and 52):

    FirebaseApp.initializeApp(Context);
    dataBase = FirebaseDatabase.getInstance();

It looks like it should work, but Context get's an error! It's the old expression expected error and I've tried everything to fix it.
i've tried the following plus some more:

FirebaseApp.initializeApp(this)

FirebaseApp.initializeApp(this.context)

FirebaseApp.initializeApp(context)

FirebaseApp.initializeApp(many other things)

And nothing works! The only thing I can find to work is just (Context) except there's an error on Context... UGH.

I've tried calling it in both MainActivity and ChatActivity but there's an error for both. Please help me!

these are my dependencies:

  dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.google.firebase:firebase-storage:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.google.firebase:firebase-core:10.2.1'
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'com.google.code.gson:gson:2.8.1'
    compile 'com.google.firebase:firebase-messaging:11.0.4'
    compile 'com.firebase:firebase-client-android:2.5.0'

    testCompile 'junit:junit:4.12'

}

I've tried to use the actual code that works

example:

    FirebaseApp.initializeApp(this);
  dataBase = FirebaseDatabase.getInstance();

But even though it doesn't say there's any errors, when I run my app, it closes right away and the same error pops up.

Thanks!

EDIT:

ChatActivity onCreate method code:

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat_activity);

    Intent intent = getIntent();
    username = intent.getStringExtra("username");
    chatroomName = intent.getStringExtra("Chat_room_name");
    Incognito = intent.getBooleanExtra("Incognito", false);

    listview = (ListView) findViewById(R.id.list_view);
    chatsend = (EditText) findViewById(R.id.chat_function);
    final ArrayList<String> listArray = new ArrayList<String>();
    MyListAdapter adapter = new MyListAdapter(getApplicationContext(), listArray, ChatActivity.this);
    listview.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    context = this;
    FirebaseApp.initializeApp(this);
  dataBase = FirebaseDatabase.getInstance();
     ref = dataBase.getReference();

    // listArray.add(chatsend);

}

Thanks! This code was altered after trying to fix a attempts from comments although none worked as whenever, like said before, I put (this) or anything that isn't (Context), it just asks for (Context) instead.

Edit including the manifest File:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.teo.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ChatActivity"/>
    </application>

</manifest>

Thanks!


来源: stackexchange

问:
When is NAT-T natting performed on Azure policy based basic VNet gateway, IKEv1 site-to-site connection
I have a strange requirement for IKEv1 VPN to a Cisco ASA and Checkpoint system with Azure.

We setup two Azure policy based VNet gateways, virtual networks and associated virtual machines.

The connection has to be IKEv1 AES-256-SHA1-DHGroup2 site-to-site connection per their test and production environments so we setup one for test and production.

The third party system does not support RFC1918 addressing within VPN
  tunnels (encryption domain) and/or Peers.  There must be publicly
  assigned IP addresses for the VPN tunnel, as well as a publicly routed
  IP address for the peer.

They recommend using subnets within the tunnel negotiations, and using
  your access-lists to narrow this down to specific hosts (subnet SA’s
  vs. host SA’s).  In the event you need to “hide” multiple hosts behind
  a single IP address, you should PAT using a publicly assigned address
  to be included in the VPN tunnel.  NAT-T (UDP Encapsulation of IPSEC)
  is not supported due to global configuration items which affect
  multiple customers.

My question is when is NAT-T performed when connecting to an Azure virtual network gateway in policy-based (IKEv1) mode on site-to-site (S2S) connections? Is it done at all or when is it performed? Is it only performed if there is a load balancer out front?

答:
I think I tried to answer the same questions on the MSDN forum. Just re-iterate the answers:

NAT-T is performed on the outer packets/addresses of IPsec packets.

Azure VPN gateway does NOT perform any NAT/PAT functionality on the inner packets in/out of IPsec tunnels. So if you use public IP addresses inside of your on-premises network and your Azure virtual network they will stay the same to/from the Azure VPN gateways and IPsec tunnels.

You can use public IP address spaces as "private" IP addresses on your Azure VMs / Azure virtual network. These will be treated like "private" addresses by the Azure VPN gateways. We will not NAT those inner packets.

Hope this helps.

Thanks,
Yushun [MSFT]

ContentLicense: CC BY-SA 3.0


问:
how can I assign a name to duplicate
my data is like this

```<code>df<- structure(list(label = c("afghanestan", "afghanestan", "afghanestanIndia",
"afghanestanindiaholad", "afghanestanUSA", "USA", "Argentina",
"Brazil", "Argentinabrazil", "Brazil"), Start = c(114, 516, 89,
22, 33, 67, 288, 362, 45, 362), Stop = c(127, 544, 105, 34, 50,
85, 299, 381, 68, 381)), class = "data.frame", .Names = c("label",
"Start", "Stop"), row.names = c(NA, -10L))
</code>```

when I want to remove the exact duplicate , I simply do this

```<code>df[!duplicated(df[,c('label','Start','Stop')]),]
</code>```

now the problem is that I want to recognize those that are similar in the label but possibly different in the start and stop. so I would like to generate something like this afterwards

```<code>                  label Start Stop NewLab
1           afghanestan   114  127  TRUE
2           afghanestan   516  544  TRUE
3      afghanestanIndia    89  105  FALSE
4 afghanestanindiaholad    22   34  FALSE
5        afghanestanUSA    33   50  FLASE
6                   USA    67   85  FALSE
7             Argentina   288  299  FALSE
8                Brazil   362  381  FALSE
9       Argentinabrazil    45   68  FALSE
</code>```

答:
Here is a somewhat convoluted methods using dplyr

```<code>library(tidyverse)

df %>%
  group_by(label) %>%
  mutate(n = n()) %>%
  group_by(Start, Stop) %>%
  mutate(n2 = n()) %>%
  mutate(newlabel = ifelse(n>1 & n2==1, TRUE, FALSE)) %>%
  dplyr::select(-n, -n2)
</code>```

First create a grouping variable of labels - take a count, then a grouping variable of start and stop times - take a count, use an ifelse to assign True/False, then remove the intermediate columns.

Title: how can I assign a name to duplicate

Body:
my data is like this

df<- structure(list(label = c("afghanestan", "afghanestan", "afghanestanIndia",
"afghanestanindiaholad", "afghanestanUSA", "USA", "Argentina",
"Brazil", "Argentinabrazil", "Brazil"), Start = c(114, 516, 89,
22, 33, 67, 288, 362, 45, 362), Stop = c(127, 544, 105, 34, 50,
85, 299, 381, 68, 381)), class = "data.frame", .Names = c("label",
"Start", "Stop"), row.names = c(NA, -10L))

when I want to remove the exact duplicate , I simply do this

df[!duplicated(df[,c('label','Start','Stop')]),]

now the problem is that I want to recognize those that are similar in the label but possibly different in the start and stop. so I would like to generate something like this afterwards

                  label Start Stop NewLab
1           afghanestan   114  127  TRUE
2           afghanestan   516  544  TRUE
3      afghanestanIndia    89  105  FALSE
4 afghanestanindiaholad    22   34  FALSE
5        afghanestanUSA    33   50  FLASE
6                   USA    67   85  FALSE
7             Argentina   288  299  FALSE
8                Brazil   362  381  FALSE
9       Argentinabrazil    45   68  FALSE

Body:
Here is a somewhat convoluted methods using dplyr

library(tidyverse)

df %>%
  group_by(label) %>%
  mutate(n = n()) %>%
  group_by(Start, Stop) %>%
  mutate(n2 = n()) %>%
  mutate(newlabel = ifelse(n>1 & n2==1, TRUE, FALSE)) %>%
  dplyr::select(-n, -n2)

First create a grouping variable of labels - take a count, then a grouping variable of start and stop times - take a count, use an ifelse to assign True/False, then remove the intermediate columns.


问:
how to implment click-once submit button in asp.net mvc 2?
I need to implement a click-once button for my asp.net mvc 2 application. I have just a very simple submit form, and when the user clicks on the submit button, I need to change its image to a "please wait..." type of graphics and disables the click event for further submits until the server comes back.

Is there an example or code snippet for this? I used to be able to do it in the asp.net webforms, but that technique does not apply here.

thanks!

答:
Here is example of how create ajax login using asp.net mvc and jQuery:
How to implement a Client-side Ajax Login on Asp.Net MVC (A link to the solution for Asp.Net Webforms is in here)</p>

ContentLicense: CC BY-SA 2.5


问:
Transfering Data From CSV to XLS w/ python
I am looking to transfer data from a csv file to a template xls file. I would like to take the column in the csv file and insert them under specific headers in the xls file. Let's say I have data that looks like:

example.csv:

```<code>4/5/2015 13:34,Apples,73
4/5/2015 3:41,Cherries,85
4/6/2015 12:46,Pears,14
4/8/2015 8:59,Oranges,52
4/10/2015 2:07,Apples,152
4/10/2015 18:10,Bananas,23
4/10/2015 2:40,Strawberries,98
</code>```

and I have headers that are on row #3 of the XLS file on sheet 2 that are:

headers.xls:

```<code>Date, Time, Type, Color, Count
</code>```

I want to insert the .csv under these row #3 headers but they need to fit the column. Here I do not have information on color so it needs to be skipped.

答:
This provides several options for working with Excel using Python.

http://www.python-excel.org/

Body:
I am looking to transfer data from a csv file to a template xls file. I would like to take the column in the csv file and insert them under specific headers in the xls file. Let's say I have data that looks like:

example.csv:

4/5/2015 13:34,Apples,73
4/5/2015 3:41,Cherries,85
4/6/2015 12:46,Pears,14
4/8/2015 8:59,Oranges,52
4/10/2015 2:07,Apples,152
4/10/2015 18:10,Bananas,23
4/10/2015 2:40,Strawberries,98

and I have headers that are on row #3 of the XLS file on sheet 2 that are:

headers.xls:

Date, Time, Type, Color, Count

I want to insert the .csv under these row #3 headers but they need to fit the column. Here I do not have information on color so it needs to be skipped.


答:
This would work in a single line of code:

```<code>df$NewLab <- df$label %in% df[duplicated(df$label), ]$label
</code>```

And the output:

```<code>> df$NewLab <- df$label %in% df[duplicated(df$label), ]$label
> df
                  label Start Stop NewLab
1           afghanestan   114  127   TRUE
2           afghanestan   516  544   TRUE
3      afghanestanIndia    89  105  FALSE
4 afghanestanindiaholad    22   34  FALSE
5        afghanestanUSA    33   50  FALSE
6                   USA    67   85  FALSE
7             Argentina   288  299  FALSE
8                Brazil   362  381  FALSE
9       Argentinabrazil    45   68  FALSE
</code>```

Or in dplyr notation:

```<code>df <- dplyr::mutate(df, NewLab = label %in% df[duplicated(df$label), ]$label)
</code>```

Title: how can I assign a name to duplicate

Body:
This would work in a single line of code:

df$NewLab <- df$label %in% df[duplicated(df$label), ]$label

And the output:

> df$NewLab <- df$label %in% df[duplicated(df$label), ]$label
> df
                  label Start Stop NewLab
1           afghanestan   114  127   TRUE
2           afghanestan   516  544   TRUE
3      afghanestanIndia    89  105  FALSE
4 afghanestanindiaholad    22   34  FALSE
5        afghanestanUSA    33   50  FALSE
6                   USA    67   85  FALSE
7             Argentina   288  299  FALSE
8                Brazil   362  381  FALSE
9       Argentinabrazil    45   68  FALSE

Or in dplyr notation:

df <- dplyr::mutate(df, NewLab = label %in% df[duplicated(df$label), ]$label)


问:
What are some good patterns for VBA error handling?
What are some good patterns for error handling in VBA?

In particular, what should I do in this situation:

... some code ...
... some code where an error might occur ...
... some code ...
... some other code where a different error might occur ...
... some other code ...
... some code that must always be run (like a finally block) ...
```

I want to handle both errors, and resume execution after the code where the error may occur. Also, the finally code at the end must always run - no matter what exceptions are thrown earlier. How can I achieve this outcome?

答:
Also relevant to the discussion is the relatively unknown Erl function. If you have numeric labels within your code procedure, e.g.,

```<code>Sub AAA()
On Error Goto ErrorHandler

1000:
' code
1100:
' more code
1200:
' even more code that causes an error
1300:
' yet more code
9999: ' end of main part of procedure
ErrorHandler:
If Err.Number <> 0 Then
   Debug.Print "Error: " + CStr(Err.Number), Err.Descrption, _
      "Last Successful Line: " + CStr(Erl)
End If
End Sub
</code>```

The Erl function returns the most recently encountered numberic line label.  In the example above, if a run-time error occurs after label 1200: but before 1300:, the Erl function will return 1200, since that is most recently successfully encountered line label.  I find it to be a good practice to put a line label immediately above your error handling block. I typically use 9999 to indicate that the main part of the procedure ran to its expected conclusion.

Notes:

Line labels must be positive integers -- a label like MadeItHere: isn't recogonized by Erl.

Line labels are completely unrelated to the actual line numbers of a VBIDE CodeModule. You can use any positive numbers you want, in any order you want. In the example above, there are only 25 or so lines of code, but the line label numbers begin at 1000. There is no relationship between editor line numbers and line label numbers used with Erl.

Line label numbers need not be in any particular order, although if they are not in ascending, top-down order, the efficacy and benefit of Erl is greatly diminished, but Erl will still report the correct number.

Line labels are specific to the procedure in which they appear. If procedure ProcA calls procedure ProcB and an error occurs in ProcB that passes control back to ProcA, Erl (in ProcA) will return the most recently encounterd line label number in ProcA before it calls ProcB. From within ProcA, you cannot get the line label numbers that might appear in ProcB.

Use care when putting line number labels within a loop. For example,

```<code>For X = 1 To 100
500:
' some code that causes an error
600:
Next X
</code>```

If the code following line label 500 but before 600 causes an error, and that error arises on the 20th iteration of the loop, Erl will return 500, even though 600 has been encountered successfully in the previous 19 iterations of the loop.

Proper placement of line labels within the procedure is critical to using the Erl function to get truly meaningful information.

There are any number of free utilities on the Internet that will insert numeric line label in a procedure automatically, so you have fine-grained error information while developing and debugging, and then remove those labels once code goes live.

If your code displays error information to the end user if an unexpected error occurs, providing the value from Erl in that information can make finding and fixing the problem vastly simpler than if value of Erl is not reported.

ContentLicense: CC BY-SA 4.0

Body:
What are some good patterns for error handling in VBA?

In particular, what should I do in this situation:

... some code ...
... some code where an error might occur ...
... some code ...
... some other code where a different error might occur ...
... some other code ...
... some code that must always be run (like a finally block) ...

I want to handle both errors, and resume execution after the code where the error may occur. Also, the finally code at the end must always run - no matter what exceptions are thrown earlier. How can I achieve this outcome?

Body:
Also relevant to the discussion is the relatively unknown Erl function. If you have numeric labels within your code procedure, e.g.,

Sub AAA()
On Error Goto ErrorHandler

1000:
' code
1100:
' more code
1200:
' even more code that causes an error
1300:
' yet more code
9999: ' end of main part of procedure
ErrorHandler:
If Err.Number <> 0 Then
   Debug.Print "Error: " + CStr(Err.Number), Err.Descrption, _
      "Last Successful Line: " + CStr(Erl)
End If
End Sub

The Erl function returns the most recently encountered numberic line label.  In the example above, if a run-time error occurs after label 1200: but before 1300:, the Erl function will return 1200, since that is most recently successfully encountered line label.  I find it to be a good practice to put a line label immediately above your error handling block. I typically use 9999 to indicate that the main part of the procedure ran to its expected conclusion.

Notes:

Line labels must be positive integers -- a label like MadeItHere: isn't recogonized by Erl.

Line labels are completely unrelated to the actual line numbers of a VBIDE CodeModule. You can use any positive numbers you want, in any order you want. In the example above, there are only 25 or so lines of code, but the line label numbers begin at 1000. There is no relationship between editor line numbers and line label numbers used with Erl.

Line label numbers need not be in any particular order, although if they are not in ascending, top-down order, the efficacy and benefit of Erl is greatly diminished, but Erl will still report the correct number.

Line labels are specific to the procedure in which they appear. If procedure ProcA calls procedure ProcB and an error occurs in ProcB that passes control back to ProcA, Erl (in ProcA) will return the most recently encounterd line label number in ProcA before it calls ProcB. From within ProcA, you cannot get the line label numbers that might appear in ProcB.

Use care when putting line number labels within a loop. For example,

For X = 1 To 100
500:
' some code that causes an error
600:
Next X

If the code following line label 500 but before 600 causes an error, and that error arises on the 20th iteration of the loop, Erl will return 500, even though 600 has been encountered successfully in the previous 19 iterations of the loop.

Proper placement of line labels within the procedure is critical to using the Erl function to get truly meaningful information.

There are any number of free utilities on the Internet that will insert numeric line label in a procedure automatically, so you have fine-grained error information while developing and debugging, and then remove those labels once code goes live.

If your code displays error information to the end user if an unexpected error occurs, providing the value from Erl in that information can make finding and fixing the problem vastly simpler than if value of Erl is not reported.


问:
Angular 2 Material Customize md-menu
I am new to Angular 2 Material and I am trying to customize the style of the md-menu component.

```<code><md-icon class="material-icons" [mdMenuTriggerFor]="menu">dehaze</md-icon>
<md-menu #menu="mdMenu" [overlapTrigger]="false">
  <button md-menu-item>Item 1</button>
  <button md-menu-item>Item 2</button>
</md-menu>
</code>```

The predefined style settings work fine (e.g. setting the Menu to non-overlapping), but I would like to set the md-menu to 100% width and have a little space between the md-icon button, that expands the menu, which I can not do with the predefined directives from Angular 2 Material.

So far I found a solution with the /deep/ css command, but I read that the command is not supported by the major browsers any more.

What is a good way to customize a Angular 2 Material component? How could I style my md-menu, so that it has 100% width and some space between it´s expanding button?

To illustrate what I am talking about:
Draft of the menu

答:
In Angular, ViewEncapsulation.Emulated is the default option which means, it tries to narrow-down the scope of the affect by adding surrogate keys to the host-element etc. One option could be is to add below css. But mind, this ng-deep will also be deprecated soon. Have to wait to know the alternative! https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep</p>

```<code>::ng-deep .mat-menu-panel {
  max-width: none!important;
  min-width: 400px!important;
}
</code>```

Title: Angular 2 Material Customize md-menu

Body:
I am new to Angular 2 Material and I am trying to customize the style of the md-menu component.

<md-icon class="material-icons" [mdMenuTriggerFor]="menu">dehaze</md-icon>
<md-menu #menu="mdMenu" [overlapTrigger]="false">
  <button md-menu-item>Item 1</button>
  <button md-menu-item>Item 2</button>
</md-menu>

The predefined style settings work fine (e.g. setting the Menu to non-overlapping), but I would like to set the md-menu to 100% width and have a little space between the md-icon button, that expands the menu, which I can not do with the predefined directives from Angular 2 Material.

So far I found a solution with the /deep/ css command, but I read that the command is not supported by the major browsers any more.

What is a good way to customize a Angular 2 Material component? How could I style my md-menu, so that it has 100% width and some space between it´s expanding button?

To illustrate what I am talking about:
Draft of the menu

Body:
In Angular, ViewEncapsulation.Emulated is the default option which means, it tries to narrow-down the scope of the affect by adding surrogate keys to the host-element etc. One option could be is to add below css. But mind, this ng-deep will also be deprecated soon. Have to wait to know the alternative! https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep

::ng-deep .mat-menu-panel {
  max-width: none!important;
  min-width: 400px!important;
}


问:
Nested @IBDesignables using xibs?
I'm trying to create a component-based system on iOS, and I'd like to do the following:

Create a "PaddedView" component that has 8px of space around any added child components, like a container type component.

Add another IBDesignable view into this PaddedView on a storyboard, and see both render.

Is this possible?

Right now, I'm using the following superclass for all IBDesignable components to load their views from xibs:

```<code>import Foundation
import UIKit

@IBDesignable
class SKDesignableView: UIView {
    var view: UIView?

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

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.loadXib()
    }

    func loadXib() {
        self.view = self.viewFromXib()
        self.view!.frame = self.bounds
        self.view!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
        self.addSubview(self.view!)
    }

    func viewFromXib() -> UIView {
        let bundle = UINib(nibName: String(describing: self.getType()), bundle: Bundle(for: self.getType()))
        let views = bundle.instantiate(withOwner: self, options: nil)
        return views.first as! UIView
    }

    func getType() -> AnyClass {
        fatalError()
    }
}
</code>```

How do I create placeholders for other IBDesignables?

答:
The view initially contains the children, so add a container view as a subview to any component that needs children.

```<code>func loadXib() {
        var subview: UIView? = nil
        if self.subviews.count > 0 {
            subview = self.subviews[0]
        }
        subview?.removeFromSuperview()

        self.view = self.viewFromXib()
        self.view!.frame = self.bounds
        self.view!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]

        if let subview = subview {
            let lConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal,
                    toItem: self.view!, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 8)
            let rConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal,
                    toItem: self.view!, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -8)
            let tConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal,
                    toItem: self.view!, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 8)
            let bConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal,
                    toItem: self.view!, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -8)
            self.view!.addSubview(subview)
            self.view!.addConstraints([lConstraint, rConstraint, tConstraint, bConstraint])
        }
        self.addSubview(self.view!)
    }
</code>```

This approach can be generalized with tags etc to add multiple subviews.

Title: Nested @IBDesignables using xibs?

Body:
I'm trying to create a component-based system on iOS, and I'd like to do the following:

Create a "PaddedView" component that has 8px of space around any added child components, like a container type component.

Add another IBDesignable view into this PaddedView on a storyboard, and see both render.

Is this possible?

Right now, I'm using the following superclass for all IBDesignable components to load their views from xibs:

import Foundation
import UIKit

@IBDesignable
class SKDesignableView: UIView {
    var view: UIView?

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

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.loadXib()
    }

    func loadXib() {
        self.view = self.viewFromXib()
        self.view!.frame = self.bounds
        self.view!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
        self.addSubview(self.view!)
    }

    func viewFromXib() -> UIView {
        let bundle = UINib(nibName: String(describing: self.getType()), bundle: Bundle(for: self.getType()))
        let views = bundle.instantiate(withOwner: self, options: nil)
        return views.first as! UIView
    }

    func getType() -> AnyClass {
        fatalError()
    }
}

How do I create placeholders for other IBDesignables?

Body:
The view initially contains the children, so add a container view as a subview to any component that needs children.

func loadXib() {
        var subview: UIView? = nil
        if self.subviews.count > 0 {
            subview = self.subviews[0]
        }
        subview?.removeFromSuperview()

        self.view = self.viewFromXib()
        self.view!.frame = self.bounds
        self.view!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]

        if let subview = subview {
            let lConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal,
                    toItem: self.view!, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 8)
            let rConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal,
                    toItem: self.view!, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -8)
            let tConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal,
                    toItem: self.view!, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 8)
            let bConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal,
                    toItem: self.view!, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -8)
            self.view!.addSubview(subview)
            self.view!.addConstraints([lConstraint, rConstraint, tConstraint, bConstraint])
        }
        self.addSubview(self.view!)
    }

This approach can be generalized with tags etc to add multiple subviews.


问:
HTML form with array of maps
say I want to work with a array where the values are maps.

IE

```<code>[ %{ "foo" => "bar"}, %{ "foo" => "baz"} ]
</code>```

I can get this to work with.

```<code> <input name = "post[list][][foo]" value = "bar">
 <input name = "post[list][][foo]" value = "baz">
</code>```

Ok so that works but what if I want to add more keys to one of the maps or both?

This is where things fall apart for me.

```<code><input name = "post[list][][email]" value = "1@aol.com">
<input name = "post[list][][primary]" value = "false">

<input name = "post[list][][email]" value = "2@aol.com">
<input name = "post[list][][primary]" value = "true">
</code>```

I end up with an array of 4 items like so.

```<code>[%{"email" => "1@aol.com"}, %{"primary" => "false"}, %{"email" => "2@aol.com"}, %{"primary" => "true"}]
</code>```

When what I really wanted was an array of two items like so.

```<code>[%{"email" => "1@aol.com", "primary" => "false"}, %{"email" => "2@aol.com", "primary" => "true"}]
</code>```

Notice that each maps has two keys email, and primary as the desired map. IE %{"email" => "1@aol.com", "primary" => "false"} as opose to what I ended up with which was an array of 4 maps each with one key.

Now I know this has to do with the way I named my inputs. Can anyone here help me?

FYI the context of this array and map is from Elixir.

答:
I bet you have index when iterating to render inputs.

You can render inputs like this with index.

```<code><input name = "post[list][0][email]" value = "1@aol.com">
<input name = "post[list][0][primary]" value = "false">

<input name = "post[list][1][email]" value = "2@aol.com">
<input name = "post[list][1][primary]" value = "true">
</code>```

Title: HTML form with array of maps

Body:
say I want to work with a array where the values are maps.

IE

[ %{ "foo" => "bar"}, %{ "foo" => "baz"} ]

I can get this to work with.

 <input name = "post[list][][foo]" value = "bar">
 <input name = "post[list][][foo]" value = "baz">

Ok so that works but what if I want to add more keys to one of the maps or both?

This is where things fall apart for me.

<input name = "post[list][][email]" value = "1@aol.com">
<input name = "post[list][][primary]" value = "false">

<input name = "post[list][][email]" value = "2@aol.com">
<input name = "post[list][][primary]" value = "true">

I end up with an array of 4 items like so.

[%{"email" => "1@aol.com"}, %{"primary" => "false"}, %{"email" => "2@aol.com"}, %{"primary" => "true"}]

When what I really wanted was an array of two items like so.

[%{"email" => "1@aol.com", "primary" => "false"}, %{"email" => "2@aol.com", "primary" => "true"}]

Notice that each maps has two keys email, and primary as the desired map. IE %{"email" => "1@aol.com", "primary" => "false"} as opose to what I ended up with which was an array of 4 maps each with one key.

Now I know this has to do with the way I named my inputs. Can anyone here help me?

FYI the context of this array and map is from Elixir.

Body:
I bet you have index when iterating to render inputs.

You can render inputs like this with index.

<input name = "post[list][0][email]" value = "1@aol.com">
<input name = "post[list][0][primary]" value = "false">

<input name = "post[list][1][email]" value = "2@aol.com">
<input name = "post[list][1][primary]" value = "true">


问:
C# Odata customize native metadata
I have a simple Odata V4 service that returns persons.

This service is not accessible directly:

it is accessible through Apigee, ie with http://myApigeeServer/Person

then Apigee is pointing on a load balancer, ie with http://myLoadBalancer/Person

finally there is actually two servers behind my load balancer virtual IP, ie with http://myFirstServer/Person and http://mySecondServer/Person

My problem is that we can see the real final server URL in the service response "@odata.context" metadata, so a call to http://myApigeeServer/Person('foo') can lead to two responses:

```<code>{
    "@odata.context": "http://myFirstServer/$metadata#Person/$entity",
    "FirstName": "John",
    "LastName": "Doe",
    "Phone@odata.type": "#Collection(String)",
    "Phone": [
        "+123456789"
    ],
}
</code>```

Or

```<code>{
    "@odata.context": "http://mySecondServer/$metadata#Person/$entity",
    "FirstName": "John",
    "LastName": "Doe",
    "Phone@odata.type": "#Collection(String)",
    "Phone": [
        "+123456789"
    ],
}
</code>```

I really must hide the final servers names. So my question is: is it possible to totally remove the "@odata.context" metadata or to customize it ? In my case customization would mean forcing the "@odata.context" metadata value with the Apigee URL.

[---EDIT----]

Based on the link proposed by Dylan Nicholson (thanks!), indeed it exists a hook on the ODataMediaTypeFormatter that enables to change the service URI base address.

But in my tests, it didn't work/I didn't manage to make it work for the @odata.context URI. So from links to links and tests to tests, I arrived here and lencharest's solution works perfectly well: using a custom URL helper that rewrites each link base address. I'll see in the future if it's too brutal...

答:
@Max

To suppress the @odata.context, you can use "application/json;odata.metadata=none"

Title: C# Odata customize native metadata

Body:
I have a simple Odata V4 service that returns persons.

This service is not accessible directly:

it is accessible through Apigee, ie with http://myApigeeServer/Person

then Apigee is pointing on a load balancer, ie with http://myLoadBalancer/Person

finally there is actually two servers behind my load balancer virtual IP, ie with http://myFirstServer/Person and http://mySecondServer/Person

My problem is that we can see the real final server URL in the service response "@odata.context" metadata, so a call to http://myApigeeServer/Person('foo') can lead to two responses:

{
    "@odata.context": "http://myFirstServer/$metadata#Person/$entity",
    "FirstName": "John",
    "LastName": "Doe",
    "Phone@odata.type": "#Collection(String)",
    "Phone": [
        "+123456789"
    ],
}

Or

{
    "@odata.context": "http://mySecondServer/$metadata#Person/$entity",
    "FirstName": "John",
    "LastName": "Doe",
    "Phone@odata.type": "#Collection(String)",
    "Phone": [
        "+123456789"
    ],
}

I really must hide the final servers names. So my question is: is it possible to totally remove the "@odata.context" metadata or to customize it ? In my case customization would mean forcing the "@odata.context" metadata value with the Apigee URL.

[---EDIT----]

Based on the link proposed by Dylan Nicholson (thanks!), indeed it exists a hook on the ODataMediaTypeFormatter that enables to change the service URI base address.

But in my tests, it didn't work/I didn't manage to make it work for the @odata.context URI. So from links to links and tests to tests, I arrived here and lencharest's solution works perfectly well: using a custom URL helper that rewrites each link base address. I'll see in the future if it's too brutal...


问:
How do I query using ldapsearch what LDAP groups are members of other groups?
I'm working with an LDAP installation whose structure is not well documented.  I think the tools that are normally used to add entries into it can create nested groups that a reused for assigning multiple permissions to users.  By this, I mean:

User1 (o=users) -- is member of --> Group1 (o=groups) -- is member of
  --> Group2 (o=groups)

To confirm that this is indeed the way the system works, is there a way of querying using ldapsearch what groups are members of other groups?

答: Not easily. You will have to get the DNs of all the groups and their member attributes, whatever you're using for that, and then search for group DNs in the membership attributes.</p>


问:
Different colors for TabBar items in Tab Bar Controller
I have Tab Bar Controller with few tabs.

All tab items should have same non-selected color for image and text.

All tab items should have different selected color for image and
text.

I am ready to create images with colors needed for selected and non-selected items. And I know how to change this colors for all tabs from AppDelegate

```<code>    UITabBar.appearance().tintColor = UIColorFromRGB(rgbValue: MY_COLOR, aplhaValue: 1.0)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColorFromRGB(rgbValue: MY_COLOR, aplhaValue: 1.0)], for: UIControlState.selected)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: UIControlState.normal)
</code>```

But I want to make different colors for different items.

答:
In your Storyboard select your TabBarController and give it a custom class: TabBarController in this example:

And then create the custom TabBarController file:

```<code>//  Copyright © 2017 Erick Vavretchek. All rights reserved.

import UIKit

class TabBarController: UITabBarController {

  enum tabBarMenu: Int {
    case home
    case list
    case settings
  }

  // MARK: UITabBarController

  override func viewDidLoad() {

    super.viewDidLoad()

    guard let tabBarMenuItem = tabBarMenu(rawValue: 0) else { return }
    setTintColor(forMenuItem: tabBarMenuItem)
  }

  override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

    guard
      let menuItemSelected = tabBar.items?.index(of: item),
      let tabBarMenuItem = tabBarMenu(rawValue: menuItemSelected)
      else { return }

    setTintColor(forMenuItem: tabBarMenuItem)
  }

  // MARK: Private

  private func setTintColor(forMenuItem tabBarMenuItem: tabBarMenu) {
    switch tabBarMenuItem {
    case .home:
      viewControllers?[tabBarMenuItem.rawValue].tabBarController?.tabBar.tintColor = UIColor.green
    case .list:
      viewControllers?[tabBarMenuItem.rawValue].tabBarController?.tabBar.tintColor = UIColor.red
    case .settings:
      viewControllers?[tabBarMenuItem.rawValue].tabBarController?.tabBar.tintColor = UIColor.red
    }
  }
}
</code>```

It is also important that in your Assets.xcassets folder you select the each image you are using for your TabBarItem and set them to Render As: Template Image. That's how you can simply change its tintColor to whatever you like:

Body:
I have Tab Bar Controller with few tabs.

All tab items should have same non-selected color for image and text.

All tab items should have different selected color for image and
text.

I am ready to create images with colors needed for selected and non-selected items. And I know how to change this colors for all tabs from AppDelegate

    UITabBar.appearance().tintColor = UIColorFromRGB(rgbValue: MY_COLOR, aplhaValue: 1.0)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColorFromRGB(rgbValue: MY_COLOR, aplhaValue: 1.0)], for: UIControlState.selected)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: UIControlState.normal)

But I want to make different colors for different items.

Body:
In your Storyboard select your TabBarController and give it a custom class: TabBarController in this example:

And then create the custom TabBarController file:

//  Copyright © 2017 Erick Vavretchek. All rights reserved.

import UIKit

class TabBarController: UITabBarController {

  enum tabBarMenu: Int {
    case home
    case list
    case settings
  }

  // MARK: UITabBarController

  override func viewDidLoad() {

    super.viewDidLoad()

    guard let tabBarMenuItem = tabBarMenu(rawValue: 0) else { return }
    setTintColor(forMenuItem: tabBarMenuItem)
  }

  override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

    guard
      let menuItemSelected = tabBar.items?.index(of: item),
      let tabBarMenuItem = tabBarMenu(rawValue: menuItemSelected)
      else { return }

    setTintColor(forMenuItem: tabBarMenuItem)
  }

  // MARK: Private

  private func setTintColor(forMenuItem tabBarMenuItem: tabBarMenu) {
    switch tabBarMenuItem {
    case .home:
      viewControllers?[tabBarMenuItem.rawValue].tabBarController?.tabBar.tintColor = UIColor.green
    case .list:
      viewControllers?[tabBarMenuItem.rawValue].tabBarController?.tabBar.tintColor = UIColor.red
    case .settings:
      viewControllers?[tabBarMenuItem.rawValue].tabBarController?.tabBar.tintColor = UIColor.red
    }
  }
}

It is also important that in your Assets.xcassets folder you select the each image you are using for your TabBarItem and set them to Render As: Template Image. That's how you can simply change its tintColor to whatever you like:


问:
Python sin and cosine giving incorrect values
I have code that draws a line from 2 points; One on the middle bottom of the screen, and the other to the mouse pointer. I am trying to constrain the point by not exceeding a length parameter that I set. Heres the code:

```<code>import pygame
import Resources as r
import math as m

pygame.init()

class Segment():

    def __init__(self, _screen, _id, _start_pos, _length):
        self.screen = _screen
        self.id = _id
        self.start_pos = _start_pos
        self.length = _length

    def update(self):
        if self.id == 1:
            mouse_pos = pygame.mouse.get_pos()

            self.angle = m.atan2(mouse_pos[1]-self.start_pos[1],mouse_pos[0]-self.start_pos[0])
            self.a = self.start_pos
            self.b = (m.cos(self.angle)*self.length, m.sin(self.angle)*self.length)

            self.draw_line(self.a, self.b, r.black, 4)

    def draw_line(self, start, end, color, width):
        if self.id == 1:
            pygame.draw.line(self.screen, color, start, end, width)

    def get_data(self):
        return (self.start_pos, self.end_)
</code>```

I am seeing very different results when I run this that I would expect, it doesnt line up with my mouse and often just oscillates back and forth when the mouse is moved.

答:
self.b is calculated based on origin 0, 0, not self.start_pos.

Add coordinates in self.a to self.b.

Body:
I have code that draws a line from 2 points; One on the middle bottom of the screen, and the other to the mouse pointer. I am trying to constrain the point by not exceeding a length parameter that I set. Heres the code:

import pygame
import Resources as r
import math as m

pygame.init()

class Segment():

    def __init__(self, _screen, _id, _start_pos, _length):
        self.screen = _screen
        self.id = _id
        self.start_pos = _start_pos
        self.length = _length

    def update(self):
        if self.id == 1:
            mouse_pos = pygame.mouse.get_pos()

            self.angle = m.atan2(mouse_pos[1]-self.start_pos[1],mouse_pos[0]-self.start_pos[0])
            self.a = self.start_pos
            self.b = (m.cos(self.angle)*self.length, m.sin(self.angle)*self.length)

            self.draw_line(self.a, self.b, r.black, 4)

    def draw_line(self, start, end, color, width):
        if self.id == 1:
            pygame.draw.line(self.screen, color, start, end, width)

    def get_data(self):
        return (self.start_pos, self.end_)

I am seeing very different results when I run this that I would expect, it doesnt line up with my mouse and often just oscillates back and forth when the mouse is moved.


问:
Spring 5 Reactive - WebExceptionHandler is not getting called
I have tried all 3 solutions suggested in what is the right way to handle errors in spring-webflux, but WebExceptionHandler is not getting called. I am using Spring Boot 2.0.0.M7. Github repo here

```<code>@Configuration
class RoutesConfiguration {

  @Autowired
  private lateinit var testService: TestService

  @Autowired
  private lateinit var globalErrorHandler: GlobalErrorHandler

  @Bean
  fun routerFunction():

    RouterFunction<ServerResponse> = router {
    ("/test").nest {

      GET("/") {
        ServerResponse.ok().body(testService.test())
      }
    }
  }

}

@Component
class GlobalErrorHandler() : WebExceptionHandler {

  companion object {
    private val log = LoggerFactory.getLogger(GlobalErrorHandler::class.java)
  }

  override fun handle(exchange: ServerWebExchange?, ex: Throwable?): Mono<Void> {

    log.info("inside handle")

    /* Handle different exceptions here */
    when(ex!!) {
      is ClientException -> exchange!!.response.statusCode = HttpStatus.BAD_REQUEST
      is Exception -> exchange!!.response.statusCode = HttpStatus.INTERNAL_SERVER_ERROR
    }

    return Mono.empty()
  }
}
</code>```

UPDATE:

When I change Spring Boot version to 2.0.0.M2, the WebExceptionHandler is getting called. Do I need to do something for 2.0.0.M7?

SOLUTION:

As per Brian's suggestion, it worked as

```<code>@Bean
@Order(-2)
fun globalErrorHandler() = GlobalErrorHandler()
</code>```

答:
You can provide your own WebExceptionHandler, but you have to order it relatively to others, otherwise they might handle the error before yours get a chance to try.

the DefaultErrorWebExceptionHandler provided by Spring Boot for error handling (see reference documentation) is ordered at -1

the ResponseStatusExceptionHandler provided by Spring Framework is ordered at 0

So you can add @Order(-2) on your error handling component, to order it before the existing ones.

Body:
I have tried all 3 solutions suggested in what is the right way to handle errors in spring-webflux, but WebExceptionHandler is not getting called. I am using Spring Boot 2.0.0.M7. Github repo here

@Configuration
class RoutesConfiguration {

  @Autowired
  private lateinit var testService: TestService

  @Autowired
  private lateinit var globalErrorHandler: GlobalErrorHandler

  @Bean
  fun routerFunction():

    RouterFunction<ServerResponse> = router {
    ("/test").nest {

      GET("/") {
        ServerResponse.ok().body(testService.test())
      }
    }
  }

}

@Component
class GlobalErrorHandler() : WebExceptionHandler {

  companion object {
    private val log = LoggerFactory.getLogger(GlobalErrorHandler::class.java)
  }

  override fun handle(exchange: ServerWebExchange?, ex: Throwable?): Mono<Void> {

    log.info("inside handle")

    /* Handle different exceptions here */
    when(ex!!) {
      is ClientException -> exchange!!.response.statusCode = HttpStatus.BAD_REQUEST
      is Exception -> exchange!!.response.statusCode = HttpStatus.INTERNAL_SERVER_ERROR
    }

    return Mono.empty()
  }
}

UPDATE:

When I change Spring Boot version to 2.0.0.M2, the WebExceptionHandler is getting called. Do I need to do something for 2.0.0.M7?

SOLUTION:

As per Brian's suggestion, it worked as

@Bean
@Order(-2)
fun globalErrorHandler() = GlobalErrorHandler()


问:
Python 3 regex to split list of items?
I'm reading in some data in the form a list of items, space separated. Each item has a name, which may be one or more words, and a quantity which can either be a single integer or a fraction of integers.

Ex.

```<code>'12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank'
</code>```

I want this split into the following list:

```<code>['12 Spruce Log', '4/5 Water', '3 Orange', '3/18 Oak Plank']
</code>```

Here is my Python regex:

```<code>import re
re.findall(r'\d+(/\d+)?\D+', "12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank")
</code>```

This produces the following result, which is obviously not right:

```<code>['', '/5', '', '/18']
</code>```

What is the proper regex here?

答:
You can try this:

```<code>import re
s = '12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank'
new_s = re.split('(?<=[a-zA-Z])\s(?=\d)', s)
</code>```

Output:

```<code>['12 Spruce Log', '4/5 Water', '3 Orange', '3/18 Oak Plank']
</code>```

Or, just using re.findall:

```<code>new_list = [i[:-1] if i.endswith(' ') else i for i in re.findall('[\d\/]+\s[a-zA-Z\s]+(?=\d)|[\d\/]+\s[a-zA-Z\s]+(?=$)', s)]
</code>```

Output:

```<code>['12 Spruce Log', '4/5 Water', '3 Orange', '3/18 Oak Plank']
</code>```

Title: Python 3 regex to split list of items?

Body:
I'm reading in some data in the form a list of items, space separated. Each item has a name, which may be one or more words, and a quantity which can either be a single integer or a fraction of integers.

Ex.

'12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank'

I want this split into the following list:

['12 Spruce Log', '4/5 Water', '3 Orange', '3/18 Oak Plank']

Here is my Python regex:

import re
re.findall(r'\d+(/\d+)?\D+', "12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank")

This produces the following result, which is obviously not right:

['', '/5', '', '/18']

What is the proper regex here?

Body:
You can try this:

import re
s = '12 Spruce Log 4/5 Water 3 Orange 3/18 Oak Plank'
new_s = re.split('(?<=[a-zA-Z])\s(?=\d)', s)

Output:

['12 Spruce Log', '4/5 Water', '3 Orange', '3/18 Oak Plank']

Or, just using re.findall:

new_list = [i[:-1] if i.endswith(' ') else i for i in re.findall('[\d\/]+\s[a-zA-Z\s]+(?=\d)|[\d\/]+\s[a-zA-Z\s]+(?=$)', s)]

Output:

['12 Spruce Log', '4/5 Water', '3 Orange', '3/18 Oak Plank']


问:
Copying files from one directory to another in Java
I want to copy files from one directory to another (subdirectory) using Java. I have a directory, dir, with text files. I iterate over the first 20 files in dir, and want to copy them to another directory in the dir directory, which I have created right before the iteration.
In the code, I want to copy the review (which represents the ith text file or review) to trainingDir. How can I do this? There seems not to be such a function (or I couldn't find). Thank you.

```<code>boolean success = false;
File[] reviews = dir.listFiles();
String trainingDir = dir.getAbsolutePath() + "/trainingData";
File trDir = new File(trainingDir);
success = trDir.mkdir();
for(int i = 1; i <= 20; i++) {
    File review = reviews[i];

}
</code>```

答:
Following recursive function I have written, if it helps anyone. It will copy all the files inside sourcedirectory to destinationDirectory.

example:

rfunction("D:/MyDirectory", "D:/MyDirectoryNew", "D:/MyDirectory");

```<code>public static void rfunction(String sourcePath, String destinationPath, String currentPath) {
    File file = new File(currentPath);
    FileInputStream fi = null;
    FileOutputStream fo = null;

    if (file.isDirectory()) {
        String[] fileFolderNamesArray = file.list();
        File folderDes = new File(destinationPath);
        if (!folderDes.exists()) {
            folderDes.mkdirs();
        }

        for (String fileFolderName : fileFolderNamesArray) {
            rfunction(sourcePath, destinationPath + "/" + fileFolderName, currentPath + "/" + fileFolderName);
        }
    } else {
        try {
            File destinationFile = new File(destinationPath);

            fi = new FileInputStream(file);
            fo = new FileOutputStream(destinationPath);
            byte[] buffer = new byte[1024];
            int ind = 0;
            while ((ind = fi.read(buffer))>0) {
                fo.write(buffer, 0, ind);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            if (null != fi) {
                try {
                    fi.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != fo) {
                try {
                    fo.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
</code>```

Body:
I want to copy files from one directory to another (subdirectory) using Java. I have a directory, dir, with text files. I iterate over the first 20 files in dir, and want to copy them to another directory in the dir directory, which I have created right before the iteration.
In the code, I want to copy the review (which represents the ith text file or review) to trainingDir. How can I do this? There seems not to be such a function (or I couldn't find). Thank you.

boolean success = false;
File[] reviews = dir.listFiles();
String trainingDir = dir.getAbsolutePath() + "/trainingData";
File trDir = new File(trainingDir);
success = trDir.mkdir();
for(int i = 1; i <= 20; i++) {
    File review = reviews[i];

}

Body:
Following recursive function I have written, if it helps anyone. It will copy all the files inside sourcedirectory to destinationDirectory.

example:

rfunction("D:/MyDirectory", "D:/MyDirectoryNew", "D:/MyDirectory");

public static void rfunction(String sourcePath, String destinationPath, String currentPath) {
    File file = new File(currentPath);
    FileInputStream fi = null;
    FileOutputStream fo = null;

    if (file.isDirectory()) {
        String[] fileFolderNamesArray = file.list();
        File folderDes = new File(destinationPath);
        if (!folderDes.exists()) {
            folderDes.mkdirs();
        }

        for (String fileFolderName : fileFolderNamesArray) {
            rfunction(sourcePath, destinationPath + "/" + fileFolderName, currentPath + "/" + fileFolderName);
        }
    } else {
        try {
            File destinationFile = new File(destinationPath);

            fi = new FileInputStream(file);
            fo = new FileOutputStream(destinationPath);
            byte[] buffer = new byte[1024];
            int ind = 0;
            while ((ind = fi.read(buffer))>0) {
                fo.write(buffer, 0, ind);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            if (null != fi) {
                try {
                    fi.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != fo) {
                try {
                    fo.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}


问:
WriteFile() call works on x86, but not x64. Getting error code 6 -- The handle is invalid using VB.NET
I am using CreateFile, WriteFile and ReadFile API calls to write some data to a USB device. The code I have works perfectly on 32 bit systems. CreateFile gets a handle to the device, pass that handle and some data to WriteFile and read from that handle with ReadFile.

My problem is, the same code does not work on a 64 bit system. The error returned from WriteFile is 6, The handle is invalid. I've checked the handle for validity on the CreateFile call and it is a valid handle. A call to GetLastError() returns 0 after CreateFile. The "file" is being opened for overlapped communication and the overlapped init calls are also returning their proper values.

My question: is there some sort of different consideration I need to make because it's a 64 bit system? A different flag? A different call altogether?

Just to note, I did a little bit of a hack on the code to make it synchronous (took out the OVERLAPPED) and it worked, so I'm assuming the problem is in my OVERLAPPED structure or the way I'm initializing the calls.

Any help is greatly appreciated.

Edit:

Below are my API signatures and the code I am using for my OVERLAPPED implementation

```<code>Private Declare Auto Function CreateFile Lib "kernel32.dll" _
                                    (ByVal lpFileName As String, _
                                    ByVal dwDesiredAccess As Integer, _
                                    ByVal dwShareMode As Integer, _
                                    ByVal lpSecurityAttributes As IntPtr, _
                                    ByVal dwCreationDisposition As Integer, _
                                    ByVal dwFlagsAndAttributes As Integer, _
                                    ByVal hTemplateFile As IntPtr) As IntPtr

Private Declare Auto Function WriteFile Lib "kernel32.dll" _
                                    (ByVal hFile As IntPtr, ByVal Buffer As Byte(), _
                                    ByVal nNumberOfBytesToWrite As Integer, _
                                    ByRef lpNumberOfBytesWritten As Integer, _
                                    ByRef lpOverlapped As OVERLAPPED) As Boolean

Private Declare Auto Function ReadFile Lib "kernel32.dll" _
                                    (ByVal hFile As IntPtr, _
                                    ByVal Buffer As Byte(), _
                                    ByVal nNumberOfBytesToRead As Integer, _
                                    ByRef lpNumberOfBytesRead As Integer, _
                                    ByRef lpOverlapped As OVERLAPPED) As Boolean

Private Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal hFile As IntPtr) As Boolean

Private Declare Auto Function CancelIo Lib "kernel32.dll" (ByVal hObject As IntPtr) As Boolean

Private Declare Auto Function GetOverlappedResult Lib "kernel32.dll" ( _
                                    ByVal hFile As IntPtr, ByRef lpOverlapped As OVERLAPPED, _
                                    ByRef lpNumberOfBytesTransferred As Integer, _
                                    ByVal bWait As Boolean) As Boolean

Private Declare Auto Function CreateEvent Lib "kernel32.dll" ( _
                                    ByVal lpEventAttributes As Integer, ByVal bManualReset As Boolean, _
                                    ByVal bInitialState As Boolean, _
                                    <MarshalAs(UnmanagedType.LPStr)> ByVal lpName As String) As IntPtr

Private Declare Auto Function WaitForSingleObject Lib "kernel32.dll" ( _
                                    ByVal hHandle As IntPtr, ByVal dwMilliseconds As Integer) As Integer
</code>```

The following is the code for the write, where the issue occurs. It should be noted that in the read, the OVERLAPPED structure's hEvent parameter is initialized in the same fashion

```<code>Try

        With IOStructure
            .overlap.hEvent = CreateEvent(Nothing, True, False, Nothing)
            If .overlap.hEvent = 0 Then
                writeSuccess = False
            Else
                writeSuccess = WriteFile(.hdevice, .writeBuf, .writeBuf.Length, .bytesWritten, .overlap)

                'If the write didn't succeed, check to see if it's pending
                If Not writeSuccess Then

                    If Err.LastDllError <> ERROR_IO_PENDING Then 'The write failed
                        writeSuccess = False
                    Else ' Write is pending

                        Select Case WaitForSingleObject(.overlap.hEvent, .timeout * 0.1) 'Wait for the write to complete

                            Case 0 'The write completed, check the overlapped structure for the signalled event.
                                writeSuccess = GetOverlappedResult(.hdevice, .overlap, .bytesWritten, 0)
                            Case Else
                                writeSuccess = False
                        End Select
                    End If

                End If
            End If
            CloseHandle(.overlap.hEvent)
        End With
        '   Thread.Sleep(IOStructure.timeout * 0.3)
        ' End While
    Catch
        writeSuccess = False
    End Try
</code>```

答: Why don't you just use NativeOverlapped? It's specifically designed for this task.</p>

Body:
I am using CreateFile, WriteFile and ReadFile API calls to write some data to a USB device. The code I have works perfectly on 32 bit systems. CreateFile gets a handle to the device, pass that handle and some data to WriteFile and read from that handle with ReadFile.

My problem is, the same code does not work on a 64 bit system. The error returned from WriteFile is 6, The handle is invalid. I've checked the handle for validity on the CreateFile call and it is a valid handle. A call to GetLastError() returns 0 after CreateFile. The "file" is being opened for overlapped communication and the overlapped init calls are also returning their proper values.

My question: is there some sort of different consideration I need to make because it's a 64 bit system? A different flag? A different call altogether?

Just to note, I did a little bit of a hack on the code to make it synchronous (took out the OVERLAPPED) and it worked, so I'm assuming the problem is in my OVERLAPPED structure or the way I'm initializing the calls.

Any help is greatly appreciated.

Edit:

Below are my API signatures and the code I am using for my OVERLAPPED implementation

Private Declare Auto Function CreateFile Lib "kernel32.dll" _
                                    (ByVal lpFileName As String, _
                                    ByVal dwDesiredAccess As Integer, _
                                    ByVal dwShareMode As Integer, _
                                    ByVal lpSecurityAttributes As IntPtr, _
                                    ByVal dwCreationDisposition As Integer, _
                                    ByVal dwFlagsAndAttributes As Integer, _
                                    ByVal hTemplateFile As IntPtr) As IntPtr

Private Declare Auto Function WriteFile Lib "kernel32.dll" _
                                    (ByVal hFile As IntPtr, ByVal Buffer As Byte(), _
                                    ByVal nNumberOfBytesToWrite As Integer, _
                                    ByRef lpNumberOfBytesWritten As Integer, _
                                    ByRef lpOverlapped As OVERLAPPED) As Boolean

Private Declare Auto Function ReadFile Lib "kernel32.dll" _
                                    (ByVal hFile As IntPtr, _
                                    ByVal Buffer As Byte(), _
                                    ByVal nNumberOfBytesToRead As Integer, _
                                    ByRef lpNumberOfBytesRead As Integer, _
                                    ByRef lpOverlapped As OVERLAPPED) As Boolean

Private Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal hFile As IntPtr) As Boolean

Private Declare Auto Function CancelIo Lib "kernel32.dll" (ByVal hObject As IntPtr) As Boolean

Private Declare Auto Function GetOverlappedResult Lib "kernel32.dll" ( _
                                    ByVal hFile As IntPtr, ByRef lpOverlapped As OVERLAPPED, _
                                    ByRef lpNumberOfBytesTransferred As Integer, _
                                    ByVal bWait As Boolean) As Boolean

Private Declare Auto Function CreateEvent Lib "kernel32.dll" ( _
                                    ByVal lpEventAttributes As Integer, ByVal bManualReset As Boolean, _
                                    ByVal bInitialState As Boolean, _
                                    <MarshalAs(UnmanagedType.LPStr)> ByVal lpName As String) As IntPtr

Private Declare Auto Function WaitForSingleObject Lib "kernel32.dll" ( _
                                    ByVal hHandle As IntPtr, ByVal dwMilliseconds As Integer) As Integer

The following is the code for the write, where the issue occurs. It should be noted that in the read, the OVERLAPPED structure's hEvent parameter is initialized in the same fashion

Try

        With IOStructure
            .overlap.hEvent = CreateEvent(Nothing, True, False, Nothing)
            If .overlap.hEvent = 0 Then
                writeSuccess = False
            Else
                writeSuccess = WriteFile(.hdevice, .writeBuf, .writeBuf.Length, .bytesWritten, .overlap)

                'If the write didn't succeed, check to see if it's pending
                If Not writeSuccess Then

                    If Err.LastDllError <> ERROR_IO_PENDING Then 'The write failed
                        writeSuccess = False
                    Else ' Write is pending

                        Select Case WaitForSingleObject(.overlap.hEvent, .timeout * 0.1) 'Wait for the write to complete

                            Case 0 'The write completed, check the overlapped structure for the signalled event.
                                writeSuccess = GetOverlappedResult(.hdevice, .overlap, .bytesWritten, 0)
                            Case Else
                                writeSuccess = False
                        End Select
                    End If

                End If
            End If
            CloseHandle(.overlap.hEvent)
        End With
        '   Thread.Sleep(IOStructure.timeout * 0.3)
        ' End While
    Catch
        writeSuccess = False
    End Try


问:
Which is a better time complexity?
I have to pick out which operations have a better worst case time complexity on an AVL tree than a BST. I have established that the time complexity for each operation is the same depending on the tree...

The worst case time complexity for an AVL tree is...

```<code>Insert - O(log(n))
Remove - O(log(n))
Search - O(log(n))
</code>```

The worst case time complexity for a BST is....

```<code>Insert - O(height)
Remove - O(height)
Search - O(height)
</code>```

So is O(log(n)) a better time complexity than O(height)?

答:
The worst case time complexity on a BST for insert, remove, and search is O(n), where n is the number of nodes in the BST. You can trigger this worst case by inserting nodes into a BST in an order such that the BST is essentially a linked list (e.g. first insert 1, then insert 2, then insert 3, and so on... you will end up with a BST that looks like 1 -> 2 -> 3...).

O(log(n)) is a better time complexity than O(n).

Title: Which is a better time complexity?

Body:
I have to pick out which operations have a better worst case time complexity on an AVL tree than a BST. I have established that the time complexity for each operation is the same depending on the tree...

The worst case time complexity for an AVL tree is...

Insert - O(log(n))
Remove - O(log(n))
Search - O(log(n))

The worst case time complexity for a BST is....

Insert - O(height)
Remove - O(height)
Search - O(height)

So is O(log(n)) a better time complexity than O(height)?


答:
O(log(n)) is best case scenario for O(height). Height of your binary tree can be any integer between log(n) and n where n denotes the number of nodes.

For example if you have a BST where each node has only right child, it is the same as if it were a linked list, thus having O(n) worst case complexity for all three operations.

On the other hand AVL is self-balancing binary search tree, meaning every two sub-trees from any node have the same depth (height) +- constant. That means you are approximately halving the values at every step, thus getting O(log(n)) complexity, which is also your O(height) complexity.

Title: Which is a better time complexity?


问:
Java Error 26011 - Unpacking RT Failed
im trying to install Java on my windows 2003 VPS, it keeps coming up with the error "26077 - Unpacking RT Failed", i have 9.50GB left so its not a space problem.

Any ideas?

Lewis

答: There is an old bug log archived at Sun which says something about an conflict with an antivirus program: http://bugs.sun.com/view_bug.do?bug_id=6765272</p>

Title: Java Error 26011 - Unpacking RT Failed


问:
Cakephp inside folder online
I have a cakephp app inside a folder online like this: https://www.example.com/main

however, when I enter there, I want my url to show like this: https://www.example.com

I already tried modifying core.php

```<code>Configure::write('App.baseUrl', '/');
</code>```

And it shows what I want but returns "The requested URL /info/inicio was not found on this server."

I know that the solution would be to just remove the folder "main" and load the cakephp app directly, but at the moment that's not possible.

答:
I solved it by going to my cpanel and setting https://www.example.com/main as the pointer and then created a new domain that points to https://www.example.com/admin

Easy

Title: Cakephp inside folder online

Body:
I have a cakephp app inside a folder online like this: https://www.example.com/main

however, when I enter there, I want my url to show like this: https://www.example.com

I already tried modifying core.php

Configure::write('App.baseUrl', '/');

And it shows what I want but returns "The requested URL /info/inicio was not found on this server."

I know that the solution would be to just remove the folder "main" and load the cakephp app directly, but at the moment that's not possible.


问:
Spark calculate number of times a user has tweeted
I have to calculate the number of times a user has tweeted, with data being in a JSON file. I tried groupByKey and reduceByKey but the output is user id and the tweet itself, not the count of tweets.

Code:

```<code>from pyspark import SparkContext
from pyspark.sql import SQLContext

sc = SparkContext("local", "Twitter")
sqlc = SQLContext(sc)

df = sqlc.read.json("file.json")
tweets = df.select("user.id","text")
users = tweets.rdd.reduceByKey(lambda x,y:x+y)
</code>```

How do I get the count of tweets by their respective users as key?

答:
All you need is:

```<code>df.groupBy("user.id").count()
</code>```

This:

```<code>tweets.rdd.reduceByKey(lambda x,y:x+y)
</code>```

just adds second element (probably str concatenating results).

Body:
I have to calculate the number of times a user has tweeted, with data being in a JSON file. I tried groupByKey and reduceByKey but the output is user id and the tweet itself, not the count of tweets.

Code:

from pyspark import SparkContext
from pyspark.sql import SQLContext

sc = SparkContext("local", "Twitter")
sqlc = SQLContext(sc)

df = sqlc.read.json("file.json")
tweets = df.select("user.id","text")
users = tweets.rdd.reduceByKey(lambda x,y:x+y)

How do I get the count of tweets by their respective users as key?

Body:
All you need is:

df.groupBy("user.id").count()

This:

tweets.rdd.reduceByKey(lambda x,y:x+y)

just adds second element (probably str concatenating results).


问:
using sed from a seperate file
I have a project that I have to use a random number to alter a password. If the number is lower than value given it changes that letter. If it is higher the letter stays the same. My issue is that I am having problems finding information about using sed from another file to change the letter. Now this is not needed, but I feel that it will be cleaner in my opinion. Now my question is how could I call the file from my bash script that will use sed to substitute a letter. I just think sticking 26 sed commands in my script is a little much when I could place it in a separate file. If you know a better way that is fine.

Basic what I need either a better way. Or a way of calling a file and storing sed commands in a separate file from a bash script. And a way to pass just a single character, so if it is the second a in HaloStack, the sec command will not change the first because it would have already been changed possibly.

Below is what I have. I am working on the sed script right now. But I do not know of the way to send it only one character to change.

```<code>#!/bin/bash

#FUNCTIONS
##Random word grabber
passwdget () {
wget -qO- http://creativitygames.net/random-word-generator/randomwords/$wordamount | grep -o 'randomword_[1-9]\">[a-z]*' | awk -F ">" '{print $2}' > test.txt
}

#parses the words from one file
oneline () {
paste -s test.txt | sed 's/[[:blank:]]//g' > testnospace.txt
rm test.txt
mv testnospace.txt test.txt
}

passwdrnd () {
# Declare array
passwdstr=$(cat test.txt)
}

#VARIABLES
wordamount=4
complexity=0.0

#GET OPTIONS
while getopts ":n:t:" opt; do
    case ${opt} in
        n ) wordamount="$OPTARG";;
        t ) complexity="$OPTARG";;
        \?) ;;#invalad option
        : ) ;;#missing arguments for an option
    esac
done

#MAIN PROGRAM
passwdget
oneline
passwdrnd
echo $passwdstr

exit 0

#Use next information for getting a random number between 0.0 - 1.0
#awk -v seed=$RANDOM 'BEGIN{srand(seed);print rand()}'

#Get position echo ${var:position:length}
</code>```

Sample word list that needs to be altered in different ways.

```<code>pimplefrogsoapchimp
</code>```

答:
If I understand your question correctly, you need to loop over characters in the password and change them based on some conditions. sed might not be a good solution here.

There are a lot of ways to iterate over characters in a string. Using only Bash:

```<code>pass="somepassword"

for (( i=0; i < ${#pass}; i++ )); do
    char=${pass:$i:1}
    echo "$char"
    #some magic with chars here
done
</code>```

```<code>while IFS= read -r -d '' -n 1 char; do
    echo "$char"
    #some magic with chars here
done <<< "$pass"
</code>```

Using awk:

```<code>awk '{
   split($0, chars, "")
   for ( i=1; i <= length($0); i++ )
   {
      print chars[i]
      #do some magic with chars here
   }
}' <<< "$pass"
</code>```

```<code>awk 'BEGIN { FS="" }
{
   for ( i=1; i <= NF; i++ )
   {
      print $i
      #some magic with chars here (i = char)
   }
}' <<< "$pass"
</code>```

Let's say your goal is this simple logic: to change each letter s to b. You could do the following:

```<code>for (( i=0; i < ${#pass}; i++ )); do
   char=${pass:$i:1}
   if [[ $char = "s" ]]; then
      newpass="${newpass}b"
   else
      newpass="${newpass}${char}"
   fi
done
</code>```

This simple example can be easily done with sed 's/s/b/g' <<< "$pass". But with looping over all characters, you can do a lot more complicated logic/calculations. Using awk might give you even more flexibility.

EDIT: If you want to just map each character to some different output, use associative array to map them instead. Mapping for three characters, a, b and c:

```<code>pass="abba"
declare -A map=( [a]="cc" [b]="ff" [c]="rr" )

for (( i=0; i < ${#pass}; i++ )); do
        char=${pass:$i:1}
        newpass="${newpass}${map[$char]}"
done

#newpass is now: ccffffcc
</code>```

Title: using sed from a seperate file

Body:
I have a project that I have to use a random number to alter a password. If the number is lower than value given it changes that letter. If it is higher the letter stays the same. My issue is that I am having problems finding information about using sed from another file to change the letter. Now this is not needed, but I feel that it will be cleaner in my opinion. Now my question is how could I call the file from my bash script that will use sed to substitute a letter. I just think sticking 26 sed commands in my script is a little much when I could place it in a separate file. If you know a better way that is fine.

Basic what I need either a better way. Or a way of calling a file and storing sed commands in a separate file from a bash script. And a way to pass just a single character, so if it is the second a in HaloStack, the sec command will not change the first because it would have already been changed possibly.

Below is what I have. I am working on the sed script right now. But I do not know of the way to send it only one character to change.

#!/bin/bash

#FUNCTIONS
##Random word grabber
passwdget () {
wget -qO- http://creativitygames.net/random-word-generator/randomwords/$wordamount | grep -o 'randomword_[1-9]\">[a-z]*' | awk -F ">" '{print $2}' > test.txt
}

#parses the words from one file
oneline () {
paste -s test.txt | sed 's/[[:blank:]]//g' > testnospace.txt
rm test.txt
mv testnospace.txt test.txt
}

passwdrnd () {
# Declare array
passwdstr=$(cat test.txt)
}

#VARIABLES
wordamount=4
complexity=0.0

#GET OPTIONS
while getopts ":n:t:" opt; do
    case ${opt} in
        n ) wordamount="$OPTARG";;
        t ) complexity="$OPTARG";;
        \?) ;;#invalad option
        : ) ;;#missing arguments for an option
    esac
done

#MAIN PROGRAM
passwdget
oneline
passwdrnd
echo $passwdstr

exit 0

#Use next information for getting a random number between 0.0 - 1.0
#awk -v seed=$RANDOM 'BEGIN{srand(seed);print rand()}'

#Get position echo ${var:position:length}

Sample word list that needs to be altered in different ways.

pimplefrogsoapchimp

Body:
If I understand your question correctly, you need to loop over characters in the password and change them based on some conditions. sed might not be a good solution here.

There are a lot of ways to iterate over characters in a string. Using only Bash:

pass="somepassword"

for (( i=0; i < ${#pass}; i++ )); do
    char=${pass:$i:1}
    echo "$char"
    #some magic with chars here
done

while IFS= read -r -d '' -n 1 char; do
    echo "$char"
    #some magic with chars here
done <<< "$pass"

Using awk:

awk '{
   split($0, chars, "")
   for ( i=1; i <= length($0); i++ )
   {
      print chars[i]
      #do some magic with chars here
   }
}' <<< "$pass"

awk 'BEGIN { FS="" }
{
   for ( i=1; i <= NF; i++ )
   {
      print $i
      #some magic with chars here (i = char)
   }
}' <<< "$pass"

Let's say your goal is this simple logic: to change each letter s to b. You could do the following:

for (( i=0; i < ${#pass}; i++ )); do
   char=${pass:$i:1}
   if [[ $char = "s" ]]; then
      newpass="${newpass}b"
   else
      newpass="${newpass}${char}"
   fi
done

This simple example can be easily done with sed 's/s/b/g' <<< "$pass". But with looping over all characters, you can do a lot more complicated logic/calculations. Using awk might give you even more flexibility.

EDIT: If you want to just map each character to some different output, use associative array to map them instead. Mapping for three characters, a, b and c:

pass="abba"
declare -A map=( [a]="cc" [b]="ff" [c]="rr" )

for (( i=0; i < ${#pass}; i++ )); do
        char=${pass:$i:1}
        newpass="${newpass}${map[$char]}"
done

#newpass is now: ccffffcc


问:
How to use hapi js on Firebase Cloud Function?
I try to learn from an example to use express together with  handlebars on firebase.

For the express way, we can send the "app" instance directly to the "functions.https.onRequest" like...

```<code>const app = express();
...
app.get('/', (req, res) => {
    ...
});

exports.app = functions.https.onRequest(app);
</code>```

See live functions

As my understanding it's working because "express"  act like http-node, so it can respond "http plain".

Comparing to hapi, here is hello-world

```<code>const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: 8000
});

server.route({
    method: 'GET',
    path:'/hello',
    handler: function (request, reply) {
        return reply('hello world');
    }
});

server.start((err) => {
    console.log('Server running at:', server.info.uri);
});
</code>```

From the hapi example, is it possible to use hapi on firebase cloud function?

Can I use hapi without starting a server like express?

答:
This code was straight forward as i mixed the express API that used by Firebase with hapijs API, thanks to the blog given by mister @dkolba
You can ivoke the url hapijs handler by going to
http://localhost:5000/your-app-name/some-location/v1/hi

example: http://localhost:5000/helloworld/us-central1/v1/hi

```<code>const Hapi = require('hapi');
const server = new Hapi.Server();
const functions = require('firebase-functions');

server.connection();

const options = {
    ops: {
        interval: 1000
    },
    reporters: {
        myConsoleReporter: [{
            module: 'good-squeeze',
            name: 'Squeeze',
            args: [{ log: '*', response: '*' }]
        }, {
            module: 'good-console'
        }, 'stdout']
     }
};

server.route({
    method: 'GET',
    path: '/hi',
    handler: function (request, reply) {
        reply({data:'helloworld'});
    }
});
server.register({
    register: require('good'),
    options,
}, (err) => {

    if (err) {
        return console.error(err);
    }

});

// Create and Deploy Your First Cloud Functions
// https://firebase.google.com/docs/functions/write-firebase-functions
exports.v1 = functions.https.onRequest((event, resp) => {
    const options = {
        method: event.httpMethod,
        url: event.path,
        payload: event.body,
        headers: event.headers,
        validate: false
    };
    console.log(options);
    server.inject(options, function (res) {
        const response = {
            statusCode: res.statusCode,
            body: res.result
        };
        resp.status(res.statusCode).send(res.result);
    });
    //resp.send("Hellworld");

});
</code>```

Body:
I try to learn from an example to use express together with  handlebars on firebase.

For the express way, we can send the "app" instance directly to the "functions.https.onRequest" like...

const app = express();
...
app.get('/', (req, res) => {
    ...
});

exports.app = functions.https.onRequest(app);

See live functions

As my understanding it's working because "express"  act like http-node, so it can respond "http plain".

Comparing to hapi, here is hello-world

const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: 8000
});

server.route({
    method: 'GET',
    path:'/hello',
    handler: function (request, reply) {
        return reply('hello world');
    }
});

server.start((err) => {
    console.log('Server running at:', server.info.uri);
});

From the hapi example, is it possible to use hapi on firebase cloud function?

Can I use hapi without starting a server like express?

Body:
This code was straight forward as i mixed the express API that used by Firebase with hapijs API, thanks to the blog given by mister @dkolba
You can ivoke the url hapijs handler by going to
http://localhost:5000/your-app-name/some-location/v1/hi

example: http://localhost:5000/helloworld/us-central1/v1/hi

const Hapi = require('hapi');
const server = new Hapi.Server();
const functions = require('firebase-functions');

server.connection();

const options = {
    ops: {
        interval: 1000
    },
    reporters: {
        myConsoleReporter: [{
            module: 'good-squeeze',
            name: 'Squeeze',
            args: [{ log: '*', response: '*' }]
        }, {
            module: 'good-console'
        }, 'stdout']
     }
};

server.route({
    method: 'GET',
    path: '/hi',
    handler: function (request, reply) {
        reply({data:'helloworld'});
    }
});
server.register({
    register: require('good'),
    options,
}, (err) => {

    if (err) {
        return console.error(err);
    }

});

// Create and Deploy Your First Cloud Functions
// https://firebase.google.com/docs/functions/write-firebase-functions
exports.v1 = functions.https.onRequest((event, resp) => {
    const options = {
        method: event.httpMethod,
        url: event.path,
        payload: event.body,
        headers: event.headers,
        validate: false
    };
    console.log(options);
    server.inject(options, function (res) {
        const response = {
            statusCode: res.statusCode,
            body: res.result
        };
        resp.status(res.statusCode).send(res.result);
    });
    //resp.send("Hellworld");

});


问:
Assert if any of two strings are present
I have a webpage with two different strings depending on time of the day - "Good day" or "Good night".

Is there any way to do some sort of assert_content(my_string) that check if one of the two given strings is present?

It doesn't matter which one is present, just that one is.

答:
If using MiniTest then you can use assert_match:

```<code>assert_match /Good day|Good night/, string
</code>```

If using RSpec then you can use match:

```<code>expect(string).to match /Good day|Good night/
</code>```

Body:
If using MiniTest then you can use assert_match:

assert_match /Good day|Good night/, string

If using RSpec then you can use match:

expect(string).to match /Good day|Good night/


问:
PHP Function - Trapping for Error or Success Result
I'm working on my first function with PHP - it's a login function that calls cURL to login to an API. This is all working well so far, but I would like to add some error checking so that if the login fails or succeeds I can branch for that.

There's 2 possible types of errors that I can see:

cURL errors

API login errors

If there are no cURL errors the API will return a response in JSON like this for a successful login:

```<code>{
    "token": "6a2b4af445bb7e02a77891a380f7a47a57d3f99ff408ec57a62a",
    "layout": "Tasks",
    "errorCode": "0",
    "result": "OK"
}
</code>```

and this for a failed login:

```<code>{
    "errorMessage": "Invalid user account and/or password; please try again",
    "errorCode": "212"
}
</code>```

so that should be easy enough to trap for by the error code or result value. If there is a cURL error there could be many types of errors.

Here's the outline of my function at the moment:

```<code>function Login ($username, $password, $layout) {

    $curl = curl_init();

    // set curl options

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      return json_decode($response, true);
    }

}
</code>```

and I call it via:

$login = Login($username, $password, $layout);

Looking for advice on how I can return an error if there was a curl error and check the response on the calling page that calls the function.

答:
As suggested by @larwence-cherone in the comments, you should throw and catch exceptions.

```<code>// note: made the method name lowercase, because uppercase usually indicates a class
function login ($username, $password, $layout) {

    $curl = curl_init();

    // set curl options
    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        throw new Exception($err);
    } else {
        // returns an associative array
        $result = json_decode($response, true);
        // the status was not OK or if we received an error code.
        // Check the API doc for a recommended way to do this
        if ($result['result'] !== 'OK' || $result['errorCode'] > 0) {
            $errorMessage = $result['errorMessage'];
            // no error message: return a genuine error
            if (!$errorMessage) {
                $errorMessage = 'An undefined error occurred';
            }
            throw new Exception($errorMessage);
        }
        // if no error occurred, return the API result as an
        return $result;
    }
}
</code>```

call the method in a try/catch block:

```<code>try {
    $login = login($username, $password, $layout);
    print_r($login);
} catch (Exception $error) {
    echo $error;
}
</code>```

If you want to refine it, you could create your own exception(s) by extending the SPL Exception class.

Body:
I'm working on my first function with PHP - it's a login function that calls cURL to login to an API. This is all working well so far, but I would like to add some error checking so that if the login fails or succeeds I can branch for that.

There's 2 possible types of errors that I can see:

cURL errors

API login errors

If there are no cURL errors the API will return a response in JSON like this for a successful login:

{
    "token": "6a2b4af445bb7e02a77891a380f7a47a57d3f99ff408ec57a62a",
    "layout": "Tasks",
    "errorCode": "0",
    "result": "OK"
}

and this for a failed login:

{
    "errorMessage": "Invalid user account and/or password; please try again",
    "errorCode": "212"
}

so that should be easy enough to trap for by the error code or result value. If there is a cURL error there could be many types of errors.

Here's the outline of my function at the moment:

function Login ($username, $password, $layout) {

    $curl = curl_init();

    // set curl options

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      return json_decode($response, true);
    }

}

and I call it via:

$login = Login($username, $password, $layout);

Looking for advice on how I can return an error if there was a curl error and check the response on the calling page that calls the function.

Body:
As suggested by @larwence-cherone in the comments, you should throw and catch exceptions.

// note: made the method name lowercase, because uppercase usually indicates a class
function login ($username, $password, $layout) {

    $curl = curl_init();

    // set curl options
    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        throw new Exception($err);
    } else {
        // returns an associative array
        $result = json_decode($response, true);
        // the status was not OK or if we received an error code.
        // Check the API doc for a recommended way to do this
        if ($result['result'] !== 'OK' || $result['errorCode'] > 0) {
            $errorMessage = $result['errorMessage'];
            // no error message: return a genuine error
            if (!$errorMessage) {
                $errorMessage = 'An undefined error occurred';
            }
            throw new Exception($errorMessage);
        }
        // if no error occurred, return the API result as an
        return $result;
    }
}

call the method in a try/catch block:

try {
    $login = login($username, $password, $layout);
    print_r($login);
} catch (Exception $error) {
    echo $error;
}

If you want to refine it, you could create your own exception(s) by extending the SPL Exception class.