问:
How to register DRF router url patterns in django 2
My DRF routers specify a namespace so that I can reverse my urls:

urls.py:

```<code>router = DefaultRouter()
router.register('widget/', MyWidgetViewSet, base_name='widgets')
urlpatterns =+ [
    url(r'/path/to/API/', include(router.urls, namespace='widget-api'),
]
</code>```

Which, when upgrading to django 2, gives:

django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.

Django 2 now requires app_name if the namespace kwarg is specified when using include. What's the right way to specify app_name when the url patterns are constructed by a DRF url router? I don't think the documentation is up-to-date for django 2 on this subject.

答:
You need to put app_name = 'x' in your application's url.py file. This is a little buried in the documentation:

https://docs.djangoproject.com/en/2.0/topics/http/urls/#id5

For example, if in /project/project/urls.py you have:

```<code>path('', include('app.urls', namespace='app'))
</code>```

Then in the corresponding url file (in /project/app/urls.py) you need to specify the app_name parameter with:

```<code>app_name = 'app'  #the weird code
urlpatterns = [
    path('', views.index, name = 'index'), #this can be anything
]
</code>```

Body:
My DRF routers specify a namespace so that I can reverse my urls:

urls.py:

router = DefaultRouter()
router.register('widget/', MyWidgetViewSet, base_name='widgets')
urlpatterns =+ [
    url(r'/path/to/API/', include(router.urls, namespace='widget-api'),
]

Which, when upgrading to django 2, gives:

django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.

Django 2 now requires app_name if the namespace kwarg is specified when using include. What's the right way to specify app_name when the url patterns are constructed by a DRF url router? I don't think the documentation is up-to-date for django 2 on this subject.

Body:
You need to put app_name = 'x' in your application's url.py file. This is a little buried in the documentation:

https://docs.djangoproject.com/en/2.0/topics/http/urls/#id5

For example, if in /project/project/urls.py you have:

path('', include('app.urls', namespace='app'))

Then in the corresponding url file (in /project/app/urls.py) you need to specify the app_name parameter with:

app_name = 'app'  #the weird code
urlpatterns = [
    path('', views.index, name = 'index'), #this can be anything
]


来源: stackexchange

问:
Are progress/indeterminate dialog boxes added to the end of the UI thread? Do they require a second thread?
I have a simple dialog box.  When I click a button the dialog box is supposed to be shown, while a file save operation is performed, and then the dialog box is dismissed.  The problem I am having is the dialog box isn't shown until after the onClick event of the button finishes.

Taken from the Dialog developer doc:

The setup is simple. Most of the code
  needed to create a progress dialog is
  actually involved in the process that
  updates it. You might find that it's
  necessary to create a second thread in
  your application for this work and
  then report the progress back to the
  Activity's UI thread with a Handler
  object. If you're not familiar with
  using additional threads with a
  Handler, see the example Activity
  below that uses a second thread to
  increment a progress dialog managed by
  the Activity.

Why isn't the dialog shown until after the onClick method finishes?  Is the dialog added to the end of the UI thread?

Is the only way to do this to create a new thread and handler?  That's fairly bad wording in the developer doc if so.

Thanks all.

```<code>    Button send = (Button) findViewById(R.id.send);
    send.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(SAVING_DIALOG);
            //Do all the file saving operations
            ...
            ...
            dismissDialog(SAVING_DIALOG);
        }
    });
</code>```

Here is the dialog

```<code>@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case SAVING_DIALOG: {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage("Saving file...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            return dialog;
        }
    }
    return null;
}
</code>```

答:
For showing a progress dialog while something is processing, you have to process your code in another thread, otherwise your dialog freezes or wont be shown.

So I would use following method:

```<code>final Handler threadHandler = new Handler();

// in your onClick:
showDialog(SAVING_DIALOG);
new Thread(){
    public void run(){
        // new thread
        // Do all the file saving operations
        // ...
        threadHandler.post(new Runnable(){public void run(){
            // back in UI thread
            dismissDialog(SAVING_DIALOG);
        }});
    }
}.start();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a simple dialog box.  When I click a button the dialog box is supposed to be shown, while a file save operation is performed, and then the dialog box is dismissed.  The problem I am having is the dialog box isn't shown until after the onClick event of the button finishes.

Taken from the Dialog developer doc:

The setup is simple. Most of the code
  needed to create a progress dialog is
  actually involved in the process that
  updates it. You might find that it's
  necessary to create a second thread in
  your application for this work and
  then report the progress back to the
  Activity's UI thread with a Handler
  object. If you're not familiar with
  using additional threads with a
  Handler, see the example Activity
  below that uses a second thread to
  increment a progress dialog managed by
  the Activity.

Why isn't the dialog shown until after the onClick method finishes?  Is the dialog added to the end of the UI thread?

Is the only way to do this to create a new thread and handler?  That's fairly bad wording in the developer doc if so.

Thanks all.

    Button send = (Button) findViewById(R.id.send);
    send.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(SAVING_DIALOG);
            //Do all the file saving operations
            ...
            ...
            dismissDialog(SAVING_DIALOG);
        }
    });

Here is the dialog

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case SAVING_DIALOG: {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage("Saving file...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            return dialog;
        }
    }
    return null;
}

Body:
For showing a progress dialog while something is processing, you have to process your code in another thread, otherwise your dialog freezes or wont be shown.

So I would use following method:

final Handler threadHandler = new Handler();

// in your onClick:
showDialog(SAVING_DIALOG);
new Thread(){
    public void run(){
        // new thread
        // Do all the file saving operations
        // ...
        threadHandler.post(new Runnable(){public void run(){
            // back in UI thread
            dismissDialog(SAVING_DIALOG);
        }});
    }
}.start();


问:
How do I initialize and use exported ReactJS classes from other modules (with WebPack and ES6)?
I'm using WebPack and ES6, so I can't use module.exports and have to use export default. I have a library like this:

```<code>// helloworld.js
import React from 'react';

class HelloWorld extends React.Component {
        test() {
                alert("TEST FROM test()");
        }
        render() {
                alert("TEST");
                return (
                        <p>Hello, world!</p>
                );
        }
}

// THIS WORKS WHEN I REQUIRE THIS MODULE
// var thing = new HelloWorld();
// thing.test();

export default HelloWorld;
</code>```

The commented out portions work when I var helloworld = require('helloworld.js');, but I can't figure out how to initialize and use this object outside where I require this.

None of these attempts work. How do I initialize this object and use it?

```<code>// hello_world.test();
// hello_world.HelloWorld.test();
// var thing = new hello_world();
// var thing = new hello_world.HelloWorld();
</code>```

My main reason is because I need the component in a route using ReactRouter like this and none of these attempts work.

I tried this (bellow) and this tells me to check the render method...

```<code>ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world}/>
        </Switch>
</BrowserRouter>)
</code>```

This (bellow) renders a BLANK PAGE!!!!

```<code>ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world.HelloWorld}/>
        </Switch>
</BrowserRouter>)
</code>```

I'm out of ideas. This does not help. Neither does this. Could please someone lend me some pointers?

EDIT:

Solution was simply to add default at the end of require (var hello_world = require('./helloworld.js').default;). This works to use this in the route like: <Route exact path="/helloworld" component={hello_world}/>.

If you were to use this outside the scope, you would do:

```<code>var thing = new hello_world();
thing.test();
</code>```

Working solution:

```<code>var hello_world = require('./hello_world.js').default; // Must add default.

// Using it outside a route, with a class method called test().
var thing = new hello_world();
thing.test();

// Using it in a router (ReactRouter with Switch).
ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world}/>
        </Switch>
</BrowserRouter>)
, document.getElementById("root"));
</code>```

答:
var helloworld = require('helloworld.js').default is working for me.
Can you check this?
Please guide me if I'm doing wrong here.

ContentLicense: CC BY-SA 3.0

Body:
I'm using WebPack and ES6, so I can't use module.exports and have to use export default. I have a library like this:

// helloworld.js
import React from 'react';

class HelloWorld extends React.Component {
        test() {
                alert("TEST FROM test()");
        }
        render() {
                alert("TEST");
                return (

Hello, world!

                );
        }
}

// THIS WORKS WHEN I REQUIRE THIS MODULE
// var thing = new HelloWorld();
// thing.test();

export default HelloWorld;

The commented out portions work when I var helloworld = require('helloworld.js');, but I can't figure out how to initialize and use this object outside where I require this.

None of these attempts work. How do I initialize this object and use it?

// hello_world.test();
// hello_world.HelloWorld.test();
// var thing = new hello_world();
// var thing = new hello_world.HelloWorld();

My main reason is because I need the component in a route using ReactRouter like this and none of these attempts work.

I tried this (bellow) and this tells me to check the render method...

ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world}/>
        </Switch>
</BrowserRouter>)

This (bellow) renders a BLANK PAGE!!!!

ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world.HelloWorld}/>
        </Switch>
</BrowserRouter>)

I'm out of ideas. This does not help. Neither does this. Could please someone lend me some pointers?

EDIT:

Solution was simply to add default at the end of require (var hello_world = require('./helloworld.js').default;). This works to use this in the route like: <Route exact path="/helloworld" component={hello_world}/>.

If you were to use this outside the scope, you would do:

var thing = new hello_world();
thing.test();

Working solution:

var hello_world = require('./hello_world.js').default; // Must add default.

// Using it outside a route, with a class method called test().
var thing = new hello_world();
thing.test();

// Using it in a router (ReactRouter with Switch).
ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world}/>
        </Switch>
</BrowserRouter>)
, document.getElementById("root"));


问:
vbscript start a process
I have a vb script that starts an exe (or even a process without gui):

```<code>strCom = "Start calc"
WSHShell.Run(strCom)
</code>```

It doesn't start the program, when I open task manager I can't see it.

But when I write the command "Start calc" directly in the command line it opens it.

How can I do it using the script?

答:
Starting a system process like calc.exe or cmd.exe

code

```<code>    Dim shl
    Set shl = CreateObject("Wscript.Shell")
    Call shl.Run("""calc.exe""")
    Set shl = Nothing
    WScript.Quit
</code>```

Starting a normal process

code

```<code>   Dim shl
   Set shl = CreateObject("Wscript.Shell")
   Call shl.Run("""D:\testvbs\someServices.exe""")
   Set shl = Nothing
   WScript.Quit
</code>```

You can launch any batch file too using VBscript.
just provide the path of batch file in shl.run() while calling it.

Title: vbscript start a process

Body:
I have a vb script that starts an exe (or even a process without gui):

strCom = "Start calc"
WSHShell.Run(strCom)

It doesn't start the program, when I open task manager I can't see it.

But when I write the command "Start calc" directly in the command line it opens it.

How can I do it using the script?

Body:
Starting a system process like calc.exe or cmd.exe

code

    Dim shl
    Set shl = CreateObject("Wscript.Shell")
    Call shl.Run("""calc.exe""")
    Set shl = Nothing
    WScript.Quit

Starting a normal process

code

   Dim shl
   Set shl = CreateObject("Wscript.Shell")
   Call shl.Run("""D:\testvbs\someServices.exe""")
   Set shl = Nothing
   WScript.Quit

You can launch any batch file too using VBscript.
just provide the path of batch file in shl.run() while calling it.


问:
Windows - GDI - Scaling a screen DC to a printer DC without modifying the draw functions
I'm writing a Windows application showing a document to the user. The content is painted using the GDI functions, and all appears as expected on the screen.

Now I want to print this document. I get a printer device context, and I do the exact same drawing as I do on the screen. Of course the printed content appears tiny on the top of the printed page. The reason of this behavior is clear for me, and is fully explained here:

https://www.codeproject.com/Articles/764057/GDI-Drawing-and-Printing

So I need to add a scaled viewport on my printer DC, and there are several functions to achieve that in the GDI. However I'm a little puzzled about HOW to configure these functions. I tried various examples found on the internet, but none of them worked for me.

My screen resolution is 1920x1080 pixels, and I'm trying to print on an A4 portrait page. I tested various configurations, and I found that the best approximation to fit on my printed page is the following:

::SetMapMode(hDC, MM_ISOTROPIC);
::SetWindowExtEx(hDC, 1, 1, NULL);
::SetViewportExtEx(hDC, 5, 5, NULL);
::SetViewportOrgEx(hDC, -10200, 0, NULL);
```

As the screen and print configurations may, of course, change on other PC, I need to know how the above values may be calculated, but I cannot find a formula that works in my case. Especially I don't know why I need to scale my canvas origin using the SetViewportOrgEx() function, nobody mentioned that on the documents I read.

So what is the correct manner to calculate my print DC viewport, considering that:

The exactly same painting functions will be used for both the screen and printer drawing, and I will NEVER write different functions to print on the screen and the printer

The screen and printer devices may be entirely configured by the user, but the printed result should always fit the document on both the screen and the printer

And as an additional question, it would be better to use a metafile to do this kind of job?

答:
In order to map the screen coordinates to paper coordinates, we need the width and length of the paper. This information is available in GetDeviceCaps(hdc, PHYSICALWIDTH) and GetDeviceCaps(hdc, PHYSICALHEIGHT), where hdc is printer's device context. We already have the screen coordinates somewhere.

The printer cannot print on the edges of the paper. We can get that information from PHYSICALOFFSETX and PHYSICALOFFSETY.

The example below uses uses a common function paint which does all the painting. print doesn't do any painting, it calls paint instead.

This assumes that rc.left and rc.right is (0,0) in screen coordinates.

```<code>void paint(HDC hdc, RECT rc)
{
    HBRUSH brush = GetSysColorBrush(COLOR_WINDOWTEXT);
    InflateRect(&rc, -10, -10);
    FrameRect(hdc, &rc, brush);
    DrawText(hdc, L"hello world", -1, &rc, 0);
}

void print(HWND hWnd, RECT rc)
{
    PRINTDLG pd = { sizeof(pd) };
    pd.hwndOwner = hWnd;
    pd.Flags = PD_RETURNDC;
    if(!PrintDlg(&pd))
        return;

    HDC hdc = pd.hDC;
    DOCINFO doc = { sizeof(doc) };
    StartDoc(hdc, &doc);
    StartPage(hdc);
    SetMapMode(hdc, MM_ISOTROPIC);
    SetWindowExtEx(hdc, rc.right, rc.bottom, NULL);
    SetViewportExtEx(hdc,
      GetDeviceCaps(hdc, PHYSICALWIDTH), GetDeviceCaps(hdc, PHYSICALHEIGHT), NULL);
    SetViewportOrgEx(hdc,
      -GetDeviceCaps(hdc, PHYSICALOFFSETX), -GetDeviceCaps(hdc, PHYSICALOFFSETY), NULL);

    paint(hdc, rc);

    EndPage(hdc);
    EndDoc(hdc);
    DeleteObject(hdc);
}
</code>```

Testing:

```<code>case WM_PAINT:
{
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hwnd, &ps);
    RECT rc;
    GetClientRect(hwnd, &rc);
    paint(hdc, rc);
    EndPaint(hwnd, &ps);
    break;
}

case WM_LBUTTONDOWN:
{
    RECT rc;
    GetClientRect(hwnd, &rc);
    print(hwnd, rc);
    break;
}
</code>```

Body:
I'm writing a Windows application showing a document to the user. The content is painted using the GDI functions, and all appears as expected on the screen.

Now I want to print this document. I get a printer device context, and I do the exact same drawing as I do on the screen. Of course the printed content appears tiny on the top of the printed page. The reason of this behavior is clear for me, and is fully explained here:

https://www.codeproject.com/Articles/764057/GDI-Drawing-and-Printing

So I need to add a scaled viewport on my printer DC, and there are several functions to achieve that in the GDI. However I'm a little puzzled about HOW to configure these functions. I tried various examples found on the internet, but none of them worked for me.

My screen resolution is 1920x1080 pixels, and I'm trying to print on an A4 portrait page. I tested various configurations, and I found that the best approximation to fit on my printed page is the following:

::SetMapMode(hDC, MM_ISOTROPIC);
::SetWindowExtEx(hDC, 1, 1, NULL);
::SetViewportExtEx(hDC, 5, 5, NULL);
::SetViewportOrgEx(hDC, -10200, 0, NULL);

As the screen and print configurations may, of course, change on other PC, I need to know how the above values may be calculated, but I cannot find a formula that works in my case. Especially I don't know why I need to scale my canvas origin using the SetViewportOrgEx() function, nobody mentioned that on the documents I read.

So what is the correct manner to calculate my print DC viewport, considering that:

The exactly same painting functions will be used for both the screen and printer drawing, and I will NEVER write different functions to print on the screen and the printer

The screen and printer devices may be entirely configured by the user, but the printed result should always fit the document on both the screen and the printer

And as an additional question, it would be better to use a metafile to do this kind of job?

Body:
In order to map the screen coordinates to paper coordinates, we need the width and length of the paper. This information is available in GetDeviceCaps(hdc, PHYSICALWIDTH) and GetDeviceCaps(hdc, PHYSICALHEIGHT), where hdc is printer's device context. We already have the screen coordinates somewhere.

The printer cannot print on the edges of the paper. We can get that information from PHYSICALOFFSETX and PHYSICALOFFSETY.

The example below uses uses a common function paint which does all the painting. print doesn't do any painting, it calls paint instead.

This assumes that rc.left and rc.right is (0,0) in screen coordinates.

void paint(HDC hdc, RECT rc)
{
    HBRUSH brush = GetSysColorBrush(COLOR_WINDOWTEXT);
    InflateRect(&rc, -10, -10);
    FrameRect(hdc, &rc, brush);
    DrawText(hdc, L"hello world", -1, &rc, 0);
}

void print(HWND hWnd, RECT rc)
{
    PRINTDLG pd = { sizeof(pd) };
    pd.hwndOwner = hWnd;
    pd.Flags = PD_RETURNDC;
    if(!PrintDlg(&pd))
        return;

    HDC hdc = pd.hDC;
    DOCINFO doc = { sizeof(doc) };
    StartDoc(hdc, &doc);
    StartPage(hdc);
    SetMapMode(hdc, MM_ISOTROPIC);
    SetWindowExtEx(hdc, rc.right, rc.bottom, NULL);
    SetViewportExtEx(hdc,
      GetDeviceCaps(hdc, PHYSICALWIDTH), GetDeviceCaps(hdc, PHYSICALHEIGHT), NULL);
    SetViewportOrgEx(hdc,
      -GetDeviceCaps(hdc, PHYSICALOFFSETX), -GetDeviceCaps(hdc, PHYSICALOFFSETY), NULL);

    paint(hdc, rc);

    EndPage(hdc);
    EndDoc(hdc);
    DeleteObject(hdc);
}

Testing:

case WM_PAINT:
{
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hwnd, &ps);
    RECT rc;
    GetClientRect(hwnd, &rc);
    paint(hdc, rc);
    EndPaint(hwnd, &ps);
    break;
}

case WM_LBUTTONDOWN:
{
    RECT rc;
    GetClientRect(hwnd, &rc);
    print(hwnd, rc);
    break;
}


问:
Programmatically sending an app to background
Is there a way to send the application to background? Similarly to how you can call XCUIApplication.terminate(), I have some UI Elements to test on applicationDidBecomeActive(_:). Does anyone know if this is at all possible?

答:
In Xcode 9.0, Apple introduced XCUIApplication.activate(). activate() will launch the application if necessary, but will not terminate it if it is already running. Thus:

```<code>func testExample() {
    // Background the app
    XCUIDevice().press(.home)
    // Reactivate the app
    XCUIApplication().launch()
}
</code>```

Body:
In Xcode 9.0, Apple introduced XCUIApplication.activate(). activate() will launch the application if necessary, but will not terminate it if it is already running. Thus:

func testExample() {
    // Background the app
    XCUIDevice().press(.home)
    // Reactivate the app
    XCUIApplication().launch()
}


问:
error: void cannot be dereferenced
I'm trying to implement a library which provides maps marker animations, but when I try to add some advanced methods, it throws me an error on the second one ".withFillColor(Color.BLUE)" which says: error: void cannot be dereferenced.</p>

```<code>// mMap is GoogleMap object, latLng is the location on map from which ripple should start
    actualUbicacion = new LatLng(3.385264, -76.526551);
    mapRipple = new MapRipple(mMap, actualUbicacion, this)
            .withNumberOfRipples(3) //int
            .withFillColor(Color.BLUE) //here I get the error
            .withStrokeColor(Color.BLACK) //if I delete the previous one, the next one gets the error
            .withStrokewidth(10)      // 10dp
            .withDistance(2000)      // 2000 metres radius
            .withRippleDuration(12000)    //12000ms
            .withTransparency(0.5f);
    mapRipple.startRippleMapAnimation();      //in onMapReadyCallBack

Error:(623, 17) error: void cannot be dereferenced
</code>```

答:
From Code

The return type is void

```<code>public void withNumberOfRipples(int numberOfRipples) {
    if (numberOfRipples > 4 || numberOfRipples < 1)
        numberOfRipples = 4;
    this.numberOfRipples = numberOfRipples;
}
</code>```

so you cannot chained your function calls , you need to invoke every function on MapRipple instance, not on void

Solution : reduce the calls to single level

```<code>mapRipple = new MapRipple(mMap, actualUbicacion, this);
mapRipple.withNumberOfRipples(3);
mapRipple.withFillColor(Color.BLUE);
mapRipple.withStrokeColor(Color.BLACK);
mapRipple.withStrokewidth(10);      // 10dp
mapRipple.withDistance(2000);      // 2000 metres radius
mapRipple.withRippleDuration(12000);    //12000ms
mapRipple.withTransparency(0.5f);
mapRipple.startRippleMapAnimation();
</code>```

Title: error: void cannot be dereferenced

Body:
I'm trying to implement a library which provides maps marker animations, but when I try to add some advanced methods, it throws me an error on the second one ".withFillColor(Color.BLUE)" which says: error: void cannot be dereferenced.

// mMap is GoogleMap object, latLng is the location on map from which ripple should start
    actualUbicacion = new LatLng(3.385264, -76.526551);
    mapRipple = new MapRipple(mMap, actualUbicacion, this)
            .withNumberOfRipples(3) //int
            .withFillColor(Color.BLUE) //here I get the error
            .withStrokeColor(Color.BLACK) //if I delete the previous one, the next one gets the error
            .withStrokewidth(10)      // 10dp
            .withDistance(2000)      // 2000 metres radius
            .withRippleDuration(12000)    //12000ms
            .withTransparency(0.5f);
    mapRipple.startRippleMapAnimation();      //in onMapReadyCallBack

Error:(623, 17) error: void cannot be dereferenced

Body:
From Code

The return type is void

public void withNumberOfRipples(int numberOfRipples) {
    if (numberOfRipples > 4 || numberOfRipples < 1)
        numberOfRipples = 4;
    this.numberOfRipples = numberOfRipples;
}

so you cannot chained your function calls , you need to invoke every function on MapRipple instance, not on void

Solution : reduce the calls to single level

mapRipple = new MapRipple(mMap, actualUbicacion, this);
mapRipple.withNumberOfRipples(3);
mapRipple.withFillColor(Color.BLUE);
mapRipple.withStrokeColor(Color.BLACK);
mapRipple.withStrokewidth(10);      // 10dp
mapRipple.withDistance(2000);      // 2000 metres radius
mapRipple.withRippleDuration(12000);    //12000ms
mapRipple.withTransparency(0.5f);
mapRipple.startRippleMapAnimation();


问:
NotFoundHttpException in laravel Auth login
i can't login with Auth in laravel i got an error NotFoundHttpException
my form for login

```<code><form id="login-form" method="POST" action="{{ route('login') }}">
      {{ csrf_field() }}
</code>```

My file Router.php

```<code>public function auth(){
        // Authentication Routes...
        $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
        $this->post('login', 'Auth\LoginController@login');
        $this->post('logout', 'Auth\LoginController@logout')->name('logout');
}
</code>```

My route:

```<code>Route::group(['middleware' => ['auth']], function () {
 Route::get('home', 'NavmenuController@menuright')->name('home');
}
Auth::routes();
Route::group(['middleware' => ['guest']], function () {
    Route::get('/', function () {
        return view('auth.login');
    });
});
</code>```

答:
Make login for post to named route. Change from

```<code> $this->post('login', 'Auth\LoginController@login');
</code>```

to

```<code>$this->post('login', 'Auth\LoginController@login')->name('login');
</code>```

Body:
i can't login with Auth in laravel i got an error NotFoundHttpException
my form for login

<form id="login-form" method="POST" action="{{ route('login') }}">
      {{ csrf_field() }}

My file Router.php

public function auth(){
        // Authentication Routes...
        $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
        $this->post('login', 'Auth\LoginController@login');
        $this->post('logout', 'Auth\LoginController@logout')->name('logout');
}

My route:

Route::group(['middleware' => ['auth']], function () {
 Route::get('home', 'NavmenuController@menuright')->name('home');
}
Auth::routes();
Route::group(['middleware' => ['guest']], function () {
    Route::get('/', function () {
        return view('auth.login');
    });
});

Body:
Make login for post to named route. Change from

 $this->post('login', 'Auth\LoginController@login');

to

$this->post('login', 'Auth\LoginController@login')->name('login');


问:
incorrect hyperlink relative paths with ajax calls
I have recently upgraded my application to .net 4.0. I have a problem with the hyperlink navigateurl relative paths being rendered properly. I am calling a webmethod through jquery which loads a usercontrol and get the html which I display it on the page. The usercontrol has a gridview with a hyperlink field which is bound to some application relative paths using tilde(~).

For replicating this issue I have created a website say "TestWebsite" under "Default Website" in IIS. I have a page "Test.aspx" under the root folder. Also I have UserControls folder which has my usercontrol "TestUserControl.ascx". Now I just call my webmethod in the page which will load the control and return the html. The issue I am having is the Hyperlink url relative path is rendered incorrectly. It displays

http://localhost/SubFolder/Sample1.aspx  instead of starting with my root folder (TestWebsite)

http://localhost/TestWebsite/SubFolder/Sample1.aspx .

Here is the sample code

Test.aspx

```<code><div>
     <script type="text/javascript">

         $(document).ready(function () {
             $.ajax({
                 type: "POST",
                 url: "Test.aspx/TestMethod",
                 data: "{}",
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 success: function (msg) {
                     $("#result").html(msg.d);
                 }
             });
         });
</script>

</div>

<div id="result"></div>
</code>```

Test.aspx.cs - webmethod

```<code> [WebMethod]
public static string TestMethod()
{
    StringWriter tw = new StringWriter();
    Control control = null;

    Page page = new Page();
    try
    {
        control = page.LoadControl("~/UserControls/TestUserControl.ascx");
    }
    catch (Exception ex)
    {
        string name = ex.Message;
    }

    HtmlForm form = new HtmlForm();
    form.ID = "_form";
    page.Controls.Add(form);

    form.Controls.Add(control);

    page.Controls.Add(form);

    HttpContext.Current.Server.Execute(page, tw, true);

    string html = tw.ToString();
    return html;
}
</code>```

UserControl

```<code> protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("TestLink");
    DataRow dr = dt.NewRow();
    dr["TestLink"] = "~/SubFolder/Sample1.aspx";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr["TestLink"] = "~/SubFolder/Sample2.aspx";
    dt.Rows.Add(dr);

    GVTest.DataSource = dt;
    GVTest.DataBind();
}
</code>```

TestUserControl.ascx

Iam not able to copy my code here due to formatting issues but  I have a simple gridview here with a hyperlink server control where I bind the navigateurl.

After some search on the web I found this similar issue at

Asp.Net single control render for AJAX calls

where it was mentioned to set AppRelativeTemplateSourceDirectory. but even after setting this to AppDomainAppVirtualPath, it doesn't work for me.

After Server.Execute the relative url (~/SubFolder/) changes to one level up giving (../SubFolder/)

I am not sure if I am missing anything? I would appreciate if any one could help me on resolving this issue.

FYI: I am using IIS 7.5 and windows 7.

Thanks,
Prashant

答:
Everything that Marty described is correct, and I'm not sure how to fix this issue either, but here's a workaround that I use, which detects when the extra "../" is prepended and corrects the situation by readding the subdirectory into the URL:</p>

```<code>        // this is the link that will be appended to the fullpath+subdirectory of the app
        var resolvedLinkInBrowser = this.ResolveClientUrl(builtUrl);

        if (resolvedLinkInBrowser.Contains("../"))
        {
            // when an ajax call is made, it is made using a service call. This service call for some
            // reason does not think that it should serve links relative to the subdirectory, but thinks
            // that it should serve links relative to the root of the domain. That is why when the link is resolved,
            // WebForms adds a '../' to the link, to get it back to the root domain. Since we've detected this case,
            // we can insert the subdirectory in to our not-yet-resolved url, to force the resulting url to be correct.
            // this is a workaround. If this issue can be fixed any other way, please do that.
            builtUrl = builtUrl.Replace("~/", "~" + HttpRuntime.AppDomainAppVirtualPath + "/");
        }
</code>```

Body:
I have recently upgraded my application to .net 4.0. I have a problem with the hyperlink navigateurl relative paths being rendered properly. I am calling a webmethod through jquery which loads a usercontrol and get the html which I display it on the page. The usercontrol has a gridview with a hyperlink field which is bound to some application relative paths using tilde(~).

For replicating this issue I have created a website say "TestWebsite" under "Default Website" in IIS. I have a page "Test.aspx" under the root folder. Also I have UserControls folder which has my usercontrol "TestUserControl.ascx". Now I just call my webmethod in the page which will load the control and return the html. The issue I am having is the Hyperlink url relative path is rendered incorrectly. It displays

http://localhost/SubFolder/Sample1.aspx  instead of starting with my root folder (TestWebsite)

http://localhost/TestWebsite/SubFolder/Sample1.aspx .

Here is the sample code

Test.aspx

Test.aspx.cs - webmethod

 [WebMethod]
public static string TestMethod()
{
    StringWriter tw = new StringWriter();
    Control control = null;

    Page page = new Page();
    try
    {
        control = page.LoadControl("~/UserControls/TestUserControl.ascx");
    }
    catch (Exception ex)
    {
        string name = ex.Message;
    }

    HtmlForm form = new HtmlForm();
    form.ID = "_form";
    page.Controls.Add(form);

    form.Controls.Add(control);

    page.Controls.Add(form);

    HttpContext.Current.Server.Execute(page, tw, true);

    string html = tw.ToString();
    return html;
}

UserControl

 protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("TestLink");
    DataRow dr = dt.NewRow();
    dr["TestLink"] = "~/SubFolder/Sample1.aspx";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr["TestLink"] = "~/SubFolder/Sample2.aspx";
    dt.Rows.Add(dr);

    GVTest.DataSource = dt;
    GVTest.DataBind();
}

TestUserControl.ascx

Iam not able to copy my code here due to formatting issues but  I have a simple gridview here with a hyperlink server control where I bind the navigateurl.

After some search on the web I found this similar issue at

Asp.Net single control render for AJAX calls

where it was mentioned to set AppRelativeTemplateSourceDirectory. but even after setting this to AppDomainAppVirtualPath, it doesn't work for me.

After Server.Execute the relative url (~/SubFolder/) changes to one level up giving (../SubFolder/)

I am not sure if I am missing anything? I would appreciate if any one could help me on resolving this issue.

FYI: I am using IIS 7.5 and windows 7.

Thanks,
Prashant

Body:
Everything that Marty described is correct, and I'm not sure how to fix this issue either, but here's a workaround that I use, which detects when the extra "../" is prepended and corrects the situation by readding the subdirectory into the URL:

        // this is the link that will be appended to the fullpath+subdirectory of the app
        var resolvedLinkInBrowser = this.ResolveClientUrl(builtUrl);

        if (resolvedLinkInBrowser.Contains("../"))
        {
            // when an ajax call is made, it is made using a service call. This service call for some
            // reason does not think that it should serve links relative to the subdirectory, but thinks
            // that it should serve links relative to the root of the domain. That is why when the link is resolved,
            // WebForms adds a '../' to the link, to get it back to the root domain. Since we've detected this case,
            // we can insert the subdirectory in to our not-yet-resolved url, to force the resulting url to be correct.
            // this is a workaround. If this issue can be fixed any other way, please do that.
            builtUrl = builtUrl.Replace("~/", "~" + HttpRuntime.AppDomainAppVirtualPath + "/");
        }


问:
Multiple select queries on the same table in Oracle
I have a table with all my data. I have tried joins, subqueries and unions, but none give me the desired result. I am running Oracle 12g.

This is a sample table:

```<code>FILENAME | VALUE | RAW
AA       | XX    | ZZ
AA       | YY    | WW
DD       | GG    | II
DD       | HH    | JJ
</code>```

The current SQL statement that I use is:

```<code>SELECT FILENAME, VALUE VALUE1 FROM TABLE WHERE FILENAME='AA';
SELECT FILENAME, VALUE VALUE2 FROM TABLE WHERE FILENAME='DD';
</code>```

And I get the following result:

```<code>FILENAME | VALUE1
AA       | XX
AA       | YY
</code>```

and

```<code>FILENAME | VALUE2
DD       | GG
DD       | HH
</code>```

but I need the result to be:

```<code>FILENAME | VALUE1 | VALUE2
AA       | XX     | GG
AA       | YY     | HH
</code>```

It doesn't matter if AA or DD is in the FILENAME. There are no foreign keys or unique values that I can do a simple INNER JOIN. I am not able to add new columns to the table. I was hoping to do sort my data and then use Oracle's ROWNUM as a temp column which I could then use to do a SELF JOIN but Oracle won't let me.

Example:

```<code>SELECT L.FILENAME, L.VALUE VALUE1, R.VALUE VALUE2
FROM TABLE L JOIN TABLE R
ON (L.ROWNUM=R.ROWNUM)
WHERE L.FILENAME IN ('AA','DD');
</code>```

Any help is appreciated.

答:
Can you try this way:  </p>

```<code>SELECT T1.FILENAME, T1.VALUE VALUE1, T2.VALUE VALUE2
FROM
(SELECT FILENAME, VALUE, RAW, rownum RNUM FROM TABLE1 WHERE FILENAME = 'AA') T1,
(SELECT FILENAME, VALUE, RAW, rownum RNUM FROM TABLE1 WHERE FILENAME = 'DD') T2
WHERE T1.RNUM = T2.RNUM;
</code>```

Body:
I have a table with all my data. I have tried joins, subqueries and unions, but none give me the desired result. I am running Oracle 12g.

This is a sample table:

FILENAME | VALUE | RAW
AA       | XX    | ZZ
AA       | YY    | WW
DD       | GG    | II
DD       | HH    | JJ

The current SQL statement that I use is:

SELECT FILENAME, VALUE VALUE1 FROM TABLE WHERE FILENAME='AA';
SELECT FILENAME, VALUE VALUE2 FROM TABLE WHERE FILENAME='DD';

And I get the following result:

FILENAME | VALUE1
AA       | XX
AA       | YY

and

FILENAME | VALUE2
DD       | GG
DD       | HH

but I need the result to be:

FILENAME | VALUE1 | VALUE2
AA       | XX     | GG
AA       | YY     | HH

It doesn't matter if AA or DD is in the FILENAME. There are no foreign keys or unique values that I can do a simple INNER JOIN. I am not able to add new columns to the table. I was hoping to do sort my data and then use Oracle's ROWNUM as a temp column which I could then use to do a SELF JOIN but Oracle won't let me.

Example:

SELECT L.FILENAME, L.VALUE VALUE1, R.VALUE VALUE2
FROM TABLE L JOIN TABLE R
ON (L.ROWNUM=R.ROWNUM)
WHERE L.FILENAME IN ('AA','DD');

Any help is appreciated.

Body:
Can you try this way:

SELECT T1.FILENAME, T1.VALUE VALUE1, T2.VALUE VALUE2
FROM
(SELECT FILENAME, VALUE, RAW, rownum RNUM FROM TABLE1 WHERE FILENAME = 'AA') T1,
(SELECT FILENAME, VALUE, RAW, rownum RNUM FROM TABLE1 WHERE FILENAME = 'DD') T2
WHERE T1.RNUM = T2.RNUM;


问:
SMS Telephone number confirmation with ionic and firebase
I am developing a mobile application with ionic and firebase. The thing I want is that for the user to be confirmed he has to enter his mobile number, receive an sms, enter the code, and then it will be confirmed.
I looked around and found some sms tools like twilio but I am not sure if I can use them.
What is the best way to do it?</p>

答:
```<code>  import { Firebase } from '@ionic-native/firebase';

  let number = "+91"+ number;
  this.platform.ready().then(()=>{
  (<any>window).FirebasePlugin.verifyPhoneNumber(number, 120, (credential) => {
    var verificationId = credential.verificationId;
    this.navCtrl.push(VerificationPage, { verificationId: verificationId, phoneNumber: this.emailPasswordForm.value["phoneNumber"]  }); //This is STEP 3 - passing verification ID to OTP Page
  }, (error) => {
    //this.eer = error;
    alert('Failed to send OTP. Try again');
    console.error(error);
  });
</code>```

first set the sha1 to firebase setting and generate google config.json then add to poject's root directory and add to build.gradle dependency.
it'll work properly

Body:
  import { Firebase } from '@ionic-native/firebase';

  let number = "+91"+ number;
  this.platform.ready().then(()=>{
  (<any>window).FirebasePlugin.verifyPhoneNumber(number, 120, (credential) => {
    var verificationId = credential.verificationId;
    this.navCtrl.push(VerificationPage, { verificationId: verificationId, phoneNumber: this.emailPasswordForm.value["phoneNumber"]  }); //This is STEP 3 - passing verification ID to OTP Page
  }, (error) => {
    //this.eer = error;
    alert('Failed to send OTP. Try again');
    console.error(error);
  });

first set the sha1 to firebase setting and generate google config.json then add to poject's root directory and add to build.gradle dependency.
it'll work properly


问:
Applescript copy files to specific folders
I want to copy files to specific folders. The folder names and the file names have the first 14 characters in common.
This is my folder structure:

The Source File Structure:

```<code>Proxy
     RED_A001_0101R7 (the last 6 digits are random)

          A001_C001_0101RN_001_Proxy.mp4 (video file to be copied)
          A001_C002_0101D5_001_Proxy.mp4 (video file to be copied)
                          ...
     RED_A001_0525A1
     RED_A002_010107
     ...
</code>```

The Destination File Structure:

```<code>FullRes
     RED_A001_0101R7
          A001_C001_0101RN.RDC (Folder in which the correct _Proxy file should be copied in)
          A001_C002_0101D5.RDC (Folder in which the correct _Proxy file should be copied in)
                   ...
     RED_A001_0525A1
     RED_A002_010107
     ...
</code>```

As you can see unfortunately sometimes two folders begin with the same folder name (but are distinguished by the random digits that follow)

I managed to put together the following script:

```<code>set ProxyFolder to (choose folder with prompt "Choose the Source Folder")
set FullresFolder to (choose folder with prompt "Choose the Destination Folder")

tell application "System Events"
      set folderList to name of folders of FullresFolder
      set fileList to name of files of ProxyFolder
end tell

repeat with i from 1 to (count folderList)
      set folderName to item i of folderList
      set beginFolderName to text items 1 thru 14 of folderName
      set filesToMove to {}
           repeat with j from 1 to (count fileList)
                   set filename to item j of fileList
                   if filename begins with beginFolderName then
                       set end of filesToMove to alias ((ProxyFolder as string) & filename)
                   end if
            end repeat

tell application "Finder"
                   duplicate filesToMove to alias ((FullresFolder as string) & folderName & ":")
        end tell
end repeat
</code>```

The script works - but right now I have to choose my source and destination folder for every folder A001, A002 etc.  It would be more convenient to be able to choose the top-level folders as source (Folder Proxy) and destination (Folder FullRes).  How can I do that?

答:
Thats it!!

I edited my original script and it works as well, but yours is way more elegant and probably faster. Thank you very much!

Here my version:

```<code>set topLevelProxyFolder to (choose folder with prompt "Choose the PROXY Folder")
set topLevelFullresFolder to (choose folder with prompt "Choose the FULL RES Folder")

tell application "System Events"
    set folderList to name of folders of topLevelFullresFolder
    set proxyFolderList to name of folders of topLevelProxyFolder
end tell

set allFilesList to {}

repeat with thisProxyFolder from 1 to (count proxyFolderList)
    set thisProxyFolderName to item thisProxyFolder of proxyFolderList
    set thisSubProxyFolder to alias ((topLevelProxyFolder as string) & thisProxyFolderName)

    tell application "System Events"
        set thisFileList to name of files of thisSubProxyFolder
    end tell

    set allFilesList to allFilesList & thisFileList

end repeat

repeat with thisFolder from 1 to (count folderList)
    set thisFolderName to item thisFolder of folderList
    set thisSubFolder to alias ((topLevelFullresFolder as string) & thisFolderName)

    tell application "System Events"
        set subFolderList to name of folders of thisSubFolder
    end tell

repeat with i from 1 to (count subFolderList)
    set thisSubFolderName to item i of subFolderList
    set beginSubFolderName to text items 1 thru ((get offset of "." in thisSubFolderName) - 1) of thisSubFolderName
    set filesToMove to {}

    repeat with j from 1 to (count allFilesList)
        set fileName to item j of allFilesList
        if fileName begins with beginSubFolderName then
            set end of filesToMove to alias ((topLevelProxyFolder as string) & thisFolderName & ":" & fileName)
        end if

    end repeat

    tell application "Finder"
        duplicate filesToMove to alias ((topLevelFullresFolder as string) & thisFolderName & ":" & thisSubFolderName & ":")
    end tell

    end repeat
end repeat
</code>```

Body:
I want to copy files to specific folders. The folder names and the file names have the first 14 characters in common.
This is my folder structure:

The Source File Structure:

Proxy
     RED_A001_0101R7 (the last 6 digits are random)

          A001_C001_0101RN_001_Proxy.mp4 (video file to be copied)
          A001_C002_0101D5_001_Proxy.mp4 (video file to be copied)
                          ...
     RED_A001_0525A1
     RED_A002_010107
     ...

The Destination File Structure:

FullRes
     RED_A001_0101R7
          A001_C001_0101RN.RDC (Folder in which the correct _Proxy file should be copied in)
          A001_C002_0101D5.RDC (Folder in which the correct _Proxy file should be copied in)
                   ...
     RED_A001_0525A1
     RED_A002_010107
     ...

As you can see unfortunately sometimes two folders begin with the same folder name (but are distinguished by the random digits that follow)

I managed to put together the following script:

set ProxyFolder to (choose folder with prompt "Choose the Source Folder")
set FullresFolder to (choose folder with prompt "Choose the Destination Folder")

tell application "System Events"
      set folderList to name of folders of FullresFolder
      set fileList to name of files of ProxyFolder
end tell

repeat with i from 1 to (count folderList)
      set folderName to item i of folderList
      set beginFolderName to text items 1 thru 14 of folderName
      set filesToMove to {}
           repeat with j from 1 to (count fileList)
                   set filename to item j of fileList
                   if filename begins with beginFolderName then
                       set end of filesToMove to alias ((ProxyFolder as string) & filename)
                   end if
            end repeat

tell application "Finder"
                   duplicate filesToMove to alias ((FullresFolder as string) & folderName & ":")
        end tell
end repeat

The script works - but right now I have to choose my source and destination folder for every folder A001, A002 etc.  It would be more convenient to be able to choose the top-level folders as source (Folder Proxy) and destination (Folder FullRes).  How can I do that?

Body:
Thats it!!

I edited my original script and it works as well, but yours is way more elegant and probably faster. Thank you very much!

Here my version:

set topLevelProxyFolder to (choose folder with prompt "Choose the PROXY Folder")
set topLevelFullresFolder to (choose folder with prompt "Choose the FULL RES Folder")

tell application "System Events"
    set folderList to name of folders of topLevelFullresFolder
    set proxyFolderList to name of folders of topLevelProxyFolder
end tell

set allFilesList to {}

repeat with thisProxyFolder from 1 to (count proxyFolderList)
    set thisProxyFolderName to item thisProxyFolder of proxyFolderList
    set thisSubProxyFolder to alias ((topLevelProxyFolder as string) & thisProxyFolderName)

    tell application "System Events"
        set thisFileList to name of files of thisSubProxyFolder
    end tell

    set allFilesList to allFilesList & thisFileList

end repeat

repeat with thisFolder from 1 to (count folderList)
    set thisFolderName to item thisFolder of folderList
    set thisSubFolder to alias ((topLevelFullresFolder as string) & thisFolderName)

    tell application "System Events"
        set subFolderList to name of folders of thisSubFolder
    end tell

repeat with i from 1 to (count subFolderList)
    set thisSubFolderName to item i of subFolderList
    set beginSubFolderName to text items 1 thru ((get offset of "." in thisSubFolderName) - 1) of thisSubFolderName
    set filesToMove to {}

    repeat with j from 1 to (count allFilesList)
        set fileName to item j of allFilesList
        if fileName begins with beginSubFolderName then
            set end of filesToMove to alias ((topLevelProxyFolder as string) & thisFolderName & ":" & fileName)
        end if

    end repeat

    tell application "Finder"
        duplicate filesToMove to alias ((topLevelFullresFolder as string) & thisFolderName & ":" & thisSubFolderName & ":")
    end tell

    end repeat
end repeat


问:
Finding last word in a string
I'm trying to return the last word in a string but am having trouble with the for loops. When I try to test the function I am only getting empty strings. Not really sure what the problem is. Any help is much appreciated.</p>

```<code>string getLastWord(string text)

{
    string revLastWord = "";
    string lastWord = "";
    if(text == "")
    {
        return text;
    }

    for(size_t i = text.size()-1; i > -1; i--)
    {

        if((isalpha(text[i])))
        {
             revLastWord+=text[i];
        }
        if(revLastWord.size()>=1 && !isalpha(text[i-1]))
        {
             break;
        }
    }

    for(size_t k = revLastWord.size()-1; k > -1; k--)
    {
        lastWord+=revLastWord[k];
    }

    return lastWord;
}
</code>```

答:
The other answers tell you what's wrong, though you should also know why it's wrong.

In general,  you should be very careful about using unsigned value types in loop conditions. Comparing an unsigned type like std::size_t and a signed type, like your constant -1, will cause the signed to get converted into an  unsigned type, so -1 becomes the largest possible std::size_t value.

If you put some print statements throughout your code, you'll notice that your loops are never actually entered, because the conditional is always false. Use an int when performing arithmetic and especially when signed numbers are compared with.

Title: Finding last word in a string

Body:
I'm trying to return the last word in a string but am having trouble with the for loops. When I try to test the function I am only getting empty strings. Not really sure what the problem is. Any help is much appreciated.

string getLastWord(string text)

{
    string revLastWord = "";
    string lastWord = "";
    if(text == "")
    {
        return text;
    }

    for(size_t i = text.size()-1; i > -1; i--)
    {

        if((isalpha(text[i])))
        {
             revLastWord+=text[i];
        }
        if(revLastWord.size()>=1 && !isalpha(text[i-1]))
        {
             break;
        }
    }

    for(size_t k = revLastWord.size()-1; k > -1; k--)
    {
        lastWord+=revLastWord[k];
    }

    return lastWord;
}


答:
```<code>$this->post('login', 'Auth\LoginController@login');
</code>```

where is the named route assign?? change to this.

```<code>$this->post('login', 'Auth\LoginController@login')->name('post_login');
and in your form add this

<form id="login-form" method="POST" action="{{ route('post_login') }}">
</code>```

Title: NotFoundHttpException in laravel Auth login

Body:
$this->post('login', 'Auth\LoginController@login');

where is the named route assign?? change to this.

$this->post('login', 'Auth\LoginController@login')->name('post_login');
and in your form add this

<form id="login-form" method="POST" action="{{ route('post_login') }}">


问:
windowResize problem
I want to make a web browser adjustment margin left. I use windowResize, but how to adjustment margin left even if the custom click the restore button of the web browser? I upload 2 screenshort images for explain. first image, I open the web browser not maximize, so the page make a windowResize and count the margin-left, then I click the windows maximize, then get the second image, but the content is not in the center of the page. How to do a right windowResize? Thanks.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="jquery-1.4.4.min.js"></script>
    <script type="text/javascript">
    jQuery(document).ready(function() {
       var width = document.body.clientWidth;
       windowResize(width);
       $(window).resize(function() {
           windowResize(width);
           });
       });
    function windowResize(width) {
    if(width>1024){
    $('#content').css({
       'margin-left':(width-1024)/2+32 + 'px'
       });
    }else{
        $('#content').css({
       'margin-left': 32 + 'px'
       });
    }
    }
    </script>
    </head>
    <body>
    <style>
    body, #box{min-width:1024px;width:100%;}
    #content{float:left;width:960px;height:300px;background-color:#F00;}
    </style>
    <div id="box">
    <div id="content">
        some words
    </div>
    </div>
    </body>
    </html>
</code>```

答:
One thing I notice is that this code will only ever call windowResize with the initial width:

```<code>jQuery(document).ready(function() {
   // this value will always be passed to windowResize
   var width = document.body.clientWidth;
   windowResize(width);
   $(window).resize(function() {
       windowResize(width);
       });
   });
</code>```

I changed it so the width is calculated inside of windowResize and things work.

```<code>jQuery(document).ready(function() {
  windowResize();
  $(window).resize(windowResize);
});

function windowResize() {
  var width = document.body.clientWidth;
  if(width>1024){
    $('#content').css({
       'margin-left':(width-1024)/2+32 + 'px'
    });
  }else{
    $('#content').css({
       'margin-left': 32 + 'px'
    });
  }
}
</code>```

Title: windowResize problem

Body:
I want to make a web browser adjustment margin left. I use windowResize, but how to adjustment margin left even if the custom click the restore button of the web browser? I upload 2 screenshort images for explain. first image, I open the web browser not maximize, so the page make a windowResize and count the margin-left, then I click the windows maximize, then get the second image, but the content is not in the center of the page. How to do a right windowResize? Thanks.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

        some words

Body:
One thing I notice is that this code will only ever call windowResize with the initial width:

jQuery(document).ready(function() {
   // this value will always be passed to windowResize
   var width = document.body.clientWidth;
   windowResize(width);
   $(window).resize(function() {
       windowResize(width);
       });
   });

I changed it so the width is calculated inside of windowResize and things work.

jQuery(document).ready(function() {
  windowResize();
  $(window).resize(windowResize);
});

function windowResize() {
  var width = document.body.clientWidth;
  if(width>1024){
    $('#content').css({
       'margin-left':(width-1024)/2+32 + 'px'
    });
  }else{
    $('#content').css({
       'margin-left': 32 + 'px'
    });
  }
}


问:
How can you store the results from a forEach in Spark
DataSet#foreach(f) applies the function f to each row in the dataset. In a clustered environment, the data is split across the cluster. How can the results from each of these functions be collected?

For example, say the function would count the number of characters stored in each row. How can you create a DataSet or RDD that contains the results of each of these functions applied to each row?

答:
The definition for foreach looks something like :

```<code>final  def  foreach(f: (A) ⇒ Unit): Unit
</code>```

f : The function that is applied for its side-effect to every element.
               The result of function f is discarded

foreach in Scala is generally used to denote the usage of a function that involves a side-effect, e.g. printing to STDOUT.

If you want to return something by applying a particular function, you'll have to use map

```<code>final  def  map[B](f: (A) ⇒ B): List[B]
</code>```

I copied the syntax from the documentation for List but it'll be something similar for RDDs as well.

As you can see, it works the function f on datatype A and returns a collection of datatype B where A and B can be the same data type as well.

```<code>val rdd = sc.parallelize(Array(
      "String1",
      "String2",
      "String3" ))

scala> rdd.foreach(x => (x, x.length) )

// Nothing happens

rdd.map(x => (x, x.length) ).collect

// Array[(String, Int)] = Array((String1,7), (String2,7), (String3,7))
</code>```

Body:
The definition for foreach looks something like :

final  def  foreach(f: (A) ⇒ Unit): Unit

f : The function that is applied for its side-effect to every element.
               The result of function f is discarded

foreach in Scala is generally used to denote the usage of a function that involves a side-effect, e.g. printing to STDOUT.

If you want to return something by applying a particular function, you'll have to use map

final  def  map[B](f: (A) ⇒ B): List[B]

I copied the syntax from the documentation for List but it'll be something similar for RDDs as well.

As you can see, it works the function f on datatype A and returns a collection of datatype B where A and B can be the same data type as well.

val rdd = sc.parallelize(Array(
      "String1",
      "String2",
      "String3" ))

scala> rdd.foreach(x => (x, x.length) )

// Nothing happens

rdd.map(x => (x, x.length) ).collect

// Array[(String, Int)] = Array((String1,7), (String2,7), (String3,7))


问:
What is best text container for multiline text in IOS
I try to make Android/IOS app with chat in Visual Studio with Xamarin. And I have a problem with chat baloons.  For Android it's ok, I use Text View as message container. But in IOS I met a problem - If I use TextView I got only white rectangles. To implement list of messages I use UITableView with this code

```<code>public override void ViewDidLoad(){
  _chatsMessagesListAdapter = new MessagesTableSourceClass(chatData._messages);
  messagesList.Source = _chatsMessagesListAdapter;
}

public class MessagesTableSourceClass : UITableViewSource
    {
        readonly List<MessageData> _dataList;
        public MessagesTableSourceClass(List<MessageData> dataList)
        {
            _dataList = dataList;
        }
        public override nint RowsInSection(UITableView tableview, nint section)
        {
            return _dataList.Count;
        }
        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
OwnerMessageTableViewCell cell = tableView.DequeueReusableCell(MessageTableViewCell.Key) as OwnerMessageTableViewCell ?? OwnerMessageTableViewCell.Create();
cell.BindData(_dataList[indexPath.Row]._message, _dataList[indexPath.Row]._image);
return cell;
        }
        public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            tableView.DeselectRow(indexPath, true);
        }
        public override UIView GetViewForFooter(UITableView tableView, nint section)
        {
            return new UIView();
        }
    }
</code>```

OwnerMessageTableViewCell.xib is simple structure TableViewCell -> View -> TextView

But in result TableView messagesList is shown like white rectangle.
Can anybody help me with this problem?

UPDATED
Here the implementation of OwnerMessageTableViewCell

```<code>public partial class OwnerMessageTableViewCell : UITableViewCell
    {
        public static readonly UINib Nib = UINib.FromName("OwnerMessageTableViewCell", NSBundle.MainBundle);
        public static readonly NSString Key = new NSString("OwnerMessageTableViewCell");
        public OwnerMessageTableViewCell (IntPtr handle) : base (handle)
        {
        }
        public static OwnerMessageTableViewCell Create()
        {
            return (OwnerMessageTableViewCell)Nib.Instantiate(null, null)[0];
        }
        internal void BindData(string message, UIImage avatar)
        {
            messageIcon.Image = avatar;
            workerIcon.Hidden = false;
            messageText.Text = message;
        }
    }
</code>```

Here xib file content

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="13529" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13527"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <objects>
        <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
        <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" id="252" customClass="OwnerMessageTableViewCell" rowHeight="44">
            <rect key="frame" x="0.0" y="0.0" width="240" height="44"/>
            <autoresizingMask key="autoresizingMask"/>
            <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="252" id="253">
                <rect key="frame" x="0.0" y="0.0" width="240" height="43"/>
                <autoresizingMask key="autoresizingMask"/>
                <subviews>
                    <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" id="280" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" clipsSubviews="YES" image="Images/worker_icon.png">
                        <rect key="frame" x="190" y="0.0" width="50" height="50"/>
                        <autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMinY="YES"/>
                        <userDefinedRuntimeAttributes>
                            <userDefinedRuntimeAttribute keyPath="layer.cornerRadius" type="number">
                                <real key="value" value="25"/>
                            </userDefinedRuntimeAttribute>
                        </userDefinedRuntimeAttributes>
                    </imageView>
                    <textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" textAlignment="justified" id="307" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" text="Message Text here..." editable="NO" selectable="NO">
                        <rect key="frame" x="0.0" y="0.0" width="182" height="50"/>
                        <autoresizingMask key="autoresizingMask"/>
                        <color key="backgroundColor" colorSpace="calibratedRGB" red="0.094117647058823528" green="0.31372549019607843" blue="0.63921568627450975" alpha="1"/>
                        <fontDescription key="fontDescription" type="system" pointSize="14"/>
                        <textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
                        <color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
                        <inset key="scrollIndicatorInsets" minX="5" minY="5" maxX="5" maxY="5"/>
                        <userDefinedRuntimeAttributes>
                            <userDefinedRuntimeAttribute keyPath="layer.cornerRadius" type="number">
                                <real key="value" value="15"/>
                            </userDefinedRuntimeAttribute>
                        </userDefinedRuntimeAttributes>
                    </textView>
                    <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" id="384" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" image="Images/worker_icon.png">
                        <rect key="frame" x="220" y="30" width="20" height="20"/>
                        <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                    </imageView>
                </subviews>
            </tableViewCellContentView>
            <point key="canvasLocation" x="-132.5" y="-317"/>
            <connections>
                <outlet property="messageIcon" destination="280" id="name-outlet-280"/>
                <outlet property="messageText" destination="307" id="name-outlet-307"/>
                <outlet property="workerIcon" destination="384" id="name-outlet-384"/>
            </connections>
            <color key="backgroundColor" colorSpace="calibratedRGB" red="0.54117647058823526" green="0.54117647058823526" blue="0.54117647058823526" alpha="1"/>
        </tableViewCell>
    </objects>
    <resources>
        <image name="chat_bg.jpg" width="414" height="648"/>
    </resources>
</document>
</code>```

UPDATED

Here a screens of VS designer window

;

;

;

答: Create a uiview that will act as the container for the text view. Add the textview inside the uiview. Then set the colour of the text view to transparent. Set the constraints so that the text view is positioned correctly inside the uiview. Apply a corner radius to the uiview to make it appear like a bubble. You will need to adjust the height of the cell depending on the containing text.</p>

ContentLicense: CC BY-SA 4.0

Body:
I try to make Android/IOS app with chat in Visual Studio with Xamarin. And I have a problem with chat baloons.  For Android it's ok, I use Text View as message container. But in IOS I met a problem - If I use TextView I got only white rectangles. To implement list of messages I use UITableView with this code

public override void ViewDidLoad(){
  _chatsMessagesListAdapter = new MessagesTableSourceClass(chatData._messages);
  messagesList.Source = _chatsMessagesListAdapter;
}

public class MessagesTableSourceClass : UITableViewSource
    {
        readonly List<MessageData> _dataList;
        public MessagesTableSourceClass(List<MessageData> dataList)
        {
            _dataList = dataList;
        }
        public override nint RowsInSection(UITableView tableview, nint section)
        {
            return _dataList.Count;
        }
        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
OwnerMessageTableViewCell cell = tableView.DequeueReusableCell(MessageTableViewCell.Key) as OwnerMessageTableViewCell ?? OwnerMessageTableViewCell.Create();
cell.BindData(_dataList[indexPath.Row]._message, _dataList[indexPath.Row]._image);
return cell;
        }
        public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            tableView.DeselectRow(indexPath, true);
        }
        public override UIView GetViewForFooter(UITableView tableView, nint section)
        {
            return new UIView();
        }
    }

OwnerMessageTableViewCell.xib is simple structure TableViewCell -> View -> TextView

But in result TableView messagesList is shown like white rectangle.
Can anybody help me with this problem?

UPDATED
Here the implementation of OwnerMessageTableViewCell

public partial class OwnerMessageTableViewCell : UITableViewCell
    {
        public static readonly UINib Nib = UINib.FromName("OwnerMessageTableViewCell", NSBundle.MainBundle);
        public static readonly NSString Key = new NSString("OwnerMessageTableViewCell");
        public OwnerMessageTableViewCell (IntPtr handle) : base (handle)
        {
        }
        public static OwnerMessageTableViewCell Create()
        {
            return (OwnerMessageTableViewCell)Nib.Instantiate(null, null)[0];
        }
        internal void BindData(string message, UIImage avatar)
        {
            messageIcon.Image = avatar;
            workerIcon.Hidden = false;
            messageText.Text = message;
        }
    }

Here xib file content

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="13529" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13527"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <objects>
        <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
        <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" id="252" customClass="OwnerMessageTableViewCell" rowHeight="44">
            <rect key="frame" x="0.0" y="0.0" width="240" height="44"/>
            <autoresizingMask key="autoresizingMask"/>
            <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="252" id="253">
                <rect key="frame" x="0.0" y="0.0" width="240" height="43"/>
                <autoresizingMask key="autoresizingMask"/>
                <subviews>
                    <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" id="280" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" clipsSubviews="YES" image="Images/worker_icon.png">
                        <rect key="frame" x="190" y="0.0" width="50" height="50"/>
                        <autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMinY="YES"/>
                        <userDefinedRuntimeAttributes>
                            <userDefinedRuntimeAttribute keyPath="layer.cornerRadius" type="number">
                                <real key="value" value="25"/>
                            </userDefinedRuntimeAttribute>
                        </userDefinedRuntimeAttributes>
                    </imageView>
                    <textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" textAlignment="justified" id="307" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" text="Message Text here..." editable="NO" selectable="NO">
                        <rect key="frame" x="0.0" y="0.0" width="182" height="50"/>
                        <autoresizingMask key="autoresizingMask"/>
                        <color key="backgroundColor" colorSpace="calibratedRGB" red="0.094117647058823528" green="0.31372549019607843" blue="0.63921568627450975" alpha="1"/>
                        <fontDescription key="fontDescription" type="system" pointSize="14"/>
                        <textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
                        <color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
                        <inset key="scrollIndicatorInsets" minX="5" minY="5" maxX="5" maxY="5"/>
                        <userDefinedRuntimeAttributes>
                            <userDefinedRuntimeAttribute keyPath="layer.cornerRadius" type="number">
                                <real key="value" value="15"/>
                            </userDefinedRuntimeAttribute>
                        </userDefinedRuntimeAttributes>
                    </textView>
                    <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" id="384" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" image="Images/worker_icon.png">
                        <rect key="frame" x="220" y="30" width="20" height="20"/>
                        <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                    </imageView>
                </subviews>
            </tableViewCellContentView>
            <point key="canvasLocation" x="-132.5" y="-317"/>
            <connections>
                <outlet property="messageIcon" destination="280" id="name-outlet-280"/>
                <outlet property="messageText" destination="307" id="name-outlet-307"/>
                <outlet property="workerIcon" destination="384" id="name-outlet-384"/>
            </connections>
            <color key="backgroundColor" colorSpace="calibratedRGB" red="0.54117647058823526" green="0.54117647058823526" blue="0.54117647058823526" alpha="1"/>
        </tableViewCell>
    </objects>
    <resources>
        <image name="chat_bg.jpg" width="414" height="648"/>
    </resources>
</document>

UPDATED

Here a screens of VS designer window

;

;

;


问:
face_recognition.load_image_file("{}"), what does it mean?
I'm newbie in python. Now I'm working with python related project. I saw following code while I am searching in google related to project.

```<code>image = face_recognition.load_image_file("{}")
</code>```

What does "{}" do inside load_image_file() function? Also, When and where should I use it?

答:
It's hard to answer, without knowing more of how this method load_image_file works.  But here are 2 educated guesses which might be accurate:

{} would be an empty dictionary.  Dictionaries are very important and useful in Python and work with key:value pairs.  For instance, the following would be a more useful dictionary than the empty one given:

phone_nums = {'home': '867-5309', 'work': '555-1212'} would create a dictionary that has 2 keys ('home' and 'work'), which are associated with the 2 phone numbers.  For instance, phone_nums['home'] would yield 867-5309.

"{}" would be a JSON representation of an empty "Python dictionary". I put Python dictionary in quotes because a key aspect of the JSON representation is that it can "talk" across different languages.  You can write an object to a JSON structure in Python, then open it up in Javascript, or many other languages.  (I mention Javascript because that is where JSON originally comes from.)

But back to your question of what it's doing in that method.  If I were to guess, I'd say that the method:

Looks for a string that is in a JSON representation.

Looks for some relevant key name in that representation, such as something like 'filename': 'C:\\Users\\my_file.jpeg'.

If it cannot find the 'filename' keyword, then it uses a default path.

In this case, that's what's happening, and what the author of that snippet of code wanted.  However, s/he couldn't simply pass null or an empty string, if indeed there was some requirement of a JSON representation of an object/dictionary.  That's all entirely conjecture, though.

Body:
I'm newbie in python. Now I'm working with python related project. I saw following code while I am searching in google related to project.

image = face_recognition.load_image_file("{}")

What does "{}" do inside load_image_file() function? Also, When and where should I use it?


问:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
I have some code and when it executes, it throws a IndexOutOfRangeException, saying,

Index was outside the bounds of the array.

What does this mean, and what can I do about it?

Depending on classes used it can also be ArgumentOutOfRangeException

An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

答:
To easily understand the problem, imagine we wrote this code:

```<code>static void Main(string[] args)
{
    string[] test = new string[3];
    test[0]= "hello1";
    test[1]= "hello2";
    test[2]= "hello3";

    for (int i = 0; i <= 3; i++)
    {
        Console.WriteLine(test[i].ToString());
    }
}
</code>```

Result will be:

```<code>hello1
hello2
hello3

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
</code>```

Size of array is 3 (indices 0, 1 and 2), but the for-loop loops 4 times (0, 1, 2 and 3).
So when it tries to access outside the bounds with (3) it throws the exception.

Body:
To easily understand the problem, imagine we wrote this code:

static void Main(string[] args)
{
    string[] test = new string[3];
    test[0]= "hello1";
    test[1]= "hello2";
    test[2]= "hello3";

    for (int i = 0; i <= 3; i++)
    {
        Console.WriteLine(test[i].ToString());
    }
}

Result will be:

hello1
hello2
hello3

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.

Size of array is 3 (indices 0, 1 and 2), but the for-loop loops 4 times (0, 1, 2 and 3).
So when it tries to access outside the bounds with (3) it throws the exception.


问:
Wrong hibernate dialect for MSSQL 2014
I have a problem with inserting entities, that use sequences, to a MSSQL 2014 database. I use hibernate that is shipped with Wildfly 10 CR4 (but in CR1 and CR2 I got the same issue).

Here is a general info on the webapp run environment:

Wildfly 10 (CR4)

Java 8 u 51

Windows 7 Proffesional 64bit

MSSQL Server 2014

MSSQL driver: sqljdbc42.jar is deployed on the application server

My persistence.xml file looks like this:

```<code><persistence-unit name="mb_managed_pu" transaction-type="JTA">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <jta-data-source>java:/jdbc/datasource</jta-data-source>
    <properties>
        <property name="hibernate.archive.autodetection" value="class, hbm" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="true" />
        <property name="hibernate.jdbc.batch_size" value="0" />
        <property name="hibernate.default_schema_" value="openmap"/>
        <property name="hibernate.connection.useUnicode" value="yes"/>
        <property name="hibernate.connection.characterEncoding" value="UTF-8"/>
    </properties>
</persistence-unit>
</code>```

Now here is what happens when I run into an error.

First, when Wildfly is started, I can see this warning:

WARN  [org.hibernate.engine.jdbc.dialect.internal.StandardDialectResolver] (ServerService Thread Pool -- 68) HHH000385: Unknown Microsoft SQL Server major version [12] using SQL Server 2000 dialect

I looked through the web and found that this problem is already known since January 2015, but unfortunately it is still an open issue.

The error itself is raised when I try to persist a new entity that has the ID configured to use sequences:

```<code>@Id
@Column(name = "MAP_BOOKMARK_ID")
@SequenceGenerator(name = "SEQ_MAP_BOOKMARKS", sequenceName = "SEQ_MAP_BOOKMARKS", allocationSize = 1)
@GeneratedValue(generator = "SEQ_MAP_BOOKMARKS", strategy = GenerationType.SEQUENCE)
private long                    id;
</code>```

The exception raised is as follows:

com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name „SEQ_MAP_BOOKMARKS”.

This is not a surprise since hibernate is using the wrong dialect - the one that does not know anything about sequences.

When I modify persistence.xml and add this line:

```<code><property name="hibernate.dialect" value="org.hibernate.dialect.SQLServer2012Dialect"/>
</code>```

everything works like a charm.

The problem is that the application will also work with Oracle database on another server and on Postgres on another. I'd like to avoid having to prepare multiple versions of the same application.

Does anybody know of a solution to this problem ? Or should I wait for another Wildfly and/or hibernate version to appear ?

答:
For Springboot 1.4.7 and lower add below to properties file</p>

```<code>spring.jpa.properties.hibernate.dialect =org.hibernate.dialect.SQLServer2012Dialect
</code>```

Title: Wrong hibernate dialect for MSSQL 2014

Body:
I have a problem with inserting entities, that use sequences, to a MSSQL 2014 database. I use hibernate that is shipped with Wildfly 10 CR4 (but in CR1 and CR2 I got the same issue).

Here is a general info on the webapp run environment:

Wildfly 10 (CR4)

Java 8 u 51

Windows 7 Proffesional 64bit

MSSQL Server 2014

MSSQL driver: sqljdbc42.jar is deployed on the application server

My persistence.xml file looks like this:

<persistence-unit name="mb_managed_pu" transaction-type="JTA">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <jta-data-source>java:/jdbc/datasource</jta-data-source>
    <properties>
        <property name="hibernate.archive.autodetection" value="class, hbm" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="true" />
        <property name="hibernate.jdbc.batch_size" value="0" />
        <property name="hibernate.default_schema_" value="openmap"/>
        <property name="hibernate.connection.useUnicode" value="yes"/>
        <property name="hibernate.connection.characterEncoding" value="UTF-8"/>
    </properties>
</persistence-unit>

Now here is what happens when I run into an error.

First, when Wildfly is started, I can see this warning:

WARN  [org.hibernate.engine.jdbc.dialect.internal.StandardDialectResolver] (ServerService Thread Pool -- 68) HHH000385: Unknown Microsoft SQL Server major version [12] using SQL Server 2000 dialect

I looked through the web and found that this problem is already known since January 2015, but unfortunately it is still an open issue.

The error itself is raised when I try to persist a new entity that has the ID configured to use sequences:

@Id
@Column(name = "MAP_BOOKMARK_ID")
@SequenceGenerator(name = "SEQ_MAP_BOOKMARKS", sequenceName = "SEQ_MAP_BOOKMARKS", allocationSize = 1)
@GeneratedValue(generator = "SEQ_MAP_BOOKMARKS", strategy = GenerationType.SEQUENCE)
private long                    id;

The exception raised is as follows:

com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name „SEQ_MAP_BOOKMARKS”.

This is not a surprise since hibernate is using the wrong dialect - the one that does not know anything about sequences.

When I modify persistence.xml and add this line:

<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServer2012Dialect"/>

everything works like a charm.

The problem is that the application will also work with Oracle database on another server and on Postgres on another. I'd like to avoid having to prepare multiple versions of the same application.

Does anybody know of a solution to this problem ? Or should I wait for another Wildfly and/or hibernate version to appear ?

Body:
For Springboot 1.4.7 and lower add below to properties file

spring.jpa.properties.hibernate.dialect =org.hibernate.dialect.SQLServer2012Dialect


问:
Waterline: Find by value in JSON
I have a nested address attribute in one of my models.

```<code>attributes: {
  address: {
    type: 'json'
  }
}
</code>```

How can I find model instances located i.e. the same city.
I tried several queries:

```<code>Model.find({ "address.city": city })
Model.find({ address: { contains: city }})
</code>```

But none seem to work for. Any ideas on how to properly formulate this query?

答:
For sure, a mongo native call powered by Warerline works: https://sailsjs.com/documentation/reference/waterline-orm/models/native

Then the query object in your first attempt should work. Beware that then the mongodb documentation is the leading over the waterline one regarding query parameters. E.g. you need to cast ObjectId on id queries before using them in a native query.

Title: Waterline: Find by value in JSON

Body:
I have a nested address attribute in one of my models.

attributes: {
  address: {
    type: 'json'
  }
}

How can I find model instances located i.e. the same city.
I tried several queries:

Model.find({ "address.city": city })
Model.find({ address: { contains: city }})

But none seem to work for. Any ideas on how to properly formulate this query?


问:
How can I make custom SQL with order by in codeigniter
My code is here Sql Query :

```<code>$sql ="select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc";
$product=$this->db->query($sql)->result_array();
</code>```

view all products by using customs SQL but still not showing order by desc.

答:
Please try below code:</p>

```<code>$this->db->select('products.*');
$this->db->from('products');
$sql="status='1' AND country='5' AND (product_price > '50' AND product_price <= '100')";
$this->db->where($sql, NULL, FALSE)->order_by("product_id", "DESC");

$products_query = $this->db->get();

$products_info_array = array();

$products_info_array = $products_query->result_array();

return $products_info_array;
</code>```

Body:
My code is here Sql Query :

$sql ="select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc";
$product=$this->db->query($sql)->result_array();

view all products by using customs SQL but still not showing order by desc.

Body:
Please try below code:

$this->db->select('products.*');
$this->db->from('products');
$sql="status='1' AND country='5' AND (product_price > '50' AND product_price <= '100')";
$this->db->where($sql, NULL, FALSE)->order_by("product_id", "DESC");

$products_query = $this->db->get();

$products_info_array = array();

$products_info_array = $products_query->result_array();

return $products_info_array;


答:
It's better to use built-in Codeigniter Query-builder:</p>

```<code>$this->db->select('*');
$this->db->where([
    'status'    => 1,
    'country'   => 5,
    'product_price >' => 50,
    'product_price <=' => 100,
]);
$this->db->order_by('product_id', 'DESC');
$this->db->get('products');
$product = $this->db->result();
</code>```

Title: How can I make custom SQL with order by in codeigniter

Body:
It's better to use built-in Codeigniter Query-builder:

$this->db->select('*');
$this->db->where([
    'status'    => 1,
    'country'   => 5,
    'product_price >' => 50,
    'product_price <=' => 100,
]);
$this->db->order_by('product_id', 'DESC');
$this->db->get('products');
$product = $this->db->result();


问:
order from the newest post in ionic and firebase
i want to order from the newest post that i send to firebase but this code done do the thing that i want, this code just post from the last to the new post, but i want the new post place first.

here is the typescript :

```<code>this.db.list('/laporan/'+this.id,{query:{limitToLast :'7'}}).subscribe(data => {

      for(var i = 0,j=0; i<data.length;i++)
      {
              this.hehe[j]=data[i];
              j++;

      }
</code>```

here is the html

```<code><ul>
        <li *ngFor="let laporanHarian of hehe;">
          Tanggal :  <span> {{ laporanHarian.mydate.day}}</span> {{ laporanHarian.mydate.month}} {{ laporanHarian.mydate.year}} <br>
          Porsi Karbohidrat :{{ laporanHarian.porsiKarbohidrat }}<br>
          Porsi Protein Hewani :{{ laporanHarian.porsiProteinHewani }}<br>
          Porsi Protein Nabati : {{ laporanHarian.porsiProteinNabati }}<br>
          Porsi lemak : {{ laporanHarian.porsiLemak }}<br>
        </li>
      </ul>
</code>```

答:
I believe you want to reverse the response array so that the newest post becomes the first element. If you are using a library like lodash, then you could use the reverse method.

Alternatively you could just modify your code like:

```<code>for(var i=0,j=data.length; j > -1; j--) {
         this.hehe[j-1] = data[i];
         i++;
 }
</code>```

(The .length would return the number of elements in the array whereas the ordering will be 0 to length-1. Hence the [j-1])

Hope this helps you. Thanks.

Body:
i want to order from the newest post that i send to firebase but this code done do the thing that i want, this code just post from the last to the new post, but i want the new post place first.

here is the typescript :

this.db.list('/laporan/'+this.id,{query:{limitToLast :'7'}}).subscribe(data => {

      for(var i = 0,j=0; i<data.length;i++)
      {
              this.hehe[j]=data[i];
              j++;

      }

here is the html

          Tanggal :   {{ laporanHarian.mydate.day}} {{ laporanHarian.mydate.month}} {{ laporanHarian.mydate.year}}

          Porsi Karbohidrat :{{ laporanHarian.porsiKarbohidrat }}

          Porsi Protein Hewani :{{ laporanHarian.porsiProteinHewani }}

          Porsi Protein Nabati : {{ laporanHarian.porsiProteinNabati }}

          Porsi lemak : {{ laporanHarian.porsiLemak }}

Body:
I believe you want to reverse the response array so that the newest post becomes the first element. If you are using a library like lodash, then you could use the reverse method.

Alternatively you could just modify your code like:

for(var i=0,j=data.length; j > -1; j--) {
         this.hehe[j-1] = data[i];
         i++;
 }

(The .length would return the number of elements in the array whereas the ordering will be 0 to length-1. Hence the [j-1])

Hope this helps you. Thanks.


问:
Using decimal to binary conversion in SQL Server stored procedure
I need to be able to convert an int column to binary form. This column represents a combination of bit values to store multiple values in one column. I found a solution that creates a function to change an int value to its binary form but I cannot create additional functions in this database and would like to implement it in my procedure as is.

```<code>select @StoreFlags = r.StoreFlags
from insert I, StorageRule r
where r.Active = 1 and I.Active = 0

PRINT CONVERT(VARBINARY(16),@StoreFlags)

IF(@StoreFlags = 11)
    insert into StoreQueue (TimeToExecute, Operation, Parameter, StorageID, StoreFlags)
       select
           DateAdd(mi, @Time, getutcdate()), 1, I.ID, r.ID, r.StoreFlags
       from
           insert I, StorageRule r
       where
           r.Active = 1 and I.Active = 0
</code>```

The print statement above shows where I initially tried to convert to binary but that seems to be in hex form. the function below does what I need but I need to apply it against the variable @StoreFlags and specifically use the returned answer in the If statement instead of an integer constant. Thereafter I need to manipulate the bits to convert it to a new value.

```<code>CREATE FUNCTION dbo.Int2Binary (@i INT)
RETURNS NVARCHAR(16)
AS
BEGIN
    RETURN
        CASE WHEN CONVERT(VARCHAR(16), @i & 32768 ) > 0 THEN '1' ELSE '0'     END
        CASE WHEN CONVERT(VARCHAR(16), @i & 16384 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &  8192 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &  4096 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &  2048 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &  1024 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &   512 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &   256 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &   128 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &    64 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &    32 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &    16 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &     8 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &     4 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &     2 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &     1 ) > 0 THEN '1' ELSE '0'   END
 END;
 GO

 SELECT dbo.Int2Binary(11)
 GO
</code>```

Any advice on how to implement this.

EDIT:

Just to clarify; the function will return for 11: 0000000000001011. So I then need to change a single bit there to use in the insert following the If. Which in my case would be to change to the value 9, 0000000000001001.

答:
You can use this query instead of function:

```<code>DECLARE @StoreFlags int = 11,
        @StoreFlagsBin nvarchar(100) = N''

WHILE @StoreFlags > 0
BEGIN
    SET @StoreFlagsBin = @StoreFlagsBin + CAST(@StoreFlags%2 as nvarchar(1))
    SET @StoreFlags = @StoreFlags/2
END

SELECT REVERSE(@StoreFlagsBin)
</code>```

Output:

```<code>1011
</code>```

Body:
I need to be able to convert an int column to binary form. This column represents a combination of bit values to store multiple values in one column. I found a solution that creates a function to change an int value to its binary form but I cannot create additional functions in this database and would like to implement it in my procedure as is.

select @StoreFlags = r.StoreFlags
from insert I, StorageRule r
where r.Active = 1 and I.Active = 0

PRINT CONVERT(VARBINARY(16),@StoreFlags)

IF(@StoreFlags = 11)
    insert into StoreQueue (TimeToExecute, Operation, Parameter, StorageID, StoreFlags)
       select
           DateAdd(mi, @Time, getutcdate()), 1, I.ID, r.ID, r.StoreFlags
       from
           insert I, StorageRule r
       where
           r.Active = 1 and I.Active = 0

The print statement above shows where I initially tried to convert to binary but that seems to be in hex form. the function below does what I need but I need to apply it against the variable @StoreFlags and specifically use the returned answer in the If statement instead of an integer constant. Thereafter I need to manipulate the bits to convert it to a new value.

CREATE FUNCTION dbo.Int2Binary (@i INT)
RETURNS NVARCHAR(16)
AS
BEGIN
    RETURN
        CASE WHEN CONVERT(VARCHAR(16), @i & 32768 ) > 0 THEN '1' ELSE '0'     END
        CASE WHEN CONVERT(VARCHAR(16), @i & 16384 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &  8192 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &  4096 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &  2048 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &  1024 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &   512 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &   256 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &   128 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &    64 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &    32 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &    16 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &     8 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &     4 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &     2 ) > 0 THEN '1' ELSE '0'   END
        CASE WHEN CONVERT(VARCHAR(16), @i &     1 ) > 0 THEN '1' ELSE '0'   END
 END;
 GO

 SELECT dbo.Int2Binary(11)
 GO

Any advice on how to implement this.

EDIT:

Just to clarify; the function will return for 11: 0000000000001011. So I then need to change a single bit there to use in the insert following the If. Which in my case would be to change to the value 9, 0000000000001001.

Body:
You can use this query instead of function:

DECLARE @StoreFlags int = 11,
        @StoreFlagsBin nvarchar(100) = N''

WHILE @StoreFlags > 0
BEGIN
    SET @StoreFlagsBin = @StoreFlagsBin + CAST(@StoreFlags%2 as nvarchar(1))
    SET @StoreFlags = @StoreFlags/2
END

SELECT REVERSE(@StoreFlagsBin)

Output:

1011