问:
MYSQL query that can group by the highest datetime from two rows that might have the same value but flip flopped
I have a MYSQL 5.x database that I can't change the schema, read only access:

```<code>SELECT * FROM table;

--------------------+------------+------------+---------
stamp               | src        | dst        | data
--------------------+------------+------------+---------
2017-12-06 11:08:39 | 2055551234 | 2059999999 | somedata
2017-12-04 16:04:14 | 2059999999 | 2055551234 | somedata
2017-12-04 14:28:21 | 2055551234 | 2059999999 | somedata
2017-12-04 14:26:24 | 8004441111 | 2562428766 | somedata
2017-12-04 14:06:22 | 2562428766 | 8004441111 | somedata
2017-12-04 13:15:52 | 8004441111 | 2562428766 | somedata
+---------------------+------------+------------+-------
</code>```

I need all rows that service sets of two numbers, for example 2055551234 and 2055551234, each can be SRC or DST.  I need the most recent row.

I need rows that contain both 2055551234 and 2055551234 but in either SRC or DST columns.  The values can be in either column and thus my problem.

Each of the matching SRC,DST sets has multiple rows, I need the row with the most recent datetime from each set.

I thought I had it outsmarted when I decided to try to create a hash with MD5(SRC+DST) which would also equal MD5(DST+SRC) but I got unreliable results.

There can be anywhere from 1 to thousands of groups of rows that have matching sets.

I need to be able to LIMIT the results so just iterating client side isn't going to work because of the unknown rows in each group.

I can't store any procedures, any iterating work will have to be done client side.

From the above data I would like:

```<code>--------------------+------------+------------+---------
stamp               | src        | dst        | data
--------------------+------------+------------+---------
2017-12-06 11:08:39 | 2055551234 | 2059999999 | somedata
2017-12-04 14:26:24 | 8004441111 | 2562428766 | somedata
+---------------------+------------+------------+-------
</code>```

Thoughts?

答:
```<code>SELECT *
FROM mytbl AS t1
WHERE stamp IN (
    SELECT MAX(stamp) AS maxStamp
    FROM (
        SELECT *, CONCAT(GREATEST(src, dst), '.', LEAST(src, dst)) AS gbval
        FROM `mytbl` AS t2
    ) AS t3
    GROUP BY t3.gbval
    HAVING maxStamp = t1.stamp
)
</code>```

Does this work?

Body:
I have a MYSQL 5.x database that I can't change the schema, read only access:

SELECT * FROM table;

--------------------+------------+------------+---------
stamp               | src        | dst        | data
--------------------+------------+------------+---------
2017-12-06 11:08:39 | 2055551234 | 2059999999 | somedata
2017-12-04 16:04:14 | 2059999999 | 2055551234 | somedata
2017-12-04 14:28:21 | 2055551234 | 2059999999 | somedata
2017-12-04 14:26:24 | 8004441111 | 2562428766 | somedata
2017-12-04 14:06:22 | 2562428766 | 8004441111 | somedata
2017-12-04 13:15:52 | 8004441111 | 2562428766 | somedata
+---------------------+------------+------------+-------

I need all rows that service sets of two numbers, for example 2055551234 and 2055551234, each can be SRC or DST.  I need the most recent row.

I need rows that contain both 2055551234 and 2055551234 but in either SRC or DST columns.  The values can be in either column and thus my problem.

Each of the matching SRC,DST sets has multiple rows, I need the row with the most recent datetime from each set.

I thought I had it outsmarted when I decided to try to create a hash with MD5(SRC+DST) which would also equal MD5(DST+SRC) but I got unreliable results.

There can be anywhere from 1 to thousands of groups of rows that have matching sets.

I need to be able to LIMIT the results so just iterating client side isn't going to work because of the unknown rows in each group.

I can't store any procedures, any iterating work will have to be done client side.

From the above data I would like:

--------------------+------------+------------+---------
stamp               | src        | dst        | data
--------------------+------------+------------+---------
2017-12-06 11:08:39 | 2055551234 | 2059999999 | somedata
2017-12-04 14:26:24 | 8004441111 | 2562428766 | somedata
+---------------------+------------+------------+-------

Thoughts?

Body:
SELECT *
FROM mytbl AS t1
WHERE stamp IN (
    SELECT MAX(stamp) AS maxStamp
    FROM (
        SELECT *, CONCAT(GREATEST(src, dst), '.', LEAST(src, dst)) AS gbval
        FROM `mytbl` AS t2
    ) AS t3
    GROUP BY t3.gbval
    HAVING maxStamp = t1.stamp
)

Does this work?


来源: stackexchange

问:
422 (Unprocessable Entity) in Angular to post in laravel login api
i am trying to login using frontend(angular 4) to larvel auth api then i am getting this error on console log.

```<code>422 (Unprocessable Entity)
</code>```

it looks like sending empty form fields, this is response

```<code>{"message":"The given data was invalid.","errors":{"email":["The email field is required."],"password":["The password field is required."]}}
</code>```

It work fine in postman application for test, i also change content type(application/json and application/x-www-form-urlencoded) on angular code.

the error happens in login, for registration everything work fine.

this is login.components.ts file

```<code><div class="modal-body">
      <form [formGroup]="loginForm">
        <div class="input-group">
          <input type="email" class="form-control loc2" formControlName="email" placeholder="{{ 'LOGIN_DIALOG.EMAIL_PLACEHOLDER' | translate}}" required="">
          <p *ngIf="loginForm.get('email').hasError('validateEMAIL') && (loginForm.get('email').touched || formSubmit)" class="value-err show">{{ 'LOGIN_DIALOG.EMAIL_INVALID_MSG' | translate}}</p>
        </div>
        <div class="input-group">
          <input type="password" class="form-control loc" formControlName="password" placeholder="{{ 'LOGIN_DIALOG.PASSWORD_PLACEHOLDER' | translate}}" required="">
          <p *ngIf="loginForm.get('password').hasError('minlength') && (loginForm.get('password').touched || formSubmit)" class="value-err show">{{ 'LOGIN_DIALOG.PASSWORD_INVALID_LEN_MSG' | translate}}</p>
          <p *ngIf="loginForm.get('password').hasError('required') && (loginForm.get('password').touched || formSubmit)" class="value-err show">{{ 'LOGIN_DIALOG.PASSWORD_REQUIRED' | translate}}</p>
        </div>
        <p class="pull-right space10">{{ 'LOGIN_DIALOG.PASSWORD_FORGET' | translate}} </p>
        <div class="form-group">
          <button type="button" (click)="onClickLogin()" class="btn up me">{{ 'LOGIN_DIALOG.LOGIN_BUTTON' | translate}}</button>
        </div>
        <div class="form-group our">
          <input type="checkbox" id="custom_checkbox2">
          <label for="custom_checkbox2">{{ 'LOGIN_DIALOG.REMEMBER_ME' | translate}} </label>
        </div>
      </form>
      <p class="text-center">{{ 'LOGIN_DIALOG.LOGIN_WITH_MSG' | translate}}</p>
    </div>
</code>```

this is auth.service.ts file for login function

```<code>logInUser(signInData) {
    this.http.post(
      'api/login', { signInData }
    ).subscribe((res: Response) => {
      const data = res.json();
      if (data.error == 1) {
       // const message = data.error.user_authentication[0];
        this.toastyService.error(data.message);
      }else if (data.error == 2) {
        // const message = data.error.user_authentication[0];
         this.toastyService.error(data.message.original.message);
       } else {
        this.store.dispatch(this.authActions.loginSuccess(data));
        this.modalShow$.next(false);
        this.toastyService.success('Login Success');
        this.setTokenInLocalStorage(res.headers.toJSON());
      }
    });
  }
</code>```

this is http.ts, here i changed content type but not working.

```<code> post(url: string, body: any, options?: RequestOptionsArgs): Observable<any> {
    this.requestInterceptor();
    return super.post(this.getFullUrl(url), body, this.requestOptions(options))
      .catch(this.onCatch.bind(this))
      .do((res: Response) => {
        this.onSubscribeSuccess(res);
      }, (error: any) => {
        this.onSubscribeError(error);
      })
      .finally(() => {
        this.onFinally();
      });
  }

 private requestOptions(options?: RequestOptionsArgs): RequestOptionsArgs {
    if (options == null) {
      options = new RequestOptions();
    }

    if (options.headers == null) {
      const token = localStorage.getItem('accessToken');
      options.headers = new Headers({
        'Content-Type': 'application/json',
        'Authorization': token
      });
    }
    return options;
  }
</code>```

This is laravel loginController class for login function

```<code>public function login(Request $request)
    {
      $this->validateLogin($request);

        if ($this->attemptLogin($request)) {
            $user = $this->guard()->user();
            if($user['confirmed'] == 0){
                $response['error'] = 1;
                $response['message'] = "you havn't verified your email..";
                return response()->json($response, 201);
            }else{
                $user->generateToken();
                return response()->json(
                    $user->toArray()
               );
            }

        }
        $res['errors'] = 2;
        $res['message'] = $this->sendFailedLoginResponse($request);
       return response()->json($res, 201);
    }
</code>```

THis is AuthenticateUser.php file

```<code>trait AuthenticatesUsers
{
    use RedirectsUsers, ThrottlesLogins;

    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    protected function validateLogin(Request $request)
    {

        $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );
    }

    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }

    protected function authenticated(Request $request, $user)
    {
        //
    }

    protected function sendFailedLoginResponse(Request $request)
    {
        /*
        throw ValidationException::withMessages([
            $this->username() => [trans('auth.failed')],
        ]);*/
        return response()->JSON([ 'success' => false, 'message' => 'Invalid username or password!' ]);
     }
   public function username()
     {
        return 'email';
     }
}
</code>```

my response is here when giving any invalid input but i havent got this response in frontend but it work in postman application.

```<code>{
    "errors": 2,
    "message": {
        "headers": {},
        "original": {
            "success": false,
            "message": "Invalid username or password!"
        },
        "exception": null
    }
}
</code>```

when i check in laravel debugger i got

```<code>The given data was invalid.
</code>```

I tried related post of 422 error, but not able find solution. Where do i fix this issue?

答: I think it is not an error. Laravel validator sends validation responses with 422 error code if request type is ajax. Here the message is coming from sendFailedLoginResponse() function in AuthenticatesUsers class and that is looking fine. You can catch the JSON file and display to the page that is "Invalid username or password!". The problem you are getting the same error with correct credentials right? Check config/auth.php file has correct user model name and user model is Authenticatable </p>

ContentLicense: CC BY-SA 3.0

Body:
i am trying to login using frontend(angular 4) to larvel auth api then i am getting this error on console log.

422 (Unprocessable Entity)

it looks like sending empty form fields, this is response

{"message":"The given data was invalid.","errors":{"email":["The email field is required."],"password":["The password field is required."]}}

It work fine in postman application for test, i also change content type(application/json and application/x-www-form-urlencoded) on angular code.

the error happens in login, for registration everything work fine.

this is login.components.ts file

      <form [formGroup]="loginForm">

          <input type="email" class="form-control loc2" formControlName="email" placeholder="{{ 'LOGIN_DIALOG.EMAIL_PLACEHOLDER' | translate}}" required="">

{{ 'LOGIN_DIALOG.EMAIL_INVALID_MSG' | translate}}

          <input type="password" class="form-control loc" formControlName="password" placeholder="{{ 'LOGIN_DIALOG.PASSWORD_PLACEHOLDER' | translate}}" required="">

{{ 'LOGIN_DIALOG.PASSWORD_INVALID_LEN_MSG' | translate}}

{{ 'LOGIN_DIALOG.PASSWORD_REQUIRED' | translate}}

{{ 'LOGIN_DIALOG.PASSWORD_FORGET' | translate}}

          <button type="button" (click)="onClickLogin()" class="btn up me">{{ 'LOGIN_DIALOG.LOGIN_BUTTON' | translate}}</button>

          <input type="checkbox" id="custom_checkbox2">
          {{ 'LOGIN_DIALOG.REMEMBER_ME' | translate}}

      </form>

{{ 'LOGIN_DIALOG.LOGIN_WITH_MSG' | translate}}

this is auth.service.ts file for login function

logInUser(signInData) {
    this.http.post(
      'api/login', { signInData }
    ).subscribe((res: Response) => {
      const data = res.json();
      if (data.error == 1) {
       // const message = data.error.user_authentication[0];
        this.toastyService.error(data.message);
      }else if (data.error == 2) {
        // const message = data.error.user_authentication[0];
         this.toastyService.error(data.message.original.message);
       } else {
        this.store.dispatch(this.authActions.loginSuccess(data));
        this.modalShow$.next(false);
        this.toastyService.success('Login Success');
        this.setTokenInLocalStorage(res.headers.toJSON());
      }
    });
  }

this is http.ts, here i changed content type but not working.

 post(url: string, body: any, options?: RequestOptionsArgs): Observable<any> {
    this.requestInterceptor();
    return super.post(this.getFullUrl(url), body, this.requestOptions(options))
      .catch(this.onCatch.bind(this))
      .do((res: Response) => {
        this.onSubscribeSuccess(res);
      }, (error: any) => {
        this.onSubscribeError(error);
      })
      .finally(() => {
        this.onFinally();
      });
  }

 private requestOptions(options?: RequestOptionsArgs): RequestOptionsArgs {
    if (options == null) {
      options = new RequestOptions();
    }

    if (options.headers == null) {
      const token = localStorage.getItem('accessToken');
      options.headers = new Headers({
        'Content-Type': 'application/json',
        'Authorization': token
      });
    }
    return options;
  }

This is laravel loginController class for login function

public function login(Request $request)
    {
      $this->validateLogin($request);

        if ($this->attemptLogin($request)) {
            $user = $this->guard()->user();
            if($user['confirmed'] == 0){
                $response['error'] = 1;
                $response['message'] = "you havn't verified your email..";
                return response()->json($response, 201);
            }else{
                $user->generateToken();
                return response()->json(
                    $user->toArray()
               );
            }

        }
        $res['errors'] = 2;
        $res['message'] = $this->sendFailedLoginResponse($request);
       return response()->json($res, 201);
    }

THis is AuthenticateUser.php file

trait AuthenticatesUsers
{
    use RedirectsUsers, ThrottlesLogins;

    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    protected function validateLogin(Request $request)
    {

        $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );
    }

    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }

    protected function authenticated(Request $request, $user)
    {
        //
    }

    protected function sendFailedLoginResponse(Request $request)
    {
        /*
        throw ValidationException::withMessages([
            $this->username() => [trans('auth.failed')],
        ]);*/
        return response()->JSON([ 'success' => false, 'message' => 'Invalid username or password!' ]);
     }
   public function username()
     {
        return 'email';
     }
}

my response is here when giving any invalid input but i havent got this response in frontend but it work in postman application.

{
    "errors": 2,
    "message": {
        "headers": {},
        "original": {
            "success": false,
            "message": "Invalid username or password!"
        },
        "exception": null
    }
}

when i check in laravel debugger i got

The given data was invalid.

I tried related post of 422 error, but not able find solution. Where do i fix this issue?


问:
How to stop AWS Lambda [Nodejs]
I have a function within AWS Lambda uses runtime Node.js 6.10. Lambda runs my code fine but continues "executing" even though the code is completed. What I would like to happen is that Lambda stops when the code is completed. I have my logs below to see if anyone can see what the issue is. Note my callback to end the function returns success

{
  "errorMessage": "2017-12-07T17:50:55.618Z e4a5bb77-db76-11e7-b2e6-514284a81613 Task timed out after 120.09 seconds"
}

START RequestId: e4a5bb77-db76-11e7-b2e6-514284a81613 Version: $LATEST
2017-12-07T17:48:55.527Z    e4a5bb77-db76-11e7-b2e6-514284a81613    -L-llvVALjYpyUV0M6EG //gotten from code
2017-12-07T17:48:58.652Z    e4a5bb77-db76-11e7-b2e6-514284a81613    http://www.loopnewsbarbados.com/content/bitcoin-worth-millions-stolen-days-us-exchange-opens-1 //gotten from code
2017-12-07T17:49:01.150Z    e4a5bb77-db76-11e7-b2e6-514284a81613    crisis, //gotten from code
2017-12-07T17:49:01.232Z    e4a5bb77-db76-11e7-b2e6-514284a81613    success //successful callback
END RequestId: e4a5bb77-db76-11e7-b2e6-514284a81613
REPORT RequestId: e4a5bb77-db76-11e7-b2e6-514284a81613  Duration: 120093.31 ms  Billed Duration: 120000 ms  Memory Size: 128 MB Max Memory Used: 34 MB

2017-12-07T17:50:55.618Z e4a5bb77-db76-11e7-b2e6-514284a81613 Task timed out after 120.09 seconds

答:
Just put

```<code>process.exit(0)
</code>```

to terminate the execution.

Title: How to stop AWS Lambda [Nodejs]

Body:
Just put

process.exit(0)

to terminate the execution.


问:
How do you get the full set of compiler and linker flags used by ndk-build?
Is there a straightforward way to get the full set of compile and linker flags used by NDK builds?  Right now we're hacking things by looking through the cmake files created when you add C++ to an Android Studio project.

The problem is that the vast majority of the time we're building many existing 3rd-party projects that each have their own build systems.  Rewriting the build systems to use Android's tools (the cmake and ndk-build systems) would be insane; we need to use the existing make systems, and the vast majority of the time that means we need to provide things like CFLAGS, CXX_FLAGS, CPPFLAGS, LDFLAGS, etc to configuration scripts.  And those sets of flags aren't documented anywhere that I've found, other than by watching the output of native Android ndk builds.

UPDATE:  I think I wasn't quite clear on exactly what I wanted.

We had some nasty scripts that managed to suck the right set of flags out of an existing build using cmake.  (One of those projects where you say it'll take you twenty minutes, and you're laughably wrong.).  Those scripts broke with r16 beta 1.  I'd really not have to write nasty unstable scripts just to pull out flags, since they'll probably break with the next ndk release anyway.

(Here's the last output from our scripts, in case you'd like to see the flags I'm talking about: https://gist.github.com/banshee/15f1a5fbce0c71af6498656bb02ebc67)

答:
Use cmake to drive configure, or to write out the values in whatever format you need.

For example, here's a CMakeLists.txt file that configures and compiles the expat project.  It expects the source for expat to be on the system already.  Probably most of what you want is in the standard_configure_env macro; it's the modified CFLAGS etc that you'll want.

```<code>cmake_minimum_required(VERSION 3.6)

project (expat)

macro(standard_configure_env output)
set(${output}
    CC=${ANDROID_C_COMPILER}
    CXX=${ANDROID_CXX_COMPILER}
    CFLAGS=--target=${CMAKE_C_COMPILER_TARGET}\ --sysroot=${ANDROID_SYSROOT}\ \ --gcc-toolchain=${ANDROID_TOOLCHAIN_ROOT}\ ${ANDROID_COMPILER_FLAGS}
    CXXFLAGS=${ANDROID_COMPILER_FLAGS_CXX}
    AR=${ANDROID_AR}
    RANLIB=${ANDROID_RANLIB}
    LD=${CMAKE_LINKER}
    LDFLAGS=${ANDROID_LINKER_FLAGS}
)
endmacro()

include(ProcessorCount)
ProcessorCount(nCpus)

set(expat_output_dir ${CMAKE_CURRENT_BINARY_DIR}/expat)
set(expat_build_dir ${expat_output_dir}/expat_bin)
set(expat_install_dir ${expat_output_dir}/install)
set(expat_src_dir /Users/james/yourpathgoeshere/cmake/expat/src/expat-2.1.0)

set(markers_dir ${expat_output_dir}/markers)
file(MAKE_DIRECTORY ${markers_dir})

set(expat_copied ${markers_dir}/copied)
set(expat_configured ${markers_dir}/configured)

set(expat_final_lib ${expat_install_dir}/lib/libexpat.a)

file(MAKE_DIRECTORY ${expat_install_dir}/include)

standard_configure_env(configure_env)

set(configure_host ${ANDROID_HEADER_TRIPLE})
# expat doesn't understand these Android architectures, so set them by hand to what expat can
# use
if(${configure_host} STREQUAL aarch64-linux-android)
set(configure_host arm-linux-android64v8a)
elseif(${configure_host} STREQUAL armv7-linux-androideabi)
set(configure_host arm-linux-androideabiv7a)
endif()

set(configure_args
    --host=${configure_host}
    --disable-shared
    --prefix=${expat_output_dir}/install
    --exec-prefix=${expat_output_dir}/install
    )

add_custom_command(
    OUTPUT ${expat_configured}
    COMMAND ${configure_env} ./configure ${configure_args} && touch ${expat_configured}
    DEPENDS ${expat_copied}
    WORKING_DIRECTORY ${expat_build_dir}
    )

add_custom_command(
    OUTPUT ${expat_copied}
    COMMAND ${CMAKE_COMMAND} -E copy_directory ${expat_src_dir} ${expat_build_dir}
    COMMAND touch ${expat_copied}
    )

add_custom_command(
    OUTPUT ${expat_final_lib}
    COMMAND make -j${nCpus} installlib && touch ${expat_final_lib}
    WORKING_DIRECTORY ${expat_build_dir}
    DEPENDS ${expat_configured}
    )

add_custom_target(expat_build DEPENDS ${expat_final_lib})
add_library(expat STATIC IMPORTED GLOBAL)
add_dependencies(expat expat_build)

set_target_properties(expat
  PROPERTIES
  LINKER_LANGUAGE CXX
  IMPORTED_LOCATION ${expat_install_dir}/lib/libexpat.a
  INTERFACE_INCLUDE_DIRECTORIES ${expat_install_dir}/include)
</code>```

Thanks to @DanAlbert and @JakubPiskorz for pointing out that I really do want to get this from cmake.

Body:
Use cmake to drive configure, or to write out the values in whatever format you need.

For example, here's a CMakeLists.txt file that configures and compiles the expat project.  It expects the source for expat to be on the system already.  Probably most of what you want is in the standard_configure_env macro; it's the modified CFLAGS etc that you'll want.

cmake_minimum_required(VERSION 3.6)

project (expat)

macro(standard_configure_env output)
set(${output}
    CC=${ANDROID_C_COMPILER}
    CXX=${ANDROID_CXX_COMPILER}
    CFLAGS=--target=${CMAKE_C_COMPILER_TARGET}\ --sysroot=${ANDROID_SYSROOT}\ \ --gcc-toolchain=${ANDROID_TOOLCHAIN_ROOT}\ ${ANDROID_COMPILER_FLAGS}
    CXXFLAGS=${ANDROID_COMPILER_FLAGS_CXX}
    AR=${ANDROID_AR}
    RANLIB=${ANDROID_RANLIB}
    LD=${CMAKE_LINKER}
    LDFLAGS=${ANDROID_LINKER_FLAGS}
)
endmacro()

include(ProcessorCount)
ProcessorCount(nCpus)

set(expat_output_dir ${CMAKE_CURRENT_BINARY_DIR}/expat)
set(expat_build_dir ${expat_output_dir}/expat_bin)
set(expat_install_dir ${expat_output_dir}/install)
set(expat_src_dir /Users/james/yourpathgoeshere/cmake/expat/src/expat-2.1.0)

set(markers_dir ${expat_output_dir}/markers)
file(MAKE_DIRECTORY ${markers_dir})

set(expat_copied ${markers_dir}/copied)
set(expat_configured ${markers_dir}/configured)

set(expat_final_lib ${expat_install_dir}/lib/libexpat.a)

file(MAKE_DIRECTORY ${expat_install_dir}/include)

standard_configure_env(configure_env)

set(configure_host ${ANDROID_HEADER_TRIPLE})
# expat doesn't understand these Android architectures, so set them by hand to what expat can
# use
if(${configure_host} STREQUAL aarch64-linux-android)
set(configure_host arm-linux-android64v8a)
elseif(${configure_host} STREQUAL armv7-linux-androideabi)
set(configure_host arm-linux-androideabiv7a)
endif()

set(configure_args
    --host=${configure_host}
    --disable-shared
    --prefix=${expat_output_dir}/install
    --exec-prefix=${expat_output_dir}/install
    )

add_custom_command(
    OUTPUT ${expat_configured}
    COMMAND ${configure_env} ./configure ${configure_args} && touch ${expat_configured}
    DEPENDS ${expat_copied}
    WORKING_DIRECTORY ${expat_build_dir}
    )

add_custom_command(
    OUTPUT ${expat_copied}
    COMMAND ${CMAKE_COMMAND} -E copy_directory ${expat_src_dir} ${expat_build_dir}
    COMMAND touch ${expat_copied}
    )

add_custom_command(
    OUTPUT ${expat_final_lib}
    COMMAND make -j${nCpus} installlib && touch ${expat_final_lib}
    WORKING_DIRECTORY ${expat_build_dir}
    DEPENDS ${expat_configured}
    )

add_custom_target(expat_build DEPENDS ${expat_final_lib})
add_library(expat STATIC IMPORTED GLOBAL)
add_dependencies(expat expat_build)

set_target_properties(expat
  PROPERTIES
  LINKER_LANGUAGE CXX
  IMPORTED_LOCATION ${expat_install_dir}/lib/libexpat.a
  INTERFACE_INCLUDE_DIRECTORIES ${expat_install_dir}/include)

Thanks to @DanAlbert and @JakubPiskorz for pointing out that I really do want to get this from cmake.


问:
Eliminate style loading using media queries
I try to speed up initial loading by eliminating unnecessary downloading.
I split styles in to portrait and landscape css.
And want to load only one style based on media queries.
But is seems they are loading together.

  <link rel="stylesheet" type="text/css" href="style-p.css" media="(orientation: portrait)" />
  <link rel="stylesheet" type="text/css" href="style-l.css" media="(orientation: landscape)" />
```

答:
In media attribute, Use screen and (orientation: portrait) Instead of (orientation: ********)

```<code><link rel="stylesheet" type="text/css" href="style-p.css" media="screen and (orientation: portrait)" />
<link rel="stylesheet" type="text/css" href="style-l.css" media="screen and (orientation: landscape)" />
</code>```

Body:
In media attribute, Use screen and (orientation: portrait) Instead of (orientation: ********)

<link rel="stylesheet" type="text/css" href="style-p.css" media="screen and (orientation: portrait)" />
<link rel="stylesheet" type="text/css" href="style-l.css" media="screen and (orientation: landscape)" />


问:
Chrome: Mixed content issue for local IP address 192.168
I have a website which is all secure content on https and am using javascript sdk for local network printer which starts with 192.168.x.x
My printer is listening on that IP address with port 8008 (http)
When my application starts printing, the printer is initialized as soemthing like this
http://192.168.199.69:8008/socket.io/1/?t=1512574905603
Chrome is blocking this request and I am not able to print. Error msg as below.

How can I tell chrome that its a local URL and make it allow to request that URL?

epos-2.6.0.js:6 Mixed Content: The page at 'https://mywebsite/order-list.html' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://192.168.199.69:8008/socket.io/1/?t=1512574905603'. This request has been blocked; the content must be served over HTTPS.

答:
Get a self signed certificate, upload to your service/server and there you go.
However the basic question of getting around http in a mixed content mode still remains or it won't be allowed..
Firefox adds an exception but chrome , im not sure</p>


问:
Trying to get a Java function to return an array based on a string parameter passed to it
Here's what I am trying to do; I am trying to write a small program that uses a function to get an array containing the members of a department based on the department selected. There are about 40 departments, and each department has 1 to 4 members. So this what I did, but I can't seem to resolve to a variable:

From main:

```<code>String[]names = initial(department)
</code>```

Departments is the name of the department being passed to the function. In the function I have:

```<code>public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }
</code>```

So the way it stands, "assignInitial cannot be resolved to a variable" (that's what it says by the return statement.) If I try to initialize the variable before the first "if" statement, and then remove the initialization of String[] next to the assignInitial in the first "if" statement, then it says "Array constants can only be used in initializers." I am sure there is a better way to do this, but I can't seem to make any headway with what I am found online. Any takers?

Thank you much!
-The Munch

答:
You can also do it this way and skip the whole variable thing. If it doesn't match anything it will return an empty array.</p>

```<code>public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        return new String[] {"Mike Davis", "Ben Jones", "Ann Smith"};
     }

    if (responsibleDepartment.equals("Customer Service")) {
         return new String[] {"Mary Wexler", "Turd Ferguson"};
     }

    return new String[] {};

}
</code>```

Body:
Here's what I am trying to do; I am trying to write a small program that uses a function to get an array containing the members of a department based on the department selected. There are about 40 departments, and each department has 1 to 4 members. So this what I did, but I can't seem to resolve to a variable:

From main:

String[]names = initial(department)

Departments is the name of the department being passed to the function. In the function I have:

public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }

So the way it stands, "assignInitial cannot be resolved to a variable" (that's what it says by the return statement.) If I try to initialize the variable before the first "if" statement, and then remove the initialization of String[] next to the assignInitial in the first "if" statement, then it says "Array constants can only be used in initializers." I am sure there is a better way to do this, but I can't seem to make any headway with what I am found online. Any takers?

Thank you much!
-The Munch

Body:
You can also do it this way and skip the whole variable thing. If it doesn't match anything it will return an empty array.

public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        return new String[] {"Mike Davis", "Ben Jones", "Ann Smith"};
     }

    if (responsibleDepartment.equals("Customer Service")) {
         return new String[] {"Mary Wexler", "Turd Ferguson"};
     }

    return new String[] {};

}


问:
jquery animate opacity has an impact of other divs? weird behavior
I've got a really strange jquery behavior. I want to make a grid like background with animated tiles (opacity to .8 and back to .25 on mouseover and mouseleave).

As this should be my background it should'n have an impact on my content div.

Unfortunately it doesn't work as expected. THe content div(Which i colored red for testing purposes) gets animated, too.

Here's a link the the site.

答:
Part of the problem could be that, when you mouseover the background tiles, the event is bubbling up to the content div. You could try doing this somewhere in your event listeners:</p>

```<code>e.stopPropagation();
</code>```

Body:
Part of the problem could be that, when you mouseover the background tiles, the event is bubbling up to the content div. You could try doing this somewhere in your event listeners:

e.stopPropagation();

ContentLicense: CC BY-SA 2.5


问:
How to write raw MongoDB command involving regex in Pymongo
In a mongo shell, I'm able to execute this command:

```<code>db.getSiblingDB('myDatabase')
.myCollection
.find({
    city_id:{$ne:123},
    company: {$not: new RegExp('^acme.*', 'i')}
})
.forEach(function (item) {
    var x = db.myCollection.findOne({
        city_id:123,
        company:'abc123'
    });
    item.address = x.address;
    item.phone = x.phone;

    db.myCollection.deleteOne({_id: item._id});
    db.myCollection.insert(item);
});
</code>```

How to write such in pymongo or any other mongodb python driver?

答:
According to suggestion from @AnirudhBagri, Here's what worked:</p>

```<code>x = db.myCollection.find_one({city_id:123, company:'abc123'})
for item in db.myCollection.find({"$and": [{"city_id": {'$ne':123}}, {"company": {'$not': re.compile('^acme.*')}}]}):
    item.address = x.address
    item.phone = x.phone
    db.myCollection.delete_one({"_id": item._id});
    db.myCollection.insert(item)
</code>```

Body:
In a mongo shell, I'm able to execute this command:

db.getSiblingDB('myDatabase')
.myCollection
.find({
    city_id:{$ne:123},
    company: {$not: new RegExp('^acme.*', 'i')}
})
.forEach(function (item) {
    var x = db.myCollection.findOne({
        city_id:123,
        company:'abc123'
    });
    item.address = x.address;
    item.phone = x.phone;

    db.myCollection.deleteOne({_id: item._id});
    db.myCollection.insert(item);
});

How to write such in pymongo or any other mongodb python driver?

Body:
According to suggestion from @AnirudhBagri, Here's what worked:

x = db.myCollection.find_one({city_id:123, company:'abc123'})
for item in db.myCollection.find({"$and": [{"city_id": {'$ne':123}}, {"company": {'$not': re.compile('^acme.*')}}]}):
    item.address = x.address
    item.phone = x.phone
    db.myCollection.delete_one({"_id": item._id});
    db.myCollection.insert(item)


问:
Param I'm trying to pass through hidden field is showing as an object?
I am trying to use a hidden field in a form to pass a param with a value of 1 to a method in my controller, which will add the value to the quantity of an order item in a shopping cart. When I check what I'm getting with a binding pry, I see that for params the :update_by param I am trying to pass is showing as an object "order_items=>{"update_by"=>"1"}. So, when I try to grab the param in the method using params[:update_by], I get nil (or 0 if .to_i). Why is the param an object?

Please see the html for the form

```<code><% if @order_items.any? %>
  <% @order_items.each do |item| %>
    <%= form_for item do |f| %>
      <%= f.hidden_field :update_by, value: 1 %>
        <%= button_tag type:"submit", class: "cart_quantity_button"
        do %>
        <i class="fa fa-plus-circle" aria-hidden="true"></i>
      <% end %>
    <% end %>
<% end %>
</code>```

And the method in the controller

```<code>def update
  @order = current_order
  @item = OrderItem.find(params[:id])
  @item.update(:quantity=> @item.quantity + params[:update_by].to_i)
  @item.save!
  redirect_to cart_path
end

private

def item_params
  params.require(:order_item).permit(:quantity, :product_id,
  :user_id, :update_by)
  end
end
</code>```

I am grabbing the data I want from the other varaiables in my method. The problem is that I can't grab the value of :update_by if it's an object, right? Let me know if you need any more information. Thanks!

答:
You have this for your form:

```<code><%= form_for item do |f| %>
  <%= f.hidden_field :update_by, value: 1 %>
  ...
<% end %>
</code>```

and item is an OrderItem. That means that everything that f's methods produce (such as that f.hidden_field) will live inside the order_item namespace. Hence the

```<code>"order_item"=>{"update_by"=>"1"}
</code>```

in your controller. You can also see this in your item_params controller method:

```<code>def item_params
  params.require(:order_item).permit(:quantity, :product_id, :user_id, :update_by)
  end
end
</code>```

The require call means that you're looking for "order_item" and the permit call means that you're looking for those things inside "order_item".

You should use your item_params method to unpack the parameters:

```<code>@item.update(:quantity => @item.quantity + item_params[:update_by].to_i)
</code>```

Body:
I am trying to use a hidden field in a form to pass a param with a value of 1 to a method in my controller, which will add the value to the quantity of an order item in a shopping cart. When I check what I'm getting with a binding pry, I see that for params the :update_by param I am trying to pass is showing as an object "order_items=>{"update_by"=>"1"}. So, when I try to grab the param in the method using params[:update_by], I get nil (or 0 if .to_i). Why is the param an object?

Please see the html for the form

<% if @order_items.any? %>
  <% @order_items.each do |item| %>
    <%= form_for item do |f| %>
      <%= f.hidden_field :update_by, value: 1 %>
        <%= button_tag type:"submit", class: "cart_quantity_button"
        do %>

      <% end %>
    <% end %>
<% end %>

And the method in the controller

def update
  @order = current_order
  @item = OrderItem.find(params[:id])
  @item.update(:quantity=> @item.quantity + params[:update_by].to_i)
  @item.save!
  redirect_to cart_path
end

private

def item_params
  params.require(:order_item).permit(:quantity, :product_id,
  :user_id, :update_by)
  end
end

I am grabbing the data I want from the other varaiables in my method. The problem is that I can't grab the value of :update_by if it's an object, right? Let me know if you need any more information. Thanks!

Body:
You have this for your form:

<%= form_for item do |f| %>
  <%= f.hidden_field :update_by, value: 1 %>
  ...
<% end %>

and item is an OrderItem. That means that everything that f's methods produce (such as that f.hidden_field) will live inside the order_item namespace. Hence the

"order_item"=>{"update_by"=>"1"}

in your controller. You can also see this in your item_params controller method:

def item_params
  params.require(:order_item).permit(:quantity, :product_id, :user_id, :update_by)
  end
end

The require call means that you're looking for "order_item" and the permit call means that you're looking for those things inside "order_item".

You should use your item_params method to unpack the parameters:

@item.update(:quantity => @item.quantity + item_params[:update_by].to_i)


问:
Empty closing div at the beginning of loop surrounding a grouping
I don't even know what to search for, so what I've tried is not much since I'm stumped.

This is the loop, getting the month name and then grouping the events inside that month. The comment //* Close the Div : PROBLEM is where the issue is. The code does what it's supposed to do, but there is an empty div before the list.

```<code>if ( have_posts() ) :

    $current_month = '';

    while ( have_posts() ) : the_post();

            if( $current_month != eo_get_the_start( 'm' ) ) :

                    $month = eo_get_the_start('F Y');

                    //* Close the Div : PROBLEM this is where it echos an empty closing div before first month name
                    echo '</div><!-- /events-by-month -->';

                    //* Start new group
                    echo '<h3 class="event-month" id="'. $month . '">' . $month . '</h3>';

                    //* Open div around the events in this month
                    echo '<div class="events-by-month" style="border:1px solid green">'; //* inline style so I can see

            endif;

                $current_month = eo_get_the_start('m');

                eo_get_template_part( 'eo-loop-single-event' );

    endwhile;

    //* Genesis Numbered Pagination
    genesis_numeric_posts_nav();

    else:

        echo '<p>'. __( 'No Events', 'joyful' ) . '</p>';

endif;
</code>```

答:
Your while loop is going to initially loop once and echo out the closing tag before an initial opening tag has been echoed.

Simply checking that $current_month is not empty should fix it.

echo !empty($current_month) ? '
' : null;

Body:
I don't even know what to search for, so what I've tried is not much since I'm stumped.

This is the loop, getting the month name and then grouping the events inside that month. The comment //* Close the Div : PROBLEM is where the issue is. The code does what it's supposed to do, but there is an empty div before the list.

if ( have_posts() ) :

    $current_month = '';

    while ( have_posts() ) : the_post();

            if( $current_month != eo_get_the_start( 'm' ) ) :

                    $month = eo_get_the_start('F Y');

                    //* Close the Div : PROBLEM this is where it echos an empty closing div before first month name
                    echo '
';

                    //* Start new group
                    echo '
' . $month . '
';

                    //* Open div around the events in this month
                    echo '
'; //* inline style so I can see

            endif;

                $current_month = eo_get_the_start('m');

                eo_get_template_part( 'eo-loop-single-event' );

    endwhile;

    //* Genesis Numbered Pagination
    genesis_numeric_posts_nav();

    else:

        echo '
'. __( 'No Events', 'joyful' ) . '
';

endif;

Body:
Your while loop is going to initially loop once and echo out the closing tag before an initial opening tag has been echoed.

Simply checking that $current_month is not empty should fix it.

echo !empty($current_month) ? '</div><!-- /events-by-month -->' : null;


问:
Converting a date and and a char 'time' field to a single date
I am trying to concatenate two fields and load the data into a date field.

I have a table with hier_dt as DATE datatype and hier_tm as CHAR datatype, with data like:

```<code>hier_dt   | hier_tm
16-JAN-17 | 16:54
16-JAN-17 | 16:54
16-JAN-17 | 16:54
16-JAN-17 | 16:54
17-JAN-17 | 17:54
</code>```

I would like to concatenate both of these into a single DATE datatype field, to produce:

```<code>hier_dt_tm
----------------
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/17 17:54
</code>```

Is there a way I can accomplish this?

My current query is:

```<code>select to_date(concat(to_char(NVL(hier_DT,'01-JAN-1900'), 'yyyy/mm/dd'),
  concat(' ',NVL(hier_tm,'00:00'))), 'yyyy/mm/dd hh24:mi') as temp
from XXX1
</code>```

答:
A slight variation on the other ideas is to leave hier_dt as a date, and figure out the fraction of a day that hier_tm represents. One way to do that is to convert just the time to a date - which defaults everything else to the first of the current month - and subtract the first from that, then add the result to hier_dt:

```<code>hier_dt + (to_date(hier_tm, 'HH24:MI') - trunc(sysdate, 'MM')
</code>```

With explicit formatting back to a string just for display purposes:

```<code>select to_char(
    hier_dt + (to_date(hier_tm, 'HH24:MI') - trunc(sysdate, 'MM')),
    'YYYY/MM/DD HH24:MI') as temp
from xxx1;

TEMP
----------------
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/17 17:54
</code>```

Yet another way is to convert the time to an interval datatype using the to_dsinterval() function, which involves tacking on dummy day and second values to make the string something that function recognises:

```<code>hier_dt + to_dsinterval('0 ' || hier_tm || ':00')
</code>```

Without explicit conversion to string this time, relying instead on NLS settings:

```<code>alter session set nls_date_format = 'YYYY/MM/DD HH24:MI';

select hier_dt + to_dsinterval('0 ' || hier_tm || ':00') as temp
from xxx1;

TEMP
----------------
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/17 17:54
</code>```

For me, this approach is the most obvious in terms of understanding what the code is trying to do, though the concatenation still makes it not completely obvious at first glance, perhaps.

The query attempt in the question seems to work, aside from relying on your NLS settings and implicit conversion of '01-JAN-1900' to a date; but it can be simplified, and I'd still prefer my approach (obviously!). I'd missed the handling for null values though. So, versions handling null values in either column:

```<code>select coalesce(hier_dt, date '1900-01-01')
  + case when hier_tm is null then 0
      else (to_date(hier_tm, 'HH24:MI') - trunc(sysdate, 'MM')) end as temp
from xxx1;
</code>```

or

```<code>select coalesce(hier_dt, date '1900-01-01')
  + to_dsinterval('0 ' || coalesce(hier_tm, '00:00') || ':00') as temp
from xxx1;
</code>```

Body:
I am trying to concatenate two fields and load the data into a date field.

I have a table with hier_dt as DATE datatype and hier_tm as CHAR datatype, with data like:

hier_dt   | hier_tm
16-JAN-17 | 16:54
16-JAN-17 | 16:54
16-JAN-17 | 16:54
16-JAN-17 | 16:54
17-JAN-17 | 17:54

I would like to concatenate both of these into a single DATE datatype field, to produce:

hier_dt_tm
----------------
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/17 17:54

Is there a way I can accomplish this?

My current query is:

select to_date(concat(to_char(NVL(hier_DT,'01-JAN-1900'), 'yyyy/mm/dd'),
  concat(' ',NVL(hier_tm,'00:00'))), 'yyyy/mm/dd hh24:mi') as temp
from XXX1

Body:
A slight variation on the other ideas is to leave hier_dt as a date, and figure out the fraction of a day that hier_tm represents. One way to do that is to convert just the time to a date - which defaults everything else to the first of the current month - and subtract the first from that, then add the result to hier_dt:

hier_dt + (to_date(hier_tm, 'HH24:MI') - trunc(sysdate, 'MM')

With explicit formatting back to a string just for display purposes:

select to_char(
    hier_dt + (to_date(hier_tm, 'HH24:MI') - trunc(sysdate, 'MM')),
    'YYYY/MM/DD HH24:MI') as temp
from xxx1;

TEMP
----------------
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/17 17:54

Yet another way is to convert the time to an interval datatype using the to_dsinterval() function, which involves tacking on dummy day and second values to make the string something that function recognises:

hier_dt + to_dsinterval('0 ' || hier_tm || ':00')

Without explicit conversion to string this time, relying instead on NLS settings:

alter session set nls_date_format = 'YYYY/MM/DD HH24:MI';

select hier_dt + to_dsinterval('0 ' || hier_tm || ':00') as temp
from xxx1;

TEMP
----------------
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/16 16:54
2017/01/17 17:54

For me, this approach is the most obvious in terms of understanding what the code is trying to do, though the concatenation still makes it not completely obvious at first glance, perhaps.

The query attempt in the question seems to work, aside from relying on your NLS settings and implicit conversion of '01-JAN-1900' to a date; but it can be simplified, and I'd still prefer my approach (obviously!). I'd missed the handling for null values though. So, versions handling null values in either column:

select coalesce(hier_dt, date '1900-01-01')
  + case when hier_tm is null then 0
      else (to_date(hier_tm, 'HH24:MI') - trunc(sysdate, 'MM')) end as temp
from xxx1;

or

select coalesce(hier_dt, date '1900-01-01')
  + to_dsinterval('0 ' || coalesce(hier_tm, '00:00') || ':00') as temp
from xxx1;


Title: Reindex pandas dataframe based on uneven dates and then groupby and blank fill certain values

Body:
I have a dataframe that looks something like this:

df

Name    date          season  binary
Apple   2016-04-24    MAM     1
Banana  2016-05-01    MAM     1
Berry   2016-05-01    MAM     1
Berry   2017-11-05    OND     1
Orange  2016-11-27    OND     1
Kiwi    2017-03-27    MAM     1

And I have a long date time object of a bunch of dates like this:

df1

date        season  Week
2016-03-28  MAM     13
2016-04-04  MAM     14
2016-04-11  MAM     15
2016-04-18  MAM     16
2016-04-25  MAM     17
2016-05-02  MAM     18
2016-05-09  MAM     19
2016-05-16  MAM     20
2016-05-23  MAM     21
2016-05-30  MAM     22
2016-06-06  MAM     23
2016-06-13  MAM     24
2016-10-03  OND     40
2016-10-10  OND     41
2016-10-17  OND     42
2016-10-24  OND     43
2016-10-31  OND     44
2016-11-07  OND     45
2016-11-14  OND     46
2016-11-21  OND     47
2017-03-13  MAM     11
2017-03-20  MAM     12
2017-03-27  MAM     13
2017-04-03  MAM     14
2017-04-10  MAM     15
2017-04-17  MAM     16
2017-04-24  MAM     17
2017-05-01  MAM     18
2017-05-08  MAM     19
2017-05-15  MAM     20
2017-05-22  MAM     21
2017-05-29  MAM     22
2017-06-19  MAM     25
2017-06-26  MAM     26
2017-07-03  MAM     27
2017-07-10  MAM     28
2017-07-17  MAM     29
2017-07-24  MAM     30
2017-07-31  MAM     31
2017-08-07  MAM     32
2017-08-14  MAM     33
2017-08-21  MAM     34
2017-08-28  MAM     35
2017-09-04  MAM     36
2017-09-11  MAM     37
2017-09-18  MAM     38
2017-09-25  MAM     39
2017-10-02  OND     40
2017-10-09  OND     41
2017-10-16  OND     42
2017-10-23  OND     43
2017-10-30  OND     44
2017-11-06  OND     45
2017-11-13  OND     46
2017-11-20  OND     47

where Week is dtype: object, date is dtype: datetime64[ns], and season is dtype: object.

What I need is a bit complicated. I need a function or algorithm that recognizes df.date as the "end date" and df1.date as the "start date" for certain seasons. In other words, an event for "Apple" in df started on 2016-04-24 which is indicated by the binary=1. In a new dataframe, I need to include the weeks before 2016-04-24 but after 2016-03-28 and add a column that says binary=0 because the event had not occurred yet.

The messy thing is that there a four seasons: MAM 2016, OND 2016, MAM 2017, and OND 2017. And the "start date" for each df.date should only be considered for that season.

As an example, this is what I'm looking to get:

df_result

Name    date          season  binary
Apple   2016-03-28    MAM     0
Apple   2016-04-04    MAM     0
Apple   2016-04-11    MAM     0
Apple   2016-04-18    MAM     0
Apple   2016-04-24    MAM     1
Banana  2016-03-28    MAM     0
Banana  2016-04-04    MAM     0
Banana  2016-04-11    MAM     0
Banana  2016-04-18    MAM     0
Banana  2016-04-25    MAM     0
Banana  2016-05-01    MAM     1
Berry   2016-03-28    MAM     0
Berry   2016-04-04    MAM     0
Berry   2016-04-11    MAM     0
Berry   2016-04-18    MAM     0
Berry   2016-04-25    MAM     0
Berry   2016-05-01    MAM     1
Berry   2017-10-02    OND     0
Berry   2017-10-09    OND     0
Berry   2017-10-16    OND     0
Berry   2017-10-23    OND     0
Berry   2017-10-30    OND     0
Berry   2017-11-05    OND     1
Orange  2016-10-03    OND     0
Orange  2016-10-10    OND     0
Orange  2016-10-17    OND     0
Orange  2016-10-24    OND     0
Orange  2016-10-31    OND     0
Orange  2016-11-07    OND     0
Orange  2016-11-14    OND     0
Orange  2016-11-21    OND     0
Orange  2016-11-27    OND     1
Kiwi    2017-03-13    MAM     0
Kiwi    2017-03-20    MAM     0
Kiwi    2017-03-27    MAM     1

To summarize the seasons in start_end_dates and make it a little clearer, these are the dates:

MAM 2016: 2016-03-28 to 2016-06-13

OND 2016: 2016-10-03 to 2016-11-21

MAM 2017: 2017-03-13 to 2017-09-25

OND 2017: 2017-10-02 to 2017-11-20

With some help, I know that this I should reindex df with something like df2 = df.reindex(start_end_dates) but this doesn't work out quite right.

Then I should groupby the names and blank fill with "0" the weeks before df.date. So maybe: df3 = df3.loc[df3.groupby(level=0).binary.bfill().dropna().index].fillna(0).reset_index()

I have seen this stack overflow question but it doesn't exactly answer my question: Reindex pandas DataFrame to fill missing dates

Help greatly appreciated.

Body:
We using merge_asof

df['Year']=df['date'].dt.year
df1['Year']=df1['date'].dt.year
A=[]
for x in range(len(df)):
    Temp=pd.merge_asof(df1.sort_values('date'),df.sort_values('date').iloc[[x],:],on='date',by=['Year','season'],direction='forward',allow_exact_matches =False).dropna().drop('Week',1)
    Temp.binary=np.nan
    A.append(Temp)
A.append(df)
target=pd.concat(A).sort_values(['Name','date'])

target
Out[262]:
      Name  Year  binary       date season
0    Apple  2016     NaN 2016-03-28    MAM
1    Apple  2016     NaN 2016-04-04    MAM
2    Apple  2016     NaN 2016-04-11    MAM
3    Apple  2016     NaN 2016-04-18    MAM
0    Apple  2016     1.0 2016-04-24    MAM
0   Banana  2016     NaN 2016-03-28    MAM
1   Banana  2016     NaN 2016-04-04    MAM
2   Banana  2016     NaN 2016-04-11    MAM
3   Banana  2016     NaN 2016-04-18    MAM
4   Banana  2016     NaN 2016-04-25    MAM
1   Banana  2016     1.0 2016-05-01    MAM
0    Berry  2016     NaN 2016-03-28    MAM
1    Berry  2016     NaN 2016-04-04    MAM
2    Berry  2016     NaN 2016-04-11    MAM
3    Berry  2016     NaN 2016-04-18    MAM
4    Berry  2016     NaN 2016-04-25    MAM
2    Berry  2016     1.0 2016-05-01    MAM
47   Berry  2017     NaN 2017-10-02    OND
48   Berry  2017     NaN 2017-10-09    OND
49   Berry  2017     NaN 2017-10-16    OND
50   Berry  2017     NaN 2017-10-23    OND
51   Berry  2017     NaN 2017-10-30    OND
3    Berry  2017     1.0 2017-11-05    OND
20    Kiwi  2017     NaN 2017-03-13    MAM
21    Kiwi  2017     NaN 2017-03-20    MAM
5     Kiwi  2017     1.0 2017-03-27    MAM
12  Orange  2016     NaN 2016-10-03    OND
13  Orange  2016     NaN 2016-10-10    OND
14  Orange  2016     NaN 2016-10-17    OND
15  Orange  2016     NaN 2016-10-24    OND
16  Orange  2016     NaN 2016-10-31    OND
17  Orange  2016     NaN 2016-11-07    OND
18  Orange  2016     NaN 2016-11-14    OND
19  Orange  2016     NaN 2016-11-21    OND
4   Orange  2016     1.0 2016-11-27    OND


问:
re-export Typescript enum from namespace?
I have an enum definition in module 'some-lib'. I want to re-export it from a namespace in my module, something like this:

```<code>import { PaymentType } from 'some-lib';

namespace Payout {
    export enum PaymentType = PaymentType;
}
</code>```

I'm not having any luck. I want to do this in order to alias the enum and put it into a different namespace to avoid collisions with other types with the same name. I don't want to have to define a duplicate copy of the enum in my code, and have to maintain all the enum values.

Is there any way Typescript supports this currently?

答:
Yes, there's a way to do this, e.g.:

```<code>import { PaymentType as _PaymentType } from 'some-lib';

namespace Payout {
  export import PaymentType = _PaymentType;
}
</code>```

or alternatively:

```<code>import * as SomeLibTypes from 'some-lib';

namespace Payout {
  export import PaymentType = SomeLibTypes.PaymentType;
}
</code>```

reference: https://github.com/Microsoft/TypeScript/issues/20273#issuecomment-347079963

Body:
I have an enum definition in module 'some-lib'. I want to re-export it from a namespace in my module, something like this:

import { PaymentType } from 'some-lib';

namespace Payout {
    export enum PaymentType = PaymentType;
}

I'm not having any luck. I want to do this in order to alias the enum and put it into a different namespace to avoid collisions with other types with the same name. I don't want to have to define a duplicate copy of the enum in my code, and have to maintain all the enum values.

Is there any way Typescript supports this currently?

Body:
Yes, there's a way to do this, e.g.:

import { PaymentType as _PaymentType } from 'some-lib';

namespace Payout {
  export import PaymentType = _PaymentType;
}

or alternatively:

import * as SomeLibTypes from 'some-lib';

namespace Payout {
  export import PaymentType = SomeLibTypes.PaymentType;
}

reference: https://github.com/Microsoft/TypeScript/issues/20273#issuecomment-347079963


问:
Unable to upload file using PHP
I am unable to upload files to my CentOS 7 server running httpd using php.

I have searched all over and still cannot figure out why I am unable to upload files. :(

Here is the form:

```<code><div class="container">
    <div class="row">
        <div class="col-lg-4 col-lg-offset-4">
            <h2 class="section-heading text-white text-center">Private Upload Page</h2>
            <hr class="light">
            <form class="form-horizontal" role="form" action="upload.php" method="post" enctype="multipart/form-data">
              <div class="form-group">
              <span class="text-white">Select directory to upload to:</span><br>
              <input class="form-control" type="text" name="dir" value="/var/www/html/Private/uploads" style="width: 100%;"><br>
              <span class="text-white">Select file to upload:</span><br>
              <input class="form-control" type="file" name="fileToUpload" id="fileToUpload" style="width: 100%;"><br>
              <input class="form-control btn btn-primary" type="submit" value="Upload File" name="submit" >
            </form>
        </div>
    </div>
</div>
</code>```

And here is the php file:

```<code><?php
// Check directory from form, otherwise use uploads folder in
// /var/www/html/Private
if(isset($_POST["dir"])) {
    $target_dir = $_POST["dir"];
    echo "<p>Using " . $target_dir . " for directory.</p><br>";
}
else {
    $target_dir = "/var/www/html/Private/uploads/";
    echo "<p>Using /var/www/html/Private/uploads for directory.</p><br>";
}

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
    echo "Sorry, there was an error uploading your file.";
    }
}
?>
</code>```

I have tried setting using:

```<code>chmod 777 /var/www/html
</code>```

and:

```<code>chmod 777 /var/www
</code>```

as well as turned on file write in the php.ini file

as well as turning off the firewall and am still unable to upload a file.

I am newish to web design, so I'm sure it is an issue that I caused. Every page I looked at pointed to permissions but even allowing 777 still did not fix my issue.

答:
```<code> <form class="" id="add_downloadble" method="post" enctype="multipart/form-data" name="upload" >
                    <div class="control-group">
                        <label class="control-label" for="inputEmail">File:</label>
                        <div class="form-group">

            <input name="uploaded_file"  class="form-control" id="fileInput" type="file" required>

                            <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
                            <input type="hidden" name="id" value="<?php echo $session_id ?>"/>
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="controls">
                            <input type="text" name="name" Placeholder="File Name"  class="form-control" required>
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="controls">
                            <input type="text" name="desc" Placeholder="Description"  class="form-control" required>
                        </div>
                    </div>

                  <script>
                  jQuery(document).ready(function($){
                      e.preventDefault();
                      var _this = $(e.target);
                      var formData = new FormData($(this)[0]);
                      $.ajax({
                        type: "POST",
                        url: "save.php",
                        data: formData,
                        success: function(html){
                          window.location = 'tambah_materi.php';
                        },
                        cache: false,
                        contentType: false,
                        processData: false
                      });
                    });
                  });
                  </script>

              </div>
              <div class="col-sm-6">

            <div class="alert alert-info">Centang kelas yang ingin di tambahkan file ini.</div>

                        <div class="pull-left">
                    Check All <input type="checkbox"  name="selectAll" id="checkAll" />
                      <script>
                      $("#checkAll").click(function () {
                        $('input:checkbox').not(this).prop('checked', this.checked);
                      });
                      </script>
                    </div>
                            <table cellpadding="0" cellspacing="0" border="0" class="table" id="">

                          <thead>
                                  <tr>
                              <th></th>
                              <th>Nama Kelas</th>
                              <th>Subject Code</th>
                              </tr>

                          </thead>
                          <tbody>

                                      <?php $query = mysql_query("select * from teacher_class
                          LEFT JOIN class ON class.class_id = teacher_class.class_id
                          LEFT JOIN subject ON subject.subject_id = teacher_class.subject_id
                          where teacher_id = '$session_id' and school_year = '$school_year' ")or die(mysql_error());
                          $count = mysql_num_rows($query);

                          while($row = mysql_fetch_array($query)){
                          $id = $row['teacher_class_id'];

                          ?>
                          <tr id="del<?php echo $id; ?>">
                            <td width="30">
                              <input id="" class="" name="selector[]" type="checkbox" value="<?php echo $id; ?>">
                            </td>
                            <td><?php echo $row['class_name']; ?></td>
                            <td><?php echo $row['subject_code']; ?></td>
                          </tr>

                  <?php } ?>

                </tbody>
              </table>

                            </div>
            <div class="col-sm-12">
            <hr>
              <center>
              <div class="control-group">
                    <div class="controls">
                      <button name="Upload" type="submit" value="Upload" class="btn btn-success" /><i class="icon-upload-alt"></i> Upload</button>
                    </div>
              </div>
              </center>

               </form>
</code>```

save.php file

```<code>        include('../session.php');
        //Include database connection details
        include("../dbConnector.php");
        $connector = new DbConnector();

        $errmsg_arr = array();
        //Validation error flag
        $errflag = false;

        $uploaded_by_query = mysql_query("select * from teacher where teacher_id = '$session_id'")or die(mysql_error());
        $uploaded_by_query_row = mysql_fetch_array($uploaded_by_query);
        $uploaded_by = $uploaded_by_query_row['firstname']."".$uploaded_by_query_row['lastname'];

        /* $id_class=$_POST['id_class']; */
        $name=$_POST['name'];

        //Function to sanitize values received from the form. Prevents SQL injection
        function clean($str) {
            $str = @trim($str);
            if (get_magic_quotes_gpc()) {
                $str = stripslashes($str);
            }
            return mysql_real_escape_string($str);
        }

        //Sanitize the POST values
        $filedesc = clean($_POST['desc']);
        //$subject= clean($_POST['upname']);

        if ($filedesc == '') {
            $errmsg_arr[] = ' file diskripsi belum di isi';
            $errflag = true;
        }

        if ($_FILES['uploaded_file']['size'] >= 1048576 * 5) {
            $errmsg_arr[] = 'file selected exceeds 5MB size limit';
            $errflag = true;
        }

        //If there are input validations, redirect back to the registration form
        if ($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            ?>

           <script>
           window.location = 'downloadable.php<?php echo '?id='.$get_id;  ?>';
           </script>
           <?php exit();
        }
        //upload random name/number
        $rd2 = mt_rand(1000, 9999) . "_File";

        //Check that we have a file
        if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
            //Check if the file is JPEG image and it's size is less than 350Kb
            $filename = basename($_FILES['uploaded_file']['name']);

            $ext = substr($filename, strrpos($filename, '.') + 1);

            if (($ext != "exe") && ($_FILES["uploaded_file"]["type"] != "application/x-msdownload")) {
                //Determine the path to which we want to save this file
                //$newname = dirname(__FILE__).'/upload/'.$filename;
                $newname = "../admin/uploads/" . $rd2 . "_" . $filename;
                $name_notification  = 'Add Downloadable Materials file name'." ".'<b>'.$name.'</b>';
                //Check if the file with the same name is already exists on the server
                if (!file_exists($newname)) {
                    //Attempt to move the uploaded file to it's new place
                    if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $newname))) {
                        //successful upload
                        // echo "It's done! The file has been saved as: ".$newname;

                                    $id=$_POST['selector'];
                                                    $N = count($id);
                                                    for($i=0; $i < $N; $i++)
                                                    {

                       /*  $qry2 = "INSERT INTO files (fdesc,floc,fdatein,teacher_id,class_id,fname,uploaded_by) VALUES ('$filedesc','$newname',NOW(),'$session_id','$id[$i]','$name','$uploaded_by')"; */
                        mysql_query("INSERT INTO files (fdesc,floc,fdatein,teacher_id,class_id,fname,uploaded_by) VALUES ('$filedesc','$newname',NOW(),'$session_id','$id[$i]','$name','$uploaded_by')");
                        mysql_query("insert into notification (teacher_class_id,notification,date_of_notification,link) value('$id[$i]','$name_notification',NOW(),'downloadable_student.php')")or die(mysql_error());

                      }

        }
        }
        }
        }

        /* mysql_close(); */
        ?>
</code>```

Title: Unable to upload file using PHP

Body:
I am unable to upload files to my CentOS 7 server running httpd using php.

I have searched all over and still cannot figure out why I am unable to upload files. :(

Here is the form:

Private Upload Page

            <form class="form-horizontal" role="form" action="upload.php" method="post" enctype="multipart/form-data">

              Select directory to upload to:

              <input class="form-control" type="text" name="dir" value="/var/www/html/Private/uploads" style="width: 100%;">

              Select file to upload:

              <input class="form-control" type="file" name="fileToUpload" id="fileToUpload" style="width: 100%;">

              <input class="form-control btn btn-primary" type="submit" value="Upload File" name="submit" >
            </form>

And here is the php file:

<?php
// Check directory from form, otherwise use uploads folder in
// /var/www/html/Private
if(isset($_POST["dir"])) {
    $target_dir = $_POST["dir"];
    echo "
Using " . $target_dir . " for directory.

";
}
else {
    $target_dir = "/var/www/html/Private/uploads/";
    echo "
Using /var/www/html/Private/uploads for directory.

";
}

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
    echo "Sorry, there was an error uploading your file.";
    }
}
?>

I have tried setting using:

chmod 777 /var/www/html

and:

chmod 777 /var/www

as well as turned on file write in the php.ini file

as well as turning off the firewall and am still unable to upload a file.

I am newish to web design, so I'm sure it is an issue that I caused. Every page I looked at pointed to permissions but even allowing 777 still did not fix my issue.

Body:
 <form class="" id="add_downloadble" method="post" enctype="multipart/form-data" name="upload" >
                    <div class="control-group">
                        <label class="control-label" for="inputEmail">File:</label>
                        <div class="form-group">

            <input name="uploaded_file"  class="form-control" id="fileInput" type="file" required>

                            <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
                            <input type="hidden" name="id" value="<?php echo $session_id ?>"/>
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="controls">
                            <input type="text" name="name" Placeholder="File Name"  class="form-control" required>
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="controls">
                            <input type="text" name="desc" Placeholder="Description"  class="form-control" required>
                        </div>
                    </div>

                  <script>
                  jQuery(document).ready(function($){
                      e.preventDefault();
                      var _this = $(e.target);
                      var formData = new FormData($(this)[0]);
                      $.ajax({
                        type: "POST",
                        url: "save.php",
                        data: formData,
                        success: function(html){
                          window.location = 'tambah_materi.php';
                        },
                        cache: false,
                        contentType: false,
                        processData: false
                      });
                    });
                  });
                  </script>

              </div>
              <div class="col-sm-6">

            <div class="alert alert-info">Centang kelas yang ingin di tambahkan file ini.</div>

                        <div class="pull-left">
                    Check All <input type="checkbox"  name="selectAll" id="checkAll" />
                      <script>
                      $("#checkAll").click(function () {
                        $('input:checkbox').not(this).prop('checked', this.checked);
                      });
                      </script>
                    </div>
                            <table cellpadding="0" cellspacing="0" border="0" class="table" id="">

                          <thead>
                                  <tr>
                              <th></th>
                              <th>Nama Kelas</th>
                              <th>Subject Code</th>
                              </tr>

                          </thead>
                          <tbody>

                                      <?php $query = mysql_query("select * from teacher_class
                          LEFT JOIN class ON class.class_id = teacher_class.class_id
                          LEFT JOIN subject ON subject.subject_id = teacher_class.subject_id
                          where teacher_id = '$session_id' and school_year = '$school_year' ")or die(mysql_error());
                          $count = mysql_num_rows($query);

                          while($row = mysql_fetch_array($query)){
                          $id = $row['teacher_class_id'];

                          ?>
                          <tr id="del<?php echo $id; ?>">
                            <td width="30">
                              <input id="" class="" name="selector[]" type="checkbox" value="<?php echo $id; ?>">
                            </td>
                            <td><?php echo $row['class_name']; ?></td>
                            <td><?php echo $row['subject_code']; ?></td>
                          </tr>

                  <?php } ?>

                </tbody>
              </table>

                            </div>
            <div class="col-sm-12">
            <hr>
              <center>
              <div class="control-group">
                    <div class="controls">
                      <button name="Upload" type="submit" value="Upload" class="btn btn-success" /><i class="icon-upload-alt"></i>&nbsp;Upload</button>
                    </div>
              </div>
              </center>

               </form>

save.php file

        include('../session.php');
        //Include database connection details
        include("../dbConnector.php");
        $connector = new DbConnector();

        $errmsg_arr = array();
        //Validation error flag
        $errflag = false;

        $uploaded_by_query = mysql_query("select * from teacher where teacher_id = '$session_id'")or die(mysql_error());
        $uploaded_by_query_row = mysql_fetch_array($uploaded_by_query);
        $uploaded_by = $uploaded_by_query_row['firstname']."".$uploaded_by_query_row['lastname'];

        /* $id_class=$_POST['id_class']; */
        $name=$_POST['name'];

        //Function to sanitize values received from the form. Prevents SQL injection
        function clean($str) {
            $str = @trim($str);
            if (get_magic_quotes_gpc()) {
                $str = stripslashes($str);
            }
            return mysql_real_escape_string($str);
        }

        //Sanitize the POST values
        $filedesc = clean($_POST['desc']);
        //$subject= clean($_POST['upname']);

        if ($filedesc == '') {
            $errmsg_arr[] = ' file diskripsi belum di isi';
            $errflag = true;
        }

        if ($_FILES['uploaded_file']['size'] >= 1048576 * 5) {
            $errmsg_arr[] = 'file selected exceeds 5MB size limit';
            $errflag = true;
        }

        //If there are input validations, redirect back to the registration form
        if ($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            ?>

           <script>
           window.location = 'downloadable.php<?php echo '?id='.$get_id;  ?>';
           </script>
           <?php exit();
        }
        //upload random name/number
        $rd2 = mt_rand(1000, 9999) . "_File";

        //Check that we have a file
        if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
            //Check if the file is JPEG image and it's size is less than 350Kb
            $filename = basename($_FILES['uploaded_file']['name']);

            $ext = substr($filename, strrpos($filename, '.') + 1);

            if (($ext != "exe") && ($_FILES["uploaded_file"]["type"] != "application/x-msdownload")) {
                //Determine the path to which we want to save this file
                //$newname = dirname(__FILE__).'/upload/'.$filename;
                $newname = "../admin/uploads/" . $rd2 . "_" . $filename;
                $name_notification  = 'Add Downloadable Materials file name'." ".'<b>'.$name.'</b>';
                //Check if the file with the same name is already exists on the server
                if (!file_exists($newname)) {
                    //Attempt to move the uploaded file to it's new place
                    if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $newname))) {
                        //successful upload
                        // echo "It's done! The file has been saved as: ".$newname;

                                    $id=$_POST['selector'];
                                                    $N = count($id);
                                                    for($i=0; $i < $N; $i++)
                                                    {

                       /*  $qry2 = "INSERT INTO files (fdesc,floc,fdatein,teacher_id,class_id,fname,uploaded_by) VALUES ('$filedesc','$newname',NOW(),'$session_id','$id[$i]','$name','$uploaded_by')"; */
                        mysql_query("INSERT INTO files (fdesc,floc,fdatein,teacher_id,class_id,fname,uploaded_by) VALUES ('$filedesc','$newname',NOW(),'$session_id','$id[$i]','$name','$uploaded_by')");
                        mysql_query("insert into notification (teacher_class_id,notification,date_of_notification,link) value('$id[$i]','$name_notification',NOW(),'downloadable_student.php')")or die(mysql_error());

                      }

        }
        }
        }
        }

        /* mysql_close(); */
        ?>


问:
SSL certificates or other files not showing in Docker file structure
I have a Docker build for Gitlab, I created some ssl certificates and other files I need to pull in.  However when I exec into the container bash the files are not visible.</p>

```<code>gitlab:
  image: 'gitlab/gitlab-ce:9.1.0-ce.0'
  restart: always
  hostname: 'gitlab.example.com'
  links:
    - postgresql:postgresql
    - redis:redis
  environment:
    GITLAB_OMNIBUS_CONFIG: |
      postgresql['enable'] = false
      gitlab_rails['db_username'] = "gitlab"
      gitlab_rails['db_password'] = "gitlab"
      gitlab_rails['db_host'] = "postgresql"
      gitlab_rails['db_port'] = "5432"
      gitlab_rails['db_database'] = "gitlabhq_production"
      gitlab_rails['db_adapter'] = 'postgresql'
      gitlab_rails['db_encoding'] = 'utf8'
      redis['enable'] = false
      gitlab_rails['redis_host'] = 'redis'
      gitlab_rails['redis_port'] = '6379'
      external_url 'https://gitlab.example.com:30080'
      nginx['ssl_certificate'] = '/etc/gitlab/trusted-certs/gitlab.example.com.crt'
      nginx['ssl_certificate_key'] = '/etc/gitlab/trusted-certs/gitlab.example.com.key'
  ports:
    - "30080:30080"
    - "30022:22"
postgresql:
  restart: always
  image: postgres:9.6.2-alpine
  environment:
    - POSTGRES_USER=gitlab
    - POSTGRES_PASSWORD=gitlab
    - POSTGRES_DB=gitlabhq_production
redis:
  restart: always
  image: redis:3.0.7-alpine
</code>```

答: On creation of the self signed certificates, I need to exec into my docker container and create them using the docker bash</p>

Body:
I have a Docker build for Gitlab, I created some ssl certificates and other files I need to pull in.  However when I exec into the container bash the files are not visible.

gitlab:
  image: 'gitlab/gitlab-ce:9.1.0-ce.0'
  restart: always
  hostname: 'gitlab.example.com'
  links:
    - postgresql:postgresql
    - redis:redis
  environment:
    GITLAB_OMNIBUS_CONFIG: |
      postgresql['enable'] = false
      gitlab_rails['db_username'] = "gitlab"
      gitlab_rails['db_password'] = "gitlab"
      gitlab_rails['db_host'] = "postgresql"
      gitlab_rails['db_port'] = "5432"
      gitlab_rails['db_database'] = "gitlabhq_production"
      gitlab_rails['db_adapter'] = 'postgresql'
      gitlab_rails['db_encoding'] = 'utf8'
      redis['enable'] = false
      gitlab_rails['redis_host'] = 'redis'
      gitlab_rails['redis_port'] = '6379'
      external_url 'https://gitlab.example.com:30080'
      nginx['ssl_certificate'] = '/etc/gitlab/trusted-certs/gitlab.example.com.crt'
      nginx['ssl_certificate_key'] = '/etc/gitlab/trusted-certs/gitlab.example.com.key'
  ports:
    - "30080:30080"
    - "30022:22"
postgresql:
  restart: always
  image: postgres:9.6.2-alpine
  environment:
    - POSTGRES_USER=gitlab
    - POSTGRES_PASSWORD=gitlab
    - POSTGRES_DB=gitlabhq_production
redis:
  restart: always
  image: redis:3.0.7-alpine


问:
Spring Security & Websockets - Authentication not set for frame handler
Given the below configuration, the initial websocket handshake to "/connect" succeeds with basic auth. However, I get the following exception when I send a frame through the active websocket: org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext.

I don't get the exception when I remove the @PreAuthorize annotation from "/sendMessage" in WebsocketController. Spring documentation says the Authentication from the initial HTTP handshake should be set in the SecurityContext for future websocket frames, yet this does not appear to be happening automatically.

How should I go about setting the Authentication for the websocket connection?

@Configuration
@EnableWebSocket
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config){
        config.enableStompBrokerRelay("/outbound");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/connect").withSockJS();
    }
}

//...............

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationProvider authProvider;

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest().authenticated()
            .and().httpBasic()
        ;
    }

    @Autowired
    public void configureAuthentication(final AuthenticationManagerBuilder authBuilder) throws Exception {
        authBuilder.authenticationProvider(authProvider);
    }
}

//.............

@Controller
public class WebSocketController {

    // This fails despite successful websocket handshake
    @MessageMapping("/sendMessage")
    @SendTo("/outbound/message")
    @PreAuthorize("hasRole('USER')")
    public Message message(@Payload Message message) {
        return "web socket message";
    }

    // This HTTP call succeeds
    @RequestMapping("/httpEndpoint")
    @PreAuthorize("hasRole('USER')")
    public @ResponseBody String doSomething(){
        return "some response";
    }

}

// ..................

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
        // all are valid
        return new UsernamePasswordAuthenticationToken(username, password, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
    }

    @Override
    public boolean supports(final Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
```

答:
Spring WebSockets doesn't appear to support SpringSecurity annotations so security must instead be configured with:</p>

```<code>@Configuration
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {

    @Override
    protected void configureInbound(final MessageSecurityMetadataSourceRegistry messages) {
        messages.anyMessage().authenticated()
                .simpDestMatchers("/**").hasRole("USER")
        ;
    }
}
</code>```

Body:
Spring WebSockets doesn't appear to support SpringSecurity annotations so security must instead be configured with:

@Configuration
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {

    @Override
    protected void configureInbound(final MessageSecurityMetadataSourceRegistry messages) {
        messages.anyMessage().authenticated()
                .simpDestMatchers("/**").hasRole("USER")
        ;
    }
}


问:
this.setState is not actually setting my state at all?
I am currently creating a small React app for a shopping list. I am attempting to hold the list items as state. Once the input is submitted, for adding a new item, a function is called, which sends the new list to the App and also attempts to reset the state to ''. For some reason this is not working. I checked through logging and also I can tell by the fact that my input does not reset.

Here is the code:

```<code>class List extends React.Component {
  state = {newItem: ''};

  addItem = event => {
    event.preventDefault();

    this.props.onSubmit(this.state.newItem);
    this.setState({newItem: ''});
  }

  render() {
      return (
        <div>
          {this.props.currentUser.shoppingList.map(item =>
            <ListItem
              {...item}
              updatedList={this.props.updatedList}
            />)}
            <form onSubmit={this.addItem}>
              <input type="text" placeholder="Add new item!"
                value={this.state.newItem}
                onChange={event => this.setState({newItem: event.target.value})}
              />
              <button>Save</button>
            </form>
        </div>
      );
    }
}
</code>```

答:
Your state is working perfectly. Problem may be with your props. Here is the working sample except ListItem.

```<code><!DOCTYPE html>
<html>
  <head>
    <title>React State</title>
    <meta charset="utf-8">
    <script src="https://unpkg.com/react@16.0.0/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@16.0.0/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script type="text/jsx">
        class List extends React.Component {
            state = {newItem: ''};

            addItem = event => {
                event.preventDefault();
                console.log(this.state.newItem);
                this.setState({newItem: ''});
            }

            render() {
                return (
                    <div>
                        <form onSubmit={this.addItem}>
                          <input type="text" placeholder="Add new item!"
                            value={this.state.newItem}
                            onChange={event => this.setState({newItem: event.target.value})}
                          />
                          <button>Save</button>
                        </form>
                    </div>
                );
            }
        }

        ReactDOM.render(
          <List />,
          document.getElementById("app")
        );
    </script>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
</code>```

Body:
I am currently creating a small React app for a shopping list. I am attempting to hold the list items as state. Once the input is submitted, for adding a new item, a function is called, which sends the new list to the App and also attempts to reset the state to ''. For some reason this is not working. I checked through logging and also I can tell by the fact that my input does not reset.

Here is the code:

class List extends React.Component {
  state = {newItem: ''};

  addItem = event => {
    event.preventDefault();

    this.props.onSubmit(this.state.newItem);
    this.setState({newItem: ''});
  }

  render() {
      return (

          {this.props.currentUser.shoppingList.map(item =>
            <ListItem
              {...item}
              updatedList={this.props.updatedList}
            />)}
            <form onSubmit={this.addItem}>
              <input type="text" placeholder="Add new item!"
                value={this.state.newItem}
                onChange={event => this.setState({newItem: event.target.value})}
              />
              <button>Save</button>
            </form>

      );
    }
}

Body:
Your state is working perfectly. Problem may be with your props. Here is the working sample except ListItem.

<!DOCTYPE html>
<html>
  <head>
    <title>React State</title>
    <meta charset="utf-8">
    <script src="https://unpkg.com/react@16.0.0/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@16.0.0/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script type="text/jsx">
        class List extends React.Component {
            state = {newItem: ''};

            addItem = event => {
                event.preventDefault();
                console.log(this.state.newItem);
                this.setState({newItem: ''});
            }

            render() {
                return (
                    <div>
                        <form onSubmit={this.addItem}>
                          <input type="text" placeholder="Add new item!"
                            value={this.state.newItem}
                            onChange={event => this.setState({newItem: event.target.value})}
                          />
                          <button>Save</button>
                        </form>
                    </div>
                );
            }
        }

        ReactDOM.render(
          <List />,
          document.getElementById("app")
        );
    </script>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>


问:
Retrieve the session value and pass as required parameter of api Ajax
I want to retrieve the session value and pass that value as required parameter for the api. My session is $_SESSION['name']. And these are my codes

```<code>var uniqueName = **Here I want to retrieve session value**;
  if(**Then I want to check if uniqueName is null or undefined**) {
    $.ajax({
      url: 'http://api/check.php',
      type: 'GET',
      crossDomain: true,
      dataType:'json',
      data: {
        name: uniqueName
      },
      success: function(result) {
        alert("Success");
      },
      error: function(result) {
        alert("Error");
      }
    });
  }

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

答:
You can put PHP directly into your JS, like

```<code>var uniqueName = '<?php echo isset($_SESSION['name']) ? $_SESSION['name'] : '' ?>';
</code>```

In JS will be name or empty string.

If you haven't this JS in PHP file, you can pass a session using AJAX call, or assign to any HTML element.

```<code><input type="hidden" id="session_var" value="<?php echo isset($_SESSION['name']) ? $_SESSION['name'] : '' ?>">
</code>```

And in JS file then:

```<code>var name = document.getElementById('session_var'); // name from session or empty string.
</code>```

Body:
I want to retrieve the session value and pass that value as required parameter for the api. My session is $_SESSION['name']. And these are my codes

var uniqueName = **Here I want to retrieve session value**;
  if(**Then I want to check if uniqueName is null or undefined**) {
    $.ajax({
      url: 'http://api/check.php',
      type: 'GET',
      crossDomain: true,
      dataType:'json',
      data: {
        name: uniqueName
      },
      success: function(result) {
        alert("Success");
      },
      error: function(result) {
        alert("Error");
      }
    });
  }

  return false;
});

Body:
You can put PHP directly into your JS, like

var uniqueName = '<?php echo isset($_SESSION['name']) ? $_SESSION['name'] : '' ?>';

In JS will be name or empty string.

If you haven't this JS in PHP file, you can pass a session using AJAX call, or assign to any HTML element.

<input type="hidden" id="session_var" value="<?php echo isset($_SESSION['name']) ? $_SESSION['name'] : '' ?>">

And in JS file then:

var name = document.getElementById('session_var'); // name from session or empty string.


问:
Learning Ruby from Python; Differences and Similarities
Inspired by Learning Python from Ruby; Differences and Similarities.

I'm in the exact opposite boat - I'm pretty well-versed in Python, but I need to start learning Ruby soon (and Rails later, but that's another topic). The question I'm linking to addresses this a bit, but are there any other resources out there that teach Ruby for someone who already has Python experience? (In other words, someone with a background in programming, but who doesn't yet know the difference between code that IRB will execute properly and proper Ruby code.)

EDIT: I'm not just looking for a list of the differences between the two languages - I'm wondering if there are any guides/walkthroughs that are directed towards teaching Python programmers to write idiomatic Ruby. I know similar guides exist for migrating to Python from other languages, but I don't know about Ruby.

答:
While not targeted at Python programmers, you might find this idomatic Ruby talk useful.

(Related, but for Python: Code Like a Pythonista: Idiomatic Python)