问:
Swig: syntax error when wrapping global static constants
When I try to wrap the following code:

```<code>enum VehicleSide {
    LEFT = 0,  ///< left side of vehicle is always 0
    RIGHT = 1  ///< right side of vehicle is always 1
};

/// Class to encode the ID of a vehicle wheel.
/// By convention, wheels are counted front to rear and left to right. In other
/// words, for a vehicle with 2 axles, the order is: front-left, front-right,
/// rear-left, rear-right.
class WheelID {
  public:
    WheelID(int id) : m_id(id), m_axle(id / 2), m_side(VehicleSide(id % 2)) {}
    WheelID(int axle, VehicleSide side) : m_id(2 * axle + side), m_axle(axle), m_side(side) {}

    /// Return the wheel ID.
    int id() const { return m_id; }

    /// Return the axle index for this wheel ID.
    /// Axles are counted from the front of the vehicle.
    int axle() const { return m_axle; }

    /// Return the side for this wheel ID.
    /// By convention, left is 0 and right is 1.
    VehicleSide side() const { return m_side; }

  private:
    int m_id;            ///< wheel ID
    int m_axle;          ///< axle index (counted from the front)
    VehicleSide m_side;  ///< vehicle side (LEFT: 0, RIGHT: 1)
};

/// Global constant wheel IDs for the common topology of a 2-axle vehicle.
static const WheelID FRONT_LEFT(0, LEFT);
static const WheelID FRONT_RIGHT(0, RIGHT);
static const WheelID REAR_LEFT(1, LEFT);
static const WheelID REAR_RIGHT(1, RIGHT);
</code>```

I get "syntax error in input" at static const WheelID FRONT_LEFT(0, LEFT);.
On the interface file I'm just using %include on the corresponding header.
I have no clue of what is causing the error, so any help is appreciated, but I would prefer not to edit the header.
Thanks

EDIT:
removing the static keyword won't help

答:
Showing your SWIG .i file would help, but the cause is likely that you've put instances of your class in the header file.  I see that you don't want to edit the header, but the .h file should extern the class instances and the definition should be in the .cpp file; otherwise, you'll have multiple separate instances of your global variables if the file is included in two different .cpp files.  Also, SWIG doesn't understand it as is so you've really no choice...

Working example:

test.h

```<code>enum VehicleSide {
    LEFT = 0,  ///< left side of vehicle is always 0
    RIGHT = 1  ///< right side of vehicle is always 1
};

/// Class to encode the ID of a vehicle wheel.
/// By convention, wheels are counted front to rear and left to right. In other
/// words, for a vehicle with 2 axles, the order is: front-left, front-right,
/// rear-left, rear-right.
class WheelID {
  public:
    WheelID(int id) : m_id(id), m_axle(id / 2), m_side(VehicleSide(id % 2)) {}
    WheelID(int axle, VehicleSide side) : m_id(2 * axle + side), m_axle(axle), m_side(side) {}

    /// Return the wheel ID.
    int id() const { return m_id; }

    /// Return the axle index for this wheel ID.
    /// Axles are counted from the front of the vehicle.
    int axle() const { return m_axle; }

    /// Return the side for this wheel ID.
    /// By convention, left is 0 and right is 1.
    VehicleSide side() const { return m_side; }

  private:
    int m_id;            ///< wheel ID
    int m_axle;          ///< axle index (counted from the front)
    VehicleSide m_side;  ///< vehicle side (LEFT: 0, RIGHT: 1)
};

// Instances of these global variables must be outside the header.
// What if the header was included in two files?
extern const WheelID FRONT_LEFT;
extern const WheelID FRONT_RIGHT;
extern const WheelID REAR_LEFT;
extern const WheelID REAR_RIGHT;
</code>```

test.i

```<code>%module test

%{ // Section included verbatim in the generated wrapper source.

#include "test.h"

// One-time instances of the class.  In this case, directly
// added to the wrapper, but it could be in a separate .cpp file
// or .lib and linked to the final extension.
const WheelID FRONT_LEFT(0, LEFT);
const WheelID FRONT_RIGHT(0, RIGHT);
const WheelID REAR_LEFT(1, LEFT);
const WheelID REAR_RIGHT(1, RIGHT);

%}

// Generate wrappers for test.h contents
%include "test.h"
</code>```

Demo:

```<code>>>> import test
>>> test.REAR_RIGHT.id()
3
</code>```

Body:
When I try to wrap the following code:

enum VehicleSide {
    LEFT = 0,  ///< left side of vehicle is always 0
    RIGHT = 1  ///< right side of vehicle is always 1
};

/// Class to encode the ID of a vehicle wheel.
/// By convention, wheels are counted front to rear and left to right. In other
/// words, for a vehicle with 2 axles, the order is: front-left, front-right,
/// rear-left, rear-right.
class WheelID {
  public:
    WheelID(int id) : m_id(id), m_axle(id / 2), m_side(VehicleSide(id % 2)) {}
    WheelID(int axle, VehicleSide side) : m_id(2 * axle + side), m_axle(axle), m_side(side) {}

    /// Return the wheel ID.
    int id() const { return m_id; }

    /// Return the axle index for this wheel ID.
    /// Axles are counted from the front of the vehicle.
    int axle() const { return m_axle; }

    /// Return the side for this wheel ID.
    /// By convention, left is 0 and right is 1.
    VehicleSide side() const { return m_side; }

  private:
    int m_id;            ///< wheel ID
    int m_axle;          ///< axle index (counted from the front)
    VehicleSide m_side;  ///< vehicle side (LEFT: 0, RIGHT: 1)
};

/// Global constant wheel IDs for the common topology of a 2-axle vehicle.
static const WheelID FRONT_LEFT(0, LEFT);
static const WheelID FRONT_RIGHT(0, RIGHT);
static const WheelID REAR_LEFT(1, LEFT);
static const WheelID REAR_RIGHT(1, RIGHT);

I get "syntax error in input" at static const WheelID FRONT_LEFT(0, LEFT);.
On the interface file I'm just using %include on the corresponding header.
I have no clue of what is causing the error, so any help is appreciated, but I would prefer not to edit the header.
Thanks

EDIT:
removing the static keyword won't help

Body:
Showing your SWIG .i file would help, but the cause is likely that you've put instances of your class in the header file.  I see that you don't want to edit the header, but the .h file should extern the class instances and the definition should be in the .cpp file; otherwise, you'll have multiple separate instances of your global variables if the file is included in two different .cpp files.  Also, SWIG doesn't understand it as is so you've really no choice...

Working example:

test.h

enum VehicleSide {
    LEFT = 0,  ///< left side of vehicle is always 0
    RIGHT = 1  ///< right side of vehicle is always 1
};

/// Class to encode the ID of a vehicle wheel.
/// By convention, wheels are counted front to rear and left to right. In other
/// words, for a vehicle with 2 axles, the order is: front-left, front-right,
/// rear-left, rear-right.
class WheelID {
  public:
    WheelID(int id) : m_id(id), m_axle(id / 2), m_side(VehicleSide(id % 2)) {}
    WheelID(int axle, VehicleSide side) : m_id(2 * axle + side), m_axle(axle), m_side(side) {}

    /// Return the wheel ID.
    int id() const { return m_id; }

    /// Return the axle index for this wheel ID.
    /// Axles are counted from the front of the vehicle.
    int axle() const { return m_axle; }

    /// Return the side for this wheel ID.
    /// By convention, left is 0 and right is 1.
    VehicleSide side() const { return m_side; }

  private:
    int m_id;            ///< wheel ID
    int m_axle;          ///< axle index (counted from the front)
    VehicleSide m_side;  ///< vehicle side (LEFT: 0, RIGHT: 1)
};

// Instances of these global variables must be outside the header.
// What if the header was included in two files?
extern const WheelID FRONT_LEFT;
extern const WheelID FRONT_RIGHT;
extern const WheelID REAR_LEFT;
extern const WheelID REAR_RIGHT;

test.i

%module test

%{ // Section included verbatim in the generated wrapper source.

#include "test.h"

// One-time instances of the class.  In this case, directly
// added to the wrapper, but it could be in a separate .cpp file
// or .lib and linked to the final extension.
const WheelID FRONT_LEFT(0, LEFT);
const WheelID FRONT_RIGHT(0, RIGHT);
const WheelID REAR_LEFT(1, LEFT);
const WheelID REAR_RIGHT(1, RIGHT);

%}

// Generate wrappers for test.h contents
%include "test.h"

Demo:

>>> import test
>>> test.REAR_RIGHT.id()
3


来源: stackexchange

问:
How do I clear this array each time the inner loop finishes?
I need some help with these async loops. Each object has a materials array inside. I need to clear objectRedirects each time the materials loop ends.

```<code>  objects.map(async object => {
      objectRedirects = [];

      await Promise.all(
        object.materials.map(async material => {
          const childObject = await ItemObject.findOne({
            name: object.name,
            material: material
          })
            .lean()
            .exec();

          objectRedirects.push(childObject);
        })
      );
    });
</code>```

Currently objectRedirects will never be cleared or reset back to an empty array it will continue adding the 'materials' of each 'object'

答:
You need two Promise.alls, one for each object in objects, and one for each item in an object's materials array. Then, the .map will create a new inner array on each iteration. (.map should not be used for side-effects - use it to create another array)

```<code>const arrayOfObjectMaterialsArray = await Promise.all(objects.map(object => Promise.all(
  object.materials.map(material => (
    ItemObject.findOne({
      name: object.name,
      material: material
    })
      .lean()
      .exec()
  ))
)));
</code>```

You may just return the Promise from each .map callback alone - no need for the inner functions to be async

ContentLicense: CC BY-SA 4.0

Body:
I need some help with these async loops. Each object has a materials array inside. I need to clear objectRedirects each time the materials loop ends.

  objects.map(async object => {
      objectRedirects = [];

      await Promise.all(
        object.materials.map(async material => {
          const childObject = await ItemObject.findOne({
            name: object.name,
            material: material
          })
            .lean()
            .exec();

          objectRedirects.push(childObject);
        })
      );
    });

Currently objectRedirects will never be cleared or reset back to an empty array it will continue adding the 'materials' of each 'object'

Body:
You need two Promise.alls, one for each object in objects, and one for each item in an object's materials array. Then, the .map will create a new inner array on each iteration. (.map should not be used for side-effects - use it to create another array)

const arrayOfObjectMaterialsArray = await Promise.all(objects.map(object => Promise.all(
  object.materials.map(material => (
    ItemObject.findOne({
      name: object.name,
      material: material
    })
      .lean()
      .exec()
  ))
)));

You may just return the Promise from each .map callback alone - no need for the inner functions to be async


问:
Magento 2 AMP page: Custom JavaScript is not allowed
```<code><script async src="https://cdn.ampproject.org/v0/amp-lightbox-0.1.js"></script>
</code>```

I am using this tag in magento2 layout default.xml file and using <amp-lightbox>. But in google search console getting the error

Custom JavaScript is not allowed.

答:
It seems you're missing the custom-element attribute on your
```

Body:
It seems you're missing the custom-element attribute on your <script>.

Try using this:

<script async custom-element="amp-lightbox" src="https://cdn.ampproject.org/v0/amp-lightbox-0.1.js"></script>


问:
ServiceStack: Adding Blazor support?
I have tried adding ServiceStack-references to a client-side Blazor project, but I run into problems after adding ServiceStack.HttpClient via NuGet.

Currently, VS2019 will tell me that:

Cannot find declaration of exported type 'System.Threading'

and when ask/look around, they say that:

Blazor is built using mono-wasm as the base .NET framework
  implementation, and in this case I believe it's a missing method in
  mono-wasm that's the issue.

and

at present Mono WASM has no support for threading; check the repo
  https://github.com/lrz/mono-wasm-mono for more info

Am I getting it correctly:

ServiceStack requires System.Threading

WebAssembly and thus Blazor does not support references to System.Threading

Meaning that ServiceStack cannot be used in a Blazor app

答:
@Ted,

Blazor does not run in a multi-thread environment. Blazor (mono-wasm) runs in the same sandbox of JavaScript, in the same UI thread. No multi-threading, no concurrent or parallel programming. As I've said before, I've never heard of ServiceStack, but I guess that ServiceStack.HttpClient cannot be used in Blazor client side, as "Blazor HttpClient" is based on HttpMessageHandler, and it is adapted to work as an Ajax agent; that is, HttpClient communicate with the Back End via the JavaScript Fetch Web API, whereas ServiceStack, I believe, perform the traditional http client calls, employing Web Sockets, which is not supported in Blazor (mono-wasm). In Asp.Net Core 5.0 it is expected that Blazor client side would support Web Sockets, after mono would be replaced.

No, the ServiceStack cannot be used in a Blazor app

Hope this helps...

Title: ServiceStack: Adding Blazor support?


问:
How to re-connect to USB device without user gesture?
I am writing a web page that will perform software upgrade on custom USB device. Firstly a user performs user gesture to connect to the device and starts procedure. Then page is still open but the device resets itself. Is there a way to connect again to this device (which is already paired) without user gesture?</p>

答: As long as the device keeps the same vendor ID, product ID and serial number then the previously granted permission will still apply when the device resets. You can register a listener on navigator.usb for the connect event to be notified when the device reconnects. If those 3 identifiers change when the device resets then the browser can't tell the device is the same as the one the user granted the site permission to access previously.


问:
Convert query build to native SQL with union
I made two count queries with query build doctrine but after I found that there is several query count that repeats so I must work with UNION but there is no union in doctrine query build.

So the solution is the use of native SQL with UNION.

I do not know how to do the translation in native query

this is my request 1

/**
     * @param Analyse $analyse
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function countTotalErrorByIdAnalyse(Analyse $analyse)
    {
        return $this->createQueryBuilder('a')
                    ->select('count(a)')
                    ->innerJoin('a.analyse', 'analyse')
                    ->where('analyse.id = :analyse')
                    ->setParameter('analyse', $analyse->getId())
                    ->getQuery()
                    ->getSingleScalarResult();

    }```
</div>
</div>
</p>

<p>this is my request 2 </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> /**
     * @param Analyse $analyse
     * @param string $severity
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function countErrorsBySeverity(Analyse $analyse, string $severity){

      return   $this->createQueryBuilder('a')
                    ->select('count(a)')
                    ->innerJoin('a.analyse', 'analyse')
                    ->innerJoin('a.rule', 'rule')
                    ->where('rule.severity = :error')
                    ->setParameter('error', $severity)
                    ->getQuery()
                    ->getSingleScalarResult();

    }</code>```

答:
I would strongly suggest trying to work out your query in Doctrine but if native is the only way then it is the only way.

Native SQL in Symfony: Note I uses these in Symfony 3 but should work in Symfony 4. Once you get more use to Doctrine you will find it really does everything native can do and some items it does not do there are plugins available to expand Doctrine's abilities. Also, one way to get around Unions is to run two queries then combine the arrays.

```<code>$em = $this->getDoctrine()->getManager();
$sql = "SELECT .. FROM .. WHERE .. ";
$result = $em->getConnection()->prepare($sql);
$result->execute();
</code>```

Another option is to use a repository: Note this uses Doctrine so all Doctrine rules apply.

```<code>    $sql =
        "
        SELECT
            ...
        FROM
            App:EntityName alias
        WHERE
            ...
        "
    ;
    $query = $this->getEntityManager()->createQuery($sql);
    $results = $query->getResult();
</code>```

Body:
I made two count queries with query build doctrine but after I found that there is several query count that repeats so I must work with UNION but there is no union in doctrine query build.

So the solution is the use of native SQL with UNION.

I do not know how to do the translation in native query

this is my request 1

/**
     * @param Analyse $analyse
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function countTotalErrorByIdAnalyse(Analyse $analyse)
    {
        return $this->createQueryBuilder('a')
                    ->select('count(a)')
                    ->innerJoin('a.analyse', 'analyse')
                    ->where('analyse.id = :analyse')
                    ->setParameter('analyse', $analyse->getId())
                    ->getQuery()
                    ->getSingleScalarResult();

    }

this is my request 2

 /**
     * @param Analyse $analyse
     * @param string $severity
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function countErrorsBySeverity(Analyse $analyse, string $severity){

      return   $this->createQueryBuilder('a')
                    ->select('count(a)')
                    ->innerJoin('a.analyse', 'analyse')
                    ->innerJoin('a.rule', 'rule')
                    ->where('rule.severity = :error')
                    ->setParameter('error', $severity)
                    ->getQuery()
                    ->getSingleScalarResult();

    }

Body:
I would strongly suggest trying to work out your query in Doctrine but if native is the only way then it is the only way.

Native SQL in Symfony: Note I uses these in Symfony 3 but should work in Symfony 4. Once you get more use to Doctrine you will find it really does everything native can do and some items it does not do there are plugins available to expand Doctrine's abilities. Also, one way to get around Unions is to run two queries then combine the arrays.

$em = $this->getDoctrine()->getManager();
$sql = "SELECT .. FROM .. WHERE .. ";
$result = $em->getConnection()->prepare($sql);
$result->execute();

Another option is to use a repository: Note this uses Doctrine so all Doctrine rules apply.

    $sql =
        "
        SELECT
            ...
        FROM
            App:EntityName alias
        WHERE
            ...
        "
    ;
    $query = $this->getEntityManager()->createQuery($sql);
    $results = $query->getResult();


问:
DAO in Scala with type classes
Let my application contains business classes Order, Product, Customer, etc. and I would like to store/retrieve them in/from the database.

Usually, we use the DAO pattern for this purpose. That is, we define a DAO interface and implementation for every business class: OrderDAO, ProductDAO, etc. Now I would like to use the type class pattern:

```<code>trait DAO[T] {
  def create(t:T)
  ... // other CRUD operations
}
...
// DAO implementations for specific business objects
implicit object OrderDAO extends DAO[Order] {
   def create(o:Order) {...}
   ... // other CRUD operations
}
...
// create a business object in the database
def create[T](t:T)(implicit dao:DAO[T]) {dao.create(t)}</code>```

Now my problem is that all DAOs use a DataSource instance (a factory of database connections) and so I cannot define DAOs as objects. I should create a singleton instance of the DataSource and pass it to all DAOs upon their initialisation.

Let's say we have a function to create a DataSource: ```<code>def dataSource():DataSource = {...}</code>```
How would you implement the DAOs with type classes ?

答:
How about creating an object that holds all your DAOs and initializes them with your DataSource? Extra indirection but this would work.

I don't know (yet) the best practice to deal with Dependency Injection in Scala but this may work for you as well: http://www.assembla.com/wiki/show/liftweb/Dependency_Injection

ContentLicense: CC BY-SA 3.0

Title: DAO in Scala with type classes

Body:
Let my application contains business classes Order, Product, Customer, etc. and I would like to store/retrieve them in/from the database.

Usually, we use the DAO pattern for this purpose. That is, we define a DAO interface and implementation for every business class: OrderDAO, ProductDAO, etc. Now I would like to use the type class pattern:

trait DAO[T] {
  def create(t:T)
  ... // other CRUD operations
}
...
// DAO implementations for specific business objects
implicit object OrderDAO extends DAO[Order] {
   def create(o:Order) {...}
   ... // other CRUD operations
}
...
// create a business object in the database
def create[T](t:T)(implicit dao:DAO[T]) {dao.create(t)}

Now my problem is that all DAOs use a DataSource instance (a factory of database connections) and so I cannot define DAOs as objects. I should create a singleton instance of the DataSource and pass it to all DAOs upon their initialisation.

Let's say we have a function to create a DataSource:
def dataSource():DataSource = {...}

How would you implement the DAOs with type classes ?


问:
Forcing www and https redirect on NGINX as backend of Google cloud Load Balancer using $http_x_forwarded_proto
I have a NGINX backend instance for the google cloud platform load balancer. I have and have successfully set up the https redirect. I want to force from non-www to www. For the most part all but one instance redirects to a www url. to Summarize:

https://ampkart.com not successful and stays as https://ampkart.com

I have tried multiple edits to the redirect in the default.conf file to force it but to no avail. I know it probably has something to 'http' in the
  bracket and it is only affecting the http urls to redirect to www but the https urls are not affected. Can someone please help me modify this code for the redirect to work? Here is my default.conf file for my NGINX server.

```<code> server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /storage;

        # Add index.php to the list if you are using PHP
        index index.php index.html index.htm index.nginx-debian.html;

        server_name ampkart.com;

        location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
                error_page  405     =200 $uri;
        }

        # pass PHP scripts to FastCGI server
        #
        location ~ \.php$ {

            if ($http_x_forwarded_proto = 'http'){
            rewrite  ^/(.*)$  https://www.ampkart.com/$1 permanent;
        }
                    include snippets/fastcgi-php.conf;
        #   # With php-fpm (or other unix sockets):
            fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        #   # With php-cgi (or other tcp sockets):
        #   fastcgi_pass 127.0.0.1:9000;
        if ($request_method ~* "(GET|POST|OPTIONS)") {
                    add_header "Access-Control-Allow-Methods" "GET, POST,
        OPTIONS";
                    add_header "Access-Control-Allow-Credentials" "true";
                    add_header "Access-Control-Allow-Origin"
         "https://www.ampkart.com";
                    add_header "Access-Control-Expose-Headers" "AMP-
         Access-Control-Allow-Source-Origin,Content-Length,Content-Range";
                    add_header 'Access-Control-Allow-Headers' 'DNT,User-
         Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-
         Type,Range';
                    add_header 'AMP-Access-Control-Allow-Source-Origin'
         "https://www.ampkart.com";
                    add_header "AMP-Same-Origin" "true";
                    add_header "AMP-Redirect-to"
         "https://www.ampkart.com$request_uri";
              }
            }

          # deny access to .htaccess files, if Apache's document root
          # concurs with nginx's one
          #
          location ~ /\.ht {
            deny all;
          }
          }
</code>```

I would like to be able to redirect https://ampkartcom to https://www.ampkart.com

答:
Solved. If you are trying to implement forced https and www or non-www with a nginx backend of Google cloud load balancer, just use the cold below: Place it underneath the server_name, change example.com to your domain.

```<code>if ($http_host ~* '^example.com'){
rewrite ^(.*)$ https://www.example.com$request_uri redirect; }

</code>```

this will force https with the nginx backend and if you don't want the www and want to force non-www, just remove the "www."

Also, here is a full default.conf for my website nginx backend of the google cloud load balancer with php-fpm enabled. Enjoy!

```<code>##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    #listen 443 ssl default_server;
    #listen [::]:443 ssl default_server;

        #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /www;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    server_name www.example.com;

if ($http_host ~* '^example.com'){
rewrite ^(.*)$ https://www.example.com$request_uri redirect; }

                location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
            error_page  405     =200 $uri;
}

    # pass PHP scripts to FastCGI server
    #
    location ~ \.php$ {

                include snippets/fastcgi-php.conf;
    #   # With php-fpm (or other unix sockets):
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    #   # With php-cgi (or other tcp sockets):
    #   fastcgi_pass 127.0.0.1:9000;

}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }

}

# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#   listen 80;
#   listen [::]:80;
#
#   server_name example.com;
#
#   root /var/www/example.com;
#   index index.html;
#
#   location / {
#       try_files $uri $uri/ =404;
#   }
#}
</code>```

Body:
I have a NGINX backend instance for the google cloud platform load balancer. I have and have successfully set up the https redirect. I want to force from non-www to www. For the most part all but one instance redirects to a www url. to Summarize:

https://ampkart.com not successful and stays as https://ampkart.com

I have tried multiple edits to the redirect in the default.conf file to force it but to no avail. I know it probably has something to 'http' in the
  bracket and it is only affecting the http urls to redirect to www but the https urls are not affected. Can someone please help me modify this code for the redirect to work? Here is my default.conf file for my NGINX server.

 server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /storage;

        # Add index.php to the list if you are using PHP
        index index.php index.html index.htm index.nginx-debian.html;

        server_name ampkart.com;

        location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
                error_page  405     =200 $uri;
        }

        # pass PHP scripts to FastCGI server
        #
        location ~ \.php$ {

            if ($http_x_forwarded_proto = 'http'){
            rewrite  ^/(.*)$  https://www.ampkart.com/$1 permanent;
        }
                    include snippets/fastcgi-php.conf;
        #   # With php-fpm (or other unix sockets):
            fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        #   # With php-cgi (or other tcp sockets):
        #   fastcgi_pass 127.0.0.1:9000;
        if ($request_method ~* "(GET|POST|OPTIONS)") {
                    add_header "Access-Control-Allow-Methods" "GET, POST,
        OPTIONS";
                    add_header "Access-Control-Allow-Credentials" "true";
                    add_header "Access-Control-Allow-Origin"
         "https://www.ampkart.com";
                    add_header "Access-Control-Expose-Headers" "AMP-
         Access-Control-Allow-Source-Origin,Content-Length,Content-Range";
                    add_header 'Access-Control-Allow-Headers' 'DNT,User-
         Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-
         Type,Range';
                    add_header 'AMP-Access-Control-Allow-Source-Origin'
         "https://www.ampkart.com";
                    add_header "AMP-Same-Origin" "true";
                    add_header "AMP-Redirect-to"
         "https://www.ampkart.com$request_uri";
              }
            }

          # deny access to .htaccess files, if Apache's document root
          # concurs with nginx's one
          #
          location ~ /\.ht {
            deny all;
          }
          }

I would like to be able to redirect https://ampkartcom to https://www.ampkart.com

Body:
Solved. If you are trying to implement forced https and www or non-www with a nginx backend of Google cloud load balancer, just use the cold below: Place it underneath the server_name, change example.com to your domain.

if ($http_host ~* '^example.com'){
rewrite ^(.*)$ https://www.example.com$request_uri redirect; }

this will force https with the nginx backend and if you don't want the www and want to force non-www, just remove the "www."

Also, here is a full default.conf for my website nginx backend of the google cloud load balancer with php-fpm enabled. Enjoy!

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    #listen 443 ssl default_server;
    #listen [::]:443 ssl default_server;

        #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /www;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    server_name www.example.com;

if ($http_host ~* '^example.com'){
rewrite ^(.*)$ https://www.example.com$request_uri redirect; }

                location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
            error_page  405     =200 $uri;
}

    # pass PHP scripts to FastCGI server
    #
    location ~ \.php$ {

                include snippets/fastcgi-php.conf;
    #   # With php-fpm (or other unix sockets):
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    #   # With php-cgi (or other tcp sockets):
    #   fastcgi_pass 127.0.0.1:9000;

}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }

}

# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#   listen 80;
#   listen [::]:80;
#
#   server_name example.com;
#
#   root /var/www/example.com;
#   index index.html;
#
#   location / {
#       try_files $uri $uri/ =404;
#   }
#}


问:
Registry mismatch Get-NetAdapter
I took an image from another Windows 10 PC and setup a new PC with this image.
Now I have the problem, that I change interface alias:

```<code>Rename-NetAdapter -InterfaceAlias "SwitchLan" -NewName "test"
</code>```

and it says that the value  "test" is already there.

```
Rename-NetAdapter : {Object Exists} An attempt was made to create an object and the object name already existed.
At line:1 char:1
+ Rename-NetAdapter -InterfaceAlias "SwitchLan" -NewName "test"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: (MSFT_NetAdapter... "PC-Name"):ROOT/StandardCimv2/MSFT_NetAdapter) [
   Rename-NetAdapter], CimException
    + FullyQualifiedErrorId : Windows System Error 698,Rename-NetAdapter
 ```

In the registry, I deleted the entry "test", but still, even when I change the entry "SwitchLAN" to "test", I can see in the Windows overview the interface "test", but when I put ipconfig in the commandlet I get the entry "SwitchLan", the same with PowerShell Get-NetAdapter.

Reboot didn't work.

Where can this value be stored, what happens here?

Also, when I want to change "test" to "test2" it says that there is no "test" interface, but when I want to change "SwitchLan" to "test" it says "test" is already there.

On the previous Image, there was an interface with the name "test".

答: In the Device-Manager -> show hidden devices -> then uninstall all adapters which aren't connected to the system anymore.</p>

Title: Registry mismatch Get-NetAdapter

Body:
I took an image from another Windows 10 PC and setup a new PC with this image.
Now I have the problem, that I change interface alias:

Rename-NetAdapter -InterfaceAlias "SwitchLan" -NewName "test"

and it says that the value  "test" is already there.

Rename-NetAdapter : {Object Exists} An attempt was made to create an object and the object name already existed.
At line:1 char:1
+ Rename-NetAdapter -InterfaceAlias "SwitchLan" -NewName "test"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: (MSFT_NetAdapter... "PC-Name"):ROOT/StandardCimv2/MSFT_NetAdapter) [
   Rename-NetAdapter], CimException
    + FullyQualifiedErrorId : Windows System Error 698,Rename-NetAdapter

In the registry, I deleted the entry "test", but still, even when I change the entry "SwitchLAN" to "test", I can see in the Windows overview the interface "test", but when I put ipconfig in the commandlet I get the entry "SwitchLan", the same with PowerShell Get-NetAdapter.

Reboot didn't work.

Where can this value be stored, what happens here?

Also, when I want to change "test" to "test2" it says that there is no "test" interface, but when I want to change "SwitchLan" to "test" it says "test" is already there.

On the previous Image, there was an interface with the name "test".


问:
Find and replace in PowerShell
My PowerShell script reads a big text file and does a bunch of stuff to it. The part I'm stuck on is how to edit an entire line of text based on part of it.

For example, this line is in my text file:

Blah Blah 123

I would use this PowerShell:

```<code>$FileContents=$FileContents.Replace("Blah Blah 123","Whatever")
</code>```

My problem is the "123" part might be different from line to line, but I still need to delete the entire line. So I still need to delete this line:

Blah Blah 456

But my PowerShell wouldn't see that.

I can point it at just the "Blah Blah" part, but then it only replaces that part, leaving the "456" behind.

Does PowerShell have a way to handle this? I was thinking of maybe getting the character location (like an array?) of the first character of the line, and then getting a substring from there until a new line character. But I'm not sure that's even possible...

答:
If what you want to do is remove lines entirely that meet a certain criteria I would use the -notmatch operator inside a Where{} statement. For example:

```<code>$MyArray = 'Dogs make great pets','Cats make great pets','Chupacabra make great pets','Hamsters make great pets'
$Pets = $MyArray | Where{ $_ -notmatch 'Chupacabra' }
</code>```

At this point $Pets contains the strings:

```<code>Dogs make great pets
Cats make great pets
Hamsters make great pets
</code>```

Title: Find and replace in PowerShell

Body:
My PowerShell script reads a big text file and does a bunch of stuff to it. The part I'm stuck on is how to edit an entire line of text based on part of it.

For example, this line is in my text file:

Blah Blah 123

I would use this PowerShell:

$FileContents=$FileContents.Replace("Blah Blah 123","Whatever")

My problem is the "123" part might be different from line to line, but I still need to delete the entire line. So I still need to delete this line:

Blah Blah 456

But my PowerShell wouldn't see that.

I can point it at just the "Blah Blah" part, but then it only replaces that part, leaving the "456" behind.

Does PowerShell have a way to handle this? I was thinking of maybe getting the character location (like an array?) of the first character of the line, and then getting a substring from there until a new line character. But I'm not sure that's even possible...

Body:
If what you want to do is remove lines entirely that meet a certain criteria I would use the -notmatch operator inside a Where{} statement. For example:

$MyArray = 'Dogs make great pets','Cats make great pets','Chupacabra make great pets','Hamsters make great pets'
$Pets = $MyArray | Where{ $_ -notmatch 'Chupacabra' }

At this point $Pets contains the strings:

Dogs make great pets
Cats make great pets
Hamsters make great pets


问:
How to use REACTJS and Context in HTML tags
In my project, I use a context to translate strings into various Language. In my project, I translate strings with this structure:

```<code>{Language.La_LAST_PURCHASE_PRICE}
</code>```

Which "Language" refers to context and "La_LAST_PURCHASE_PRICE" is the key to the context that works and does not have any problems.
I have a sales invoice stylesheet that is in HTML format and I save it in the database and put it in a state after running the program and displaying the invoice to the user with the following code.

```<code><div dangerouslySetInnerHTML = {{__html: this.state.currentStyleTheme}} />
</code>```

In invoice style, I want to write the title with the context to change the language. (Instead of writing the title directly) as follows:

```<code>{Language.La_INVOICE_TITLE}
</code>```

But in the output of the invoice, it displays {Language.La_INVOICE_TITLE} It does not display the output of the Context and does not work properly.
How to write context or reactJS code between HTML tags stored in database and run in the project? (html is stored in the database with the data type TEXT)

答:
When you use

```<code><div dangerouslySetInnerHTML = {{__html: this.state.currentStyleTheme}} />
</code>```

this.state.currentStyleTheme is treated as a string.

In my opinion, you have 3 choices,

use a String.replace() method. e.g. this.state.currentStyleTheme.replace('${Language.La_INVOICE_TITLE}', state.title)

Use server-side rendering so you can manipulate the html element without using dangerouslySetInnerHTML

use the same structure for each template and dynamic styling from database.

Option 3 might not work if you have a massive difference in the html templates.

Body:
In my project, I use a context to translate strings into various Language. In my project, I translate strings with this structure:

{Language.La_LAST_PURCHASE_PRICE}

Which "Language" refers to context and "La_LAST_PURCHASE_PRICE" is the key to the context that works and does not have any problems.
I have a sales invoice stylesheet that is in HTML format and I save it in the database and put it in a state after running the program and displaying the invoice to the user with the following code.

In invoice style, I want to write the title with the context to change the language. (Instead of writing the title directly) as follows:

{Language.La_INVOICE_TITLE}

But in the output of the invoice, it displays {Language.La_INVOICE_TITLE} It does not display the output of the Context and does not work properly.
How to write context or reactJS code between HTML tags stored in database and run in the project? (html is stored in the database with the data type TEXT)

Body:
When you use

<div dangerouslySetInnerHTML = {{__html: this.state.currentStyleTheme}} />

this.state.currentStyleTheme is treated as a string.

In my opinion, you have 3 choices,

use a String.replace() method. e.g. this.state.currentStyleTheme.replace('${Language.La_INVOICE_TITLE}', state.title)

Use server-side rendering so you can manipulate the html element without using dangerouslySetInnerHTML

use the same structure for each template and dynamic styling from database.

Option 3 might not work if you have a massive difference in the html templates.


问:
Need to install pandas library directly from a python file on MacOS
I am required  to use a fresh Mac OS with no libraries unless I can find a way to download pandas using a .py file on the fresh VM. How would I do this on MacOS?</p>

答:
You will need to have the entire .tar.gz download in order to install the package, not just a single .py file. As described here as well, once you have the .tar.gz, you can unpack it, navigate to the directory, and execute the setup.py file:

```<code>python setup.py install
</code>```

You can get the latest version of pandas here.

Update after comment/update

Check out using subprocess to issue commands.

```<code>import subprocess
import sys

version = 0.24.2
package = 'pandas'

subprocess.call(['sudo', sys.executable, '-m', 'pip', 'install', '{}=={}'.format(package, version)])
</code>```

Body:
You will need to have the entire .tar.gz download in order to install the package, not just a single .py file. As described here as well, once you have the .tar.gz, you can unpack it, navigate to the directory, and execute the setup.py file:

python setup.py install

You can get the latest version of pandas here.

Update after comment/update

Check out using subprocess to issue commands.

import subprocess
import sys

version = 0.24.2
package = 'pandas'

subprocess.call(['sudo', sys.executable, '-m', 'pip', 'install', '{}=={}'.format(package, version)])


问:
null object reference of TextView in Fragment
I have two fragments and a main activity. The first fragment, FriendsFragment (extends ListFragment) is displayed on the screen and when the user clicks an item, the main Activity replaces the FriendsFragment with FeedFragment, then calls a method from FeedFragment to update the textView.

I'm getting an error that the textView object in the FeedFragment class is null even though I instantiate using the findViewById method.

I have looked at related questions and have tried the solutions but nothing is working. I've tried doing getView().findViewById(R.id.feed_view), getActivity().findViewById(R.id.feed_view), and I've tried putting these in onActivityCreated() and onCreateView()

The only thing that worked is writing this code in onActivityCreated():

```<code>text = getView().findViewById(R.id.feed_view);
text.setText("some string");
</code>```

but this is not what I want

FeedFragments.java

```<code>public class FeedFragment extends Fragment {
    private static String TAG = "Feed Fragment";
    private TextView text;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.i(TAG, "Entered FeedFragment.java onActivityCreated()");
        super.onActivityCreated(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    Log.i(TAG, "Entered FeedFragment.java onCreateView()");
    View v = inflater.inflate(R.layout.fragment_feed, container,false);;
    text = v.findViewById(R.id.feed_view);
    return v;
}

public void updateDisplay(int position)
{
    Log.i(TAG, "FeedFragment.java: updateDisplay()");
    text.setText(position);
}
</code>```

MainActivity.java

```<code>// previously declared feedFragment: feedFragment = new FeedFragment();
public void onItemSelected(int position)
{
    Log.i(TAG, "Entered onItemSelected(" + position + ")");
    fragManager = getFragmentManager();
    FragmentTransaction fragTransaction = fragManager.beginTransaction();
    fragTransaction.replace(R.id.fragment_container, feedFragment, "feed_fragment");
    fragTransaction.addToBackStack(null);
    fragTransaction.commit();

    feedFragment.updateDisplay(position);
}
</code>```

fragment_feed.xml

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

    <TextView
        android:id="@+id/feed_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/greeting" />

</ScrollView>
</code>```

activity_main.xml

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</code>```

答:
onViewcreated() is being called after updateDisplay() because the system doesn't run it right away.

you need to pass a value to the feedFragment on it's creation and store it in a bundle and retrieve it after the fragment internal code is run by the system.

the way you solve it is like this:

when you instantiate feedFragment you do it like this:

```<code>feedFragment = FeedFragment.newInstance(position)
</code>```

and inside FeedFragment class you should have a static code:

```<code>private static final String ARG_PARAM1 = "param1";

public static FeedFragment newInstance(int param1) {
    FeedFragment fragment = new FeedFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_PARAM1, param1);
    fragment.setArguments(args);
    return fragment;
}
</code>```

and non static code:

```<code>private int mParam1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getInt(ARG_PARAM1);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    Log.i(TAG, "Entered FeedFragment.java onCreateView()");
    View v = inflater.inflate(R.layout.fragment_feed, container,false);;
    text = v.findViewById(R.id.feed_view);
    text.setText(String.valueOf(mParam1));
    return v;
}
</code>```

I wrapped mParam1 in String.valueOf() because when you pass integer to setText it thinks you try to use a Strings.xml resource instead of the number you chose.

also I used very generic variable names. please change them to something meaningful so that your code makes sense.

Body:
I have two fragments and a main activity. The first fragment, FriendsFragment (extends ListFragment) is displayed on the screen and when the user clicks an item, the main Activity replaces the FriendsFragment with FeedFragment, then calls a method from FeedFragment to update the textView.

I'm getting an error that the textView object in the FeedFragment class is null even though I instantiate using the findViewById method.

I have looked at related questions and have tried the solutions but nothing is working. I've tried doing getView().findViewById(R.id.feed_view), getActivity().findViewById(R.id.feed_view), and I've tried putting these in onActivityCreated() and onCreateView()

The only thing that worked is writing this code in onActivityCreated():

text = getView().findViewById(R.id.feed_view);
text.setText("some string");

but this is not what I want

FeedFragments.java

public class FeedFragment extends Fragment {
    private static String TAG = "Feed Fragment";
    private TextView text;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.i(TAG, "Entered FeedFragment.java onActivityCreated()");
        super.onActivityCreated(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    Log.i(TAG, "Entered FeedFragment.java onCreateView()");
    View v = inflater.inflate(R.layout.fragment_feed, container,false);;
    text = v.findViewById(R.id.feed_view);
    return v;
}

public void updateDisplay(int position)
{
    Log.i(TAG, "FeedFragment.java: updateDisplay()");
    text.setText(position);
}

MainActivity.java

// previously declared feedFragment: feedFragment = new FeedFragment();
public void onItemSelected(int position)
{
    Log.i(TAG, "Entered onItemSelected(" + position + ")");
    fragManager = getFragmentManager();
    FragmentTransaction fragTransaction = fragManager.beginTransaction();
    fragTransaction.replace(R.id.fragment_container, feedFragment, "feed_fragment");
    fragTransaction.addToBackStack(null);
    fragTransaction.commit();

    feedFragment.updateDisplay(position);
}

fragment_feed.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

    <TextView
        android:id="@+id/feed_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/greeting" />

</ScrollView>

activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Body:
onViewcreated() is being called after updateDisplay() because the system doesn't run it right away.

you need to pass a value to the feedFragment on it's creation and store it in a bundle and retrieve it after the fragment internal code is run by the system.

the way you solve it is like this:

when you instantiate feedFragment you do it like this:

feedFragment = FeedFragment.newInstance(position)

and inside FeedFragment class you should have a static code:

private static final String ARG_PARAM1 = "param1";

public static FeedFragment newInstance(int param1) {
    FeedFragment fragment = new FeedFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_PARAM1, param1);
    fragment.setArguments(args);
    return fragment;
}

and non static code:

private int mParam1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getInt(ARG_PARAM1);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    Log.i(TAG, "Entered FeedFragment.java onCreateView()");
    View v = inflater.inflate(R.layout.fragment_feed, container,false);;
    text = v.findViewById(R.id.feed_view);
    text.setText(String.valueOf(mParam1));
    return v;
}

I wrapped mParam1 in String.valueOf() because when you pass integer to setText it thinks you try to use a Strings.xml resource instead of the number you chose.

also I used very generic variable names. please change them to something meaningful so that your code makes sense.


问:
How to generate sample data based of weighted base values
Using SQL, I need to generate some sample data of N rows based off some base values which have assigned weights.

For example: if my base values and their corresponding weights are:

a-1,

b-2,

c-3,

d-4,

e-5

And if the sample size required is 15, then the rowset returned should have:

5 rows of e,

4 rows of d,

3 rows of c,

2 rows of b.

and  1 row of a

for a total of 15 rows.

答:
in sql server,you can use left,right to split the value then use cte + recursion get mutiple rows,and this logic is also common to other rdbms.

Table & DDL

|val|
|--- |
|a-1|
|b-2|
|c-3|
|d-4|
|e-5|
```

<p><img src="https://i.imgur.com/Hcc75XA.png" alt=""></p>

<h3>Query SQL</h3>

<pre class="lang-sql prettyprint-override"><code>with cte as (
  select
   left(val, CHARINDEX('-', val)-1)  id
   ,convert(int, right(val, CHARINDEX('-', val)-1 ))  cnt
  from t
)
,cte2 as (
  select T1.id,T1.cnt - 1 as cnt from cte T1
  union all
  select T1.id,T2.cnt - 1 as cnt from cte T1
  inner join cte2 T2 on T1.id = T2.id and T2.cnt > 0
)
select id from cte2
order by id,cnt
</code>```

online demo link | db<>fiddle

Body:
in sql server,you can use left,right to split the value then use cte + recursion get mutiple rows,and this logic is also common to other rdbms.

Table & DDL

|val|
|--- |
|a-1|
|b-2|
|c-3|
|d-4|
|e-5|

Query SQL

with cte as (
  select
   left(val, CHARINDEX('-', val)-1)  id
   ,convert(int, right(val, CHARINDEX('-', val)-1 ))  cnt
  from t
)
,cte2 as (
  select T1.id,T1.cnt - 1 as cnt from cte T1
  union all
  select T1.id,T2.cnt - 1 as cnt from cte T1
  inner join cte2 T2 on T1.id = T2.id and T2.cnt > 0
)
select id from cte2
order by id,cnt

online demo link | db<>fiddle


问:
Line breaks in Django rest response
I see that in JSON response "\n" doesn't work for string values as
below. Is there any specific way for this in Django-rest Framewore. I am using "BrowsableAPIRenderer" from Django rest framework.</p>

```<code>{
  "count"   : "10",
  "results" : [
    {
      "id" : "10",
      "output" : "line1 \n line2 \n line3"
    },
  ]
}

HTML Code

<pre class="prettyprint">
...
...
 <span class="str">
 "line1 \n line2 \n line3"
 </span>

</code>```

答:
Escape the backslash character so that '\n' is sent as your response. In your example, try
replacing the value associated with the "output" key:

```<code>"output" : "line1 \\n line2 \\n line3"
</code>```

Title: Line breaks in Django rest response

Body:
I see that in JSON response "\n" doesn't work for string values as
below. Is there any specific way for this in Django-rest Framewore. I am using "BrowsableAPIRenderer" from Django rest framework.

{
  "count"   : "10",
  "results" : [
    {
      "id" : "10",
      "output" : "line1 \n line2 \n line3"
    },
  ]
}

HTML Code

...
...

 "line1 \n line2 \n line3"

Body:
Escape the backslash character so that '\n' is sent as your response. In your example, try
replacing the value associated with the "output" key:

"output" : "line1 \\n line2 \\n line3"


问:
ContextVars across modules
I am completely newb on asyncio and ContextVars, I just read up what's new in 3.7 and discovered ContextVars, I struggle to understand it's usage, all I know it's helpful in coroutines, instead of using thread.local should use ContextVars. But none of the official doc and top google search result could help me truely understand its purpose.

So is convextvars shared across modules? I tried:

example.py

```<code>from contextvars import ContextVar

number = ContextVar('number', default=100)
number.set(1)
</code>```

then I try to import number.py

```<code>(playground) Jamess-MacBook-Pro-2:playground jlin$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> from contextvars import ContextVar
>>> number = ContextVar('number', default=200)
>>> number.get()
200
</code>```

I was expecting number.get() would return 1, but obviously I have understood its purpose wrong.

Could someone please help me understand this?

答:
Assume your use case is to use python thread.local to store your thread global variable inside multi thread application.

For example you store django request globally in thread.local

all your code has access to current (and correct) request instance

it works, because each django HTTP request handled in it's own python thread

No imagine you handle HTTP requests in asyncio as non blocking code executed in the same python thread.

HTTP request stored in thread.local isn't going to work, because multiple concurrent requests get processed in the same python thread

What happens is you overwrite same thread.local variable and all your code has access to latest (incorrect) request instance

In this case you use ContextVars designed to be used for this use case inside non blocking concurrent jobs running in same python thread.

Title: ContextVars across modules

Body:
I am completely newb on asyncio and ContextVars, I just read up what's new in 3.7 and discovered ContextVars, I struggle to understand it's usage, all I know it's helpful in coroutines, instead of using thread.local should use ContextVars. But none of the official doc and top google search result could help me truely understand its purpose.

So is convextvars shared across modules? I tried:

example.py

from contextvars import ContextVar

number = ContextVar('number', default=100)
number.set(1)

then I try to import number.py

(playground) Jamess-MacBook-Pro-2:playground jlin$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> from contextvars import ContextVar
>>> number = ContextVar('number', default=200)
>>> number.get()
200

I was expecting number.get() would return 1, but obviously I have understood its purpose wrong.

Could someone please help me understand this?


问:
Can't validate form to send email
My form won't email and I think i'm missing if/elseif and return statements but not sure where to insert it

Trying to figure out where to insert return true/false statement into the code and code really use some help for this as i'm still a beginner to java script/ web development

```<code>  var message, x, j;
  message = document.getElementById("message");
  message.innerHTML == "";
  x = document.getElementById("Firstname").value;
  try {

        if(x == "")  throw "Required Field";
        if (x = /^[a-zA-Z]*$/) throw "";
        if (x = /^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/) throw "Invalid Characters Present";
        if (x = Number(x)) throw "Invalid Characters Present";
  }
  catch(err) {
    message.innerHTML = err;
  }
}
</code>```

thats the first function up above that validates the first input

```<code>

function myFunction2() {
  var message, x, j;
  message = document.getElementById("message2");
  message.innerHTML == "";
  x = document.getElementById("Lastname").value;
  try {
        if(x == "")  throw "Required Field";
        if (x = /^[a-zA-Z]*$/) throw "";
        if (x = /^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/) throw "Invalid Characters Present";
        if (x = Number(x)) throw "Invalid Characters Present";
  }
  catch(err) {
    message.innerHTML = err;
  }
}

function myFunction3  (){
  let message, x, j; //using let stops other functions from accidentally using it
   let RegExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; //pattern for email
   message = document.getElementById("message3"); //getting the error element
   message.innerHTML == ""; //declaring default value
   x = document.getElementById("Email").value; //x equals the email value

try{ //trying the conditions
   if (x === '') throw "Required Field"; //if x is blank then throw and error message
   else if (RegExp.test(x)) throw ''; //if the regexp testing pattern is valid then throw null
   else throw "Invalid Email Address"; //otherwise throw value is not valid
 }
 catch(err) { //this cathces the throw and produces the error message
   message.innerHTML = err;
 }
}

function myFunction4() {
  var message, x, j;
  message = document.getElementById("message4");
  message.innerHTML == "";
  x = document.getElementById("Subject").value;
  try {

    if(x == "")  throw "Required Field";
    if (x = /^[a-zA-Z]*$/) throw "";
  }
  catch(err) {
    message.innerHTML = err;
  }
}

function myFunction5() {
  var message, x, j;
  message = document.getElementById("message5");
  message.innerHTML == "";
  x = document.getElementById("Message").value;
  try {
    if(x == "")  throw "Required Field";
  if (x = /^[a-zA-Z]*$/) throw "";

  }
  catch(err) {
    message.innerHTML = err;
  }
}
</code>```

答:
The first thing I can see if your regex if statements need to be formatted correctly.

See here

e.g.

```<code>var phoneRE = /^\(\d\d\d\) \d\d\d-\d\d\d\d$/;
  if (phoneNo.match(phoneRE)) {
    return true;
  } else {
    alert( "The phone number entered is invalid!" );
    return false;
  }
</code>```

Title: Can't validate form to send email

Body:
My form won't email and I think i'm missing if/elseif and return statements but not sure where to insert it

Trying to figure out where to insert return true/false statement into the code and code really use some help for this as i'm still a beginner to java script/ web development

  var message, x, j;
  message = document.getElementById("message");
  message.innerHTML == "";
  x = document.getElementById("Firstname").value;
  try {

        if(x == "")  throw "Required Field";
        if (x = /^[a-zA-Z]*$/) throw "";
        if (x = /^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/) throw "Invalid Characters Present";
        if (x = Number(x)) throw "Invalid Characters Present";
  }
  catch(err) {
    message.innerHTML = err;
  }
}

thats the first function up above that validates the first input

function myFunction2() {
  var message, x, j;
  message = document.getElementById("message2");
  message.innerHTML == "";
  x = document.getElementById("Lastname").value;
  try {
        if(x == "")  throw "Required Field";
        if (x = /^[a-zA-Z]*$/) throw "";
        if (x = /^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/) throw "Invalid Characters Present";
        if (x = Number(x)) throw "Invalid Characters Present";
  }
  catch(err) {
    message.innerHTML = err;
  }
}

function myFunction3  (){
  let message, x, j; //using let stops other functions from accidentally using it
   let RegExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; //pattern for email
   message = document.getElementById("message3"); //getting the error element
   message.innerHTML == ""; //declaring default value
   x = document.getElementById("Email").value; //x equals the email value

try{ //trying the conditions
   if (x === '') throw "Required Field"; //if x is blank then throw and error message
   else if (RegExp.test(x)) throw ''; //if the regexp testing pattern is valid then throw null
   else throw "Invalid Email Address"; //otherwise throw value is not valid
 }
 catch(err) { //this cathces the throw and produces the error message
   message.innerHTML = err;
 }
}

function myFunction4() {
  var message, x, j;
  message = document.getElementById("message4");
  message.innerHTML == "";
  x = document.getElementById("Subject").value;
  try {

    if(x == "")  throw "Required Field";
    if (x = /^[a-zA-Z]*$/) throw "";
  }
  catch(err) {
    message.innerHTML = err;
  }
}

function myFunction5() {
  var message, x, j;
  message = document.getElementById("message5");
  message.innerHTML == "";
  x = document.getElementById("Message").value;
  try {
    if(x == "")  throw "Required Field";
  if (x = /^[a-zA-Z]*$/) throw "";

  }
  catch(err) {
    message.innerHTML = err;
  }
}

Body:
The first thing I can see if your regex if statements need to be formatted correctly.

See here

e.g.

var phoneRE = /^\(\d\d\d\) \d\d\d-\d\d\d\d$/;
  if (phoneNo.match(phoneRE)) {
    return true;
  } else {
    alert( "The phone number entered is invalid!" );
    return false;
  }


问:
How to make a perfect circle
I don't know what other technique i can use to make a perfect circle. The problem tells me that the circle must have 200px of diameter on CSS. Yet, someone made it differently using other variables. I want to do it the right way but don't know how.

I'd created a div which specifies the image to have 200px but still it didn't work

```<code><img class="rounded" src="https://assets.breatheco.de/apis/img/funny/einstein.png" />
</code>```

答:
Apply boder-radius: 50%; to the image:

img {
  border-radius: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://picsum.photos/200" /></code>```

Title: How to make a perfect circle

Body:
Apply boder-radius: 50%; to the image:

img {
  border-radius: 50%;
}

<img src="https://picsum.photos/200" />


问:
Is there a way to add characters based on a variable?
I'm making a text-based game about Hangman and so far I have 10 words with different amounts of characters in each word. The lowest character count is three, so I'm planning to put in three underscores at the start for me to be able to add underscores after the string.

I have a variable set up, called wordPlayingLength which counts up an integer based on the amount of characters in the word that has been selected through a random statement. My question is if there's a way to add underscores that matches up with the word's length in characters?

```<code>if (randomNumber == 10):
    wordPlaying = str("Didgeridoo") ## states the word being played
    wordPlayingLength = int(len(wordPlaying)) ## calculates the character length of the word being played
    print(str(wordPlayingLength) + " letters!")

    underscoreCount = (wordPlayingLength)
    print("_ _ _ " + ) ## this is where I got stuck, no idea here
</code>```

答:
In Python, you can multiply a string by an integer to make repetition:

```<code>>>> num_of_underscores = 9
>>> num_of_underscores * "_"
'_________'
</code>```

If you wanted spaces between the underscores, you could do something like

```<code>>>> " ".join("_" * num_of_underscores)
'_ _ _ _ _ _ _ _ _'
</code>```

where you multiply an array with a single underscore by an integer to get that many of them.

Body:
I'm making a text-based game about Hangman and so far I have 10 words with different amounts of characters in each word. The lowest character count is three, so I'm planning to put in three underscores at the start for me to be able to add underscores after the string.

I have a variable set up, called wordPlayingLength which counts up an integer based on the amount of characters in the word that has been selected through a random statement. My question is if there's a way to add underscores that matches up with the word's length in characters?

if (randomNumber == 10):
    wordPlaying = str("Didgeridoo") ## states the word being played
    wordPlayingLength = int(len(wordPlaying)) ## calculates the character length of the word being played
    print(str(wordPlayingLength) + " letters!")

    underscoreCount = (wordPlayingLength)
    print("_ _ _ " + ) ## this is where I got stuck, no idea here

Body:
In Python, you can multiply a string by an integer to make repetition:

>>> num_of_underscores = 9
>>> num_of_underscores * "_"
'_________'

If you wanted spaces between the underscores, you could do something like

>>> " ".join("_" * num_of_underscores)
'_ _ _ _ _ _ _ _ _'

where you multiply an array with a single underscore by an integer to get that many of them.


问:
How to create references to objects created in a loop?
I'm sure this question has been asked but I cannot find it (on SO or Google) for my life.

How can I most effectively create a reference to multiple objects that I create in a loop?
In this specific case, I am using Swing to add JButtons to a GridLayout.

```<code>int numOfButtons = 10;
for (int i = 0; i < numOfButtons; i++){
    add(new JButton("" + i));}
</code>```

If later I want to change the text on the buttons, how would I do so? Say, if I wanted to change button number 8:

```<code>buttonEight.setText("DO NOT CLICK!!!);
</code>```

How would I create a reference to the button with the 8 on it from buttonEight?

The only thing I can think of is creating a bunch of instance variables before the loop. Except... Well. Actually , that wouldn't work (I don't think)

Something that would do this:

```<code>JButton button8;
    for (int i = 0; i < numOfButtons; i++){

    button + i = new JButton(""+ i);
    //like, if i = 8 then button + i gets me button8 to reference it or something?
    //obviously that doesn't work
    }

button8.setText("DO NOT CLICK!!!);
</code>```

and also I'd be in trouble creating the right number of instance variables if numOfButtons is variable.

How should I do this?

答:
Use an ArrayList:

```<code>ArrayList<JButton> list=new ArrayList<>();
int numOfButtons = 10;
for (int i = 0; i < numOfButtons; i++){
    JButton jb=new JButton("" + i);
    list.add(jb);
    add(jb);
}
</code>```

Later (assuming you want to change the text of 8th button (which is 7 in list)):

```<code>list.get(7).setText("...");
</code>```

The list only create a reference to JButton object. Then any change made to it will reflect on the UI.

Body:
I'm sure this question has been asked but I cannot find it (on SO or Google) for my life.

How can I most effectively create a reference to multiple objects that I create in a loop?
In this specific case, I am using Swing to add JButtons to a GridLayout.

int numOfButtons = 10;
for (int i = 0; i < numOfButtons; i++){
    add(new JButton("" + i));}

If later I want to change the text on the buttons, how would I do so? Say, if I wanted to change button number 8:

buttonEight.setText("DO NOT CLICK!!!);

How would I create a reference to the button with the 8 on it from buttonEight?

The only thing I can think of is creating a bunch of instance variables before the loop. Except... Well. Actually , that wouldn't work (I don't think)

Something that would do this:

JButton button8;
    for (int i = 0; i < numOfButtons; i++){

    button + i = new JButton(""+ i);
    //like, if i = 8 then button + i gets me button8 to reference it or something?
    //obviously that doesn't work
    }

button8.setText("DO NOT CLICK!!!);

and also I'd be in trouble creating the right number of instance variables if numOfButtons is variable.

How should I do this?

Body:
Use an ArrayList:

ArrayList<JButton> list=new ArrayList<>();
int numOfButtons = 10;
for (int i = 0; i < numOfButtons; i++){
    JButton jb=new JButton("" + i);
    list.add(jb);
    add(jb);
}

Later (assuming you want to change the text of 8th button (which is 7 in list)):

list.get(7).setText("...");

The list only create a reference to JButton object. Then any change made to it will reflect on the UI.


问:
PrestaShop - Overriding a controller does not work
I want to override a controller in PrestaShop

```<code><?php

class ProductController extends ProductControllerCore{

    public function initContent()
    {

        parent::initContent();
    }
    public function init()
    {
        parent::init();
        echo "datbase";
        die;
    }
}

?>
</code>```

The file containing my Override is located in:

projectname/override/controllers/front/ProductController.php

But my override does not work.

答:
Updated answer for PrestaShop 1.7.x

In PrestaShop 1.7.x versions, the class_index.php file is now located in /var/cache/prod:

Don't forget to delete this file in case you've just added a new override, otherwise it won't work.

I hope this helps!

Body:
I want to override a controller in PrestaShop

<?php

class ProductController extends ProductControllerCore{

    public function initContent()
    {

        parent::initContent();
    }
    public function init()
    {
        parent::init();
        echo "datbase";
        die;
    }
}

?>

The file containing my Override is located in:

projectname/override/controllers/front/ProductController.php

But my override does not work.


问:
How to update an object inside a Mongo Document Array (at a specific index)
I want to let a user check off whether they've "acquired" a grocery item and update the Database.

In more concrete terms, when a user checks a box, I want to toggle a Boolean property acquired on an ingredient object. Ingredients are stored in an array on the GroceryList document:

Here is the Schema for a Grocery List

```<code>const GroceryListSchema = mongoose.Schema({
  createdAt         : { type: Date, default: Date.now },
  updatedAt         : { type: Date },
  ingredients       : { type: Array },
  recipes           : { type: Array },
  user              : { type: mongoose.Schema.Types.ObjectId, ref: 'UserSchema', required: true },
}
</code>```

An ingredient looks like this:

```<code>{ quantity: '3',
  unit: null,
  ingredient: 'zucchinis, chopped',
  minQty: '3',
  maxQty: '3',
  acquired: false }
</code>```

I've looked at a lot of similar questions, the Mongoose documentation and the MongoDB documentation and I've tried a ton of different versions but I'm stumped.

Frontend:

```<code>function toggleIngredient(elmt, groceryListId, ingrIdx) {
  $.post('/cart/grocery-list/toggleIngredient', {
    groceryListId,
    ingrIdx,
    newValue: elmt.checked, // if checkbox was checked before toggling it
  })
    .then((res) => {
      console.log(res);
    })
    .catch((err) => {
      console.log(err);
    });
}
</code>```

Backend:

```<code>  app.post('/cart/grocery-list/toggleIngredient', (req, res, next) => {
    const { groceryListId, ingrIdx, newValue } = req.body;

    GroceryListSchema.findById(groceryListId, (err, groceryList) => {
      if (err) return next(err);

      // if was unchecked, change to checked & vice-versa
      groceryList.ingredients[ingrIdx].acquired = newValue;

      // save updated grocery list
      groceryList.save().then((updatedList) => {
        console.log(updatedList.ingredients);
      }).catch(error => next(error));
    });
  });
</code>```

RESULTS / THE PROBLEM:
When I run the code above, I successfully see 1 ingredient's acquired property get toggled from false->true in the callback

```<code>console.log(updatedList.ingredients);
</code>```

However, the next time I fetch the grocery list, that same ingredient's acquired = false. This leads me to believe that the GroceryList document isn't actually getting updated in the database. How do I fix this?

答:
mongoose can't track changes inside the array if you modify array element directly using its index

try adding this line before saving

```<code>groceryList.markModified(`ingredients.${ingrIdx}.acquired`);
</code>```

Body:
I want to let a user check off whether they've "acquired" a grocery item and update the Database.

In more concrete terms, when a user checks a box, I want to toggle a Boolean property acquired on an ingredient object. Ingredients are stored in an array on the GroceryList document:

Here is the Schema for a Grocery List

const GroceryListSchema = mongoose.Schema({
  createdAt         : { type: Date, default: Date.now },
  updatedAt         : { type: Date },
  ingredients       : { type: Array },
  recipes           : { type: Array },
  user              : { type: mongoose.Schema.Types.ObjectId, ref: 'UserSchema', required: true },
}

An ingredient looks like this:

{ quantity: '3',
  unit: null,
  ingredient: 'zucchinis, chopped',
  minQty: '3',
  maxQty: '3',
  acquired: false }

I've looked at a lot of similar questions, the Mongoose documentation and the MongoDB documentation and I've tried a ton of different versions but I'm stumped.

Frontend:

function toggleIngredient(elmt, groceryListId, ingrIdx) {
  $.post('/cart/grocery-list/toggleIngredient', {
    groceryListId,
    ingrIdx,
    newValue: elmt.checked, // if checkbox was checked before toggling it
  })
    .then((res) => {
      console.log(res);
    })
    .catch((err) => {
      console.log(err);
    });
}

Backend:

  app.post('/cart/grocery-list/toggleIngredient', (req, res, next) => {
    const { groceryListId, ingrIdx, newValue } = req.body;

    GroceryListSchema.findById(groceryListId, (err, groceryList) => {
      if (err) return next(err);

      // if was unchecked, change to checked & vice-versa
      groceryList.ingredients[ingrIdx].acquired = newValue;

      // save updated grocery list
      groceryList.save().then((updatedList) => {
        console.log(updatedList.ingredients);
      }).catch(error => next(error));
    });
  });

RESULTS / THE PROBLEM:
When I run the code above, I successfully see 1 ingredient's acquired property get toggled from false->true in the callback

console.log(updatedList.ingredients);

However, the next time I fetch the grocery list, that same ingredient's acquired = false. This leads me to believe that the GroceryList document isn't actually getting updated in the database. How do I fix this?

Body:
mongoose can't track changes inside the array if you modify array element directly using its index

try adding this line before saving

groceryList.markModified(`ingredients.${ingrIdx}.acquired`);


问:
Querying UUID Type Values in MongoDB
Documents stored in a collection include a UUID type value when they are inserted and when they are returned from Monger's find-maps function. For example:

```<code>{:_id "5515e636314525806f24ceb3"
 :a #uuid "cfda7109-6e50-44c0-b13d-48712f7509a1"}
</code>```

However when I specify query with this criterion:

```<code>(find-maps db collection {:a #uuid "cfda7109-6e50-44c0-b13d-48712f7509a1"})
</code>```

or this:

```<code>(find-maps db collection {:a "cfda7109-6e50-44c0-b13d-48712f7509a1"})
</code>```

no results are returned. Do I need to use a type converter, or should I just store :a as some other type? Or, perhaps there is some other way?

答:
Try converting using the fromString static method of java.util.UUID:

```<code>(ns my.project
  (import [java.util UUID]))

(find-maps db collection {:a (UUID/fromString "cfda7109-6e50-44c0-b13d-48712f7509a1")})
</code>```

Title: Querying UUID Type Values in MongoDB

Body:
Documents stored in a collection include a UUID type value when they are inserted and when they are returned from Monger's find-maps function. For example:

{:_id "5515e636314525806f24ceb3"
 :a #uuid "cfda7109-6e50-44c0-b13d-48712f7509a1"}

However when I specify query with this criterion:

(find-maps db collection {:a #uuid "cfda7109-6e50-44c0-b13d-48712f7509a1"})

or this:

(find-maps db collection {:a "cfda7109-6e50-44c0-b13d-48712f7509a1"})

no results are returned. Do I need to use a type converter, or should I just store :a as some other type? Or, perhaps there is some other way?

Body:
Try converting using the fromString static method of java.util.UUID:

(ns my.project
  (import [java.util UUID]))

(find-maps db collection {:a (UUID/fromString "cfda7109-6e50-44c0-b13d-48712f7509a1")})


问:
Add new columns to a existing database througt doctrine command Symfony
I need help, I'm working in symfony, adn I created a database with 3 tables, but now I need to add some new columns into the tables, I created a new properties on the entity that I want to add them (new columns) into my tables. I installed the migrations Bundle but it doesn't work, I tried the schema uopdate as the documentation said and then I tried the migrations:diff and then the Migrate, and it seems like there is no changes to add to the entity/table, I'm very lost, could someone guide me please ? Is the private $usuario;</p>

```<code>/**
 * @ORM\OneToOne(targetEntity="Usuario", inversedBy="user")
 * @ORM\JoinColumn(name="usuario_id", referencedColumnName="id")
 */
private $usuario;
</code>```

答:
So you need to make the changes to your Entity and save it. Verify the changes have been made.

Then from the command prompt run:

```<code>php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate
</code>```

Out of the box on a Symfony 4.2.x app this should work with no issues.

Body:
I need help, I'm working in symfony, adn I created a database with 3 tables, but now I need to add some new columns into the tables, I created a new properties on the entity that I want to add them (new columns) into my tables. I installed the migrations Bundle but it doesn't work, I tried the schema uopdate as the documentation said and then I tried the migrations:diff and then the Migrate, and it seems like there is no changes to add to the entity/table, I'm very lost, could someone guide me please ? Is the private $usuario;

/**
 * @ORM\OneToOne(targetEntity="Usuario", inversedBy="user")
 * @ORM\JoinColumn(name="usuario_id", referencedColumnName="id")
 */
private $usuario;

Body:
So you need to make the changes to your Entity and save it. Verify the changes have been made.

Then from the command prompt run:

php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate

Out of the box on a Symfony 4.2.x app this should work with no issues.