问:
What's the best way to manage the EF context in a three layer architecture with WebApi 2.0?
I'm trying to create an API architecture using WebApi 2.0 and Entity Framework 6.0 and I want to be near to the best practices so here is what I have atm.

API is an Azure API template and have references to BusinessLogic and Domain

BusinessLogic is a Class Library and have references to DataAccess and Domain

DataAccess is a Class Library and have a reference to Domain (also there are here the EF references)

I have edited the T4 template in DataAccess to generate POCO classes in Domain project and alterated the namespaces generation to acomplish that.
At this point it's all ok but my big concern is related to the layer independence regarding this architecture and EF model context.

What I know (let me know if I'm wrong in anyone):

Have a shared model context (singleton pattern) with the EF context in a WebApi is a bad practice.

The only place where I should have EF context object is in Domain

Any request to the API who generate a db interaction should create its independent EF Model context (independent from other request) but try to use the same context along the all db interactions at this particular request.

So thinking on that, what's the best way to manage the EF context in a three layer architecture with WebApi 2.0

答:
yes, shared model context is bad practice, in this case you cannot use transactions for instance

Use POCO and make them as simple as possible, get rid of any extra dependencies like EF, ServiceModel and so on.

Your #3 is correct, use independent context for each API request. You can implement Unit of Work pattern to incapsulate DBContext and get rid of direct reference to EF from BusinessLogic assembly (see the link, it is about MVC but it is applicable in your case)


来源: stackexchange

问:
How to write a program thats asks for a letter and number then prints out the letter that many times in python 3
I am trying to write a program that asks the user to type a letter then a number after that it prints out the letter as many times as the number, here is my code.

```<code>letter = input('Please enter a letter: ')
number = input('Please enter a number: ')
for i in range(number, letter):
    print(i)
</code>```

and this is the error I get.

```<code>Traceback (most recent call last):
  File "C:/Users/lajdt/Desktop/GCSE/Task 8/Task 8b.py", line 3, in <module>
    for i in range(number, letter):
TypeError: 'str' object cannot be interpreted as an integer
</code>```

I hope someone could help me.

答:
```<code>letter = input('Please enter a letter: ')
number = int(input('Please enter a number: '))
print(letter*number)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write a program that asks the user to type a letter then a number after that it prints out the letter as many times as the number, here is my code.

letter = input('Please enter a letter: ')
number = input('Please enter a number: ')
for i in range(number, letter):
    print(i)

and this is the error I get.

Traceback (most recent call last):
  File "C:/Users/lajdt/Desktop/GCSE/Task 8/Task 8b.py", line 3, in <module>
    for i in range(number, letter):
TypeError: 'str' object cannot be interpreted as an integer

I hope someone could help me.


问:
(android) an scrollview that gets programmatically filled loses title
I have this layout:

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:layout_centerVertical="true"
    android:background="#000"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical">

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_horizontal|center_vertical">

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/play"
                android:gravity="center_horizontal"
                android:scaleType="centerInside"
                android:text="@string/highScores"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#fff" />

            <View
                android:layout_width="1dp"
                android:layout_height="20dp"></View>

            <TableLayout
                android:id="@+id/container"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical|center_horizontal">

            </TableLayout>

        </LinearLayout>

    </ScrollView>

</LinearLayout>
</code>```

I fill the 'container' TableLayout with elements like this:

```<code>    layout.addView(buildTitleRow());

    for (int i = 0; i < users.length(); i++) {

        JSONObject parent = (JSONObject) users.get(i);

        layout.addView(buildRowFrom(parent, i + 1));
    }
</code>```

buildTitleRow:

```<code>private TableRow buildTitleRow(){

    TableRow result = new TableRow(this);

    int color = Color.parseColor("#ffff00");

    View view = new View(this);
    view.setMinimumWidth(10);
    result.addView(view);

    view = new View(this);
    view.setMinimumWidth(10);
    result.addView(view);

    //the same for other views

    return result;
}
</code>```

buildRowFrom:

```<code>private TableRow buildRowFrom(final JSONObject element, int counter) throws JSONException {

    TableRow result = new TableRow(this);

    String rowName = element.getString("name");

    int color = Color.parseColor("#00ff00");

    if(rowName.equals(userName)){
        color = Color.parseColor("#ffffff");
    }

    TextView textView = new TextView(this);
    textView.setText(counter + ".");
    textView.setTextColor(color);
    result.addView(textView);

    //some other views

    return result;
}
</code>```

this really works well just until the scrolling needs to take place...

Once there are more elements than the height of the screen the table remains scrollable (luckily) but the original 'title' Textview doesn't show up anymore (you can't scroll up towards it anymore)

Does anyone know how to tweak the layout to keep it visible once more elements are added than the size of the screen?

Thanks a lot,

S.

答:
I did the adaptations Paul suggested + change android:layout_height of the ScrollView to "wrap_content" to keep the inner LinearLayout centered when the android:layout_gravity="center" was removed from it (see complete layout below).

I wouldn't have found it without Paul's suggestion and explanation so I'll accept his answer as answer, this answer is just for the sake of completeness...

I'm not expecting this question to get that much of attention anyways ;-)

Thanks Paul :-D

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:layout_centerVertical="true"
    android:background="#000"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical">

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal|center_vertical">

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/play"
                android:gravity="center_horizontal"
                android:scaleType="centerInside"
                android:text="@string/highScores"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#fff" />

            <View
                android:layout_width="1dp"
                android:layout_height="20dp"></View>

            <TableLayout
                android:id="@+id/container"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical|center_horizontal">

            </TableLayout>

        </LinearLayout>

    </ScrollView>

</LinearLayout>
</code>```

Body:
I have this layout:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:layout_centerVertical="true"
    android:background="#000"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical">

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_horizontal|center_vertical">

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/play"
                android:gravity="center_horizontal"
                android:scaleType="centerInside"
                android:text="@string/highScores"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#fff" />

            <View
                android:layout_width="1dp"
                android:layout_height="20dp"></View>

            <TableLayout
                android:id="@+id/container"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical|center_horizontal">

            </TableLayout>

        </LinearLayout>

    </ScrollView>

</LinearLayout>

I fill the 'container' TableLayout with elements like this:

    layout.addView(buildTitleRow());

    for (int i = 0; i < users.length(); i++) {

        JSONObject parent = (JSONObject) users.get(i);

        layout.addView(buildRowFrom(parent, i + 1));
    }

buildTitleRow:

private TableRow buildTitleRow(){

    TableRow result = new TableRow(this);

    int color = Color.parseColor("#ffff00");

    View view = new View(this);
    view.setMinimumWidth(10);
    result.addView(view);

    view = new View(this);
    view.setMinimumWidth(10);
    result.addView(view);

    //the same for other views

    return result;
}

buildRowFrom:

private TableRow buildRowFrom(final JSONObject element, int counter) throws JSONException {

    TableRow result = new TableRow(this);

    String rowName = element.getString("name");

    int color = Color.parseColor("#00ff00");

    if(rowName.equals(userName)){
        color = Color.parseColor("#ffffff");
    }

    TextView textView = new TextView(this);
    textView.setText(counter + ".");
    textView.setTextColor(color);
    result.addView(textView);

    //some other views

    return result;
}

this really works well just until the scrolling needs to take place...

Once there are more elements than the height of the screen the table remains scrollable (luckily) but the original 'title' Textview doesn't show up anymore (you can't scroll up towards it anymore)

Does anyone know how to tweak the layout to keep it visible once more elements are added than the size of the screen?

Thanks a lot,

S.

Body:
I did the adaptations Paul suggested + change android:layout_height of the ScrollView to "wrap_content" to keep the inner LinearLayout centered when the android:layout_gravity="center" was removed from it (see complete layout below).

I wouldn't have found it without Paul's suggestion and explanation so I'll accept his answer as answer, this answer is just for the sake of completeness...

I'm not expecting this question to get that much of attention anyways ;-)

Thanks Paul :-D

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:layout_centerVertical="true"
    android:background="#000"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical">

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal|center_vertical">

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/play"
                android:gravity="center_horizontal"
                android:scaleType="centerInside"
                android:text="@string/highScores"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#fff" />

            <View
                android:layout_width="1dp"
                android:layout_height="20dp"></View>

            <TableLayout
                android:id="@+id/container"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical|center_horizontal">

            </TableLayout>

        </LinearLayout>

    </ScrollView>

</LinearLayout>


问:
Does anybody have experience with Visual Studio 2008 on Windows 7?
Has anyone already tried this, anything particulair that I need to be aware of?</p>

答:
Yep, been running it for a while and I haven't hit any problems yet. Can't say I've use it all day every day, but I've built WPF, WinForms, Web and Console apps with it for testing various things and haven't had any hitches.

I have it on my Dell X1, which is effectively my "NetBook", and it's really pretty rapid. The only glitch I have had at all is some problems with graphics acceleration, but that's down to the Intel driver I'm using being an old XP driver, and it was easily worked around.

OwnerDisplayName: Jeroen Landheer

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Steve Robbins


问:
Taking dot products of high dimensional numpy arrays
I am trying to take the dot product between three numpy arrays. However, I am struggling with wrapping my head around this.

The problem is as follows:

I have two (4,) shaped numpy arrays a and b respectively, as well as a numpy array with shape (4, 4, 3), c.

```<code>import numpy as np

a = np.array([0, 1, 2, 3])
b = np.array([[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
          [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
          [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],
          [[4, 4, 4], [4, 4, 4], [4, 4, 4], [4, 4, 4]]])
c = np.array([4, 5, 6, 7])
</code>```

I want to compute the dot product in such a way that my result is a 3-tuple. That is, first dot a with b and then dotting with c, taking transposes if needed. In other words, I want to compute the dot product between a, b and c as if c was of shape (4, 4), but I want a 3-tuple as result.

I have tried:

Reshaping a and c, and then computing the dot product:

```<code>a = np.reshape(a, (4, 1))
c = np.reshape(c, (4, 1))

tmp = np.dot(a.T, b) # now has shape (1, 4, 3)
result = np.dot(tmp, c)
</code>```

Ideally, I should now have:

```<code>print(result.shape)
>> (1, 1, 3)
</code>```

but I get the error

ValueError: shapes (1,4,3) and (4,1) not aligned: 3 (dim 2) != 4 (dim 0)

I have also tried using the tensordot function from numpy, but without luck.

答:
Not automagical but does the job:

```<code>np.einsum('i,ijk,j->k',a,b,c)
# array([440, 440, 440])
</code>```

This computes d of shape (3,) such that d_k = sum_{ij} a_i b_{ijk} c_j.

Body:
I am trying to take the dot product between three numpy arrays. However, I am struggling with wrapping my head around this.

The problem is as follows:

I have two (4,) shaped numpy arrays a and b respectively, as well as a numpy array with shape (4, 4, 3), c.

import numpy as np

a = np.array([0, 1, 2, 3])
b = np.array([[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]],
          [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
          [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]],
          [[4, 4, 4], [4, 4, 4], [4, 4, 4], [4, 4, 4]]])
c = np.array([4, 5, 6, 7])

I want to compute the dot product in such a way that my result is a 3-tuple. That is, first dot a with b and then dotting with c, taking transposes if needed. In other words, I want to compute the dot product between a, b and c as if c was of shape (4, 4), but I want a 3-tuple as result.

I have tried:

Reshaping a and c, and then computing the dot product:

a = np.reshape(a, (4, 1))
c = np.reshape(c, (4, 1))

tmp = np.dot(a.T, b) # now has shape (1, 4, 3)
result = np.dot(tmp, c)

Ideally, I should now have:

print(result.shape)
>> (1, 1, 3)

but I get the error

ValueError: shapes (1,4,3) and (4,1) not aligned: 3 (dim 2) != 4 (dim 0)

I have also tried using the tensordot function from numpy, but without luck.

Body:
Not automagical but does the job:

np.einsum('i,ijk,j->k',a,b,c)
# array([440, 440, 440])

This computes d of shape (3,) such that d_k = sum_{ij} a_i b_{ijk} c_j.


问:
How to use async method in DelegateCommand
I want to link async method to a delegate command in prism framework in Xamarin.Forms and my question is how to do it?

Is below solution correct? Is there exist any pitfall? (deadlock, UI slow or freezing, bad practices, ...)

```<code>{      // My view model constructor
       ...
       MyCommand = new DelegateCommand(async () => await MyJobAsync());
       ...
}

private async Task MyJobAsync()
{
       ... // Some await calls
       ... // Some UI element changed such as binded Observable collections
}
</code>```

答:
```<code>public DelegateCommand MyCommand => new DelegateCommand(MyMethod);

private async void MyMethod()
{

}
</code>```

There are no pitfalls. A void return type in async method was created especially for delegates. If you want to change something, that has reflected on UI, insert relevant code in this block:

```<code>Device.BeginOnMainThread(()=>
{
    your code;
});
</code>```

Actually, ICommand and DelegateCommand pretty similar, so an above answer is quite right.

Body:
I want to link async method to a delegate command in prism framework in Xamarin.Forms and my question is how to do it?

Is below solution correct? Is there exist any pitfall? (deadlock, UI slow or freezing, bad practices, ...)

{      // My view model constructor
       ...
       MyCommand = new DelegateCommand(async () => await MyJobAsync());
       ...
}

private async Task MyJobAsync()
{
       ... // Some await calls
       ... // Some UI element changed such as binded Observable collections
}

Body:
public DelegateCommand MyCommand => new DelegateCommand(MyMethod);

private async void MyMethod()
{

}

There are no pitfalls. A void return type in async method was created especially for delegates. If you want to change something, that has reflected on UI, insert relevant code in this block:

Device.BeginOnMainThread(()=>
{
    your code;
});

Actually, ICommand and DelegateCommand pretty similar, so an above answer is quite right.


问:
How to workaround IE bug where it is unable to properly absolute center element inside a parent without fixed size?
I've encountered a problem IE11 has (maybe other IE's too), where the centered elements (using absolute position method) are not positioned properly if parent has no fixed size. The size is determined by the content.

Is there any known workaround for this?

Example:

.box{
    position: absolute;
    top:0;
    right: 0;
    left: 0;
    bottom:0;
    margin:auto;
    height:20px;
    width:20px;
    background-color:#000;
}

.container{
    position: relative;
    background:red;
    padding-left:100px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td class="container">
      <div class="box">
      </div>
    </td>
    <td>
      Some content Some content Some content Some content Some content <br>
      Some content Some content Some content Some content Some content <br>
      Some content Some content Some content Some content Some content <br>
      Some content Some content Some content Some content Some content <br>
    </td>
  </tr>
</table></code>```

答:
you should use
 as a parent because relative position for  won't work on IE

check the updated snippet

.bg {
  background: red;
}

.box {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  margin: auto;
  height: 20px;
  width: 20px;
  background-color: #000;
}

.container {
  position: relative;
  padding-left: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td class="bg">
      <div class="container">
        <div class="box">
        </div>
      </div>
    </td>
    <td>
      Some content Some content Some content Some content Some content <br> Some content Some content Some content Some content Some content <br> Some content Some content Some content Some content Some content <br> Some content Some content Some content
      Some content Some content <br>
    </td>
  </tr>
</table></code>```

Body:
I've encountered a problem IE11 has (maybe other IE's too), where the centered elements (using absolute position method) are not positioned properly if parent has no fixed size. The size is determined by the content.

Is there any known workaround for this?

Example:

.box{
    position: absolute;
    top:0;
    right: 0;
    left: 0;
    bottom:0;
    margin:auto;
    height:20px;
    width:20px;
    background-color:#000;
}

.container{
    position: relative;
    background:red;
    padding-left:100px;
 }

      Some content Some content Some content Some content Some content

      Some content Some content Some content Some content Some content

      Some content Some content Some content Some content Some content

      Some content Some content Some content Some content Some content

Body:
you should use <div> as a parent because relative position for <td> won't work on IE

check the updated snippet

.bg {
  background: red;
}

.box {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  margin: auto;
  height: 20px;
  width: 20px;
  background-color: #000;
}

.container {
  position: relative;
  padding-left: 100px;
}

<table>
  <tr>
    <td class="bg">
      <div class="container">
        <div class="box">
        </div>
      </div>
    </td>
    <td>
      Some content Some content Some content Some content Some content <br> Some content Some content Some content Some content Some content <br> Some content Some content Some content Some content Some content <br> Some content Some content Some content
      Some content Some content <br>
    </td>
  </tr>
</table>


问:
How to control playback state function on MPMusicPlayer
how to control playback state function in MPMusicPlayer....for example i want open

ipod playlist file  when the no item available at the end of next track...

how it is possible on iphone.....please help me.....

答:
Here's a bit of my code that does that:

```<code>    MPMediaQuery *everything = [MPMediaQuery songsQuery];

[everything setGroupingType: MPMediaGroupingPlaylist];

self.playlists = [NSMutableArray arrayWithArray:[everything collections]];
</code>```

....

```<code>    NSArray *songsList = [[self.playlists objectAtIndex: currentPlayListIndex] items];

int nowIndex = [songsList indexOfObject:nowPlayingViewController.nowPlayingItem];

if(++nowIndex >= [songsList count])
    nowIndex = 0;

if(![self playItem: [songsList objectAtIndex:nowIndex]])
</code>```

Body:
Here's a bit of my code that does that:

    MPMediaQuery *everything = [MPMediaQuery songsQuery];

[everything setGroupingType: MPMediaGroupingPlaylist];

self.playlists = [NSMutableArray arrayWithArray:[everything collections]];

....

    NSArray *songsList = [[self.playlists objectAtIndex: currentPlayListIndex] items];

int nowIndex = [songsList indexOfObject:nowPlayingViewController.nowPlayingItem];

if(++nowIndex >= [songsList count])
    nowIndex = 0;

if(![self playItem: [songsList objectAtIndex:nowIndex]])


问:
How would I go about drawing a rectangular selection on-screen when the mouse is dragged and then getting a screenshot of the selected area?
I'm looking for a way to draw a rectangular selection-visualiser, basically similar to Gyazo.

If any of you are familiar with iOS jailbreaking and have used Snapper 2 before, I'm trying to do that but for Windows. For those of you who aren't, it allows you to select an area you want for a screenshot and then keeps it on top of everything else, allowing you to drag it around, save it etc. It's really useful for phone numbers, WiFi passwords among other things.

The only issue is that I don't know how I'd go about drawing a selection area and grabbing an image of it.

Any help would be appreciated.

答:
Windows since 7 has the Snipping tool. It might be close enough to the droid you are looking for: https://support.microsoft.com/en-us/help/13776/windows-use-snipping-tool-to-capture-screenshots

If you mean .NET with C#, there is Graphics.CopyFromScreen. Note that it does not work from Windows services - a interactive session is required and Services are barred from those by default since Vista.

One issues is having this thing be drawn "on top". Generally the topmost game is one you and the user can only loose. Everything that is able to win it is either part of Windows itself. Or uses a "intercept GPU output, draw something on top" approach, wich is not trivial.


问:
yii2 redirect in controller action does not work?
I am posting a form to /user/save in order to save user data. The problem occurs when i try to redirect the user if the $_SERVER['REQUEST_METHOD'] is NOT 'post'.

My user controller code

```<code>namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\MyUser;

class UserController extends Controller {

public function actionSave() {

    if(!Yii::$app->request->getIsPost()) {
       $this->redirect('/user/index',302);
       exit(0);
   }

   //do something to save user submitted data
}

}//~CLASS
</code>```

The is no way to get the redirection to work. Although !Yii::$app->request->getIsPost() is false the call to $this->redirect does nothing!

Any help appreciated.

答:
Don't use exit(0); That's bad practice at the best of times. Use Yii::$app->end();

So your code would look like

```<code>$this->redirect(['index'], 302);
Yii::$app->end();
</code>```

That said though the actual problem was stopping POST requests, this is the wrong solution to that problem (although it does work). To stop POST requests you need to use access control.

```<code>public function behaviors()
{
    return [
        'access' => [
            'class' => \yii\filters\AccessControl::className(),
            'only' => ['create', 'update'],
            'rules' => [
                // deny all POST requests
                [
                    'allow' => false,
                    'verbs' => ['POST']
                ],
                // allow authenticated users
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
                // everything else is denied
            ],
        ],
    ];
}
</code>```

Body:
I am posting a form to /user/save in order to save user data. The problem occurs when i try to redirect the user if the $_SERVER['REQUEST_METHOD'] is NOT 'post'.

My user controller code

namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\MyUser;

class UserController extends Controller {

public function actionSave() {

    if(!Yii::$app->request->getIsPost()) {
       $this->redirect('/user/index',302);
       exit(0);
   }

   //do something to save user submitted data
}

}//~CLASS

The is no way to get the redirection to work. Although !Yii::$app->request->getIsPost() is false the call to $this->redirect does nothing!

Any help appreciated.

Body:
Don't use exit(0); That's bad practice at the best of times. Use Yii::$app->end();

So your code would look like

$this->redirect(['index'], 302);
Yii::$app->end();

That said though the actual problem was stopping POST requests, this is the wrong solution to that problem (although it does work). To stop POST requests you need to use access control.

public function behaviors()
{
    return [
        'access' => [
            'class' => \yii\filters\AccessControl::className(),
            'only' => ['create', 'update'],
            'rules' => [
                // deny all POST requests
                [
                    'allow' => false,
                    'verbs' => ['POST']
                ],
                // allow authenticated users
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
                // everything else is denied
            ],
        ],
    ];
}


问:
Why can my synchronized methods lock on different objects?
I am learning Java concurrency right now. I came across a piece of code like this:

```<code>package pac1;

import java.util.*;
import java.util.concurrent.*;

class A1 {
    public void f() {
        synchronized (this) {
            for (int i = 0; i < 5; i++)
                System.out.println("f()");
        }
    }
}

class B1 {
    public void g() {
        synchronized (this) {
            for (int i = 0; i < 5; i++)
                System.out.println("g()");
        }
    }
}

class C1 {
    public void p() {
        synchronized (this) {
            for (int i = 0; i < 5; i++)
                System.out.println("p()");
        }
    }

}

public class V {
    public static void main(String[] args) {
        A1 a = new A1();
        B1 b = new B1();
        C1 c = new C1();
        new Thread() {
            public void run() {
                a.f();
            }
        }.start();
        new Thread() {
            public void run() {
                c.p();
            }
        }.start();
        b.g();
    }

}
</code>```

Since this code uses different objects to call synchronized methods,  I supposed that it would not prevent them from interfering with each other. However, the result is as follows:

```<code>f()
f()
f()
f()
f()
g()
g()
g()
g()
g()
p()
p()
p()
p()
p()
</code>```

BTW, the result is the same using Lock:

```<code>package pac1;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class A {
    Lock lock = new ReentrantLock();

    public void f() {
        lock.lock();
        try {
            for (int i = 0; i < 5; i++)
                System.out.println("f()");
        } finally {
            lock.unlock();
        }
    }
}

class B {
    Lock lock = new ReentrantLock();

    public void g() {
        lock.lock();
        try {
            for (int i = 0; i < 5; i++)
                System.out.println("g()");
        } finally {
            lock.unlock();
        }
    }
}

class C {
    Lock lock = new ReentrantLock();

    public void p() {
        lock.lock();
        try {
            for (int i = 0; i < 5; i++)
                System.out.println("p()");
        } finally {
            lock.unlock();
        }
    }
}

public class Ex16 {

    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        C c = new C();
        new Thread() {
            public void run() {
                a.f();
            }
        }.start();
        new Thread() {
            public void run() {
                c.p();
            }
        }.start();
        b.g();
    }

}
</code>```

答:
Actually the loops simply are not long enough hence allowing threads to finalize in the same order they were launched. In order to make apparent that threads do not interfere you may try one of the following approaches :

Make the loop to run longer, e.g. 1000 iterations should be more then enough :

synchronized (this) {
           for (int i = 0; i < 1000; i++)
               System.out.println("f()");
       }

Suspend the threads within the loops but make sure to have different intervals set for each loop :

synchronized (this) {
        for (int i = 0; i < 5; i++) {
            System.out.println("p()");
            try {
                Thread.sleep(3000);
            } catch (final InterruptedException ex) {
                // Swallow
            }
        }
    }

So long story short : These locks actually do not interfere.

Body:
I am learning Java concurrency right now. I came across a piece of code like this:

package pac1;

import java.util.*;
import java.util.concurrent.*;

class A1 {
    public void f() {
        synchronized (this) {
            for (int i = 0; i < 5; i++)
                System.out.println("f()");
        }
    }
}

class B1 {
    public void g() {
        synchronized (this) {
            for (int i = 0; i < 5; i++)
                System.out.println("g()");
        }
    }
}

class C1 {
    public void p() {
        synchronized (this) {
            for (int i = 0; i < 5; i++)
                System.out.println("p()");
        }
    }

}

public class V {
    public static void main(String[] args) {
        A1 a = new A1();
        B1 b = new B1();
        C1 c = new C1();
        new Thread() {
            public void run() {
                a.f();
            }
        }.start();
        new Thread() {
            public void run() {
                c.p();
            }
        }.start();
        b.g();
    }

}

Since this code uses different objects to call synchronized methods,  I supposed that it would not prevent them from interfering with each other. However, the result is as follows:

f()
f()
f()
f()
f()
g()
g()
g()
g()
g()
p()
p()
p()
p()
p()

BTW, the result is the same using Lock:

package pac1;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class A {
    Lock lock = new ReentrantLock();

    public void f() {
        lock.lock();
        try {
            for (int i = 0; i < 5; i++)
                System.out.println("f()");
        } finally {
            lock.unlock();
        }
    }
}

class B {
    Lock lock = new ReentrantLock();

    public void g() {
        lock.lock();
        try {
            for (int i = 0; i < 5; i++)
                System.out.println("g()");
        } finally {
            lock.unlock();
        }
    }
}

class C {
    Lock lock = new ReentrantLock();

    public void p() {
        lock.lock();
        try {
            for (int i = 0; i < 5; i++)
                System.out.println("p()");
        } finally {
            lock.unlock();
        }
    }
}

public class Ex16 {

    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        C c = new C();
        new Thread() {
            public void run() {
                a.f();
            }
        }.start();
        new Thread() {
            public void run() {
                c.p();
            }
        }.start();
        b.g();
    }

}


问:
GridLayout border lines/visible separators?
I'm relatively new to android and I want to know how to put a visible divider/borders around images.

答:
In the item's layout you could put a View with heigth of 1dp or width 1dp and fill it with some color. This is a item for a list with a text and a bottom divider.</p>

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorPrimary"/>
</FrameLayout>
</code>```

Body:
In the item's layout you could put a View with heigth of 1dp or width 1dp and fill it with some color. This is a item for a list with a text and a bottom divider.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorPrimary"/>
</FrameLayout>


问:
Wildcard Pattern Matching fails for some cases

You are given a string pattern which consists of characters 'a' to 'z' and exactly one asterisk character ('*') behaving as a wildcard. The wildcard matches zero or more arbitrary characters. The wildcard might be at the front, back, or in the middle of the pattern string.

Given an integer N, followed by N strings. Your task is to find which of these strings match with the pattern.

Example input:

```<code>pl*
3
play
pluck
prune
</code>```

Example output:

```<code>play
pluck
</code>```

Here's my code. The approach is to find where the position of the asterisk in the pattern string, and compare the substring of pattern before the asterisk with the first # characters of the testing string, and also the substring of pattern after the asterisk with the last # characters of the testing string.

It runs almost perfectly, but there is one test case that outputs the wrong answer. I tried to come up with some random cases but it all work as intended. I don't know the case that makes my code go wrong yet. Can you help me find those cases or point out some mistakes from my code? Thanks

```<code>#include <iostream>
#include <string>
using namespace std;

int main(){
    string pattern;
    cin >> pattern;
    int patternLen = pattern.length();
    int asterPos = pattern.find('*');

    int n;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        string temp;
        cin >> temp;
        int tempLen = temp.length();

        bool verdict;
        if (tempLen >= patternLen - asterPos - 1) {
            verdict = (temp.substr(0, asterPos) == pattern.substr(0, asterPos)) && (temp.substr(tempLen - patternLen + asterPos + 1) == pattern.substr(asterPos + 1));
        } else {
            verdict = false;
        }

        if (verdict) {
            cout << temp << '\n';
        }
    }
    return 0;
}
</code>```

答:
I found out a counter-case:

```<code>ab*ca
1
abc
</code>```

Which should not match, but it did.

The mistake underlies in the substrings of the matching string, because in some cases they can overlap, which should not happen (in this case "ab" and "bc").

Therefore, another condition in the if statement must be made to prevent overlapping substrings. The total length of the non-overlapping substrings should be bigger than or equal to the pattern string without the asterisk.

Thus, the statement would be:

```<code>if ((tempLen >= asterPos) && (tempLen >= patternLen - asterPos - 1) && (tempLen >= patternLen - 1)) {
        verdict = (temp.substr(0, asterPos) == pattern.substr(0, asterPos)) && (temp.substr(tempLen - patternLen + asterPos + 1) == pattern.substr(asterPos + 1));
} else {
        verdict = false;
}
</code>```

Body:
You are given a string pattern which consists of characters 'a' to 'z' and exactly one asterisk character ('*') behaving as a wildcard. The wildcard matches zero or more arbitrary characters. The wildcard might be at the front, back, or in the middle of the pattern string.

Given an integer N, followed by N strings. Your task is to find which of these strings match with the pattern.

Example input:

pl*
3
play
pluck
prune

Example output:

play
pluck

Here's my code. The approach is to find where the position of the asterisk in the pattern string, and compare the substring of pattern before the asterisk with the first # characters of the testing string, and also the substring of pattern after the asterisk with the last # characters of the testing string.

It runs almost perfectly, but there is one test case that outputs the wrong answer. I tried to come up with some random cases but it all work as intended. I don't know the case that makes my code go wrong yet. Can you help me find those cases or point out some mistakes from my code? Thanks

#include <iostream>
#include <string>
using namespace std;

int main(){
    string pattern;
    cin >> pattern;
    int patternLen = pattern.length();
    int asterPos = pattern.find('*');

    int n;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        string temp;
        cin >> temp;
        int tempLen = temp.length();

        bool verdict;
        if (tempLen >= patternLen - asterPos - 1) {
            verdict = (temp.substr(0, asterPos) == pattern.substr(0, asterPos)) && (temp.substr(tempLen - patternLen + asterPos + 1) == pattern.substr(asterPos + 1));
        } else {
            verdict = false;
        }

        if (verdict) {
            cout << temp << '\n';
        }
    }
    return 0;
}

Body:
I found out a counter-case:

ab*ca
1
abc

Which should not match, but it did.

The mistake underlies in the substrings of the matching string, because in some cases they can overlap, which should not happen (in this case "ab" and "bc").

Therefore, another condition in the if statement must be made to prevent overlapping substrings. The total length of the non-overlapping substrings should be bigger than or equal to the pattern string without the asterisk.

Thus, the statement would be:

if ((tempLen >= asterPos) && (tempLen >= patternLen - asterPos - 1) && (tempLen >= patternLen - 1)) {
        verdict = (temp.substr(0, asterPos) == pattern.substr(0, asterPos)) && (temp.substr(tempLen - patternLen + asterPos + 1) == pattern.substr(asterPos + 1));
} else {
        verdict = false;
}


问:
Read the first two lines of each document in a corpus in R
I am having trouble figuring out how to read the first two lines of each document in a corpus in R. The first two lines contain headlines from news articles that I want to analyze. I want to search the headlines (not the rest of each text) for the word 'abortion.'

Here is my code for creating the corpus:

```<code>myCorp <- corpus(readtext(file='~/R/win-library/3.3/quanteda/Abortion/1972/*'))
</code>```

I have tried using readLines in a for loop:

```<code>for (mycorp in myCorp) {
titles <- readLines(mycorp, n = 2)
write.table(mycorp, "1972_text_P.txt", sep="\n\n", append=TRUE)
write.table(titles, "1972_text_P.txt", append=TRUE)
}
</code>```

Error in readLines(mycorp, n = 2) : 'con' is not a connection

I have intentionally not created a DFM because I want to keep the 465 files as single documents in the corpus. How can I get the headlines from the article textx? Or, ideally, how would I search only the first two lines of each document for a keyword (abortion) and create a file that contains only those headlines with the keyword in them? Thanks for any and all help with this.

答:
I'd suggest two options:

regex substitution to keep just first 2 lines

If your first two lines contain what you need, then just extract them using a regular expression that plucks out the first two lines.  This is faster than the loop.

@rconradin's solution works but as you will note in ?corpus, we strongly discourage directly accessing a corpus object's internals (since it will change soon).  Not looping is also faster.

```<code># test corpus for demonstration
testcorp <- corpus(c(
    d1 = "This is doc1, line 1.\nDoc1, Line 2.\nLine 3 of doc1.",
    d2 = "This is doc2, line 1.\nDoc2, Line 2.\nLine 3 of doc2."
))

summary(testcorp)
## Corpus consisting of 2 documents.
##
##  Text Types Tokens Sentences
##    d1    12     17         3
##    d2    12     17         3
</code>```

Now overwrite the texts with just the first two lines.  (This also discards the second newline, which if you wish to keep, just move it to the first capture group.)

```<code>texts(testcorp) <-
    stringi::stri_replace_all_regex(texts(testcorp), "(.*\\n.*)(\\n).*", "$1")
## Corpus consisting of 2 documents.
##
##  Text Types Tokens Sentences
##    d1    10     12         2
##    d2    10     12         2

texts(testcorp)
##                                     d1                                     d2
## "This is doc1, line 1.\nDoc1, Line 2." "This is doc2, line 1.\nDoc2, Line 2."
</code>```

using corpus_segment():

Another solution would have been to use corpus_segment():

```<code>testcorp2 <- corpus_segment(testcorp, what = "other", delimiter = "\\n",
                            valuetype = "regex")
summary(testcorp2)
## Corpus consisting of 6 documents.
##
##  Text Types Tokens Sentences
##  d1.1     7      7         1
##  d1.2     5      5         1
##  d1.3     5      5         1
##  d2.1     7      7         1
##  d2.2     5      5         1
##  d2.3     5      5         1

# get the serial number from each docname
docvars(testcorp2, "sentenceno") <-
    as.integer(gsub(".*\\.(\\d+)", "\\1", docnames(testcorp2)))
summary(testcorp2)
## Corpus consisting of 6 documents.
##
##  Text Types Tokens Sentences sentenceno
##  d1.1     7      7         1          1
##  d1.2     5      5         1          2
##  d1.3     5      5         1          3
##  d2.1     7      7         1          1
##  d2.2     5      5         1          2
##  d2.3     5      5         1          3

testcorp3 <- corpus_subset(testcorp2, sentenceno <= 2)
texts(testcorp3)
##                    d1.1                    d1.2                    d2.1                    d2.2
## "This is doc1, line 1."         "Doc1, Line 2." "This is doc2, line 1."         "Doc2, Line 2."
</code>```

Body:
I am having trouble figuring out how to read the first two lines of each document in a corpus in R. The first two lines contain headlines from news articles that I want to analyze. I want to search the headlines (not the rest of each text) for the word 'abortion.'

Here is my code for creating the corpus:

myCorp <- corpus(readtext(file='~/R/win-library/3.3/quanteda/Abortion/1972/*'))

I have tried using readLines in a for loop:

for (mycorp in myCorp) {
titles <- readLines(mycorp, n = 2)
write.table(mycorp, "1972_text_P.txt", sep="\n\n", append=TRUE)
write.table(titles, "1972_text_P.txt", append=TRUE)
}

Error in readLines(mycorp, n = 2) : 'con' is not a connection

I have intentionally not created a DFM because I want to keep the 465 files as single documents in the corpus. How can I get the headlines from the article textx? Or, ideally, how would I search only the first two lines of each document for a keyword (abortion) and create a file that contains only those headlines with the keyword in them? Thanks for any and all help with this.

Body:
I'd suggest two options:

regex substitution to keep just first 2 lines

If your first two lines contain what you need, then just extract them using a regular expression that plucks out the first two lines.  This is faster than the loop.

@rconradin's solution works but as you will note in ?corpus, we strongly discourage directly accessing a corpus object's internals (since it will change soon).  Not looping is also faster.

# test corpus for demonstration
testcorp <- corpus(c(
    d1 = "This is doc1, line 1.\nDoc1, Line 2.\nLine 3 of doc1.",
    d2 = "This is doc2, line 1.\nDoc2, Line 2.\nLine 3 of doc2."
))

summary(testcorp)
## Corpus consisting of 2 documents.
##
##  Text Types Tokens Sentences
##    d1    12     17         3
##    d2    12     17         3

Now overwrite the texts with just the first two lines.  (This also discards the second newline, which if you wish to keep, just move it to the first capture group.)

texts(testcorp) <-
    stringi::stri_replace_all_regex(texts(testcorp), "(.*\\n.*)(\\n).*", "$1")
## Corpus consisting of 2 documents.
##
##  Text Types Tokens Sentences
##    d1    10     12         2
##    d2    10     12         2

texts(testcorp)
##                                     d1                                     d2
## "This is doc1, line 1.\nDoc1, Line 2." "This is doc2, line 1.\nDoc2, Line 2."

using corpus_segment():

Another solution would have been to use corpus_segment():

testcorp2 <- corpus_segment(testcorp, what = "other", delimiter = "\\n",
                            valuetype = "regex")
summary(testcorp2)
## Corpus consisting of 6 documents.
##
##  Text Types Tokens Sentences
##  d1.1     7      7         1
##  d1.2     5      5         1
##  d1.3     5      5         1
##  d2.1     7      7         1
##  d2.2     5      5         1
##  d2.3     5      5         1

# get the serial number from each docname
docvars(testcorp2, "sentenceno") <-
    as.integer(gsub(".*\\.(\\d+)", "\\1", docnames(testcorp2)))
summary(testcorp2)
## Corpus consisting of 6 documents.
##
##  Text Types Tokens Sentences sentenceno
##  d1.1     7      7         1          1
##  d1.2     5      5         1          2
##  d1.3     5      5         1          3
##  d2.1     7      7         1          1
##  d2.2     5      5         1          2
##  d2.3     5      5         1          3

testcorp3 <- corpus_subset(testcorp2, sentenceno <= 2)
texts(testcorp3)
##                    d1.1                    d1.2                    d2.1                    d2.2
## "This is doc1, line 1."         "Doc1, Line 2." "This is doc2, line 1."         "Doc2, Line 2."


问:
using unallocated memory without error?
Why does that work?

```<code>#include <iostream>
using namespace std;

int main() {
    float* tab[3];

    int i = 0;
    while(i < 3) {
        tab[i] = new float[3-i];
        i++;
    }

    cout << tab[2][7] << endl;
    tab[2][7] = 6.87;
    cout << tab[2][7] << endl;

    i = 0;
    while(i < 3)
        delete[] tab[i];
}
</code>```

while this one doesn't?

```<code>#include <iostream>
using namespace std;

int main() {
    float* tab = new float[3];

    cout << tab[7] << endl;
    tab[7] = 6.87;
    cout << tab[7] << endl;

    delete[] tab;
}
</code>```

I tried both programs on Win XP with MS VS 2008, both compiled without errors and the first one ran without any errors. The second made pop up some error window, however I can't remember it and can't reproduce (no access to Windows at the moment).

I tried them also on Linux (Kubuntu 10.10 with precompiled kernel package version 2.6.35.23.25) with g++ and both compile and run without any errors.

Why? Shouldn't there be any pop-ups with something like "Wrong access to unallocated memory"?

I know it should (and, luckily, does) compile without errors, but I thought it shouldn't run without them... And why the second example makes errors on Windows and not on Linux?

答:
Use of unallocated memory results in undefined behaviour.  You can have no expectations of what will happen when you do this even on the same system and compiler, let alone across different combinations of hardware and compiler.

The program might crash immediately, it might work for a while and then fail later, it might even appear to work perfectly.

Accessing memory you don't own is always a programming error, though.  Don't think of the appearance of correct operation as "it sometimes works", think of it as "I got really unlucky and my bug does not show up quickly".

Title: using unallocated memory without error?

Body:
Why does that work?

#include <iostream>
using namespace std;

int main() {
    float* tab[3];

    int i = 0;
    while(i < 3) {
        tab[i] = new float[3-i];
        i++;
    }

    cout << tab[2][7] << endl;
    tab[2][7] = 6.87;
    cout << tab[2][7] << endl;

    i = 0;
    while(i < 3)
        delete[] tab[i];
}

while this one doesn't?

#include <iostream>
using namespace std;

int main() {
    float* tab = new float[3];

    cout << tab[7] << endl;
    tab[7] = 6.87;
    cout << tab[7] << endl;

    delete[] tab;
}

I tried both programs on Win XP with MS VS 2008, both compiled without errors and the first one ran without any errors. The second made pop up some error window, however I can't remember it and can't reproduce (no access to Windows at the moment).

I tried them also on Linux (Kubuntu 10.10 with precompiled kernel package version 2.6.35.23.25) with g++ and both compile and run without any errors.

Why? Shouldn't there be any pop-ups with something like "Wrong access to unallocated memory"?

I know it should (and, luckily, does) compile without errors, but I thought it shouldn't run without them... And why the second example makes errors on Windows and not on Linux?


问:
spring rabbit amqp @RabbitListener configure min and max number of consumers
I am using spring amqp rabbit @RabbitListener annotation
 from : artifact spring-rabbit-1.7.1.RELEASE
I wonder if there is a way to configure for each queue the number of consumers ?
I have been digging in the documentation and found nothing yet , is there a way to configure in the related container for each queue the number of consumers ?
Thanks in advance. </p>

答:
Configure the concurrency via the container factory bean as shown in the documentation.

```<code>@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory());
    factory.setConcurrentConsumers(3);
    factory.setMaxConcurrentConsumers(10);
    return factory;
}
</code>```

If you are using Spring Boot, which creates the factory bean for you, you can configure them using properties.

If you want a fixed number of consumers, just omit the max.

If you want different settings for each listener, you need a different factory for each set of settings. You would then reference the particular container factory for a @RabbitListener in its containerFactory property.

Body:
Configure the concurrency via the container factory bean as shown in the documentation.

@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory());
    factory.setConcurrentConsumers(3);
    factory.setMaxConcurrentConsumers(10);
    return factory;
}

If you are using Spring Boot, which creates the factory bean for you, you can configure them using properties.

If you want a fixed number of consumers, just omit the max.

If you want different settings for each listener, you need a different factory for each set of settings. You would then reference the particular container factory for a @RabbitListener in its containerFactory property.


问:
How to start a session, and then retrieve the session variable?
First and foremost, I have looked throughout the site and haven't been able to find a solution that works for my program.

Saying this, I am trying to create an authentication page that starts a session, and will save a username from a login page as a session variable. Then, I want my thrid page to retrieve the username session variable.

This is my Form:

```<code><html>
<head>
<title>Form Test</title>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<h1 align="center">Log in with your username and</h1>
<form class="form-horizontal" method="POST" action="formauth.php">
 <div class="form-group">
          <div class="control-label col-sm-3">
            <label for="card">Username:</label>
          </div>
          <div class="col-sm-5">
            <input type="text" name="username" placeholder="enter username here">
          </div>
        </div>
        <div class="form-group">
 <div class="form-group">
          <div class="control-label col-sm-3">
            <label for="card">Password:</label>
          </div>
          <div class="col-sm-5">
            <input type="text" name="password" placeholder="enter password here">
          </div>
        </div>
        <div class="form-group">
          <div class="control-label col-sm-3">
 <div name="buttons" class="col-sm-offset-3">
          <button type="submit" class="btn btn-primary">Submit</button>
 </div>
</body>
</html>
</code>```

Here is my authentication page. For some reason, I can't get this to save the username that is input into the form as a session variable.

```<code><?php
  session_start();
  $_SESSION['username'] =$user_name;
  if (isset($_POST['username']) &&
      isset($_POST['password']))
  {
    $user = $_POST['username'];
    $pwd = $_POST['password'];
    require_once "login.php";
    $conn = new mysqli($hn, $un, $pwd, $db);
    if ($conn->connect_error) die($conn->connect_error);
    $query = "Select Password from Users where Username = '$user'";
    $result = $conn->query($query);
    if (!$result) {
        $result->close();
        $conn->close();
        header('Location: http://localhost/FormAuth/loginForm.html');

    }
    else {
        $rows = $result->num_rows;
        $result->data_seek(0);
        $p=$result->fetch_assoc()['password'];
        if ($p == $password) {
            header("Location: http://localhost/FormAuth/afterlogin.php");
        }
        else {
            $result->close();
            $conn->close();
            $result->close();
            $conn->close();
            header('Location: http://localhost/loginForm.html');
        }
    }
    $result->close();
    $conn->close();

  }
  else
  {
    $result->close();
    $conn->close();
    header('Location: http://localhost/loginForm.html');
  }
?>
</code>```

Now for my third page, I can't retrieve the username session variable.

```<code>session_start();
if (!isset($_SESSION['username'])) {
echo "Username is: ".$_user_name['username'] . "<br>";
echo "Test, I made it here!";
}else{
echo "You not logged in.";
}

?>
<html>
<head>
</head>
<body>
</body>
</html>
</code>```

This results in:

```<code>Username is:
Test, I made it here!
</code>```

答:
You need to first check whether the posted values are set or not.

```<code><?php
    session_start();
    if (isset($_POST['username'], $_POST['password'])){
      ...
</code>```

Then, only when the passwords match, set the session variable $_POST['username'] before redirecting.

```<code>    if ($p == $password) {
        $_SESSION['username'] =$user;
        header("Location: http://localhost/FormAuth/afterlogin.php");
    }
</code>```

Then you can access your set session variable $_SESSION['username'] on any page provided you use session_start();. Take the third page for instance,

```<code>    session_start();
    if(isset($_POST['username']) && !empty($_POST['username'])){
        // proceed to account dashboard / your required page
    } else {
        // redirect to login page / index
    }
</code>```

Body:
First and foremost, I have looked throughout the site and haven't been able to find a solution that works for my program.

Saying this, I am trying to create an authentication page that starts a session, and will save a username from a login page as a session variable. Then, I want my thrid page to retrieve the username session variable.

This is my Form:

<title>Form Test</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Log in with your username and

<form class="form-horizontal" method="POST" action="formauth.php">

            Username:

            <input type="text" name="username" placeholder="enter username here">

            Password:

            <input type="text" name="password" placeholder="enter password here">

          <button type="submit" class="btn btn-primary">Submit</button>

Here is my authentication page. For some reason, I can't get this to save the username that is input into the form as a session variable.

<?php
  session_start();
  $_SESSION['username'] =$user_name;
  if (isset($_POST['username']) &&
      isset($_POST['password']))
  {
    $user = $_POST['username'];
    $pwd = $_POST['password'];
    require_once "login.php";
    $conn = new mysqli($hn, $un, $pwd, $db);
    if ($conn->connect_error) die($conn->connect_error);
    $query = "Select Password from Users where Username = '$user'";
    $result = $conn->query($query);
    if (!$result) {
        $result->close();
        $conn->close();
        header('Location: http://localhost/FormAuth/loginForm.html');

    }
    else {
        $rows = $result->num_rows;
        $result->data_seek(0);
        $p=$result->fetch_assoc()['password'];
        if ($p == $password) {
            header("Location: http://localhost/FormAuth/afterlogin.php");
        }
        else {
            $result->close();
            $conn->close();
            $result->close();
            $conn->close();
            header('Location: http://localhost/loginForm.html');
        }
    }
    $result->close();
    $conn->close();

  }
  else
  {
    $result->close();
    $conn->close();
    header('Location: http://localhost/loginForm.html');
  }
?>

Now for my third page, I can't retrieve the username session variable.

session_start();
if (!isset($_SESSION['username'])) {
echo "Username is: ".$_user_name['username'] . "
";
echo "Test, I made it here!";
}else{
echo "You not logged in.";
}

?>

This results in:

Username is:
Test, I made it here!

Body:
You need to first check whether the posted values are set or not.

<?php
    session_start();
    if (isset($_POST['username'], $_POST['password'])){
      ...

Then, only when the passwords match, set the session variable $_POST['username'] before redirecting.

    if ($p == $password) {
        $_SESSION['username'] =$user;
        header("Location: http://localhost/FormAuth/afterlogin.php");
    }

Then you can access your set session variable $_SESSION['username'] on any page provided you use session_start();. Take the third page for instance,

    session_start();
    if(isset($_POST['username']) && !empty($_POST['username'])){
        // proceed to account dashboard / your required page
    } else {
        // redirect to login page / index
    }


问:
Form Request Validation returns empty error messages – Laravel 5.3
I've got a problem with error messages during validation in Laravel. I've got my custom Request:

```<code>class CreateCv extends Request
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required',
            'surname' => 'required',
        ];
    }

    public function messages()
    {
        return [
            'name.required' => 'Fill the name!',
            'surname.required'  => 'Fill the surname!',
        ];
    }
}
</code>```

and then I've got a controller with create method:

```<code>class CvController extends Controller
{

    public function create(Requests\CreateCv $request) {
        return response()->json(['ok' => true], 200);
    }
}
</code>```

If everything is filled up, then it returns json response "ok" : true correctly. But when something is missing, then it returns empty msg: "msg": "". What causes this problem?

EDIT
here's the handler.php file

```<code>class Handler extends ExceptionHandler
{
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        //ValidationException::class,
    ];

    public function report(Exception $e)
    {
        parent::report($e);
    }

    public function render($request, Exception $e)
    {
        return $e;
        //return response()->json(['msg' => $e->getMessage()], 422);
        //return parent::render($request, $e);
    }
}
</code>```

答:
Can you try in your CreateCv class to extend Illuminate\Foundation\Http\FormRequest.

I encountered this recently during creating an API for a web application, every time I test the validation fields without the Accept application/json header, the errors object (I customized the ValidationException to return an errors object) is always empty.

Body:
I've got a problem with error messages during validation in Laravel. I've got my custom Request:

class CreateCv extends Request
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required',
            'surname' => 'required',
        ];
    }

    public function messages()
    {
        return [
            'name.required' => 'Fill the name!',
            'surname.required'  => 'Fill the surname!',
        ];
    }
}

and then I've got a controller with create method:

class CvController extends Controller
{

    public function create(Requests\CreateCv $request) {
        return response()->json(['ok' => true], 200);
    }
}

If everything is filled up, then it returns json response "ok" : true correctly. But when something is missing, then it returns empty msg: "msg": "". What causes this problem?

EDIT
here's the handler.php file

class Handler extends ExceptionHandler
{
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        //ValidationException::class,
    ];

    public function report(Exception $e)
    {
        parent::report($e);
    }

    public function render($request, Exception $e)
    {
        return $e;
        //return response()->json(['msg' => $e->getMessage()], 422);
        //return parent::render($request, $e);
    }
}


问:
xlrd import issue with Python 2.7
I have an assignment to read excel data in Python. I have Python 2.7 installed. I tried installing xlrd0.8.0 with the following commands in Windows.

```<code>C:\Python27\xlrd-0.8.0>python setup.py build
running build
running build_py
creating build
creating build\lib
creating build\lib\xlrd
copying xlrd\biffh.py -> build\lib\xlrd
....

C:\Python27\xlrd-0.8.0>python setup.py install
running install
running build
running build_py
running build_scripts
running install_lib
running install_scripts
running install_egg_info
Writing C:\Python27\Lib\site-packages\xlrd-0.8.0-py2.7.egg-info
</code>```

I don't get any error message while installing. I also see xlrd-0.8.0 folder in site-packages in /lib folder...

But when I try to import it, Python is not able to recognize it...

```<code>>>> import xlrd
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import xlrd
ImportError: No module named xlrd
</code>```

Can you suggest how to find the issue?

答:
For me, running python in spyder on a mac, it didn't work even after I installed xlrd using pip, because it was installed to a different location than the one spyder was using. To fix this, I first found where xlrd was installed to:

```<code>$pip install xlrd
Requirement already satisfied: xlrd in /usr/local/lib/python2.7/site-packages
</code>```

Then copied the xlrd folder from there into where Spyder could access it:

```<code>$cd /Applications/Spyder.app/Contents/Resources/lib/python2.7/
$cp -r /usr/local/lib/python2.7/site-packages/xlrd.
</code>```

Then updated the module within spyder, but I'm not sure whether this was necessary. Restarting Spyder might have also worked after making those changes.

Title: xlrd import issue with Python 2.7

Body:
I have an assignment to read excel data in Python. I have Python 2.7 installed. I tried installing xlrd0.8.0 with the following commands in Windows.

C:\Python27\xlrd-0.8.0>python setup.py build
running build
running build_py
creating build
creating build\lib
creating build\lib\xlrd
copying xlrd\biffh.py -> build\lib\xlrd
....

C:\Python27\xlrd-0.8.0>python setup.py install
running install
running build
running build_py
running build_scripts
running install_lib
running install_scripts
running install_egg_info
Writing C:\Python27\Lib\site-packages\xlrd-0.8.0-py2.7.egg-info

I don't get any error message while installing. I also see xlrd-0.8.0 folder in site-packages in /lib folder...

But when I try to import it, Python is not able to recognize it...

>>> import xlrd
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import xlrd
ImportError: No module named xlrd

Can you suggest how to find the issue?

Body:
For me, running python in spyder on a mac, it didn't work even after I installed xlrd using pip, because it was installed to a different location than the one spyder was using. To fix this, I first found where xlrd was installed to:

$pip install xlrd
Requirement already satisfied: xlrd in /usr/local/lib/python2.7/site-packages

Then copied the xlrd folder from there into where Spyder could access it:

$cd /Applications/Spyder.app/Contents/Resources/lib/python2.7/
$cp -r /usr/local/lib/python2.7/site-packages/xlrd.

Then updated the module within spyder, but I'm not sure whether this was necessary. Restarting Spyder might have also worked after making those changes.


问:
Drawable.createFromStream() returns null
In my Android Studio project, I created a custom folder called assets, which in turn contains another folder called flags, which in turn contains a lot of XML files representing SVG images.
Whenever I try to load such XML files and create Drawables from them via the function Drawable.createFromStream(), I obtain a null.

Here is the code:

```<code>AssetManager am = getApplicationContext().getAssets();
String[] files = new String[0];
try
{
  files = am.list("flags");
}
catch (IOException e)
{
  e.printStackTrace();
}
// At this point, variable 'files' correctly contains all the names of my XML files
ArrayList<Drawable> drawables = new ArrayList<>();
for (String file : files)
{
  Drawable d = null;
  try
  {
    d = Drawable.createFromStream(am.open("flags/" + file), null);
  }
  catch (IOException e)
  {
    Log.i("EX2", "Second exception: " + file + " not found");
    e.printStackTrace();
  }
  drawables.add(d);
  if (d == null) // This message is always printed, but no exception occurs
    Log.i("FLAG", "Null drawable");
}
</code>```

As you can see fromt he code above, the message Null drawable is always printed even if the XML file is found (in fact, no exception occurs).

答:
which in turn contains a lot of XML files representing SVG images

Android has no ability to use SVG files as drawables, whether as assets or anything else. Try a third-party SVG library instead of Drawable.createFromStream().

In your case, you do not have SVG files, but rather vector drawables created from those SVG files. Apparently, Drawable.createFromStream() does not support those. Or, perhaps you are testing on older devices; Drawable.createFromStream() definitely does not support vector drawables on Android 4.4 and older devices. In your case, just store the vector drawables as drawables, not assets.

Body:
In my Android Studio project, I created a custom folder called assets, which in turn contains another folder called flags, which in turn contains a lot of XML files representing SVG images.
Whenever I try to load such XML files and create Drawables from them via the function Drawable.createFromStream(), I obtain a null.

Here is the code:

AssetManager am = getApplicationContext().getAssets();
String[] files = new String[0];
try
{
  files = am.list("flags");
}
catch (IOException e)
{
  e.printStackTrace();
}
// At this point, variable 'files' correctly contains all the names of my XML files
ArrayList<Drawable> drawables = new ArrayList<>();
for (String file : files)
{
  Drawable d = null;
  try
  {
    d = Drawable.createFromStream(am.open("flags/" + file), null);
  }
  catch (IOException e)
  {
    Log.i("EX2", "Second exception: " + file + " not found");
    e.printStackTrace();
  }
  drawables.add(d);
  if (d == null) // This message is always printed, but no exception occurs
    Log.i("FLAG", "Null drawable");
}

As you can see fromt he code above, the message Null drawable is always printed even if the XML file is found (in fact, no exception occurs).


问:
Transferring Value through session in JSP
I have 4 jsp forms name Sample1.jsp,Sample2.jsp,Sample3.jsp,Sample4.jsp
I want to transfer value from one page to another through Session
and I used this method

Sample1.jsp

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form action="sample2.jsp" method="post">
            <h1>Page1</h1>
            <input type="text" name="name">
            <input type="submit" value="Go">
        </form>
    </body>
</html>
</code>```

Sample2.jsp
Got the value name from Sample1.jsp and redirected to sample3.jsp

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>page2</h1>
        <%
            String name = request.getParameter("name");
            session.setAttribute("name",name);
            out.println(name);
            //response.sendRedirect("sample3.jsp");
            request.getRequestDispatcher("sample3.jsp").forward(request, response);
        %>
    </body>
</html>
</code>```

Sample3.jsp
Got the value name from Sample2.jsp and not displaying the anchor tag hyperlink in Sample3.jsp and directly jump to Sample4.jsp

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Page 3</h1>
        <%
            String lname = (String)session.getAttribute("name");
            out.println(lname);
            //session.setAttribute("lname",lname);
        %>

        <a href="<%request.getRequestDispatcher("sample4.jsp").forward(request, response);%>" value=""><%out.println(lname);%> </a>
    </body>
</html>
</code>```

The Code directly jump to Sample4.jsp without allowing the user to click the hyperlink in anchor tags in Form Sample3.jsp. Wanted to stop the page and allow the user to Click and move forward.

Sample4.jsp

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>page 4</h1>
        <%String name =(String)session.getAttribute("name");
        out.println(name);%>

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

答:
The problem in your  ..... tag in which you forward your request into sample2.jsp and in sample3.jsp page you again forward the request so ultimately, request the reached to sample4.jsp.
Read more about from here href="http://www.javatpoint.com/requestdispatcher-in-servlet" rel="nofollow noreferrer">RequestDispatcher.

The solution of this problem :

try this

Web.xml :

```<code><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
   <welcome-file>sample1.jsp</welcome-file>
</welcome-file-list>

</web-app>
</code>```

Sample1.jsp

```<code><body>
    <form action="sample2.jsp" method="post">
        <h1>Page1</h1>
        <input type="text" name="name">
        <input type="submit" value="Go">
    </form>
</body>
</code>```

Sample2.jsp

```<code><body>
    <h1>page2</h1>
    <%
        String name = request.getParameter("name");
        session.setAttribute("name",name);
        //out.println(name);
        //response.sendRedirect("sample3.jsp");

    %>
    <a href="sample3.jsp"><%out.println(name);%></a>

</body>
</code>```

Sample3.jsp

```<code><body>
    <h1>Page 3</h1>
    <%
        String lname = (String)session.getAttribute("name");
        //out.println(lname+"\n");
        //session.setAttribute("lname",lname);
    %>

    <a href="sample4.jsp"><%out.println(lname);%></a>
</body>
</code>```

Sample4.jsp

```<code><body>
    <h1>page 4</h1>
    <%String name =(String)session.getAttribute("name");
    out.println(name);%>

</body>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 4 jsp forms name Sample1.jsp,Sample2.jsp,Sample3.jsp,Sample4.jsp
I want to transfer value from one page to another through Session
and I used this method

Sample1.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <form action="sample2.jsp" method="post">

Page1

            <input type="text" name="name">
            <input type="submit" value="Go">
        </form>

Sample2.jsp
Got the value name from Sample1.jsp and redirected to sample3.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

page2

        <%
            String name = request.getParameter("name");
            session.setAttribute("name",name);
            out.println(name);
            //response.sendRedirect("sample3.jsp");
            request.getRequestDispatcher("sample3.jsp").forward(request, response);
        %>

Sample3.jsp
Got the value name from Sample2.jsp and not displaying the anchor tag hyperlink in Sample3.jsp and directly jump to Sample4.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

Page 3

        <%
            String lname = (String)session.getAttribute("name");
            out.println(lname);
            //session.setAttribute("lname",lname);
        %>

        <a href="<%request.getRequestDispatcher("sample4.jsp").forward(request, response);%>" value=""><%out.println(lname);%>

The Code directly jump to Sample4.jsp without allowing the user to click the hyperlink in anchor tags in Form Sample3.jsp. Wanted to stop the page and allow the user to Click and move forward.

Sample4.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

page 4

        <%String name =(String)session.getAttribute("name");
        out.println(name);%>

Body:
The problem in your <a href ..... tag in which you forward your request into sample2.jsp and in sample3.jsp page you again forward the request so ultimately, request the reached to sample4.jsp.
Read more about from here RequestDispatcher.

The solution of this problem :

try this

Web.xml :

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
   <welcome-file>sample1.jsp</welcome-file>
</welcome-file-list>

</web-app>

Sample1.jsp

<body>
    <form action="sample2.jsp" method="post">
        <h1>Page1</h1>
        <input type="text" name="name">
        <input type="submit" value="Go">
    </form>
</body>

Sample2.jsp

<body>
    <h1>page2</h1>
    <%
        String name = request.getParameter("name");
        session.setAttribute("name",name);
        //out.println(name);
        //response.sendRedirect("sample3.jsp");

    %>
    <a href="sample3.jsp"><%out.println(name);%></a>

</body>

Sample3.jsp

<body>
    <h1>Page 3</h1>
    <%
        String lname = (String)session.getAttribute("name");
        //out.println(lname+"\n");
        //session.setAttribute("lname",lname);
    %>

    <a href="sample4.jsp"><%out.println(lname);%></a>
</body>

Sample4.jsp

<body>
    <h1>page 4</h1>
    <%String name =(String)session.getAttribute("name");
    out.println(name);%>

</body>


问:
Use embedded JDK
I have just installed the latest version of Android Studio.
I installed it before JDK on the mac.
So it seems I did things in the wrong order.

When I look at my project strucutre, I see that 'use embedded JDK' is recommended. Does it work well in this case?
Should I reinstall Android Studio now JDK is installed?

Thanks a lot for your answers!

答:
Should I reinstall Android Studio now JDK is installed?

Why would you do this?

In the same location that recommends the embedded JDK, you can simply change that to the installed one.

Title: Use embedded JDK


问:
How / Where can I see all TSLint errors for current project in WebStorm?
May be I am missing something but I have not found a dedicated place in WebStorm where I can see (and navigate) all errors reported by TSLint.

In the best case I can find the errors while opening a file and pressing F2 (to go to Next Highlighted Error) which not always working as well.

PS. There is a dedicated TypeScript Pane/l in WebStorm but it doesn't show any TSLint errors, neither these reported in Event Log Pane/l.

答:
Select npm tab  from the bottom left side.

Run linting script (you must have it in package.json).
See screenshot below for example:
List of tslint errors/warnings


答:
You need to set username in session after check username and password in your database.

```<code><?php
  session_start();

  if (isset($_POST['username']) &&
      isset($_POST['password']))
  {
    $user = $_POST['username'];
    $pwd = $_POST['password'];
    require_once "login.php";
    $conn = new mysqli($hn, $un, $pwd, $db);
    if ($conn->connect_error) die($conn->connect_error);
    $query = "Select Password from Users where Username = '$user'";
    $result = $conn->query($query);
    if (!$result) {
        $result->close();
        $conn->close();
        header('Location: http://localhost/FormAuth/loginForm.html');

    }
    else {
        $rows = $result->num_rows;
        $result->data_seek(0);
        $p=$result->fetch_assoc()['password'];

        if ($p == $pwd) { // use $pwd instead of $password
            $_SESSION['username'] = $user; // set username here
            header("Location: http://localhost/FormAuth/afterlogin.php");
        }
        else {
            $result->close();
            $conn->close();
            $result->close();
            $conn->close();
            header('Location: http://localhost/loginForm.html');
        }
    }
    $result->close();
    $conn->close();

  }
  else
  {
    $result->close();
    $conn->close();
    header('Location: http://localhost/loginForm.html');
  }
?>
</code>```

And In your third part, check if your username is set in session before try to display it:

```<code>if (isset($_SESSION['username'])) {
    echo "Username is: ".$_SESSION['username'] . "<br>";
}
</code>```

Title: How to start a session, and then retrieve the session variable?

Body:
You need to set username in session after check username and password in your database.

<?php
  session_start();

  if (isset($_POST['username']) &&
      isset($_POST['password']))
  {
    $user = $_POST['username'];
    $pwd = $_POST['password'];
    require_once "login.php";
    $conn = new mysqli($hn, $un, $pwd, $db);
    if ($conn->connect_error) die($conn->connect_error);
    $query = "Select Password from Users where Username = '$user'";
    $result = $conn->query($query);
    if (!$result) {
        $result->close();
        $conn->close();
        header('Location: http://localhost/FormAuth/loginForm.html');

    }
    else {
        $rows = $result->num_rows;
        $result->data_seek(0);
        $p=$result->fetch_assoc()['password'];

        if ($p == $pwd) { // use $pwd instead of $password
            $_SESSION['username'] = $user; // set username here
            header("Location: http://localhost/FormAuth/afterlogin.php");
        }
        else {
            $result->close();
            $conn->close();
            $result->close();
            $conn->close();
            header('Location: http://localhost/loginForm.html');
        }
    }
    $result->close();
    $conn->close();

  }
  else
  {
    $result->close();
    $conn->close();
    header('Location: http://localhost/loginForm.html');
  }
?>

And In your third part, check if your username is set in session before try to display it:

if (isset($_SESSION['username'])) {
    echo "Username is: ".$_SESSION['username'] . "<br>";
}


问:
TYPO3 gridelements not selectable
I'm running a TYPO3 webseite with TYPO3 version 7.6.16 and the extensions gridelements 7.0.5. In backend the selection for gridelements is empty ... what could be the reason?

also missing is this tap in new page item wizard

答:
Did you follow the steps in manual?
https://docs.typo3.org/typo3cms/extensions/gridelements/Chapters/Installation/Index.html

Include static template

Create some CE backend layouts

Create new Grid Elements

Title: TYPO3 gridelements not selectable


问:
How to access URL segment(s) in ExpressJS
So let's say we have the following url:

```<code>http://example.com/shops/map/search
</code>```

I want to access the second segment (map) and check its value.
How can I achieve this in Express? Thanks in advance!

答:
You can use a route parameters with a constant set of values.

Express uses path-to-regexp to parse the strings you provide for routes. That package permits providing a custom pattern with a parameter to limit the values that can be matched.

```<code>app.get('/shops/:kind(list|map)/search', searchShops);
</code>```

The contents of the parenthesis, (...), are a partial RegExp pattern, in this case equivalent to:

```<code>/(?:list|map)/
# within a non-capturing group, match an alternative of either "list" or "map" literally
</code>```

Then, within searchShops, you can determine which value was given with req.params:

```<code>function searchShops(req, res) {
    console.log(req.params.kind); // 'list' or 'map'
    // ...
}
</code>```

Alternatively, you can leave the parameter open, checking the value within the handler, and invoke next('route') when the value isn't acceptable:

```<code>app.get('/shops/:kind/search', searchShops);

var searchKinds = ['list', 'map'];

function searchShops(req, res, next) {
    if (!searchKinds.includes(req.params.kind)) return next('route');

    // ...
}
</code>```

Body:
So let's say we have the following url:

http://example.com/shops/map/search

I want to access the second segment (map) and check its value.
How can I achieve this in Express? Thanks in advance!

Body:
You can use a route parameters with a constant set of values.

Express uses path-to-regexp to parse the strings you provide for routes. That package permits providing a custom pattern with a parameter to limit the values that can be matched.

app.get('/shops/:kind(list|map)/search', searchShops);

The contents of the parenthesis, (...), are a partial RegExp pattern, in this case equivalent to:

/(?:list|map)/
# within a non-capturing group, match an alternative of either "list" or "map" literally

Then, within searchShops, you can determine which value was given with req.params:

function searchShops(req, res) {
    console.log(req.params.kind); // 'list' or 'map'
    // ...
}

Alternatively, you can leave the parameter open, checking the value within the handler, and invoke next('route') when the value isn't acceptable:

app.get('/shops/:kind/search', searchShops);

var searchKinds = ['list', 'map'];

function searchShops(req, res, next) {
    if (!searchKinds.includes(req.params.kind)) return next('route');

    // ...
}


问:
Why does my form not appear when connecting to a socket in the Load event?
The form from this code does not appear. How can I get it to show? Through the console, everything works.</p>

```<code> void Form1_Load(object sender, EventArgs e)
        {
            String host = Dns.GetHostName();//name kompa
            //ip pc
            IPAddress ip = Dns.GetHostByName(host).AddressList[0];
            const int port = 2222;
            label1.Text = host;
            label2.Text = "Сервер запущен на " + ip.ToString() + ":" + port.ToString();
            server.serversocket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            server.serversocket.Bind(new IPEndPoint(ip, port));
            server.serversocket.Listen(100);

            //ошибочка в цикле
            while (server.work)
            {
                MessageBox.Show("dsff");
                Socket handle = server.serversocket.Accept();
                richTextBox1.AppendText("новое подключение" + handle.RemoteEndPoint.ToString());
                new user(handle);

            }
</code>```

答:
As Hans Passant said, you are blocking the GUI thread with a while loop. That will just not do. Events must return asap and can never run indefinitely. And this Form_Load can not return until the server stops working.

It is very common mistake and basically the reason we all went crazy for multitasking and multithreading this century. You can't even do a word processor without it anymore.

Body:
The form from this code does not appear. How can I get it to show? Through the console, everything works.

 void Form1_Load(object sender, EventArgs e)
        {
            String host = Dns.GetHostName();//name kompa
            //ip pc
            IPAddress ip = Dns.GetHostByName(host).AddressList[0];
            const int port = 2222;
            label1.Text = host;
            label2.Text = "Сервер запущен на " + ip.ToString() + ":" + port.ToString();
            server.serversocket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            server.serversocket.Bind(new IPEndPoint(ip, port));
            server.serversocket.Listen(100);

            //ошибочка в цикле
            while (server.work)
            {
                MessageBox.Show("dsff");
                Socket handle = server.serversocket.Accept();
                richTextBox1.AppendText("новое подключение" + handle.RemoteEndPoint.ToString());
                new user(handle);

            }


问:
Phpmailer,SMTP,Gmail seetings and connection
I'm doing a project which sends mail. I have downloaded phpmailer.
I'm using SMTP and all code for connecting to Gmail was very fine. And also i turned Gmail 2step verification.and allowed low secured apps. I'm still getting "failed to connect"
When i specified ssl the error is on line 294 in PHPMailerAutoload.php which referring socket parameters.
 I hope anyone can help me with this connection problem and if any Gmail settings needed.</p>

答:
actually im using PHPMailer to send mails.and downloaded everything neede for it.
 Everytime when i execute i got the faallowing error
"stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:" and so on.
Later on i found the solution in this link
https://github.com/PHPMailer/PHPMailer/issues/368

then i added this

$mail->smtpConnect(
    array(
        "ssl" => array(
            "verify_peer" => false,
            "verify_peer_name" => false,
            "allow_self_signed" => true

        )));

code in my mail sending php file and finally it worked..
hope you undestand... :)


问:
What does a zlib header look like?
In my project I need to know what a zlib header looks like. I've heard it's rather simple but I cannot find any description of the zlib header.

For example, does it contain a magic number?

答:
ZLIB/GZIP headers

```<code>Level | ZLIB  | GZIP
  1   | 78 01 | 1F 8B
  2   | 78 5E | 1F 8B
  3   | 78 5E | 1F 8B
  4   | 78 5E | 1F 8B
  5   | 78 5E | 1F 8B
  6   | 78 9C | 1F 8B
  7   | 78 DA | 1F 8B
  8   | 78 DA | 1F 8B
  9   | 78 DA | 1F 8B
</code>```

Deflate doesn't have common headers

Title: What does a zlib header look like?

Body:
ZLIB/GZIP headers

Level | ZLIB  | GZIP
  1   | 78 01 | 1F 8B
  2   | 78 5E | 1F 8B
  3   | 78 5E | 1F 8B
  4   | 78 5E | 1F 8B
  5   | 78 5E | 1F 8B
  6   | 78 9C | 1F 8B
  7   | 78 DA | 1F 8B
  8   | 78 DA | 1F 8B
  9   | 78 DA | 1F 8B

Deflate doesn't have common headers


问:
Windows batch: sleep
How do I get a Windows batch script to wait a few seconds?

sleep and wait don't seem to work (unrecognized command).

答:
You can try

```<code>ping -n XXX 127.0.0.1 >nul
</code>```

where XXX is the number of seconds to wait, plus one.

Title: Windows batch: sleep

Body:
You can try

ping -n XXX 127.0.0.1 >nul

where XXX is the number of seconds to wait, plus one.


问:
Can't use UIkit with Webpack
Simply set up a project with webpack. Just install uikit with
npm install uikit --save

in my main js file I use

```<code>import 'jquery';
import 'uikit/dist/js/uikit.js';
</code>```

In my main html file I write below code

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.12/css/uikit.min.css" />
</head>
<body>

<ul uk-accordion>
    <li class="uk-open">
        <h3 class="uk-accordion-title">Item 1</h3>
        <div class="uk-accordion-content">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
        </div>
    </li>
    <li>
        <h3 class="uk-accordion-title">Item 2</h3>
        <div class="uk-accordion-content">
            <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor reprehenderit.</p>
        </div>
    </li>
    <li>
        <h3 class="uk-accordion-title">Item 3</h3>
        <div class="uk-accordion-content">
            <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat proident.</p>
        </div>
    </li>
</ul>

<script src="dist/main.js"></script>
</body>
</html>
</code>```

White run the npm start everything works well.. But it says Uncaught ReferenceError: UIkit is not defined.

Error picture is here. click on me

What I missing.. thanks for the help.

答:
UIKit needs its stuff in the window object. So this might be the naive way to do it in main.js:

```<code>import Vue from 'vue';
import UIkit from 'uikit';
import Icons from 'uikit/dist/js/uikit-icons';
import jQuery from 'jquery';
import App from './App';

UIkit.use(Icons);

window.jQuery = jQuery;
window.UIkit = UIkit;

module.exports = new Vue({
  router,
  el: '#app',
  template: '<App/>',
  components: { App },
  store,
});
</code>```

Instead, a better solution seems to be to edit the Webpack config, as per this SO answer.  So, this works for me:

```<code>{
    test: require.resolve('jquery'),
    loader: 'expose-loader?jQuery!expose-loader?$'
  },
  {
    test: require.resolve('uikit'),
    loader: 'expose-loader?UIkit'
  }
</code>```

Title: Can't use UIkit with Webpack

Body:
Simply set up a project with webpack. Just install uikit with
npm install uikit --save

in my main js file I use

import 'jquery';
import 'uikit/dist/js/uikit.js';

In my main html file I write below code

<!doctype html>

    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.12/css/uikit.min.css" />

Item 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Item 2

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor reprehenderit.

Item 3

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat proident.

White run the npm start everything works well.. But it says Uncaught ReferenceError: UIkit is not defined.

Error picture is here. click on me

What I missing.. thanks for the help.

Body:
UIKit needs its stuff in the window object. So this might be the naive way to do it in main.js:

import Vue from 'vue';
import UIkit from 'uikit';
import Icons from 'uikit/dist/js/uikit-icons';
import jQuery from 'jquery';
import App from './App';

UIkit.use(Icons);

window.jQuery = jQuery;
window.UIkit = UIkit;

module.exports = new Vue({
  router,
  el: '#app',
  template: '<App/>',
  components: { App },
  store,
});

Instead, a better solution seems to be to edit the Webpack config, as per this SO answer.  So, this works for me:

{
    test: require.resolve('jquery'),
    loader: 'expose-loader?jQuery!expose-loader?$'
  },
  {
    test: require.resolve('uikit'),
    loader: 'expose-loader?UIkit'
  }


答:
you have to configure your express routes to accept url segments.

```<code>app.get('/shops/:type/search', function (req, res) {
    res.send(req.params)
})
</code>```

For a request like this
 http://example.com/shops/map/search

req.params will contain required URL segment.

```<code>Request URL: http://example.com/shops/map/search
req.params: { "type": "map" }
</code>```

Title: How to access URL segment(s) in ExpressJS

Body:
you have to configure your express routes to accept url segments.

app.get('/shops/:type/search', function (req, res) {
    res.send(req.params)
})

For a request like this
 http://example.com/shops/map/search

req.params will contain required URL segment.

Request URL: http://example.com/shops/map/search
req.params: { "type": "map" }