问:
Cakephp 3.5.6 disable CSRF Middleware for controller
I'm trying to disable the CSRF check for a single controller (API), but I'm unable to find how I'm able to achieve this.

The pre 3.5.0 CSRF Component had the ability to be disabled on certain request using:

```<code>$this->eventManager()->off($this->Csrf);
</code>```

答:
There are two ways to do that.

Apply the middleware to specific routing scopes (or even routes)

Depending on what routes you create, you can apply the middleware to specific scopes only, for example:

```<code>// config/routes.php

use Cake\Http\Middleware\CsrfProtectionMiddleware;

Router::scope('/', function ($routes) {
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
        'httpOnly' => true
    ]));

    $routes->scope('/api', function ($routes) {
        // ...
    });

    $routes->scope('/blog', function ($routes) {
        $routes->applyMiddleware('csrf');
        // ...
    });

    $routes->scope('/cms', function ($routes) {
        $routes->applyMiddleware('csrf');
        // ...
    });
});
</code>```

This would apply the CSRF middleware only to the routes connected in the blog and cms scopes.

It's also possible to narrow things down further to route level, and apply the middleware on specific routes:

```<code>$routes
    ->connect('/blog/:action', ['controller' => 'Blogs'])
    ->setMiddleware(['csrf']);
</code>```

This would apply the CSRF middleware to only the /blog/* routes.

Conditionally apply the middleware "manually"

Another way would be to manually the apply the middleware when applicable. As of CakePHP 3.8, the middleware has a whitelisting method named whitelistCallback, inside of it you can check the request object and return a boolean that defines whether the checks are applied:

```<code>// src/Application.php

// ...
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Psr\Http\Message\ServerRequestInterface;

class Application extends BaseApplication
{
    // ...

    public function middleware($middleware)
    {
        $csrf = new CsrfProtectionMiddleware([
            'httpOnly' => true
        ]);
        $csrf->whitelistCallback(function (ServerRequestInterface $request) {
            $params = $request->getAttribute('params');
            return $params['controller'] !== 'Api';
        });

        $middleware
            // ...
            ->add(new RoutingMiddleware())

            ->add($csrf);

        return $middleware;
    }
}
</code>```

In earlier CakePHP versions you'll have to create a custom middleware handler so that you can access the current request object, from which you can extract the controller parameter, and then you have to invoke the CSRF middleware inside your handler, something along the lines of this:

```<code>// src/Application.php

// ...
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class Application extends BaseApplication
{
    // ...

    public function middleware($middleware)
    {
        $middleware
            // ...
            ->add(new RoutingMiddleware())

            ->add(function (
                ServerRequestInterface $request,
                ResponseInterface $response,
                callable $next
            ) {
                $params = $request->getAttribute('params');
                if ($params['controller'] !== 'Api') {
                    $csrf = new CsrfProtectionMiddleware([
                        'httpOnly' => true
                    ]);

                    // This will invoke the CSRF middleware's `__invoke()` handler,
                    // just like it would when being registered via `add()`.
                    return $csrf($request, $response, $next);
                }

                return $next($request, $response);
            });

        return $middleware;
    }
}
</code>```

Note that in both cases you must put the middleware after the routing middleware, as that is where the controller information is being set.

If applicable, you could also test against the request URL instead of the routing paramteres, for example something like this:

```<code>if (mb_strpos($request->getUri()->getPath(), '/api/') === false) {
    // apply CSRF checks
}
</code>```

When doing so, the middleware wouldn't be restricted to be placed after the routing middleware, you could theoretically place it at whichever position you want.

See also

Cookbook > Middleware > Cross Site Request Forgery (CSRF) Middleware

Cookbook > Routing > Connecting Scoped Middleware

Cookbook > Middleware > Creating Middleware

Body:
I'm trying to disable the CSRF check for a single controller (API), but I'm unable to find how I'm able to achieve this.

The pre 3.5.0 CSRF Component had the ability to be disabled on certain request using:

$this->eventManager()->off($this->Csrf);

Body:
There are two ways to do that.

Apply the middleware to specific routing scopes (or even routes)

Depending on what routes you create, you can apply the middleware to specific scopes only, for example:

// config/routes.php

use Cake\Http\Middleware\CsrfProtectionMiddleware;

Router::scope('/', function ($routes) {
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
        'httpOnly' => true
    ]));

    $routes->scope('/api', function ($routes) {
        // ...
    });

    $routes->scope('/blog', function ($routes) {
        $routes->applyMiddleware('csrf');
        // ...
    });

    $routes->scope('/cms', function ($routes) {
        $routes->applyMiddleware('csrf');
        // ...
    });
});

This would apply the CSRF middleware only to the routes connected in the blog and cms scopes.

It's also possible to narrow things down further to route level, and apply the middleware on specific routes:

$routes
    ->connect('/blog/:action', ['controller' => 'Blogs'])
    ->setMiddleware(['csrf']);

This would apply the CSRF middleware to only the /blog/* routes.

Conditionally apply the middleware "manually"

Another way would be to manually the apply the middleware when applicable. As of CakePHP 3.8, the middleware has a whitelisting method named whitelistCallback, inside of it you can check the request object and return a boolean that defines whether the checks are applied:

// src/Application.php

// ...
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Psr\Http\Message\ServerRequestInterface;

class Application extends BaseApplication
{
    // ...

    public function middleware($middleware)
    {
        $csrf = new CsrfProtectionMiddleware([
            'httpOnly' => true
        ]);
        $csrf->whitelistCallback(function (ServerRequestInterface $request) {
            $params = $request->getAttribute('params');
            return $params['controller'] !== 'Api';
        });

        $middleware
            // ...
            ->add(new RoutingMiddleware())

            ->add($csrf);

        return $middleware;
    }
}

In earlier CakePHP versions you'll have to create a custom middleware handler so that you can access the current request object, from which you can extract the controller parameter, and then you have to invoke the CSRF middleware inside your handler, something along the lines of this:

// src/Application.php

// ...
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class Application extends BaseApplication
{
    // ...

    public function middleware($middleware)
    {
        $middleware
            // ...
            ->add(new RoutingMiddleware())

            ->add(function (
                ServerRequestInterface $request,
                ResponseInterface $response,
                callable $next
            ) {
                $params = $request->getAttribute('params');
                if ($params['controller'] !== 'Api') {
                    $csrf = new CsrfProtectionMiddleware([
                        'httpOnly' => true
                    ]);

                    // This will invoke the CSRF middleware's `__invoke()` handler,
                    // just like it would when being registered via `add()`.
                    return $csrf($request, $response, $next);
                }

                return $next($request, $response);
            });

        return $middleware;
    }
}

Note that in both cases you must put the middleware after the routing middleware, as that is where the controller information is being set.

If applicable, you could also test against the request URL instead of the routing paramteres, for example something like this:

if (mb_strpos($request->getUri()->getPath(), '/api/') === false) {
    // apply CSRF checks
}

When doing so, the middleware wouldn't be restricted to be placed after the routing middleware, you could theoretically place it at whichever position you want.

See also

Cookbook > Middleware > Cross Site Request Forgery (CSRF) Middleware

Cookbook > Routing > Connecting Scoped Middleware

Cookbook > Middleware > Creating Middleware


来源: stackexchange

问:
JQuery date picker does not firing in ajax page using Rails
Here I have using datepicker from JQueryUI
in my public/javascript folder as effects,prototype,control,dragdrop js files.
in my public folder contains jqueryui development buddle. (css,js,development-bundle)

in layout/application.rhtml

```<code>    <%= stylesheet_link_tag 'application' %>
    <%=javascript_include_tag :defaults%>
    <%= stylesheet_link_tag '/jquery-ui/css/custom-theme/jquery-ui-1.8.1.custom.css' %>
<%=javascript_include_tag "/jquery-ui/js/jquery-1.4.2.min.js"%>
<%=javascript_include_tag "/jquery-ui/js/jquery-ui-1.8.1.custom.min.js"%>
<script>
       $(document).ready(function(){
            var $j=jQuery.noConflict();
            $j( '#date' ).datepicker({ dateFormat: 'dd-mm-yy' });
             });
    </script>
</code>```

in home/index.rhtml

```<code><%title "Home"%>
<%=link_to "Add Details" ,:action=>"add"%>
<%=link_to_remote "Ajax Add Details", :update=>"add" , :url=>{ :action=>"add" }%>
<div id='add' />
</code>```

in  home/add.rhtml

```<code><%title "Add details"%>
<%form_tag :action=>"create" do%>
    Name : <%=text_field_tag "name" ,"",:size=>15%>
    DOB  : <%=text_field_tag "dob","",:id=>"date"%>
    <%=submit_tag "Save"%>
<%end%>
</code>```

the datepicker works when I run home/add.rhtml directly but
the datepicker not work when i run ajax page home/index.rhtml

Any solutions for that,????

答:
This is a basic behaviour in a web page. You're affecting a behaviour on an element which is absent. You could simply get the best of callbacks methods:

You could do the following:

```<code>function format_date() {
   var $j=jQuery.noConflict();
   $j( '#date' ).datepicker({ dateFormat: 'dd-mm-yy' });
};

<%=link_to_remote "Ajax Add Details", :update=>"add" , :url=>{ :action=>"add" }, :success =>"format_date()"%>
</code>```

This will work because the element exists when you trigger the function.

For culture's sake, have a look at jQuery's live() function.

ContentLicense: CC BY-SA 2.5

Body:
Here I have using datepicker from JQueryUI
in my public/javascript folder as effects,prototype,control,dragdrop js files.
in my public folder contains jqueryui development buddle. (css,js,development-bundle)

in layout/application.rhtml

    <%= stylesheet_link_tag 'application' %>
    <%=javascript_include_tag :defaults%>
    <%= stylesheet_link_tag '/jquery-ui/css/custom-theme/jquery-ui-1.8.1.custom.css' %>
<%=javascript_include_tag "/jquery-ui/js/jquery-1.4.2.min.js"%>
<%=javascript_include_tag "/jquery-ui/js/jquery-ui-1.8.1.custom.min.js"%>

in home/index.rhtml

<%title "Home"%>
<%=link_to "Add Details" ,:action=>"add"%>
<%=link_to_remote "Ajax Add Details", :update=>"add" , :url=>{ :action=>"add" }%>

in  home/add.rhtml

<%title "Add details"%>
<%form_tag :action=>"create" do%>
    Name : <%=text_field_tag "name" ,"",:size=>15%>
    DOB  : <%=text_field_tag "dob","",:id=>"date"%>
    <%=submit_tag "Save"%>
<%end%>

the datepicker works when I run home/add.rhtml directly but
the datepicker not work when i run ajax page home/index.rhtml

Any solutions for that,????

Body:
This is a basic behaviour in a web page. You're affecting a behaviour on an element which is absent. You could simply get the best of callbacks methods:

You could do the following:

function format_date() {
   var $j=jQuery.noConflict();
   $j( '#date' ).datepicker({ dateFormat: 'dd-mm-yy' });
};

<%=link_to_remote "Ajax Add Details", :update=>"add" , :url=>{ :action=>"add" }, :success =>"format_date()"%>

This will work because the element exists when you trigger the function.

For culture's sake, have a look at jQuery's live() function.


问:
extracting lines if the first field matches another list saved in a different file -- shell command
I have two files. One contains a list of items, e.g.,

Allie
Bob
John
Laurie
```

<p>Another file (file2) contains a different list of items in a different order, but some items might overlap with the items in file 1, e.g, </p>

<pre class="lang-none prettyprint-override"><code>Laurie 45 56 6 75
Moxipen 10 45 56 56
Allie 45 56 67 23
</code>```

I want to intersect these two files and extract only those lines from file 2 whose first field matches an item in field 1.

i.e., my output should be

Allie 45 56 67 23
Laurie 45 56 6 75
```

<p>(preferably in this order, but it's OK if not)</p>

<p><code>grep -f file1 file2</code> doesn't do what I want. </p>

<p>I also need something efficient because the second file is HUGE.</p>

<p>I also tried this:</p>

```awk -F, 'FNR==NR {a[$1]=$0; next}; $1 in a {print a[$1]}' file2 file1
```

答:
This is the job that join is built for.

Providing a reproducer testable via copy-and-paste with shell functions (which you could replace with your actual input files):

```<code>cat_file1() {
  printf '%s\n' Allie Bob John Laurie
}

cat_file2() {
  printf '%s\n' 'Laurie 45 56 6 75' \
                'Moxipen 10 45 56 56' \
                'Allie 45 56 67 23'
}

join <(cat_file1 | sort) <(cat_file2 | sort)
</code>```

...properly emits:

Allie 45 56 67 23
Laurie 45 56 6 75
```

Of course, don't cat file1 | sort -- run sort <file1 to provide a real handle for better efficiency, or (better!) store your inputs in sorted form in the first place.

ContentLicense: CC BY-SA 3.0

Body:
I have two files. One contains a list of items, e.g.,

Allie
Bob
John
Laurie

Another file (file2) contains a different list of items in a different order, but some items might overlap with the items in file 1, e.g,

Laurie 45 56 6 75
Moxipen 10 45 56 56
Allie 45 56 67 23

I want to intersect these two files and extract only those lines from file 2 whose first field matches an item in field 1.

i.e., my output should be

Allie 45 56 67 23
Laurie 45 56 6 75

(preferably in this order, but it's OK if not)

grep -f file1 file2 doesn't do what I want.

I also need something efficient because the second file is HUGE.

I also tried this:

awk -F, 'FNR==NR {a[$1]=$0; next}; $1 in a {print a[$1]}' file2 file1

Body:
This is the job that join is built for.

Providing a reproducer testable via copy-and-paste with shell functions (which you could replace with your actual input files):

cat_file1() {
  printf '%s\n' Allie Bob John Laurie
}

cat_file2() {
  printf '%s\n' 'Laurie 45 56 6 75' \
                'Moxipen 10 45 56 56' \
                'Allie 45 56 67 23'
}

join <(cat_file1 | sort) <(cat_file2 | sort)

...properly emits:

Allie 45 56 67 23
Laurie 45 56 6 75

Of course, don't cat file1 | sort -- run sort <file1 to provide a real handle for better efficiency, or (better!) store your inputs in sorted form in the first place.


问:
Qt and Windows Executable Version Information
My Windows Qt widgets application uses a "version.h" file and an "RC" file to populate the version information strings against an executable.

The version.h looks like this...

```<code>#ifndef VERSION_H
#define VERSION_H

#define VERSION_MAJOR                           1
#define VERSION_MINOR                           0
#define VERSION_BUILD                           3

#define VER_FILEVERSION           VERSION_MAJOR,VERSION_MINOR,VERSION_BUILD,0
#define STR_FILEVERSION                     VERSION_MAJOR##"."##VERSION_MINOR##"."VERSION_BUILD##".0"

// Keep the product version as fixed
#define VER_PRODUCTVERSION        1.0.0.0
#define STR_PRODUCTVERSION          "1.0.0.0\0"

#define STR_COMPANYNAME                     "MyCompany"
#define STR_FILEDESCRIPTION             "MyFile"
#define STR_INTERNALNAME                    "MyFile"
#define STR_LEGALCOPYRIGHT              "Copyright © 2017 MyCompany"
#define STR_LEGALTRADEMARKS1            "All Rights Reserved"
#define STR_LEGALTRADEMARKS2            STR_LEGALTRADEMARKS1
#define STR_ORIGINALFILENAME            "MyApp.exe"
#define STR_PRODUCTNAME                     "MyApp"

#define STR_COMPANYDOMAIN                   "mywebsite.com"

#endif // VERSION_H
</code>```

And the RC file looking like:

```<code>IDI_APP_ICON    ICON    DISCARDABLE     "MyApp.ico"

#include <windows.h>
#include "version.h"

VS_VERSION_INFO VERSIONINFO
FILEVERSION     VER_FILEVERSION
PRODUCTVERSION  VER_PRODUCTVERSION
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904E4"
        BEGIN
            VALUE "CompanyName",        STR_COMPANYNAME
            VALUE "FileDescription",    STR_FILEDESCRIPTION
            VALUE "FileVersion",        STR_FILEVERSION
            VALUE "InternalName",       STR_INTERNALNAME
            VALUE "LegalCopyright",     STR_LEGALCOPYRIGHT
            VALUE "LegalTrademarks1",   STR_LEGALTRADEMARKS1
            VALUE "LegalTrademarks2",   STR_LEGALTRADEMARKS2
            VALUE "OriginalFilename",   STR_ORIGINALFILENAME
            VALUE "ProductName",        STR_PRODUCTNAME
            VALUE "ProductVersion",     STR_PRODUCTVERSION
        END
    END

    BLOCK "VarFileInfo"
    BEGIN
        VALUE "Translation", 0x409, 1252
    END
END
</code>```

And for completeness, the ".pro" file has this line inside:

```<code>RC_FILE    = MyApp.rc
</code>```

This all seems to work OK: when I right-click the exe and go to the details tab, I can see the version information and all other strings from the combined version.h and RC files.

However, if I increase the any one of the VERSION_XXX #define values and build the application, I've noticed that the reported "File version" hasn't changed - only when I do a "rebuild" does the version change.

I don't really want to have to do a complete rebuild every time I increase the version information (mainly VERSION_BUILD at the moment) so what may I need to do in order to get this information updated each time the exe is built?

答:
The problem is that qmake doesn't support dependencies of RC_FILE. So what can be done about that?

1) The simplest and quickest approach is to make use of touch: if MyApp.rc (almost) never changes, we can force its timestamp to follow one of version.h. Then something like:

MyApp.pro

```<code>TARGET = MyApp
win*:RC_FILE = $${TARGET}.rc
win*:!build_pass:touch($$RC_FILE, version.h)
# ... more to follow
</code>```

accompanied with qmake && make will do the trick.

2) Another seemingly easy solution is not to use RC_FILE at all, but let qmake automatically generate resource script from the predefined variables: VERSION, QMAKE_TARGET_COMPANY, QMAKE_TARGET_DESCRIPTION, etc. See qmake Platform Notes for a full list.

It's enough just to add VERSION = x.y.z.n (and also remove RC_FILE = MyApp.rc) to your .pro file to enable this feature.

This is sufficient for most Qt applications, as long as they use own Qt resource system, while Windows .rc script is needed for application ICON(s) and VERSIONINFO only.

An example of the above:

version.pri

```<code>RC_ICONS = MyApp.ico
VERSION = 1.0.3.0
QMAKE_TARGET_COMPANY = MyCompany
QMAKE_TARGET_DESCRIPTION = MyFile
QMAKE_TARGET_COPYRIGHT = "Copyright © 2017 MyCompany"
QMAKE_TARGET_PRODUCT = MyApp
RC_CODEPAGE = 1252
RC_LANG = 0x0409
</code>```

MyApp.pro

```<code>TARGET = MyApp
#win*:RC_FILE = $${TARGET}.rc
win*:include(version.pri)
# ... more to follow
</code>```

Unfortunately, this poses another problem: if you still need version.h in your C++ source tree, you have to synchronize it somehow with your version.pri. I think that using QMAKE_SUBSTITUTES to auto-generate version.h is the best choice. However, adding a bunch of DEFINES+=... is also an idea.

3) You can create a custom target in your .pro file and take care of compiling the resource script yourself. For example:

MyApp.pro

```<code>TARGET = MyApp
#win*:RC_FILE = $${TARGET}.rc
win* {
    QMAKE_EXTRA_TARGETS += windows_resource
    windows_resource.target = $${TARGET}_res$${first(QMAKE_EXT_OBJ)}
    windows_resource.depends = $${TARGET}.rc version.h
    msvc:windows_resource.commands = $$QMAKE_RC /fo $$windows_resource.target $${TARGET}.rc
    else:windows_resource.commands = $$QMAKE_RC $${TARGET}.rc $$windows_resource.target
    PRE_TARGETDEPS += $$windows_resource.target
    LIBS += $$windows_resource.target
}
# ... more to follow
</code>```

Body:
My Windows Qt widgets application uses a "version.h" file and an "RC" file to populate the version information strings against an executable.

The version.h looks like this...

#ifndef VERSION_H
#define VERSION_H

#define VERSION_MAJOR                           1
#define VERSION_MINOR                           0
#define VERSION_BUILD                           3

#define VER_FILEVERSION           VERSION_MAJOR,VERSION_MINOR,VERSION_BUILD,0
#define STR_FILEVERSION                     VERSION_MAJOR##"."##VERSION_MINOR##"."VERSION_BUILD##".0"

// Keep the product version as fixed
#define VER_PRODUCTVERSION        1.0.0.0
#define STR_PRODUCTVERSION          "1.0.0.0\0"

#define STR_COMPANYNAME                     "MyCompany"
#define STR_FILEDESCRIPTION             "MyFile"
#define STR_INTERNALNAME                    "MyFile"
#define STR_LEGALCOPYRIGHT              "Copyright © 2017 MyCompany"
#define STR_LEGALTRADEMARKS1            "All Rights Reserved"
#define STR_LEGALTRADEMARKS2            STR_LEGALTRADEMARKS1
#define STR_ORIGINALFILENAME            "MyApp.exe"
#define STR_PRODUCTNAME                     "MyApp"

#define STR_COMPANYDOMAIN                   "mywebsite.com"

#endif // VERSION_H

And the RC file looking like:

IDI_APP_ICON    ICON    DISCARDABLE     "MyApp.ico"

#include <windows.h>
#include "version.h"

VS_VERSION_INFO VERSIONINFO
FILEVERSION     VER_FILEVERSION
PRODUCTVERSION  VER_PRODUCTVERSION
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904E4"
        BEGIN
            VALUE "CompanyName",        STR_COMPANYNAME
            VALUE "FileDescription",    STR_FILEDESCRIPTION
            VALUE "FileVersion",        STR_FILEVERSION
            VALUE "InternalName",       STR_INTERNALNAME
            VALUE "LegalCopyright",     STR_LEGALCOPYRIGHT
            VALUE "LegalTrademarks1",   STR_LEGALTRADEMARKS1
            VALUE "LegalTrademarks2",   STR_LEGALTRADEMARKS2
            VALUE "OriginalFilename",   STR_ORIGINALFILENAME
            VALUE "ProductName",        STR_PRODUCTNAME
            VALUE "ProductVersion",     STR_PRODUCTVERSION
        END
    END

    BLOCK "VarFileInfo"
    BEGIN
        VALUE "Translation", 0x409, 1252
    END
END

And for completeness, the ".pro" file has this line inside:

RC_FILE    = MyApp.rc

This all seems to work OK: when I right-click the exe and go to the details tab, I can see the version information and all other strings from the combined version.h and RC files.

However, if I increase the any one of the VERSION_XXX #define values and build the application, I've noticed that the reported "File version" hasn't changed - only when I do a "rebuild" does the version change.

I don't really want to have to do a complete rebuild every time I increase the version information (mainly VERSION_BUILD at the moment) so what may I need to do in order to get this information updated each time the exe is built?

Body:
The problem is that qmake doesn't support dependencies of RC_FILE. So what can be done about that?

1) The simplest and quickest approach is to make use of touch: if MyApp.rc (almost) never changes, we can force its timestamp to follow one of version.h. Then something like:

MyApp.pro

TARGET = MyApp
win*:RC_FILE = $${TARGET}.rc
win*:!build_pass:touch($$RC_FILE, version.h)
# ... more to follow

accompanied with qmake && make will do the trick.

2) Another seemingly easy solution is not to use RC_FILE at all, but let qmake automatically generate resource script from the predefined variables: VERSION, QMAKE_TARGET_COMPANY, QMAKE_TARGET_DESCRIPTION, etc. See qmake Platform Notes for a full list.

It's enough just to add VERSION = x.y.z.n (and also remove RC_FILE = MyApp.rc) to your .pro file to enable this feature.

This is sufficient for most Qt applications, as long as they use own Qt resource system, while Windows .rc script is needed for application ICON(s) and VERSIONINFO only.

An example of the above:

version.pri

RC_ICONS = MyApp.ico
VERSION = 1.0.3.0
QMAKE_TARGET_COMPANY = MyCompany
QMAKE_TARGET_DESCRIPTION = MyFile
QMAKE_TARGET_COPYRIGHT = "Copyright © 2017 MyCompany"
QMAKE_TARGET_PRODUCT = MyApp
RC_CODEPAGE = 1252
RC_LANG = 0x0409

MyApp.pro

TARGET = MyApp
#win*:RC_FILE = $${TARGET}.rc
win*:include(version.pri)
# ... more to follow

Unfortunately, this poses another problem: if you still need version.h in your C++ source tree, you have to synchronize it somehow with your version.pri. I think that using QMAKE_SUBSTITUTES to auto-generate version.h is the best choice. However, adding a bunch of DEFINES+=... is also an idea.

3) You can create a custom target in your .pro file and take care of compiling the resource script yourself. For example:

MyApp.pro

TARGET = MyApp
#win*:RC_FILE = $${TARGET}.rc
win* {
    QMAKE_EXTRA_TARGETS += windows_resource
    windows_resource.target = $${TARGET}_res$${first(QMAKE_EXT_OBJ)}
    windows_resource.depends = $${TARGET}.rc version.h
    msvc:windows_resource.commands = $$QMAKE_RC /fo $$windows_resource.target $${TARGET}.rc
    else:windows_resource.commands = $$QMAKE_RC $${TARGET}.rc $$windows_resource.target
    PRE_TARGETDEPS += $$windows_resource.target
    LIBS += $$windows_resource.target
}
# ... more to follow


问:
How to remove NuGet Package from server?
I have added new package to nuget(I'm not talking about adding reference of package into project). I have added new packages to server so that others can consume/use that package in their projects.

Say package name was Parser1.0.0.0.nupkg

Problem is I forgot to add one dependency. Now I want to edit or delete and add correct one again. But I don't want to change its version number.

Anyone knows how to do it?

答:
It is possible for private NuGet servers. Use the NuGet delete command.

nuget delete MyPackage 1.0

Update: This still doesn't address the OP's issue as it doesn't allow you to reuse the version number, because it's still being locked by the server. There is no safe way to permanently delete a specific version of a package.


问:
Scanning sub folder

I am trying to search files from sd card so i can delete multiple and duplicate files.``

```<code>private List<String> searchForFileNameContainingSubstring(String substring)
{
    path = Environment.getExternalStorageDirectory().getPath() + "/";
    //This is assuming you pass in the substring from input.
    File file = new File(path); //Change this to the directory you want to search in.

    List<String> filesContainingSubstring = new ArrayList<String>();

    if (file.exists() && file.isDirectory())
    {
        String[] files = file.list(); //get the files in String format.
        for (String fileName : files)
        {
            if (fileName.contains(substring))
                filesContainingSubstring.add(fileName);
        }
    }

    for (String fileName : filesContainingSubstring)
    {
        System.out.println(fileName); //or do other operation
    }

    return filesContainingSubstring; //return the list of filenames containing substring.
}
</code>```

How can i scan other sub folders from sdcard/ directories

It only shows results from sdcard directories

答:
You can use Apache Common's FileUtils.listFiles method.
You can search recursively throughout a folder by setting the third parameter as true.
Also, you can target specific file extensions by passing in the second argument a String array as seen below. If you want to target any extensions pass null.

Note: the extensions names do not include '.' it's "jpg" and not ".jpg"

```<code>    String[] extensions = {"png","jpg"};
    Collection images = FileUtils.listFiles(new File("dirPath"),extensions, true);
    for (Object obj : images){
        File file = (File) obj;
        // your code logic
    }
</code>```

Title: Scanning sub folder

Body:
I am trying to search files from sd card so i can delete multiple and duplicate files.``

private List<String> searchForFileNameContainingSubstring(String substring)
{
    path = Environment.getExternalStorageDirectory().getPath() + "/";
    //This is assuming you pass in the substring from input.
    File file = new File(path); //Change this to the directory you want to search in.

    List<String> filesContainingSubstring = new ArrayList<String>();

    if (file.exists() && file.isDirectory())
    {
        String[] files = file.list(); //get the files in String format.
        for (String fileName : files)
        {
            if (fileName.contains(substring))
                filesContainingSubstring.add(fileName);
        }
    }

    for (String fileName : filesContainingSubstring)
    {
        System.out.println(fileName); //or do other operation
    }

    return filesContainingSubstring; //return the list of filenames containing substring.
}

How can i scan other sub folders from sdcard/ directories

It only shows results from sdcard directories

Body:
You can use Apache Common's FileUtils.listFiles method.
You can search recursively throughout a folder by setting the third parameter as true.
Also, you can target specific file extensions by passing in the second argument a String array as seen below. If you want to target any extensions pass null.

Note: the extensions names do not include '.' it's "jpg" and not ".jpg"

    String[] extensions = {"png","jpg"};
    Collection images = FileUtils.listFiles(new File("dirPath"),extensions, true);
    for (Object obj : images){
        File file = (File) obj;
        // your code logic
    }


问:
TS error with @Injectable tag Angular 5
I am running into this error when compiling my code:

```<code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class TaskService {
  constructor(private http: HttpClient) {
  }

  getTasks() {
    return this.http.get('/api/tasks');
  }
}
</code>```

ERROR in src/app/tasks/task.service.ts(4,1): error TS1238: Unable to resolve signature of class decorator when called as an expression.

I'm not sure where it's going wrong... 4,1 is the @ symbol before Injectable.

答:
try adding a return type getTasks(): Observable<any>.
Do you inject the HttpClientModule correctly ?

```<code>import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module
    // after BrowserModule.
    HttpClientModule,
  ],
})
</code>```

Title: TS error with @Injectable tag Angular 5

Body:
I am running into this error when compiling my code:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class TaskService {
  constructor(private http: HttpClient) {
  }

  getTasks() {
    return this.http.get('/api/tasks');
  }
}

ERROR in src/app/tasks/task.service.ts(4,1): error TS1238: Unable to resolve signature of class decorator when called as an expression.

I'm not sure where it's going wrong... 4,1 is the @ symbol before Injectable.

Body:
try adding a return type getTasks(): Observable<any>.
Do you inject the HttpClientModule correctly ?

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module
    // after BrowserModule.
    HttpClientModule,
  ],
})


问:
How do you dynamically allocate a matrix in MASM?
I'm trying to build a matrix calculator using MASM and I'm having trouble trying to allocate the matrix dynamically.

For Example:

If a user inputs that the matrix is 3x3, I allocate in memory a space that holds a 3x3 matrix.

I was hoping someone could show me how.

答:
How do you dynamically allocate a matrix in MASM?

You don't dynamically allocate an array in assembler (because at that low level, dynamic allocation has no precise sense).

You could call, in assembler, some function doing dynamic allocation. For example, you could call malloc from some C standard library.

If you are coding some user-mode application for some (known) operating system, you might consider doing some system call to change your virtual address space. On Linux, that might be (for example) mmap(2).

In both cases, you need to know and follow the calling conventions used by the called function or system call. You probably need to read the Application Binary Interface for your system. For Linux/x86-64, see here

The calling conventions are usually instruction set architecture specific and operating system specific. If you are using some stand-alone library or framework, that thing should also document its calling conventions.

See also this.

You could also allocate on the call stack (by changing the stack pointer appropriately).


问:
Finding two matches with the same string in regex
Is there a way in regex to find a string if it occurs twice in given structures (i.e. like in XML parsing)?
This code obviously does not work as it finds the first tag and then the last closing tag:

```<code>re.findall(r'<(.+)>([\s\S]*)</(.+)>', s)
</code>```

So is there a way to tell regex that the third match should be the same as the first?

Full code:

```<code>import re

s = '''<a1>
    <a2>
        1
    </a2>
    <b2>
        52
    </b2>
    <c2>
        <a3>
            Abc
        </a3>
    </c2>
</a1>
<b1>
    21
</b1>'''

matches = re.findall(r'<(.+)>([\s\S]*)</(.+)>', s)
for match in matches:
    print(match)
</code>```

Result should be all the tags with the contents:

```<code>    [('a1', '\n    <a2>\n        1\n    </a2>\n    <b2>\n        52\n    </b2>\n    <c2>\n        <a3>\n            Abc\n        </a3>\n    </c2>\n'),
     ('a2', '\n        1\n    '),
      ...]
</code>```

Note: I am not looking for a complete xml parsing package. The question is specificly about solving the given problem with regex.

答:
Using the help danihp gave me in the answer and obeying the hint DDeMartini gave in the comment I was able to create a lightweight xml parser that returns a dict structure of the xml:

```<code>import re

def xml_loads(xml_text):
    matches = re.findall(r'<([^<>]+)>([\s\S]*)</(\1)>', xml_text)
    if not matches:
        return xml_text.strip()
    d = {}
    for k, s2, _ in matches:
        d[k] = xml_loads(s2)
    return d

s = '''<a1>
    <a2>
        1
    </a2>
    <b2>
        52
    </b2>
    <c2>
        <a3>
            Abc
        </a3>
    </c2>
</a1>
<b1>
    21
</b1>'''

d = xml_loads(s)
print(d)
</code>```

Body:
Is there a way in regex to find a string if it occurs twice in given structures (i.e. like in XML parsing)?
This code obviously does not work as it finds the first tag and then the last closing tag:

re.findall(r'<(.+)>([\s\S]*)</(.+)>', s)

So is there a way to tell regex that the third match should be the same as the first?

Full code:

import re

s = '''<a1>
    <a2>
        1
    </a2>
    <b2>
        52
    </b2>
    <c2>
        <a3>
            Abc
        </a3>
    </c2>
</a1>
<b1>
    21
</b1>'''

matches = re.findall(r'<(.+)>([\s\S]*)</(.+)>', s)
for match in matches:
    print(match)

Result should be all the tags with the contents:

    [('a1', '\n    <a2>\n        1\n    </a2>\n    <b2>\n        52\n    </b2>\n    <c2>\n        <a3>\n            Abc\n        </a3>\n    </c2>\n'),
     ('a2', '\n        1\n    '),
      ...]

Note: I am not looking for a complete xml parsing package. The question is specificly about solving the given problem with regex.

Body:
Using the help danihp gave me in the answer and obeying the hint DDeMartini gave in the comment I was able to create a lightweight xml parser that returns a dict structure of the xml:

import re

def xml_loads(xml_text):
    matches = re.findall(r'<([^<>]+)>([\s\S]*)</(\1)>', xml_text)
    if not matches:
        return xml_text.strip()
    d = {}
    for k, s2, _ in matches:
        d[k] = xml_loads(s2)
    return d

s = '''<a1>
    <a2>
        1
    </a2>
    <b2>
        52
    </b2>
    <c2>
        <a3>
            Abc
        </a3>
    </c2>
</a1>
<b1>
    21
</b1>'''

d = xml_loads(s)
print(d)


问:
Type parameter inference in pattern matching
I am trying to create some kind of heterogeneous map and came up with the following code

```<code>sealed trait Key[V]
case object LongKey extends Key[Long]

case class KeyValue[V](key: Key[V], value: V)

object KeyValue {
  def values(key: Key[Long], kvs: List[KeyValue[_]]): List[Long] =
    kvs.collect {
      case KeyValue(LongKey, v) ⇒ v: Long // this compiles
      case KeyValue(`key`, v)   ⇒ v: Long // this doesn't
    }
}
</code>```

As Key is sealed and invariant I would have expected the 2 lines to be interchangeable.
Why does the second case not compile?

```<code>...: type mismatch;
  found   : _$1 where type _$1
  required: Long
       case KeyValue(`key`, v) ⇒ v: Long
</code>```

答:
Nice question. I initially thought this "should" work, but consider:</p>

```<code>val kv: KeyValue[_] = KeyValue[String](null, "a")
val key: Key[Long] = null
kv match {
  case KeyValue(`key`, v) => v // returns String, not Long!
}
</code>```

Body:
I am trying to create some kind of heterogeneous map and came up with the following code

sealed trait Key[V]
case object LongKey extends Key[Long]

case class KeyValue[V](key: Key[V], value: V)

object KeyValue {
  def values(key: Key[Long], kvs: List[KeyValue[_]]): List[Long] =
    kvs.collect {
      case KeyValue(LongKey, v) ⇒ v: Long // this compiles
      case KeyValue(`key`, v)   ⇒ v: Long // this doesn't
    }
}

As Key is sealed and invariant I would have expected the 2 lines to be interchangeable.
Why does the second case not compile?

...: type mismatch;
  found   : _$1 where type _$1
  required: Long
       case KeyValue(`key`, v) ⇒ v: Long

Body:
Nice question. I initially thought this "should" work, but consider:

val kv: KeyValue[_] = KeyValue[String](null, "a")
val key: Key[Long] = null
kv match {
  case KeyValue(`key`, v) => v // returns String, not Long!
}


问:
Error: You are debugging a Release build of X.dll

Background

I have an ASP.NET MVC application project, along with various other projects within a Visual Studio solution. The different projects use various versions of the NPoco library as follows:

The MVC project includes a version of NPoco through NuGet.

Some other projects include a (probably different) version of NPoco through a reference to a DLL (not the DLL provided through NuGet).

One of the projects is the source code of a version of NPoco with some alterations made.

I'm using Visual Studio 2015 Update 3 14.0.25422.01.

Error

For some reason, when I launch this application in the debugger using the normal Start Debugging command in Visual Studio, it launches, but it also produces the following warning:

If I press Continue Debugging, everything seems to still work as usual, including breakpoints.

This problem only started happening recently.

Question

Anyone know what caused the above error?

Do I have something misconfigured?

答:
In case someone is still having this issue, for me it was because I confused the GAC by installing the software I was trying to debug.

The fusion logger helped me figure this out ha.

ContentLicense: CC BY-SA 4.0


问:
Is there proper way to concatenate a base path name with a new path name?

Is there a way where you can update the char arrays of a base path with an updated path?

```<code>struct dirent *dp;
DIR *dir;
struct stat buf;
dir = opendir("./statdir/");
int x;
char base_path[11] = "./statdir/";
char* full_path;

int main(int argc, char* argv[]){
  while((dp = readdir(dir)) != NULL) {
     full_path = strcat(base_path, dp->d_name);

     if((x = lstat(full_path, &buf)) == -1) {
         perror("stat failed");
         exit(1);
       }
       printf("Debug: %s\n", full_path);

     }
     closedir(dir);
     return(0);
  }
}
</code>```

My goal is to update full_path after each loop to the base_path + whatever argument is passed to argv[] and in my directory i have two files name file1 and file2....

i.e if I ran my code and wrote ./Stat, I expected full_path to be "./statdir/file1" and then "./statdir/file2"

The results I am getting however is :

Debug: ./statdir/.

Debug: ./statdir/...

stat failed: No such file or directory

答:
You're concatenating a string onto base_path, however that array is just long enough for what you initialized with.  That means you're writing past the end of the array.  This invokes undefined behavior.

Also note that full_path is pointing to the start of base_path.

Instead, make full_path an array big enough to hold a full path.  Then use strcpy to copy over the base path, then strcat to add on the current entry.

```<code>char full_path[100];
...

  while((dp = readdir(dir)) != NULL) {
    strcpy(full_path, base_path);
    strcat(full_path, dp->d_name);
</code>```

Body:
Is there a way where you can update the char arrays of a base path with an updated path?

struct dirent *dp;
DIR *dir;
struct stat buf;
dir = opendir("./statdir/");
int x;
char base_path[11] = "./statdir/";
char* full_path;

int main(int argc, char* argv[]){
  while((dp = readdir(dir)) != NULL) {
     full_path = strcat(base_path, dp->d_name);

     if((x = lstat(full_path, &buf)) == -1) {
         perror("stat failed");
         exit(1);
       }
       printf("Debug: %s\n", full_path);

     }
     closedir(dir);
     return(0);
  }
}

My goal is to update full_path after each loop to the base_path + whatever argument is passed to argv[] and in my directory i have two files name file1 and file2....

i.e if I ran my code and wrote ./Stat, I expected full_path to be "./statdir/file1" and then "./statdir/file2"

The results I am getting however is :

Debug: ./statdir/.

Debug: ./statdir/...

stat failed: No such file or directory

Body:
You're concatenating a string onto base_path, however that array is just long enough for what you initialized with.  That means you're writing past the end of the array.  This invokes undefined behavior.

Also note that full_path is pointing to the start of base_path.

Instead, make full_path an array big enough to hold a full path.  Then use strcpy to copy over the base path, then strcat to add on the current entry.

char full_path[100];
...

  while((dp = readdir(dir)) != NULL) {
    strcpy(full_path, base_path);
    strcat(full_path, dp->d_name);


问:
XmlSerializer to convert to XmlElement or string
I am storing developer notes in XML files within the project, to eliminate storing them on a SQL instance to reduce database calls.

I have my class set up to be Serialized

```<code>[Serializable]
public class NoteDto
{
    [NonSerialized]
    private string _project;

    public string Date { get; set; }
    public string Time { get; set; }
    public string Author { get; set; }
    public string NoteText { get; set; }
    public string Project
    {
        get => _project;
        set => _project = value;
    }
}
</code>```

to create this element

```<code><Note>
  <Date></Date>
  <Time></Time>
  <NoteText></NoteText>
  <Author></Author>
</Note>
</code>```

The reason I do not want Project property serialized, is that the Note Element is in a parent element (NotesFor).

```<code><NotesFor id="project value here">
  // note element here
</NotesFor>
</code>```

I need the Project string to search for the Node where the NotesFor element id = Project
then append the created element to the end of its children.

So that leaves two questions

Do I create an XElement and append to current node or do I create a string
to append to the node in the Xml file? I don't work much with Xml so I am
not sure what the standard protocol is to update Xml files.

Is there a better way to accomplish what I am trying to do?

答:
As I understood, your data is small enough to store it in xml file(s). Xml files are stored in the file system and even you use XmlDocument or XDocument to load and save an xml file, whole of the file would be re-written to the file system.

I think It's better to use objects (NoteForDto & NoteDto) and XmlSerializer to write file. So you don't have to work with X(ml)Document complexity.  Here is the example.

And your code sample:

```<code>    public class NoteDto
    {

        private string _project;

        public string Date { get; set; }
        public string Time { get; set; }
        public string Author { get; set; }
        public string NoteText { get; set; }

        [XmlIgnore]
        public string Project
        {
            get => _project;
            set => _project = value;
        }
    }

    [XmlRoot(ElementName = "NotesFor")]
    public class NotesForDto
    {
        [XmlAttribute(AttributeName="id")]
        public string ProjectID { get; set; }

        [XmlElement(ElementName ="Note")]
        public List<NoteDto> NoteList { get; set; }
    }

    public static void Main(string[] args)
    {
        var notes = new NotesForDto
        {
            ProjectID = "SampelProject",
            NoteList = new List<NoteDto>
           {
               new NoteDto
               {
                   Author="Author1",
                   Date= "Date1",
                   NoteText="NoteText1",
                   Project="SampleProject",
                   Time="Time1"
               },
               new NoteDto
               {
                   Author="Author2",
                   Date= "Date2",
                   NoteText="NoteText2",
                   Project="SampleProject",
                   Time="Time2"
               }
           }
        };

        XmlSerializer ser = new XmlSerializer(typeof(NotesForDto));

        using (var tw = File.Open("notes.xml",FileMode.Create))
        {
            ser.Serialize(tw,notes);
        }
    }
</code>```

Output (notes.xml)

```<code><?xml version="1.0"?>
<NotesFor xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="SampelProject">
  <Note>
    <Date>Date1</Date>
    <Time>Time1</Time>
    <Author>Author1</Author>
    <NoteText>NoteText1</NoteText>
  </Note>
  <Note>
    <Date>Date2</Date>
    <Time>Time2</Time>
    <Author>Author2</Author>
    <NoteText>NoteText2</NoteText>
  </Note>
</NotesFor>
</code>```

Body:
I am storing developer notes in XML files within the project, to eliminate storing them on a SQL instance to reduce database calls.

I have my class set up to be Serialized

[Serializable]
public class NoteDto
{
    [NonSerialized]
    private string _project;

    public string Date { get; set; }
    public string Time { get; set; }
    public string Author { get; set; }
    public string NoteText { get; set; }
    public string Project
    {
        get => _project;
        set => _project = value;
    }
}

to create this element

<Note>
  <Date></Date>
  <Time></Time>
  <NoteText></NoteText>
  <Author></Author>
</Note>

The reason I do not want Project property serialized, is that the Note Element is in a parent element (NotesFor).

<NotesFor id="project value here">
  // note element here
</NotesFor>

I need the Project string to search for the Node where the NotesFor element id = Project
then append the created element to the end of its children.

So that leaves two questions

Do I create an XElement and append to current node or do I create a string
to append to the node in the Xml file? I don't work much with Xml so I am
not sure what the standard protocol is to update Xml files.

Is there a better way to accomplish what I am trying to do?

Body:
As I understood, your data is small enough to store it in xml file(s). Xml files are stored in the file system and even you use XmlDocument or XDocument to load and save an xml file, whole of the file would be re-written to the file system.

I think It's better to use objects (NoteForDto & NoteDto) and XmlSerializer to write file. So you don't have to work with X(ml)Document complexity.  Here is the example.

And your code sample:

    public class NoteDto
    {

        private string _project;

        public string Date { get; set; }
        public string Time { get; set; }
        public string Author { get; set; }
        public string NoteText { get; set; }

        [XmlIgnore]
        public string Project
        {
            get => _project;
            set => _project = value;
        }
    }

    [XmlRoot(ElementName = "NotesFor")]
    public class NotesForDto
    {
        [XmlAttribute(AttributeName="id")]
        public string ProjectID { get; set; }

        [XmlElement(ElementName ="Note")]
        public List<NoteDto> NoteList { get; set; }
    }

    public static void Main(string[] args)
    {
        var notes = new NotesForDto
        {
            ProjectID = "SampelProject",
            NoteList = new List<NoteDto>
           {
               new NoteDto
               {
                   Author="Author1",
                   Date= "Date1",
                   NoteText="NoteText1",
                   Project="SampleProject",
                   Time="Time1"
               },
               new NoteDto
               {
                   Author="Author2",
                   Date= "Date2",
                   NoteText="NoteText2",
                   Project="SampleProject",
                   Time="Time2"
               }
           }
        };

        XmlSerializer ser = new XmlSerializer(typeof(NotesForDto));

        using (var tw = File.Open("notes.xml",FileMode.Create))
        {
            ser.Serialize(tw,notes);
        }
    }

Output (notes.xml)

<?xml version="1.0"?>
<NotesFor xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="SampelProject">
  <Note>
    <Date>Date1</Date>
    <Time>Time1</Time>
    <Author>Author1</Author>
    <NoteText>NoteText1</NoteText>
  </Note>
  <Note>
    <Date>Date2</Date>
    <Time>Time2</Time>
    <Author>Author2</Author>
    <NoteText>NoteText2</NoteText>
  </Note>
</NotesFor>


问:
React - I can't populate my dropdown list using my data.json()
What i'm trying to do is populate my dropdown list with names that i requested from my API.

Here's my component :

```<code>export default class App extends Component {
constructor(props) {
    super(props);

    this.state = {
        my_data: null,
        IND: null,
    };
};

componentDidMount(){
    const query = new URLSearchParams(location.search)
    const access_token = query.get('access_token')
    const namesId = query.get('namesId')

    fetch('http://localhost:8080/api'
        + namesId, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Credentials': true,
            'Access-Control-Allow-Origin': '*',
            'Authorization': "Bearer " + access_token
        }
    }).then(response=>{
        return response.json();
    }).then(data=>{
        let my_data = [];
        my_data = data;
        let individus = hello.individus;
        let IND = [];
        IND.push({ label: individus[0].lastName, value: individus[0].firstName});
        IND.push({ label: individus[1].lastName, value: individus[1].firstName});
        IND.push({ label: individus[2].lastName, value: individus[2].firstName});
        this.setState({
            my_data: hello,
            IND: IND
        });
    }).catch(function(error) {
        console.log(error)
    });
}

render() {
    const { IND } = this.state;

    return (
        <div>
          <Select
               multi={true}
               joinValues={false}
               options={IND}
               placeholder="Select"
               simpleValue={false}
                />
           </div>

    );
}
</code>```

Weirdly all i can see on my dropdown is the first element of this.state.IND ( the 3 objects are in IND, i checked on my console ), i don't understand what i'm doing wrong

答:
Eureka !

Using the "Async options with Promises" of react-select solved my problem

Body:
What i'm trying to do is populate my dropdown list with names that i requested from my API.

Here's my component :

export default class App extends Component {
constructor(props) {
    super(props);

    this.state = {
        my_data: null,
        IND: null,
    };
};

componentDidMount(){
    const query = new URLSearchParams(location.search)
    const access_token = query.get('access_token')
    const namesId = query.get('namesId')

    fetch('http://localhost:8080/api'
        + namesId, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Credentials': true,
            'Access-Control-Allow-Origin': '*',
            'Authorization': "Bearer " + access_token
        }
    }).then(response=>{
        return response.json();
    }).then(data=>{
        let my_data = [];
        my_data = data;
        let individus = hello.individus;
        let IND = [];
        IND.push({ label: individus[0].lastName, value: individus[0].firstName});
        IND.push({ label: individus[1].lastName, value: individus[1].firstName});
        IND.push({ label: individus[2].lastName, value: individus[2].firstName});
        this.setState({
            my_data: hello,
            IND: IND
        });
    }).catch(function(error) {
        console.log(error)
    });
}

render() {
    const { IND } = this.state;

    return (

          <Select
               multi={true}
               joinValues={false}
               options={IND}
               placeholder="Select"
               simpleValue={false}
                />

    );
}

Weirdly all i can see on my dropdown is the first element of this.state.IND ( the 3 objects are in IND, i checked on my console ), i don't understand what i'm doing wrong


问:
how constantly run a script beside django
I have a Django website running  and i am looking for a way to run a script that  constantly fetch some data from the Internet and insert them into my Django app database.

how can i keep script running as long as server is up ? (no need to start it manually - and don't want to stop it at all!!)
 i guess celery is not what i want !?!

,and how can i use Django ORM in this script for inserting data into db?
i tried threading but think its should be started by calling the script or ..

答:
You can indeed use celery for this job and you can take full advantage of the ORM without any need to query your db manually. Make a task that will fetch the items from the internet and updates the DB. Define a celery task that will do what you want (fetching + saving)

```<code> @app.task
 def fetching_script():
     response = requests.get(url)
     for item in response.content:
         instance = ModelInstance(**item)
         instance.full_clean()
         instance.save()
</code>```

then in your celery config

```<code>  app.conf.update(
      CELERYBEAT_SCHEDULE={
          'fetch_and_save': {
             'task': 'path.to.your.fetching_script',
             'schedule': crontab(minute='*/15'),
          }
      }
  )
</code>```

This will execute your task every 15 minutes for example, you will need to tweak the time based on your needs or how long the script will run. Another way to achieve this is making a standalone script that will do the job (using the DB wrapper for example) and put the script into the crontab assuming you're runnin a Linux distro on the server side

Body:
You can indeed use celery for this job and you can take full advantage of the ORM without any need to query your db manually. Make a task that will fetch the items from the internet and updates the DB. Define a celery task that will do what you want (fetching + saving)

 @app.task
 def fetching_script():
     response = requests.get(url)
     for item in response.content:
         instance = ModelInstance(**item)
         instance.full_clean()
         instance.save()

then in your celery config

  app.conf.update(
      CELERYBEAT_SCHEDULE={
          'fetch_and_save': {
             'task': 'path.to.your.fetching_script',
             'schedule': crontab(minute='*/15'),
          }
      }
  )

This will execute your task every 15 minutes for example, you will need to tweak the time based on your needs or how long the script will run. Another way to achieve this is making a standalone script that will do the job (using the DB wrapper for example) and put the script into the crontab assuming you're runnin a Linux distro on the server side


问:
ZF2 multi-select form preselect values ManyToMany
I can't get to preselect values in a multiselect form element representing a many to many relation.

In my model $admin I have the proper data : an ArrayCollection containing the correct CampsTypes but in the form I can't get the multiselect to preselect the proper options.

Admins model

```<code>/**
 * @var ArrayCollection CampsTypes $campstypes
 *
 * @ORM\ManyToMany(targetEntity="CampsTypes", inversedBy="admins", cascade={"persist"})
 * @ORM\JoinTable(name="campstypes_admins",
 *      joinColumns={@ORM\JoinColumn(name="admins_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="campstypes_id", referencedColumnName="id")}
 *      )
 */
private $campstypes;
</code>```

CampsType model

```<code>/**
 * @var ArrayCollection Admins $admins
 *
 * @ORM\ManyToMany(targetEntity="Admins", mappedBy="campstypes", cascade={"persist"})
 */
private $admins;
</code>```

Then I define my form select element as follow

```<code>        [
            'type' => 'DoctrineModule\Form\Element\ObjectSelect',
            'name' => 'campTypes',
            'required' => false,
            'options' => [
                'object_manager' => $this->getServiceLocator()->get(EntityManager::class),
                'target_class'   => CampsTypes::class,
                'property'       => 'title',
                'label'          => 'Type de camps autorisés',
                'instructions'   => 'Ne rien sélectionner si edition d\'un super admin',

            ],
            'attributes' => [
                'class'    => '',
                'multiple' => 'multiple',
            ]
        ],
</code>```

And finally here is my action to receive the form

```<code>protected function saveAdmin(Admins &$admin, &$form, &$msg)
{
    $em = $this->getEntityManager();
    /** @var CampTypesService $serviceCampTypes */
    $serviceCampTypes = $this->getServiceLocator()->get(CampTypesService::class);

    $form->bind($admin);

    if ($this->getRequest()->isPost()) {
        $data = $this->getRequest()->getPost();
        if (empty($data['password'])) {
            $form->remove('password');
        }
        $form->setData($data);
        if ($form->isValid()) {
            if (isset($data['campTypes'])) {
                $ids = $form->get('campTypes')->getValue();
                $campsTypes = new ArrayCollection($serviceCampTypes->getCampTypesByIds(array_values($ids)));
                foreach ($campsTypes as &$campsType) {
                    /** @var CampsTypes $campsType*/
                    $campsType->addAdmin($admin);
                }
                $admin->setCampTypes($campsTypes);
            }
            $em->persist($admin);
            $em->flush();
            $msg = 'Sauvegarde des données effectuée';
            return;
        }
    }

    return;
}
</code>```

I'm getting out of solution to try.

Any idea what I am doing wrong ?

答:
So I made it work !

basically my main problem is that I was not using proper Doctrine naming convention for the fields name of the form.

So I had to reverse engineer my DB into doctrine entities to compare with what I had done to understand where it was not working.
And also to set the model in both end (admins in camptype and camptypse in admin) for the whole shabang to work.

Here are the working classes :

Admin form:

```<code>[
    'type' => ObjectSelect::class,
    'name' => 'campstypes',
    'required' => false,
    'options' => [
        'object_manager' => $this->getServiceLocator()->get(EntityManager::class),
        'target_class'   => CampsTypes::class,
        'property'       => 'title',
        'label'          => 'Type de camps autorisés',
        'instructions'   => 'Ne rien sélectionner si edition d\'un super admin',

    ],
    'attributes' => [
        'class'    => '',
        'multiple' => 'multiple',
    ]
],
</code>```

Admin Controller:

```<code>protected function saveAdmin(Admins &$admin, &$form, &$msg)
{
    $em = $this->getEntityManager();
    /** @var CampTypesService $serviceCampTypes */
    $serviceCampTypes = $this->getServiceLocator()->get(CampTypesService::class);

    $form->bind($admin);

    if ($this->getRequest()->isPost()) {
        $data = $this->getRequest()->getPost();
        if (empty($data['password'])) {
            $form->remove('password');
        }
        $form->setData($data);
        if ($form->isValid()) {
            if (isset($data['campstypes'])) {
                $ids = $form->get('campstypes')->getValue();
                $campsTypes = new ArrayCollection($serviceCampTypes->getCampTypesByIds(array_values($ids)));
                foreach ($campsTypes as &$campsType) {
                    /** @var CampsTypes $campsType*/
                    $campsType->addAdmin($admin);
                }
                $admin->setCampstypes($campsTypes);
            }
            $em->persist($admin);
            $em->flush();
            $msg = 'Sauvegarde des données effectuée';
            return;
        }
    }

    return;
}
</code>```

So by renaming properly the fields of my form and models and setting the data in both end model of the relation I got it to work.

Body:
I can't get to preselect values in a multiselect form element representing a many to many relation.

In my model $admin I have the proper data : an ArrayCollection containing the correct CampsTypes but in the form I can't get the multiselect to preselect the proper options.

Admins model

/**
 * @var ArrayCollection CampsTypes $campstypes
 *
 * @ORM\ManyToMany(targetEntity="CampsTypes", inversedBy="admins", cascade={"persist"})
 * @ORM\JoinTable(name="campstypes_admins",
 *      joinColumns={@ORM\JoinColumn(name="admins_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="campstypes_id", referencedColumnName="id")}
 *      )
 */
private $campstypes;

CampsType model

/**
 * @var ArrayCollection Admins $admins
 *
 * @ORM\ManyToMany(targetEntity="Admins", mappedBy="campstypes", cascade={"persist"})
 */
private $admins;

Then I define my form select element as follow

        [
            'type' => 'DoctrineModule\Form\Element\ObjectSelect',
            'name' => 'campTypes',
            'required' => false,
            'options' => [
                'object_manager' => $this->getServiceLocator()->get(EntityManager::class),
                'target_class'   => CampsTypes::class,
                'property'       => 'title',
                'label'          => 'Type de camps autorisés',
                'instructions'   => 'Ne rien sélectionner si edition d\'un super admin',

            ],
            'attributes' => [
                'class'    => '',
                'multiple' => 'multiple',
            ]
        ],

And finally here is my action to receive the form

protected function saveAdmin(Admins &$admin, &$form, &$msg)
{
    $em = $this->getEntityManager();
    /** @var CampTypesService $serviceCampTypes */
    $serviceCampTypes = $this->getServiceLocator()->get(CampTypesService::class);

    $form->bind($admin);

    if ($this->getRequest()->isPost()) {
        $data = $this->getRequest()->getPost();
        if (empty($data['password'])) {
            $form->remove('password');
        }
        $form->setData($data);
        if ($form->isValid()) {
            if (isset($data['campTypes'])) {
                $ids = $form->get('campTypes')->getValue();
                $campsTypes = new ArrayCollection($serviceCampTypes->getCampTypesByIds(array_values($ids)));
                foreach ($campsTypes as &$campsType) {
                    /** @var CampsTypes $campsType*/
                    $campsType->addAdmin($admin);
                }
                $admin->setCampTypes($campsTypes);
            }
            $em->persist($admin);
            $em->flush();
            $msg = 'Sauvegarde des données effectuée';
            return;
        }
    }

    return;
}

I'm getting out of solution to try.

Any idea what I am doing wrong ?

Body:
So I made it work !

basically my main problem is that I was not using proper Doctrine naming convention for the fields name of the form.

So I had to reverse engineer my DB into doctrine entities to compare with what I had done to understand where it was not working.
And also to set the model in both end (admins in camptype and camptypse in admin) for the whole shabang to work.

Here are the working classes :

Admin form:

[
    'type' => ObjectSelect::class,
    'name' => 'campstypes',
    'required' => false,
    'options' => [
        'object_manager' => $this->getServiceLocator()->get(EntityManager::class),
        'target_class'   => CampsTypes::class,
        'property'       => 'title',
        'label'          => 'Type de camps autorisés',
        'instructions'   => 'Ne rien sélectionner si edition d\'un super admin',

    ],
    'attributes' => [
        'class'    => '',
        'multiple' => 'multiple',
    ]
],

Admin Controller:

protected function saveAdmin(Admins &$admin, &$form, &$msg)
{
    $em = $this->getEntityManager();
    /** @var CampTypesService $serviceCampTypes */
    $serviceCampTypes = $this->getServiceLocator()->get(CampTypesService::class);

    $form->bind($admin);

    if ($this->getRequest()->isPost()) {
        $data = $this->getRequest()->getPost();
        if (empty($data['password'])) {
            $form->remove('password');
        }
        $form->setData($data);
        if ($form->isValid()) {
            if (isset($data['campstypes'])) {
                $ids = $form->get('campstypes')->getValue();
                $campsTypes = new ArrayCollection($serviceCampTypes->getCampTypesByIds(array_values($ids)));
                foreach ($campsTypes as &$campsType) {
                    /** @var CampsTypes $campsType*/
                    $campsType->addAdmin($admin);
                }
                $admin->setCampstypes($campsTypes);
            }
            $em->persist($admin);
            $em->flush();
            $msg = 'Sauvegarde des données effectuée';
            return;
        }
    }

    return;
}

So by renaming properly the fields of my form and models and setting the data in both end model of the relation I got it to work.


问:
Issue when creating a stored procedure
I'm trying to create a stored procedure as follows:

```<code>CREATE OR REPLACE PROCEDURE storedprocedure(emp number) AS
BEGIN
  DECLARE
    -- create the cursor based on a query
    cursor emp_cursor is
      select e.employeeid, firstname, lastname, e.departmentid, e.title,
        salary, d.departmentname, billrate
      from employees e
      full join departments d on e.departmentID = d.departmentID
      full join employeeproject p on e.employeeID = p.employeeID where e.employeeID = emp;

    BEGIN
      open emp_cursor;
      -- first display information about the employee
      dbms_output.put_line('- -');
      dbms_output.put_line('- -');
      dbms_output.put_line('Employee#' || e.employeeid
        || '  Name:' || TRIM(e.firstname) || ' ' || TRIM(e.lastname)
        || ' Dept: ');
      dbms_output.put_line('_________________________________________________________');
      dbms_output.put_line('- -');
      dbms_output.put_line('- -    Title: ' || e.title
        || ' Salary: ' || to_char(e.salary,'$999,999,999.99'));
      dbms_output.put_line('- -    Billing Rate: ' || to_char(billrate,'$999,999.99'));
     -- next call the stored procedure to show department information
  END;
END;
/
</code>```

But it compiles with errors. When I show errors it tells me e.employeeID, e.title, and billrate must all be declared, but they are the original query. What am I doing wrong here? Am I misunderstand what it means to have them declared?

These are all columns that exist within the tables being queried and running the query as SQL gets results.

答:
You are opening the cursor, but you are not fetching it into anything - either a series of scalar variables or a record type - which would normally be done in a loop. Then when you are in the loop you refer to the variables/record, not the table used in the cursor query - that is out of scope outside the cursor declaration.

There's a slightly simpler implicit cursor loop that you might find a bit easier in this case:

```<code>CREATE OR REPLACE PROCEDURE storedprocedure(emp number) AS
BEGIN
  FOR rec IN (
    select e.employeeid, firstname, lastname, e.departmentid, e.title,
      salary, d.departmentname, billrate
    from employees e
    full join departments d on e.departmentID = d.departmentID
    full join employeeproject p on e.employeeID = p.employeeID where e.employeeID = emp
  )
  LOOP
    -- first display information about the employee
    dbms_output.put_line('- -');
    dbms_output.put_line('- -');
    dbms_output.put_line('Employee#' || rec.employeeid
      || '  Name:' || TRIM(rec.firstname) || ' ' || TRIM(rec.lastname)
      || ' Dept: ');
    dbms_output.put_line('_________________________________________________________');
    dbms_output.put_line('- -');
    dbms_output.put_line('- -    Title: ' || rec.title
      || ' Salary: ' || to_char(rec.salary,'$999,999,999.99'));
    dbms_output.put_line('- -    Billing Rate: ' || to_char(rec.billrate,'$999,999.99'));
    -- next call the stored procedure to show department information
  END LOOP;
END;
/
</code>```

Notice that all the references to columns inside the loop are of the form rec.<field> - they are taken from the record for this time round the loop, not directly from the underlying tables.

You also had a nested block which isn't doing any harm but isn't useful, so I took that out.

If you particularly wanted to use the explicit open-fetch-close cursor handling it would look something like this:

```<code>CREATE OR REPLACE PROCEDURE storedprocedure(emp number) AS
  -- create the cursor based on a query
  cursor emp_cursor is
    select e.employeeid, firstname, lastname, e.departmentid, e.title,
      salary, d.departmentname, billrate
    from employees e
    full join departments d on e.departmentID = d.departmentID
    full join employeeproject p on e.employeeID = p.employeeID where e.employeeID = emp;

   -- record variable based on cursor definition
   rec emp_cursor%ROWTYPE;

BEGIN
  OPEN emp_cursor;
  LOOP
    -- fetch the next row result from the cursor into the record vairable
    FETCH emp_cursor INTO rec;
    -- break out of the loop if there are no more results to fetch
    EXIT WHEN emp_cursor%NOTFOUND;

    -- first display information about the employee
    dbms_output.put_line('- -');
    dbms_output.put_line('- -');
    dbms_output.put_line('Employee#' || rec.employeeid
      || '  Name:' || TRIM(rec.firstname) || ' ' || TRIM(rec.lastname)
      || ' Dept: ');
    dbms_output.put_line('_________________________________________________________');
    dbms_output.put_line('- -');
    dbms_output.put_line('- -    Title: ' || rec.title
      || ' Salary: ' || to_char(rec.salary,'$999,999,999.99'));
    dbms_output.put_line('- -    Billing Rate: ' || to_char(rec.billrate,'$999,999.99'));
    -- next call the stored procedure to show department information
  END LOOP;
  CLOSE emp_cursor;
END;
/
</code>```

Title: Issue when creating a stored procedure

Body:
I'm trying to create a stored procedure as follows:

CREATE OR REPLACE PROCEDURE storedprocedure(emp number) AS
BEGIN
  DECLARE
    -- create the cursor based on a query
    cursor emp_cursor is
      select e.employeeid, firstname, lastname, e.departmentid, e.title,
        salary, d.departmentname, billrate
      from employees e
      full join departments d on e.departmentID = d.departmentID
      full join employeeproject p on e.employeeID = p.employeeID where e.employeeID = emp;

    BEGIN
      open emp_cursor;
      -- first display information about the employee
      dbms_output.put_line('- -');
      dbms_output.put_line('- -');
      dbms_output.put_line('Employee#' || e.employeeid
        || '  Name:' || TRIM(e.firstname) || ' ' || TRIM(e.lastname)
        || ' Dept: ');
      dbms_output.put_line('_________________________________________________________');
      dbms_output.put_line('- -');
      dbms_output.put_line('- -    Title: ' || e.title
        || ' Salary: ' || to_char(e.salary,'$999,999,999.99'));
      dbms_output.put_line('- -    Billing Rate: ' || to_char(billrate,'$999,999.99'));
     -- next call the stored procedure to show department information
  END;
END;
/

But it compiles with errors. When I show errors it tells me e.employeeID, e.title, and billrate must all be declared, but they are the original query. What am I doing wrong here? Am I misunderstand what it means to have them declared?

These are all columns that exist within the tables being queried and running the query as SQL gets results.

Body:
You are opening the cursor, but you are not fetching it into anything - either a series of scalar variables or a record type - which would normally be done in a loop. Then when you are in the loop you refer to the variables/record, not the table used in the cursor query - that is out of scope outside the cursor declaration.

There's a slightly simpler implicit cursor loop that you might find a bit easier in this case:

CREATE OR REPLACE PROCEDURE storedprocedure(emp number) AS
BEGIN
  FOR rec IN (
    select e.employeeid, firstname, lastname, e.departmentid, e.title,
      salary, d.departmentname, billrate
    from employees e
    full join departments d on e.departmentID = d.departmentID
    full join employeeproject p on e.employeeID = p.employeeID where e.employeeID = emp
  )
  LOOP
    -- first display information about the employee
    dbms_output.put_line('- -');
    dbms_output.put_line('- -');
    dbms_output.put_line('Employee#' || rec.employeeid
      || '  Name:' || TRIM(rec.firstname) || ' ' || TRIM(rec.lastname)
      || ' Dept: ');
    dbms_output.put_line('_________________________________________________________');
    dbms_output.put_line('- -');
    dbms_output.put_line('- -    Title: ' || rec.title
      || ' Salary: ' || to_char(rec.salary,'$999,999,999.99'));
    dbms_output.put_line('- -    Billing Rate: ' || to_char(rec.billrate,'$999,999.99'));
    -- next call the stored procedure to show department information
  END LOOP;
END;
/

Notice that all the references to columns inside the loop are of the form rec.<field> - they are taken from the record for this time round the loop, not directly from the underlying tables.

You also had a nested block which isn't doing any harm but isn't useful, so I took that out.

If you particularly wanted to use the explicit open-fetch-close cursor handling it would look something like this:

CREATE OR REPLACE PROCEDURE storedprocedure(emp number) AS
  -- create the cursor based on a query
  cursor emp_cursor is
    select e.employeeid, firstname, lastname, e.departmentid, e.title,
      salary, d.departmentname, billrate
    from employees e
    full join departments d on e.departmentID = d.departmentID
    full join employeeproject p on e.employeeID = p.employeeID where e.employeeID = emp;

   -- record variable based on cursor definition
   rec emp_cursor%ROWTYPE;

BEGIN
  OPEN emp_cursor;
  LOOP
    -- fetch the next row result from the cursor into the record vairable
    FETCH emp_cursor INTO rec;
    -- break out of the loop if there are no more results to fetch
    EXIT WHEN emp_cursor%NOTFOUND;

    -- first display information about the employee
    dbms_output.put_line('- -');
    dbms_output.put_line('- -');
    dbms_output.put_line('Employee#' || rec.employeeid
      || '  Name:' || TRIM(rec.firstname) || ' ' || TRIM(rec.lastname)
      || ' Dept: ');
    dbms_output.put_line('_________________________________________________________');
    dbms_output.put_line('- -');
    dbms_output.put_line('- -    Title: ' || rec.title
      || ' Salary: ' || to_char(rec.salary,'$999,999,999.99'));
    dbms_output.put_line('- -    Billing Rate: ' || to_char(rec.billrate,'$999,999.99'));
    -- next call the stored procedure to show department information
  END LOOP;
  CLOSE emp_cursor;
END;
/


问:
How to re-render part of the component upon state change?
I have a component the includes progress.circle from the library react-native-progress (see link: https://github.com/oblador/react-native-progress).

Initially I set the progress prop of the progress circle to a state variable that is set to 0 at idle state as shown in the code below:

```<code><Progress.Circle
        showsText={true}
        progress={this.state.progress} // this.state.progress = 0
        size={width * 0.1388888888888}
        color={"#EF5D6C"}
/>
</code>```

Number of user interactions take place to set the state variable (this.state.progress) to a certain percentage then the component re-render to show the progress animation as intended.

Problem is the component flashes for part of a second as result of the re-rendering process.
So is there a way to only re-render the progress circle and leave the rest of the component in its current rendering form.

答: Make the progress.circle view as a separate component, as suggested in the previous answer. Keep the progress value in global state, which can be accessed by this separate component. If you are using Redux, you can do this easily. Then pass that state.progress value in the progress prop of the Progress.Circle</p>

Body:
I have a component the includes progress.circle from the library react-native-progress (see link: https://github.com/oblador/react-native-progress).

Initially I set the progress prop of the progress circle to a state variable that is set to 0 at idle state as shown in the code below:

<Progress.Circle
        showsText={true}
        progress={this.state.progress} // this.state.progress = 0
        size={width * 0.1388888888888}
        color={"#EF5D6C"}
/>

Number of user interactions take place to set the state variable (this.state.progress) to a certain percentage then the component re-render to show the progress animation as intended.

Problem is the component flashes for part of a second as result of the re-rendering process.
So is there a way to only re-render the progress circle and leave the rest of the component in its current rendering form.


问:
Import error pycrypto google app engine
I'm running a local server in Python with GAE, and importing a 3rd party library, which in turn imports pycrypto. I installed it locally using pip and included it in my app.yaml file, but when I run the server, I get the following error:

ImportError: cannot import name OSRNG

Here's what my app.yaml looks like:

```<code>runtime: python27
threadsafe: 1

handlers:
- url: /.*
  script: main.app

libraries:
- name: pycrypto
  version: "latest"
</code>```

I'm running homebrew python 2.7.

答: Official documentation seems to suggest that api_version in app.yaml is required.

Title: Import error pycrypto google app engine

Body:
I'm running a local server in Python with GAE, and importing a 3rd party library, which in turn imports pycrypto. I installed it locally using pip and included it in my app.yaml file, but when I run the server, I get the following error:

ImportError: cannot import name OSRNG

Here's what my app.yaml looks like:

runtime: python27
threadsafe: 1

handlers:
- url: /.*
  script: main.app

libraries:
- name: pycrypto
  version: "latest"

I'm running homebrew python 2.7.


问:
Possible with multiple database connections
New to the tSQLt world (great tool set) and encountered a minor issue with a stored procedure I am setting up a test for.

If I for some reason have a stored procedure which connects to mutiple databases or even multiple SQL servers (Linked Servers).

Is it possible to do unit tests with tSQLt in such a scenario?

答:
I commented already, but I would like to add some more. So as I said already, that you can do anything that fits into the single transaction.

But for your case I would suggest to create synonyms for every cross database/instance object and then use synonyms everywhere.

I've created following function to mock view/tables synonyms. It has some limitations but at least it can handle simple use cases.

```<code>CREATE PROCEDURE [tSQLt].[FakeSynonymTable] @SynonymTable VARCHAR(MAX)
AS
     BEGIN

         DECLARE @NewName VARCHAR(MAX)= @SynonymTable+REPLACE(CAST(NEWID() AS VARCHAR(100)), '-', '');
         DECLARE @RenameCmd VARCHAR(MAX)= 'EXEC sp_rename '''+@SynonymTable+''', '''+@NewName+''';';

        EXEC tSQLt.SuppressOutput
              @RenameCmd;

        DECLARE @sql VARCHAR(MAX)= 'SELECT * INTO '+@SynonymTable+' FROM '+@NewName+' WHERE 1=2;';

        EXEC (@sql);

        EXEC tSQLt.FakeTable
              @TableName = @SynonymTable;
     END;
</code>```

Body:
I commented already, but I would like to add some more. So as I said already, that you can do anything that fits into the single transaction.

But for your case I would suggest to create synonyms for every cross database/instance object and then use synonyms everywhere.

I've created following function to mock view/tables synonyms. It has some limitations but at least it can handle simple use cases.

CREATE PROCEDURE [tSQLt].[FakeSynonymTable] @SynonymTable VARCHAR(MAX)
AS
     BEGIN

         DECLARE @NewName VARCHAR(MAX)= @SynonymTable+REPLACE(CAST(NEWID() AS VARCHAR(100)), '-', '');
         DECLARE @RenameCmd VARCHAR(MAX)= 'EXEC sp_rename '''+@SynonymTable+''', '''+@NewName+''';';

        EXEC tSQLt.SuppressOutput
              @RenameCmd;

        DECLARE @sql VARCHAR(MAX)= 'SELECT * INTO '+@SynonymTable+' FROM '+@NewName+' WHERE 1=2;';

        EXEC (@sql);

        EXEC tSQLt.FakeTable
              @TableName = @SynonymTable;
     END;


问:
How fix Error:java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:
I have a project in Eclipse and I export to gradle project and open in Android Studio when I sync project I get
Error:java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:
Error:Execution failed for task ':app:mergeDebugResources'.

Error: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:

This is my build.gradle :

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.smok.maps"
        minSdkVersion 8
        targetSdkVersion 19
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:19.1.0'
    compile 'joda-time:joda-time:2.3'
    compile files('libs/ksoap2-android-assembly-3.6.0-jar-with-dependencies.jar')
    compile files('libs/osmbonuspack_v4.9.jar')
    compile files('libs/osmdroid-android-4.2-javadoc.jar')
    compile files('libs/osmdroid-android-4.2.jar')
    compile files('libs/slf4j-android-1.5.8.jar')
}
</code>```

答:
most of the time is a corrupt PNG image added recently to the project which cause this error.
Check the git log and replace the file.

Sometimes menu : File > InvalidateCaches/Restart also helps

Body:
I have a project in Eclipse and I export to gradle project and open in Android Studio when I sync project I get
Error:java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:
Error:Execution failed for task ':app:mergeDebugResources'.

Error: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:

This is my build.gradle :

apply plugin: 'com.android.application'

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.smok.maps"
        minSdkVersion 8
        targetSdkVersion 19
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:19.1.0'
    compile 'joda-time:joda-time:2.3'
    compile files('libs/ksoap2-android-assembly-3.6.0-jar-with-dependencies.jar')
    compile files('libs/osmbonuspack_v4.9.jar')
    compile files('libs/osmdroid-android-4.2-javadoc.jar')
    compile files('libs/osmdroid-android-4.2.jar')
    compile files('libs/slf4j-android-1.5.8.jar')
}


问:
What are the common defenses against XSS?
In other words, what are the most-used techniques to sanitize input and/or output nowadays? What do people in industrial (or even just personal-use) websites use to combat the problem?</p>

答:
You should refer to the excellent OWASP website for a summary of attacks (including XSS) and defenses against them. Here's the simplest explanation I could come up with, which might actually be more readable than their web page (but probably nowhere nearly as complete).

Specifying a charset. First of all, ensure that your web page specifies the UTF-8 charset in the headers or in the very beginning of the head element HTML encode all inputs to prevent a UTF-7 attack in Internet Explorer (and older versions of Firefox) despite other efforts to prevent XSS.

HTML escaping. Keep in mind that you need to HTML-escape all user input. This includes replacing < with <, > with >, & with & and " with ". If you will ever use single-quoted HTML attributes, you need to replace ' with ' as well. Typical server-side scripting languages such as PHP provide functions to do this, and I encourage you to expand on these by creating standard functions to insert HTML elements rather than inserting them in an ad-hoc manner.

Other types of escaping. You still, however, need to be careful to never insert user input as an unquoted attribute or an attribute interpreted as JavaScript (e.g. onload or onmouseover). Obviously, this also applies to script elements unless the input is properly JavaScript-escaped, which is different from HTML escaping. Another special type of escaping is URL escaping for URL parameters (do it before the HTML escaping to properly include a parameter in a link).

Validating URLs and CSS values. The same goes for URLs of links and images (without validating based on approved prefixes) because of the javascript: URL scheme, and also CSS stylesheet URLs and data within style attributes. (Internet Explorer allows inserting JavaScript expressions as CSS values, and Firefox is similarly problematic with its XBL support.) If you must include a CSS value from an untrusted source, you should safely and strictly validate or CSS escape it.

Not allowing user-provided HTML. Do not allow user-provided HTML if you have the option. That is an easy way to end up with an XSS problem, and so is writing a "parser" for your own markup language based on simple regex substitutions. I would only allow formatted text if the HTML output were generated in an obviously safe manner by a real parser that escapes any text from the input using the standard escaping functions and individually builds the HTML elements. If you have no choice over the matter, use a validator/sanitizer such as AntiSamy.

Preventing DOM-based XSS. Do not include user input in JavaScript-generated HTML code and insert it into the document. Instead, use the proper DOM methods to ensure that it is processed as text, not HTML.

Obviously, I cannot cover every single case in which an attacker can insert JavaScript code. In general, HTTP-only cookies can be used to possibly make an XSS attack a bit harder (but by no means prevent one), and giving programmers security training is essential.

Body:
You should refer to the excellent OWASP website for a summary of attacks (including XSS) and defenses against them. Here's the simplest explanation I could come up with, which might actually be more readable than their web page (but probably nowhere nearly as complete).

Specifying a charset. First of all, ensure that your web page specifies the UTF-8 charset in the headers or in the very beginning of the head element HTML encode all inputs to prevent a UTF-7 attack in Internet Explorer (and older versions of Firefox) despite other efforts to prevent XSS.

HTML escaping. Keep in mind that you need to HTML-escape all user input. This includes replacing < with &lt;, > with &gt;, & with &amp; and " with &quot;. If you will ever use single-quoted HTML attributes, you need to replace ' with &#39; as well. Typical server-side scripting languages such as PHP provide functions to do this, and I encourage you to expand on these by creating standard functions to insert HTML elements rather than inserting them in an ad-hoc manner.

Other types of escaping. You still, however, need to be careful to never insert user input as an unquoted attribute or an attribute interpreted as JavaScript (e.g. onload or onmouseover). Obviously, this also applies to script elements unless the input is properly JavaScript-escaped, which is different from HTML escaping. Another special type of escaping is URL escaping for URL parameters (do it before the HTML escaping to properly include a parameter in a link).

Validating URLs and CSS values. The same goes for URLs of links and images (without validating based on approved prefixes) because of the javascript: URL scheme, and also CSS stylesheet URLs and data within style attributes. (Internet Explorer allows inserting JavaScript expressions as CSS values, and Firefox is similarly problematic with its XBL support.) If you must include a CSS value from an untrusted source, you should safely and strictly validate or CSS escape it.

Not allowing user-provided HTML. Do not allow user-provided HTML if you have the option. That is an easy way to end up with an XSS problem, and so is writing a "parser" for your own markup language based on simple regex substitutions. I would only allow formatted text if the HTML output were generated in an obviously safe manner by a real parser that escapes any text from the input using the standard escaping functions and individually builds the HTML elements. If you have no choice over the matter, use a validator/sanitizer such as AntiSamy.

Preventing DOM-based XSS. Do not include user input in JavaScript-generated HTML code and insert it into the document. Instead, use the proper DOM methods to ensure that it is processed as text, not HTML.

Obviously, I cannot cover every single case in which an attacker can insert JavaScript code. In general, HTTP-only cookies can be used to possibly make an XSS attack a bit harder (but by no means prevent one), and giving programmers security training is essential.


问:
C# console app closes itself after I run it
When I run this simple application it closes itself without reason. How to prevent that?

Code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            int b = 20;
            int c = a * b;

            Console.WriteLine(c);
        }
    }
}
</code>```

答:
Just add Console.ReadKey(); after printing the value.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            int b = 20;
            int c = a * b;

            Console.WriteLine(c);
            Console.ReadKey();
        }
    }
}
</code>```

Body:
When I run this simple application it closes itself without reason. How to prevent that?

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            int b = 20;
            int c = a * b;

            Console.WriteLine(c);
        }
    }
}

Body:
Just add Console.ReadKey(); after printing the value.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            int b = 20;
            int c = a * b;

            Console.WriteLine(c);
            Console.ReadKey();
        }
    }
}