问:
Hidden url for external page load jQuery php
I load external php page using jQuery plugin with this line of code:

```<code><a href="cat.php" rel="container">Tab 2</a>
</code>```

How to hide href url (cat.php) for more security and not show in html source code page?

Example :

```<code><a href="Block12" rel="container">Tab 2</a>
</code>```

Block 12 is php code to generate cat.php address

Block 13 is php code to generate data.php address

etc...

Thanks

答:
Should do:

```<code>$("a[href='Block12']").attr('href', 'cat.php');
</code>```

This will reveal the destination to the user in e.g. a status bar.

Body:
I load external php page using jQuery plugin with this line of code:

Tab 2

How to hide href url (cat.php) for more security and not show in html source code page?

Example :

Tab 2

Block 12 is php code to generate cat.php address

Block 13 is php code to generate data.php address

etc...

Thanks

Body:
Should do:

$("a[href='Block12']").attr('href', 'cat.php');

This will reveal the destination to the user in e.g. a status bar.


来源: stackexchange

问:
Sending JSON to PHP via jQuery AJAX
I have looked at a bunch of questions/answers on here and none of them seem to solve my problem.  I am integrating a payment system that returns a JSON string via a JS library that I then need to parse on the server to compare the hash values to ensure that it is valid.  So I get their response and attempt to pass it via jQuery AJAX to a PHP file on the server.  The response I get from the payment system is valid JSON.  If I pass it directly the result I get on the server seems to be URL encoded.  If I JSON.stringify() it, it adds a bunch of extra quotes which results in invalid JSON.

```<code>function isValidJSON($str) {
    json_decode($str);
    return json_last_error() == JSON_ERROR_NONE;
}

$json_params = file_get_contents("php://input");
error_log($json_params);

//error_log($_POST['jsresp']);
//$respObj = json_decode(stripslashes($_POST['jsresp']));

//error_log($json_params);

if (strlen($json_params) > 0 && isValidJSON($json_params)) {
    $respObj = json_decode($json_params);
} else {
    error_log('bad json '.$json_params);
}

$result = 0;

$resp = json_encode($respObj->Response);
$hash = $respObj->Hash;
error_log($hash);
$calcHash = base64_encode(hash_hmac('sha512', $resp, $app->getSageClientSecret(), true));
error_log($calcHash);

if($hash === $calcHash) {
    $result = 1;
}

$app->updateCartResponse($_COOKIE['qid'], $result);
</code>```

And here is the jQuery AJAX call to send the data:

```<code>$(document).on('click', 'button#sps-close.sps.btn.btn-primary', function(){
    var resp = $("#resp_holder").val();
    $.ajax({
        url: "<?=$env?>sources/processors/process_hash.php",
        data: { jsresp : resp },
        type: "post",
        //dataType: "json",
        success: function( data ) {
            // nothing to do here.
        }
    });
    var url = $("#redirect_url").val();
    if(url != "") {
        location.href = $("#redirect_url").val();
    }
});
</code>```

When I do it this way, the JSON that gets to the server looks like this:

```<code>jsresp%5Bresponse%5D=%7B%22requestId%22%3A%22443594%22%2C%22gatewayResponse%22%3A%7B%22status%22%3A%22Approved%22%2C%22reference%22%3A%22EBGHNHChw0%22%2C%22message%22%3A%22APPROVED+658658%22%2C%22code%22%3A%22658658%22%2C%22cvvResult%22%3A%22P%22%2C%22avsResult%22%3A%22+%22%2C%22riskCode%22%3A%2200%22%2C%22networkId%22%3A%2210%22%2C%22isPurchaseCard%22%3Afalse%2C%22orderNumber%22%3A%22443594%22%2C%22transactionId%22%3A%22NDViMWYzNmEwNWNiOGQxZjIwOTAwNzU4MmVjYzJhMWQ%22%2C%22timestamp%22%3A%222017-11-16T23%3A17%3A12.6584893-05%3A00%22%7D%7D&jsresp%5Bhash%5D=bgd1e0Cxhj5s1FQaUFFYk7BMnSIl4Ez1jPMopZFp%2B4MyN9chFZZoo%2F3IuZPX7bbQ%2BRyaReKN1CNJXxRmjnLMRQ%3D%3D
</code>```

I don't understand what I'm doing wrong or how to get it there properly.

答:
Based on your sample, this is what you get on the server

jsresp[response]={"requestId":"443594","gatewayResponse":{"status":"Approved","reference":"EBGHNHChw0","message":"APPROVED 658658","code":"658658","cvvResult":"P","avsResult":" ","riskCode":"00","networkId":"10","isPurchaseCard":false,"orderNumber":"443594","transactionId":"NDViMWYzNmEwNWNiOGQxZjIwOTAwNzU4MmVjYzJhMWQ","timestamp":"2017-11-16T23:17:12.6584893-05:00"}}&jsresp[hash]=bgd1e0Cxhj5s1FQaUFFYk7BMnSIl4Ez1jPMopZFp+4MyN9chFZZoo/3IuZPX7bbQ+RyaReKN1CNJXxRmjnLMRQ==

So your $_REQUEST['jsresp'] is an array
you need to json_decode the 'response' index of the array :

```<code>$respObj = json_decode($_REQUEST['jsresp']['response']);
$hash = $_REQUEST['jsresp']['hash'];
</code>```

And then you can go on...

ContentLicense: CC BY-SA 3.0

Title: Sending JSON to PHP via jQuery AJAX

Body:
I have looked at a bunch of questions/answers on here and none of them seem to solve my problem.  I am integrating a payment system that returns a JSON string via a JS library that I then need to parse on the server to compare the hash values to ensure that it is valid.  So I get their response and attempt to pass it via jQuery AJAX to a PHP file on the server.  The response I get from the payment system is valid JSON.  If I pass it directly the result I get on the server seems to be URL encoded.  If I JSON.stringify() it, it adds a bunch of extra quotes which results in invalid JSON.

function isValidJSON($str) {
    json_decode($str);
    return json_last_error() == JSON_ERROR_NONE;
}

$json_params = file_get_contents("php://input");
error_log($json_params);

//error_log($_POST['jsresp']);
//$respObj = json_decode(stripslashes($_POST['jsresp']));

//error_log($json_params);

if (strlen($json_params) > 0 && isValidJSON($json_params)) {
    $respObj = json_decode($json_params);
} else {
    error_log('bad json '.$json_params);
}

$result = 0;

$resp = json_encode($respObj->Response);
$hash = $respObj->Hash;
error_log($hash);
$calcHash = base64_encode(hash_hmac('sha512', $resp, $app->getSageClientSecret(), true));
error_log($calcHash);

if($hash === $calcHash) {
    $result = 1;
}

$app->updateCartResponse($_COOKIE['qid'], $result);

And here is the jQuery AJAX call to send the data:

$(document).on('click', 'button#sps-close.sps.btn.btn-primary', function(){
    var resp = $("#resp_holder").val();
    $.ajax({
        url: "<?=$env?>sources/processors/process_hash.php",
        data: { jsresp : resp },
        type: "post",
        //dataType: "json",
        success: function( data ) {
            // nothing to do here.
        }
    });
    var url = $("#redirect_url").val();
    if(url != "") {
        location.href = $("#redirect_url").val();
    }
});

When I do it this way, the JSON that gets to the server looks like this:

jsresp%5Bresponse%5D=%7B%22requestId%22%3A%22443594%22%2C%22gatewayResponse%22%3A%7B%22status%22%3A%22Approved%22%2C%22reference%22%3A%22EBGHNHChw0%22%2C%22message%22%3A%22APPROVED+658658%22%2C%22code%22%3A%22658658%22%2C%22cvvResult%22%3A%22P%22%2C%22avsResult%22%3A%22+%22%2C%22riskCode%22%3A%2200%22%2C%22networkId%22%3A%2210%22%2C%22isPurchaseCard%22%3Afalse%2C%22orderNumber%22%3A%22443594%22%2C%22transactionId%22%3A%22NDViMWYzNmEwNWNiOGQxZjIwOTAwNzU4MmVjYzJhMWQ%22%2C%22timestamp%22%3A%222017-11-16T23%3A17%3A12.6584893-05%3A00%22%7D%7D&jsresp%5Bhash%5D=bgd1e0Cxhj5s1FQaUFFYk7BMnSIl4Ez1jPMopZFp%2B4MyN9chFZZoo%2F3IuZPX7bbQ%2BRyaReKN1CNJXxRmjnLMRQ%3D%3D

I don't understand what I'm doing wrong or how to get it there properly.

Body:
Based on your sample, this is what you get on the server

jsresp[response]={"requestId":"443594","gatewayResponse":{"status":"Approved","reference":"EBGHNHChw0","message":"APPROVED 658658","code":"658658","cvvResult":"P","avsResult":" ","riskCode":"00","networkId":"10","isPurchaseCard":false,"orderNumber":"443594","transactionId":"NDViMWYzNmEwNWNiOGQxZjIwOTAwNzU4MmVjYzJhMWQ","timestamp":"2017-11-16T23:17:12.6584893-05:00"}}&jsresp[hash]=bgd1e0Cxhj5s1FQaUFFYk7BMnSIl4Ez1jPMopZFp+4MyN9chFZZoo/3IuZPX7bbQ+RyaReKN1CNJXxRmjnLMRQ==

So your $_REQUEST['jsresp'] is an array
you need to json_decode the 'response' index of the array :

$respObj = json_decode($_REQUEST['jsresp']['response']);
$hash = $_REQUEST['jsresp']['hash'];

And then you can go on...


问:
Traefik LetsEncrypt error "too many registrations for this IP"
I'm pretty new in Docker and have problem with LetsEncrypt using Traefik. I have run new Docker Swarm cluster and run Traefik by following these instructions. But when I run Traefik service I get error:

```<code>proxy.1.wzx74oc2zvyo@docker-manager-3    | time="2017-11-17T13:42:51Z" level=error msg="Error creating TLS config: acme: Error 429 - urn:acme:error:rateLimited - Error creating new registration :: too many registrations for this IP"
proxy.1.wzx74oc2zvyo@docker-manager-3    | time="2017-11-17T13:42:51Z" level=fatal msg="Error preparing server: acme: Error 429 - urn:acme:error:rateLimited - Error creating new registration :: too many registrations for this IP"
</code>```

What cause of this error and how to fix it?

Update

This problem not related to Traefik, when I try get cert by Certbot I get the same error.

答:
Looks like you hit the rate limit, 20 certificates per domain per week.

https://letsencrypt.org/docs/rate-limits/

Update your code to avoid re-registering the same domain. This may require that you don't restart the container so often or use a volume to persist the registration in the acme.json file. See the traefik docs on setting the storage and mounting a volume for more details:

https://docs.traefik.io/configuration/acme/

Body:
I'm pretty new in Docker and have problem with LetsEncrypt using Traefik. I have run new Docker Swarm cluster and run Traefik by following these instructions. But when I run Traefik service I get error:

proxy.1.wzx74oc2zvyo@docker-manager-3    | time="2017-11-17T13:42:51Z" level=error msg="Error creating TLS config: acme: Error 429 - urn:acme:error:rateLimited - Error creating new registration :: too many registrations for this IP"
proxy.1.wzx74oc2zvyo@docker-manager-3    | time="2017-11-17T13:42:51Z" level=fatal msg="Error preparing server: acme: Error 429 - urn:acme:error:rateLimited - Error creating new registration :: too many registrations for this IP"

What cause of this error and how to fix it?

Update

This problem not related to Traefik, when I try get cert by Certbot I get the same error.


问:
What am I missing - Symfony 3 Doctrine Entity ManyToMany?
So both my entities have the ID property on them, yet I am getting a validation error about said IDs for both tables described below. I have seen a few other example of this issue here on SO, and have followed their solutions but still have yet to get passed this validation error.

I have followed Doctrines docs too and I guess I am just missing something. I have only been working with Symfony/Doctrine for a couple months now so maybe I am missing a concept.

I run php bin/console doctrine:schema:validate

```<code>[Mapping]  FAIL - The entity-class 'FacetCoreBundle\Entity\FacetUser' mapping is invalid:
* The referenced column name 'id' has to be a primary key column on the target entity class 'FacetCoreBundle\Entity\FacetUser'.
* The referenced column name 'id' has to be a primary key column on the target entity class 'FacetCoreBundle\Entity\FacetRole'.

[Database] OK - The database schema is in sync with the mapping files.
</code>```

Ok well My FacetUser entity has the ID column and it is a primary key, same with the FacetRole entity.

FacetUser.php

```<code>/**
 * @ORM\Entity()
 * @ORM\Table(name="FACET_USER")
 */
class FacetUser implements LdapUserInterface, UserInterface
{
    /**
     * @var integer
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(name="ID", type="integer")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="LDAP_GUID", type="string", length=100, unique=true)
     * LdapAttribute objectguid
     */
    private $ldapGuid;

    /**
     * @var string
     *
     * @ORM\Column(name="USERNAME", type="string", length=20)
     * LdapAttribute samaccountname
     */
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(name="FIRST_NAME", type="string", length=100)
     * LdapAttribute givenname
     */
    private $firstName;

    /**
     * @var string
     *
     * @ORM\Column(name="LAST_NAME",type="string", length=100)
     * LdapAttribute sn
     */
    private $lastName;

    /**
     * @var string
     *
     * @ORM\Column(name="DISPLAY_NAME",type="string", length=255)
     * LdapAttribute displayname
     */
    private $displayName;

    /**
     * @var string
     *
     * @ORM\Column(name="TITLE",type="string", length=255)
     * LdapAttribute title
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="DEPARTMENT",type="string", length=100)
     * LdapAttribute department
     */
    private $department;

    /**
     * @var integer
     *
     * @ORM\Column(name="EMPLOYEE_ID",type="integer", length=10)
     * LdapAttribute employeeid
     */
    private $employeeId;

    /**
     * @var string
     *
     * @ORM\Column(name="MANAGER_USERNAME",type="string", length=7, nullable=true)
     */
    private $managerUsername;

    /**
     * @var string
     *
     * @ORM\Column(name="MANAGER_DISPLAY_NAME",type="string", length=255, nullable=true)
     */
    private $managerDisplayName;

    /**
     * @var string
     *
     * @ORM\Column(name="MANAGER_LDAP_GUID",type="string", length=100, nullable=true)
     */
    private $managerLdapGuid;

    /**
     * @var integer
     *
     * @ORM\Column(name="MANAGER_EMPLOYEE_ID",type="integer", length=7, nullable=true)
     */
    private $managerEmployeeId;

    /**
     * @var string
     *
     * @ORM\Column(name="EMAIL",type="string", nullable=true)
     * LdapAttribute mail
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(name="MOBILE",type="string", nullable=true)
     * LdapAttribute mobile
     */
    private $mobile;

    /**
     * @var array
     *
     * @ORM\Column(name="LDAP_MEMBERSHIPS",type="array", nullable=true)
     * LdapAttribute memberof
     */
    private $ldapMemberships = [];

    /**
     *
     * User can have many roles
     * @var array
     *
     * @ORM\ManyToMany(targetEntity="FacetCoreBundle\Entity\FacetRole")
     * @ORM\JoinTable(name="USER_ROLES",
     *     joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
     *     )
     *
     */
    private $roles;

    public function __construct()
    {
        $this->roles = new ArrayCollection();
    }

    ....
</code>```

FacetRole.php

```<code>/**
 * FacetRole
 *
 * @ORM\Table(name="FACET_ROLE")
 * @ORM\Entity
 */
class FacetRole
{
    /**
     * @var integer
     *
     * @ORM\Column(name="ID", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     */
    private $id;

    /**
     * @var string
     *
     * @Assert\NotBlank()
     * @Assert\Length(
     *      min = 9,
     *      max = 100,
     *      minMessage = "Role name must be at least {{ limit }} characters long",
     *      maxMessage = "Role name cannot be longer than {{ limit }} characters"
     * )
     * @ORM\Column(name="ROLE_NAME", type="string", length=255, nullable=false, unique=true)
     *
     */
    private $roleName;

    /**
     * @var string
     *
     * @Assert\NotBlank()
     * @Assert\Choice({"Y","N"})
     *
     * @ORM\Column(name="GRANTABLE", type="string", length=1, nullable=false)
     */
    private $grantable;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="CREATED_ON", type="date", nullable=false)
     */
    private $createdOn;

    /**
     * @var string
     *
     * @Assert\NotBlank()
     * @Assert\Length(
     *     min="10",
     *     max="255",
     *     minMessage="Description needs to be at least {{ limit }} characters long.",
     *     maxMessage="Description needs to be less then {{ limit }} characters long."
     * )
     *
     * @ORM\Column(name="DESCRIPTION", type="string", length=255, nullable=true)
     */
    private $description;

    /**
     * @var FacetUser
     *
     * @ORM\ManyToOne(targetEntity="FacetUser")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="CREATED_BY", referencedColumnName="ID", nullable=false)
     * })
     */
    private $createdBy;

    ....
</code>```

This creates the USER_ROLES table which stores the roles a user has been granted.

答:
Per a comment by Greg, be sure to check character case! Refer to the 3rd bullet of the Doctrine Portability docs

Case-sensitivity of column keys is handled differently in all databases, even depending on identifier quoting or not. You either need to know all the rules or fix the cases to lower/upper-case only.

Body:
So both my entities have the ID property on them, yet I am getting a validation error about said IDs for both tables described below. I have seen a few other example of this issue here on SO, and have followed their solutions but still have yet to get passed this validation error.

I have followed Doctrines docs too and I guess I am just missing something. I have only been working with Symfony/Doctrine for a couple months now so maybe I am missing a concept.

I run php bin/console doctrine:schema:validate

[Mapping]  FAIL - The entity-class 'FacetCoreBundle\Entity\FacetUser' mapping is invalid:
* The referenced column name 'id' has to be a primary key column on the target entity class 'FacetCoreBundle\Entity\FacetUser'.
* The referenced column name 'id' has to be a primary key column on the target entity class 'FacetCoreBundle\Entity\FacetRole'.

[Database] OK - The database schema is in sync with the mapping files.

Ok well My FacetUser entity has the ID column and it is a primary key, same with the FacetRole entity.

FacetUser.php

/**
 * @ORM\Entity()
 * @ORM\Table(name="FACET_USER")
 */
class FacetUser implements LdapUserInterface, UserInterface
{
    /**
     * @var integer
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(name="ID", type="integer")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="LDAP_GUID", type="string", length=100, unique=true)
     * LdapAttribute objectguid
     */
    private $ldapGuid;

    /**
     * @var string
     *
     * @ORM\Column(name="USERNAME", type="string", length=20)
     * LdapAttribute samaccountname
     */
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(name="FIRST_NAME", type="string", length=100)
     * LdapAttribute givenname
     */
    private $firstName;

    /**
     * @var string
     *
     * @ORM\Column(name="LAST_NAME",type="string", length=100)
     * LdapAttribute sn
     */
    private $lastName;

    /**
     * @var string
     *
     * @ORM\Column(name="DISPLAY_NAME",type="string", length=255)
     * LdapAttribute displayname
     */
    private $displayName;

    /**
     * @var string
     *
     * @ORM\Column(name="TITLE",type="string", length=255)
     * LdapAttribute title
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="DEPARTMENT",type="string", length=100)
     * LdapAttribute department
     */
    private $department;

    /**
     * @var integer
     *
     * @ORM\Column(name="EMPLOYEE_ID",type="integer", length=10)
     * LdapAttribute employeeid
     */
    private $employeeId;

    /**
     * @var string
     *
     * @ORM\Column(name="MANAGER_USERNAME",type="string", length=7, nullable=true)
     */
    private $managerUsername;

    /**
     * @var string
     *
     * @ORM\Column(name="MANAGER_DISPLAY_NAME",type="string", length=255, nullable=true)
     */
    private $managerDisplayName;

    /**
     * @var string
     *
     * @ORM\Column(name="MANAGER_LDAP_GUID",type="string", length=100, nullable=true)
     */
    private $managerLdapGuid;

    /**
     * @var integer
     *
     * @ORM\Column(name="MANAGER_EMPLOYEE_ID",type="integer", length=7, nullable=true)
     */
    private $managerEmployeeId;

    /**
     * @var string
     *
     * @ORM\Column(name="EMAIL",type="string", nullable=true)
     * LdapAttribute mail
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(name="MOBILE",type="string", nullable=true)
     * LdapAttribute mobile
     */
    private $mobile;

    /**
     * @var array
     *
     * @ORM\Column(name="LDAP_MEMBERSHIPS",type="array", nullable=true)
     * LdapAttribute memberof
     */
    private $ldapMemberships = [];

    /**
     *
     * User can have many roles
     * @var array
     *
     * @ORM\ManyToMany(targetEntity="FacetCoreBundle\Entity\FacetRole")
     * @ORM\JoinTable(name="USER_ROLES",
     *     joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
     *     )
     *
     */
    private $roles;

    public function __construct()
    {
        $this->roles = new ArrayCollection();
    }

    ....

FacetRole.php

/**
 * FacetRole
 *
 * @ORM\Table(name="FACET_ROLE")
 * @ORM\Entity
 */
class FacetRole
{
    /**
     * @var integer
     *
     * @ORM\Column(name="ID", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     */
    private $id;

    /**
     * @var string
     *
     * @Assert\NotBlank()
     * @Assert\Length(
     *      min = 9,
     *      max = 100,
     *      minMessage = "Role name must be at least {{ limit }} characters long",
     *      maxMessage = "Role name cannot be longer than {{ limit }} characters"
     * )
     * @ORM\Column(name="ROLE_NAME", type="string", length=255, nullable=false, unique=true)
     *
     */
    private $roleName;

    /**
     * @var string
     *
     * @Assert\NotBlank()
     * @Assert\Choice({"Y","N"})
     *
     * @ORM\Column(name="GRANTABLE", type="string", length=1, nullable=false)
     */
    private $grantable;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="CREATED_ON", type="date", nullable=false)
     */
    private $createdOn;

    /**
     * @var string
     *
     * @Assert\NotBlank()
     * @Assert\Length(
     *     min="10",
     *     max="255",
     *     minMessage="Description needs to be at least {{ limit }} characters long.",
     *     maxMessage="Description needs to be less then {{ limit }} characters long."
     * )
     *
     * @ORM\Column(name="DESCRIPTION", type="string", length=255, nullable=true)
     */
    private $description;

    /**
     * @var FacetUser
     *
     * @ORM\ManyToOne(targetEntity="FacetUser")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="CREATED_BY", referencedColumnName="ID", nullable=false)
     * })
     */
    private $createdBy;

    ....

This creates the USER_ROLES table which stores the roles a user has been granted.


问:
How to use svg clipPath?
After reading the doc, I tried this code:

```<code>main =
    svg [ width "100", height "100" ]
        [ Svg.clipPath [ id "clipCircle" ] [ circle [ cx "50", cy "50", r "50" ] [] ]
        , rect
            [ width "100"
            , height "100"
            , fill "red"
            , Svg.Attributes.clipPath "clipCircle"
            ]
            []
        ]
</code>```

The rectangle is not clipped. A red square is still displayed instead of a circle. What am I doing wrong?

答:
You need to use url(...) notation when referencing clipCircle:

```<code>Svg.Attributes.clipPath "url(#clipCircle)"
</code>```

Title: How to use svg clipPath?

Body:
After reading the doc, I tried this code:

main =
    svg [ width "100", height "100" ]
        [ Svg.clipPath [ id "clipCircle" ] [ circle [ cx "50", cy "50", r "50" ] [] ]
        , rect
            [ width "100"
            , height "100"
            , fill "red"
            , Svg.Attributes.clipPath "clipCircle"
            ]
            []
        ]

The rectangle is not clipped. A red square is still displayed instead of a circle. What am I doing wrong?

Body:
You need to use url(...) notation when referencing clipCircle:

Svg.Attributes.clipPath "url(#clipCircle)"


问:
How do I do backups in MySQL?
How do I do backups in MySQL?

I'm hoping there'll be something better than just running mysqldump every "x" hours.

Is there anything like SQL Server has, where you can take a full backup each day, and then incrementals every hour, so if your DB dies you can restore up to the latest backup?

Something like the DB log, where as long as the log doesn't die, you can restore up to the  exact point where the DB died?

Also, how do these things affect locking?
I'd expect the online transactions to be locked for a while if I do a mysqldump.

答:
I use a simple script that dumps the mysql database into a tar.gz file, encrypts it using gpg and sends it to a mail account (Google Mail, but that's irrelevant really)

The script is a Python script, which basically runs the following command, and emails the output file.

mysqldump -u theuser -p mypassword thedatabase | gzip -9 - | gpg -e -r 12345 -r 23456 > 2008_01_02.tar.gz.gpg

This is the entire backup. It also has the web-backup part, which just tar/gzips/encrypts the files. It's a fairly small site, so the web backups are much less than 20MB, so can be sent to the GMail account without problem (the MySQL dumps are tiny, about 300KB compressed). It's extremely basic, and won't scale very well. I run it once a week using cron.

I'm not quite sure how we're supposed to put longish scripts in answers, so I'll just shove it as a code-block..

```<code>#!/usr/bin/env python
#encoding:utf-8
#
# Creates a GPG encrypted web and database backups, and emails it

import os, sys, time, commands

################################################
### Config

DATE = time.strftime("%Y-%m-%d_%H-%M")

# MySQL login
SQL_USER = "mysqluser"
SQL_PASS = "mysqlpassword"
SQL_DB = "databasename"

# Email addresses
BACKUP_EMAIL=["email1@example.com", "email2@example.com"] # Array of email(s)
FROM_EMAIL = "root@myserver.com" # Only one email

# Temp backup locations
DB_BACKUP="/home/backupuser/db_backup/mysite_db-%(date)s.sql.gz.gpg" % {'date':DATE}
WEB_BACKUP="/home/backupuser/web_backup/mysite_web-%(date)s.tar.gz.gpg" % {'date':DATE}

# Email subjects
DB_EMAIL_SUBJECT="%(date)s/db/mysite" % {'date':DATE}
WEB_EMAIL_SUBJECT="%(date)s/web/mysite" % {'date':DATE}

GPG_RECP = ["MrAdmin","MrOtherAdmin"]
### end Config
################################################

################################################
### Process config
GPG_RECP = " ".join(["-r %s" % (x) for x in GPG_RECP]) # Format GPG_RECP as arg

sql_backup_command = "mysqldump -u %(SQL_USER)s -p%(SQL_PASS)s %(SQL_DB)s | gzip -9 - | gpg -e %(GPG_RECP)s > %(DB_BACKUP)s" % {
    'GPG_RECP':GPG_RECP,
    'DB_BACKUP':DB_BACKUP,
    'SQL_USER':SQL_USER,
    'SQL_PASS':SQL_PASS,
    'SQL_DB':SQL_DB
}

web_backup_command = "cd /var/www/; tar -c mysite.org/ | gzip -9 | gpg -e %(GPG_RECP)s > %(WEB_BACKUP)s" % {
    'GPG_RECP':GPG_RECP,
    'WEB_BACKUP':WEB_BACKUP,
}
# end Process config
################################################

################################################
### Main application
def main():
        """Main backup function"""
        print "Backing commencing at %s" % (DATE)

        # Run commands
        print "Creating db backup..."
        sql_status,sql_cmd_out = commands.getstatusoutput(sql_backup_command)
        if sql_status == 0:
                db_file_size = round(float( os.stat(DB_BACKUP)[6]  ) /1024/1024, 2) # Get file-size in MB
                print "..successful (%.2fMB)" % (db_file_size)
                try:
                    send_mail(
                        send_from = FROM_EMAIL,
                        send_to   = BACKUP_EMAIL,
                        subject   = DB_EMAIL_SUBJECT,
                        text      = "Database backup",
                        files     = [DB_BACKUP],
                        server    = "localhost"
                    )
                    print "Sending db backup successful"
                except Exception,errormsg:
                    print "Sending db backup FAILED. Error was:",errormsg
                #end try

                # Remove backup file
                print "Removing db backup..."
                try:
                        os.remove(DB_BACKUP)
                        print "...successful"
                except Exception, errormsg:
                        print "...FAILED. Error was: %s" % (errormsg)
                #end try
        else:
                print "Creating db backup FAILED. Output was:", sql_cmd_out
        #end if sql_status

        print "Creating web backup..."
        web_status,web_cmd_out = commands.getstatusoutput(web_backup_command)
        if web_status == 0:
                web_file_size = round(float( os.stat(WEB_BACKUP)[6]  ) /1024/1024, 2) # File size in MB
                print "..successful (%.2fMB)" % (web_file_size)
                try:
                    send_mail(
                        send_from = FROM_EMAIL,
                        send_to   = BACKUP_EMAIL,
                        subject   = WEB_EMAIL_SUBJECT,
                        text      = "Website backup",
                        files     = [WEB_BACKUP],
                        server    = "localhost"
                    )
                    print "Sending web backup successful"
                except Exception,errormsg:
                    print "Sending web backup FAIELD. Error was: %s" % (errormsg)
                #end try

                # Remove backup file
                print "Removing web backup..."
                try:
                        os.remove(WEB_BACKUP)
                        print "...successful"
                except Exception, errormsg:
                        print "...FAILED. Error was: %s" % (errormsg)
                #end try
        else:
                print "Creating web backup FAILED. Output was:", web_cmd_out
        #end if web_status
#end main
################################################

################################################
# Send email function

# needed email libs..
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
        assert type(send_to)==list
        assert type(files)==list

        msg = MIMEMultipart()
        msg['From'] = send_from
        msg['To'] = COMMASPACE.join(send_to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject

        msg.attach( MIMEText(text) )

        for f in files:
                part = MIMEBase('application', "octet-stream")
                try:
                    part.set_payload( open(f,"rb").read() )
                except Exception, errormsg:
                    raise IOError("File not found: %s"%(errormsg))
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
                msg.attach(part)
    #end for f

        smtp = smtplib.SMTP(server)
        smtp.sendmail(send_from, send_to, msg.as_string())
        smtp.close()
#end send_mail
################################################

if __name__ == '__main__':
        main()
</code>```

OwnerDisplayName: Daniel Magliola

ContentLicense: CC BY-SA 2.5

Title: How do I do backups in MySQL?

LastEditorDisplayName: Thomas Owens

Body:
I use a simple script that dumps the mysql database into a tar.gz file, encrypts it using gpg and sends it to a mail account (Google Mail, but that's irrelevant really)

The script is a Python script, which basically runs the following command, and emails the output file.

mysqldump -u theuser -p mypassword thedatabase | gzip -9 - | gpg -e -r 12345 -r 23456 > 2008_01_02.tar.gz.gpg

This is the entire backup. It also has the web-backup part, which just tar/gzips/encrypts the files. It's a fairly small site, so the web backups are much less than 20MB, so can be sent to the GMail account without problem (the MySQL dumps are tiny, about 300KB compressed). It's extremely basic, and won't scale very well. I run it once a week using cron.

I'm not quite sure how we're supposed to put longish scripts in answers, so I'll just shove it as a code-block..

#!/usr/bin/env python
#encoding:utf-8
#
# Creates a GPG encrypted web and database backups, and emails it

import os, sys, time, commands

################################################
### Config

DATE = time.strftime("%Y-%m-%d_%H-%M")

# MySQL login
SQL_USER = "mysqluser"
SQL_PASS = "mysqlpassword"
SQL_DB = "databasename"

# Email addresses
BACKUP_EMAIL=["email1@example.com", "email2@example.com"] # Array of email(s)
FROM_EMAIL = "root@myserver.com" # Only one email

# Temp backup locations
DB_BACKUP="/home/backupuser/db_backup/mysite_db-%(date)s.sql.gz.gpg" % {'date':DATE}
WEB_BACKUP="/home/backupuser/web_backup/mysite_web-%(date)s.tar.gz.gpg" % {'date':DATE}

# Email subjects
DB_EMAIL_SUBJECT="%(date)s/db/mysite" % {'date':DATE}
WEB_EMAIL_SUBJECT="%(date)s/web/mysite" % {'date':DATE}

GPG_RECP = ["MrAdmin","MrOtherAdmin"]
### end Config
################################################

################################################
### Process config
GPG_RECP = " ".join(["-r %s" % (x) for x in GPG_RECP]) # Format GPG_RECP as arg

sql_backup_command = "mysqldump -u %(SQL_USER)s -p%(SQL_PASS)s %(SQL_DB)s | gzip -9 - | gpg -e %(GPG_RECP)s > %(DB_BACKUP)s" % {
    'GPG_RECP':GPG_RECP,
    'DB_BACKUP':DB_BACKUP,
    'SQL_USER':SQL_USER,
    'SQL_PASS':SQL_PASS,
    'SQL_DB':SQL_DB
}

web_backup_command = "cd /var/www/; tar -c mysite.org/ | gzip -9 | gpg -e %(GPG_RECP)s > %(WEB_BACKUP)s" % {
    'GPG_RECP':GPG_RECP,
    'WEB_BACKUP':WEB_BACKUP,
}
# end Process config
################################################

################################################
### Main application
def main():
        """Main backup function"""
        print "Backing commencing at %s" % (DATE)

        # Run commands
        print "Creating db backup..."
        sql_status,sql_cmd_out = commands.getstatusoutput(sql_backup_command)
        if sql_status == 0:
                db_file_size = round(float( os.stat(DB_BACKUP)[6]  ) /1024/1024, 2) # Get file-size in MB
                print "..successful (%.2fMB)" % (db_file_size)
                try:
                    send_mail(
                        send_from = FROM_EMAIL,
                        send_to   = BACKUP_EMAIL,
                        subject   = DB_EMAIL_SUBJECT,
                        text      = "Database backup",
                        files     = [DB_BACKUP],
                        server    = "localhost"
                    )
                    print "Sending db backup successful"
                except Exception,errormsg:
                    print "Sending db backup FAILED. Error was:",errormsg
                #end try

                # Remove backup file
                print "Removing db backup..."
                try:
                        os.remove(DB_BACKUP)
                        print "...successful"
                except Exception, errormsg:
                        print "...FAILED. Error was: %s" % (errormsg)
                #end try
        else:
                print "Creating db backup FAILED. Output was:", sql_cmd_out
        #end if sql_status

        print "Creating web backup..."
        web_status,web_cmd_out = commands.getstatusoutput(web_backup_command)
        if web_status == 0:
                web_file_size = round(float( os.stat(WEB_BACKUP)[6]  ) /1024/1024, 2) # File size in MB
                print "..successful (%.2fMB)" % (web_file_size)
                try:
                    send_mail(
                        send_from = FROM_EMAIL,
                        send_to   = BACKUP_EMAIL,
                        subject   = WEB_EMAIL_SUBJECT,
                        text      = "Website backup",
                        files     = [WEB_BACKUP],
                        server    = "localhost"
                    )
                    print "Sending web backup successful"
                except Exception,errormsg:
                    print "Sending web backup FAIELD. Error was: %s" % (errormsg)
                #end try

                # Remove backup file
                print "Removing web backup..."
                try:
                        os.remove(WEB_BACKUP)
                        print "...successful"
                except Exception, errormsg:
                        print "...FAILED. Error was: %s" % (errormsg)
                #end try
        else:
                print "Creating web backup FAILED. Output was:", web_cmd_out
        #end if web_status
#end main
################################################

################################################
# Send email function

# needed email libs..
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
        assert type(send_to)==list
        assert type(files)==list

        msg = MIMEMultipart()
        msg['From'] = send_from
        msg['To'] = COMMASPACE.join(send_to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject

        msg.attach( MIMEText(text) )

        for f in files:
                part = MIMEBase('application', "octet-stream")
                try:
                    part.set_payload( open(f,"rb").read() )
                except Exception, errormsg:
                    raise IOError("File not found: %s"%(errormsg))
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
                msg.attach(part)
    #end for f

        smtp = smtplib.SMTP(server)
        smtp.sendmail(send_from, send_to, msg.as_string())
        smtp.close()
#end send_mail
################################################

if __name__ == '__main__':
        main()

OwnerDisplayName: dbr


问:
Is there a .NET built-in structure similar with Tuple (or a recommended way to build one) that is order invariant regarding the hashcode?
Is there a .NET built-in structure similar with Tuple (or a recommended way to build one) that is order invariant regarding the equality and hashcode?

The code below has the expected ishashequal=false, the structure I am looking for would return true.

```<code>var dict = new Dictionary<Tuple<char, char>, int>();
var x = new Tuple<char, char>('a', 'b');
var y = new Tuple<char, char>('b', 'a');
dict.Add(x, 1);
bool isequal = dict.ContainsKey(y);
</code>```

答:
Is there a .NET built-in structure similar with Tuple (or a recommended way to build one) that is order invariant regarding the equality and hashcode?

No. It would be broken if there was.

There's an over-simplification often given of "a hash code of a key must not change", which is wrong. Really, "a key must not change while being used as a key" which the hash code not changing should reflect. If something changes in a way that changes how it compares to other items then the hash code must change to reflect that. This mustn't happen while it is used as a key, but that means the key must not change. Otherwise if you created an object, changed it and then used it as a key, it wouldn't work.

Okay, so to alter your question

Is there a .NET built-in structure similar with Tuple (or a recommended way to build one) that is order invariant regarding the equality and hashcode [when the component items are invariant]?

Yes, Tuple would be one example. As would ValueTuple and anonymous objects composed of the same parts.

The code below has the expected ishashequal=false, the structure I am looking for would return true

That's something different again. A tuple is a finite sequence of a given number of elements. Being a sequence means that order is signficant. We don't expect the tuple (a, b) to hash to the same thing as (b, a) because (a, b) is a different tuple to (b, a) and so must not be considered equal and ideally (but not a strict requirement) would not have the same hash code.

Indeed Tuple<int, string> can't have the same elements in different orders at all.

Tuple represents tuples, but you are describing a use of a finite set. The finite set {a, b} is the same as the finite set {b, a}  because order is not significant.

You need to do one of two things.

Create a structure to represent a finite set of two elements

```<code>public sealed class FiniteSet2<T> : IEquatable<FiniteSet2<T>>
{
    public T First { get; }
    public T Second { get; }
    public FiniteSet2(T first, T second)
    {
        First = first;
        Second = second;
    }

    public bool Equals(FiniteSet2<T> other)
    {
        if ((object)other != null)
        {
            return false;
        }

        // Test for same order.
        if (EqualityComparer<T>.Default.Equals(First, other.First))
        {
            return EqualityComparer<T>.Default.Equals(Second, other.Second);
        }

        // Test for different order.
        return EqualityComparer<T>.Default.Equals(First, other.Second)
            && EqualityComparer<T>.Default.Equals(Second, other.First)
    }

    public override bool Equals(object obj) => Equals(obj as FiniteSet2<T>);

    // Deliberately matches elements in different order.
    public override int GetHashCode() => First.GetHashCode() ^ Second.GetHashCode();
}
</code>```

Or if you really do need to use tuples, define an appropriate comparer:

```<code>public sealed class CompareAsSetEqualityComparer<T> : IEqualityComparer<Tuple<T, T>>
{
    public bool Equals(Tuple<T, T> x, Tuple<T, T> y)
    {
        if ((object)x == y)
        {
            return true;
        }

        if ((object)x == null | (object)y == null)
        {
            return false;
        }

        if (EqualityComparer<T>.Default.Equals(x.Item1, y.Item1))
        {
            return EqualityComparer<T>.Default.Equals(x.Item2, y.Item2);
        }

        return EqualityComparer<T>.Default.Equals(x.Item1, y.Item2)
            && EqualityComparer<T>.Default.Equals(x.Item2, y.Item1);
    }

    public int GetHashCode(Tuple<T, T> obj) =>
        obj == null ? 0 : obj.Item1.GetHashCode() ^ obj.Item2.GetHashCode();
}
</code>```

Of course, if the elements are reference types they could themselves be mutated, which would still mutate the otherwise-immutable set or tuple.

(Aside: A recent improvement in the jitter means that it no longer makes sense to memoise EqualityComparer<T>.Default as the sequence EqualityComparer<T>.Default.Equals(…) gets inlined).

Body:
Is there a .NET built-in structure similar with Tuple (or a recommended way to build one) that is order invariant regarding the equality and hashcode?

The code below has the expected ishashequal=false, the structure I am looking for would return true.

var dict = new Dictionary<Tuple<char, char>, int>();
var x = new Tuple<char, char>('a', 'b');
var y = new Tuple<char, char>('b', 'a');
dict.Add(x, 1);
bool isequal = dict.ContainsKey(y);

Body:
Is there a .NET built-in structure similar with Tuple (or a recommended way to build one) that is order invariant regarding the equality and hashcode?

No. It would be broken if there was.

There's an over-simplification often given of "a hash code of a key must not change", which is wrong. Really, "a key must not change while being used as a key" which the hash code not changing should reflect. If something changes in a way that changes how it compares to other items then the hash code must change to reflect that. This mustn't happen while it is used as a key, but that means the key must not change. Otherwise if you created an object, changed it and then used it as a key, it wouldn't work.

Okay, so to alter your question

Is there a .NET built-in structure similar with Tuple (or a recommended way to build one) that is order invariant regarding the equality and hashcode [when the component items are invariant]?

Yes, Tuple would be one example. As would ValueTuple and anonymous objects composed of the same parts.

The code below has the expected ishashequal=false, the structure I am looking for would return true

That's something different again. A tuple is a finite sequence of a given number of elements. Being a sequence means that order is signficant. We don't expect the tuple (a, b) to hash to the same thing as (b, a) because (a, b) is a different tuple to (b, a) and so must not be considered equal and ideally (but not a strict requirement) would not have the same hash code.

Indeed Tuple<int, string> can't have the same elements in different orders at all.

Tuple represents tuples, but you are describing a use of a finite set. The finite set {a, b} is the same as the finite set {b, a}  because order is not significant.

You need to do one of two things.

Create a structure to represent a finite set of two elements

public sealed class FiniteSet2<T> : IEquatable<FiniteSet2<T>>
{
    public T First { get; }
    public T Second { get; }
    public FiniteSet2(T first, T second)
    {
        First = first;
        Second = second;
    }

    public bool Equals(FiniteSet2<T> other)
    {
        if ((object)other != null)
        {
            return false;
        }

        // Test for same order.
        if (EqualityComparer<T>.Default.Equals(First, other.First))
        {
            return EqualityComparer<T>.Default.Equals(Second, other.Second);
        }

        // Test for different order.
        return EqualityComparer<T>.Default.Equals(First, other.Second)
            && EqualityComparer<T>.Default.Equals(Second, other.First)
    }

    public override bool Equals(object obj) => Equals(obj as FiniteSet2<T>);

    // Deliberately matches elements in different order.
    public override int GetHashCode() => First.GetHashCode() ^ Second.GetHashCode();
}

Or if you really do need to use tuples, define an appropriate comparer:

public sealed class CompareAsSetEqualityComparer<T> : IEqualityComparer<Tuple<T, T>>
{
    public bool Equals(Tuple<T, T> x, Tuple<T, T> y)
    {
        if ((object)x == y)
        {
            return true;
        }

        if ((object)x == null | (object)y == null)
        {
            return false;
        }

        if (EqualityComparer<T>.Default.Equals(x.Item1, y.Item1))
        {
            return EqualityComparer<T>.Default.Equals(x.Item2, y.Item2);
        }

        return EqualityComparer<T>.Default.Equals(x.Item1, y.Item2)
            && EqualityComparer<T>.Default.Equals(x.Item2, y.Item1);
    }

    public int GetHashCode(Tuple<T, T> obj) =>
        obj == null ? 0 : obj.Item1.GetHashCode() ^ obj.Item2.GetHashCode();
}

Of course, if the elements are reference types they could themselves be mutated, which would still mutate the otherwise-immutable set or tuple.

(Aside: A recent improvement in the jitter means that it no longer makes sense to memoise EqualityComparer<T>.Default as the sequence EqualityComparer<T>.Default.Equals(…) gets inlined).


问:
MySQL, need some advice about how to setup sitemaps for a site with a lot of pages?
At the moment I have a sitemap specified in google webmaster tools, which looks like this..

www.mydomain.com/sitemap.php?from=20000&max=10000

This shows 10,000 pages from record id 20,000

I have 80,000 pages and my site maps are slow.

I don't want to end up having lots of sitemaps with these paramaters (as only google knows about them). But the pages pump out too many pages from the database and are really slow.

Can someone advise me what will be both fast and comprehensive and available to all bots ?

答:
Set up a cron job which creates static sitemaps.

Set it to run daily, hourly, or in whatever schedule you like.

Serve the static files to search engines (no load on database, fast, etc.).

Use an index file of sitemaps


问:
Kotlin - Error: Could not find or load main class _DefaultPackage
I followed the Kotlin tutorial for eclipse here : Getting Started With Eclipse Luna

However, I'm running into this error:

```<code>Error: Could not find or load main class _DefaultPackage
</code>```

Anyone who knows to get around this?

答:
In my case I was having this problem while trying to run the program using the Application Gradle plugin. The problem was in the mainClassName property using single quotes instead of double ones

This didn't work:

```<code>mainClassName = 'demo.HelloWorldKt'
</code>```

With double quotes, it works:

```<code>mainClassName = "demo.HelloWorldKt"
</code>```

Body:
I followed the Kotlin tutorial for eclipse here : Getting Started With Eclipse Luna

However, I'm running into this error:

Error: Could not find or load main class _DefaultPackage

Anyone who knows to get around this?

Body:
In my case I was having this problem while trying to run the program using the Application Gradle plugin. The problem was in the mainClassName property using single quotes instead of double ones

This didn't work:

mainClassName = 'demo.HelloWorldKt'

With double quotes, it works:

mainClassName = "demo.HelloWorldKt"


问:
What is the JPA equivalent to Hibernate's foreign id generator?
What is the JPA equivalent to Hibernate's foreign id generator?</p>

```<code><id column="PERSON_ID" name="id" type="java.lang.Long">
   <generator class="foreign">
      <param name="property">person</param>
   </generator>
</id>
</code>```

答:
For what it's worth JPA 2.0 adds a @MappedBy annotation that can be used for foreign key importing. Starting from Christian's example and boring briefly from Ken Chan's:

```<code>@Id
@Column
private Long personId;

@ManyToOne
@JoinColumn(name = "personId")
@MapsId
private Person person;
</code>```

I know this question is from quite some time ago, but since I stumbled across it when solving the same issue and then dug up @MappedBy, I thought I'd add it for anyone who runs into this later.

Body:
What is the JPA equivalent to Hibernate's foreign id generator?

<id column="PERSON_ID" name="id" type="java.lang.Long">
   <generator class="foreign">
      <param name="property">person</param>
   </generator>
</id>

Body:
For what it's worth JPA 2.0 adds a @MappedBy annotation that can be used for foreign key importing. Starting from Christian's example and boring briefly from Ken Chan's:

@Id
@Column
private Long personId;

@ManyToOne
@JoinColumn(name = "personId")
@MapsId
private Person person;

I know this question is from quite some time ago, but since I stumbled across it when solving the same issue and then dug up @MappedBy, I thought I'd add it for anyone who runs into this later.


问:
Scala implicits and type aliases
Let's say I have the following piece of code:

```<code>object Potato extends App {

  type CoolString = String
  type AwesomeString = String

  def potato(string: String)(implicit coolString: CoolString, awesomeString: AwesomeString) = {
    s"$string is a string. Oh, but don't forget - $coolString and also $awesomeString"
  }

  implicit val ice : CoolString = "Really Cold Ice"
  implicit val awe : AwesomeString = "Awe inspiring object"

  potato("Stringerino")

}
</code>```

This code fails with a problem

```<code>[error] ... ambiguous implicit values:
[error]  both value ice in object Potato of type => Potato.CoolString
[error]  and value awe in object Potato of type => Potato.AwesomeString
[error]  match expected type Potato.CoolString
[error]   potato("Stringerino")
</code>```

Is such use of implicits impossible?

答:
Is such use of implicits impossible?

Not only is it impossible, it is dangerous to rely on such a method taking in a type as general as String as an implicit. Think about it, any String instance in scope will be an eligible candidate to get passed into the method!

A type alias is just, well, a type alias, nothing more. To the compiler both CoolString and AwesomeString are merely String.

A better approach is to leverage Tagged Types. For example, this is a tagged type using shapeless:

```<code>import shapeless.tag.@@

trait CoolString
trait AwesomeString

type ReallyCoolString = String @@ CoolString
type ReallyAwesomeString = String @@ AwesomeString
</code>```

And then:

```<code>import shapeless.tag

def potato(string: String)(implicit coolString: ReallyCoolString, awesomeString: ReallyAwesomeString) = {
  s"$string is a string. Oh, but don't forget - $coolString and also $awesomeString"
}

def main(args: Array[String]): Unit = {
  implicit val ice = tag[CoolString][String]("Really Cold Ice")
  implicit val awe = tag[AwesomeString][String]("Awe inspiring object")

  println(potato("Stringerino"))
}
</code>```

Yields:

```<code>Stringerino is a string.
Oh, but don't forget - Really Cold Ice and also Awe inspiring object
</code>```

Title: Scala implicits and type aliases

Body:
Let's say I have the following piece of code:

object Potato extends App {

  type CoolString = String
  type AwesomeString = String

  def potato(string: String)(implicit coolString: CoolString, awesomeString: AwesomeString) = {
    s"$string is a string. Oh, but don't forget - $coolString and also $awesomeString"
  }

  implicit val ice : CoolString = "Really Cold Ice"
  implicit val awe : AwesomeString = "Awe inspiring object"

  potato("Stringerino")

}

This code fails with a problem

[error] ... ambiguous implicit values:
[error]  both value ice in object Potato of type => Potato.CoolString
[error]  and value awe in object Potato of type => Potato.AwesomeString
[error]  match expected type Potato.CoolString
[error]   potato("Stringerino")

Is such use of implicits impossible?

Body:
Is such use of implicits impossible?

Not only is it impossible, it is dangerous to rely on such a method taking in a type as general as String as an implicit. Think about it, any String instance in scope will be an eligible candidate to get passed into the method!

A type alias is just, well, a type alias, nothing more. To the compiler both CoolString and AwesomeString are merely String.

A better approach is to leverage Tagged Types. For example, this is a tagged type using shapeless:

import shapeless.tag.@@

trait CoolString
trait AwesomeString

type ReallyCoolString = String @@ CoolString
type ReallyAwesomeString = String @@ AwesomeString

And then:

import shapeless.tag

def potato(string: String)(implicit coolString: ReallyCoolString, awesomeString: ReallyAwesomeString) = {
  s"$string is a string. Oh, but don't forget - $coolString and also $awesomeString"
}

def main(args: Array[String]): Unit = {
  implicit val ice = tag[CoolString][String]("Really Cold Ice")
  implicit val awe = tag[AwesomeString][String]("Awe inspiring object")

  println(potato("Stringerino"))
}

Yields:

Stringerino is a string.
Oh, but don't forget - Really Cold Ice and also Awe inspiring object


问:
Complex condition and returned value using xpath
I'm using xpath in order to get values from xml. I found a particular situation:

```<code><Docs>
    <Doc>
       <tag1>0</tag1>
       <tag2>150.0</tag2>
    </Doc>
    <Doc>
       <tag1>45</tag1>
       <tag2>0</tag2>
    </Doc>
</Docs>
</code>```

There are two posibilities for each Doc entity:

case 1: if (tag1 = 0 and tag2 != 0) or (tag2 = 0 and tag1 != 0), I need to return the non-zero value.

case 2: Maybe the two fields are 0. I need to return 0

UPDATE1:
For example:
Suppose that I query the first node Doc (/Docs/doc[0]). I need to get 150.0. For the second one (/Docs/doc[1]) I need to get 45.

How can I solve this using just xpath?

答:
Simple xpath expression:

```<code>//Doc/*[text() != '0']/text()
</code>```

XPath result:

```<code>150.0
45
</code>```

Body:
I'm using xpath in order to get values from xml. I found a particular situation:

<Docs>
    <Doc>
       <tag1>0</tag1>
       <tag2>150.0</tag2>
    </Doc>
    <Doc>
       <tag1>45</tag1>
       <tag2>0</tag2>
    </Doc>
</Docs>

There are two posibilities for each Doc entity:

case 1: if (tag1 = 0 and tag2 != 0) or (tag2 = 0 and tag1 != 0), I need to return the non-zero value.

case 2: Maybe the two fields are 0. I need to return 0

UPDATE1:
For example:
Suppose that I query the first node Doc (/Docs/doc[0]). I need to get 150.0. For the second one (/Docs/doc[1]) I need to get 45.

How can I solve this using just xpath?

Body:
Simple xpath expression:

//Doc/*[text() != '0']/text()

XPath result:

150.0
45


问:
Convert many values of a categorical column python
I had to recently map many categories in one data frame column into a few higher subcategories. I was wondering if there is a more concise way to achieve this as
the one below. </p>

```<code>df_to_map = pd.DataFrame({"cities": [ 'Thessaloniki', 'Geel', 'Bern', 'Dublin', 'Hanover' ,
 'Gurabo','Buenos Aires','Manati' ,'Panama', 'Lima',
'Washington', 'Huston', 'Kairo']})

Aggregate_cities={
 'Thessaloniki':'Europe', 'Geel':'Europe', 'Bern':'Europe', 'Dublin':'Europe', 'Hanover':'Europe',
 'Gurabo':'Latin America','Manati' :'Latin America', 'Panama':'Latin America', 'Lima': 'Latin America' ,'Buenos Aires': 'Latin America',
'Washington':'North America', 'Huston':'North America', 'Boston': 'North America'
 }

df_to_map['continent']= df_to_map.cities.map(Aggregate_cities)
</code>```

答:
As far as speed as concerned, agreed with @jezrael that you currently have just about the fastest solution for this problem.

However, you commented,

Would it be possible to put all the European cities in one list?

Yes, if you want to, form a dictionary with reversed key/value structure:

```<code>Aggregate_cities = {
    'Europe' : ['Thessaloniki', 'Geel', 'Bern', 'Dublin', 'Hanover'],
    'Latin Ameriac': ['Gurabo', 'Manati', 'Panama', 'Lima', 'Buenos Aires'],
    'North America' : ['Washington', 'Huston', 'Boston']
    }
</code>```

Then map your Series to the reverse of this:

```<code>df_to_map['continent']= df_to_map.cities.map(
    {v: k for k, cities in Aggregate_cities.items() for v in cities})
</code>```

Is this faster?  No, because your current solution doesn't require this reversal through dictionary comprehension.  But perhaps this is more readable and easier to maintain.

What you cannot do is use a list of cities as the keys in your dictionary.

Python's dictionary implementation reduces the average complexity of
  dictionary lookups to O(1) by requiring that key objects provide a
  "hash" function.

...and lists don't fulfill this requirement:

```<code>hash([1, 2, 3])
# ---------------------------------------------------------------------------
# TypeError                                 Traceback (most recent call last)
# <ipython-input-97-0b995650570c> in <module>()
# ----> 1 hash([1, 2, 3])
#
# TypeError: unhashable type: 'list'
</code>```

Body:
I had to recently map many categories in one data frame column into a few higher subcategories. I was wondering if there is a more concise way to achieve this as
the one below.

df_to_map = pd.DataFrame({"cities": [ 'Thessaloniki', 'Geel', 'Bern', 'Dublin', 'Hanover' ,
 'Gurabo','Buenos Aires','Manati' ,'Panama', 'Lima',
'Washington', 'Huston', 'Kairo']})

Aggregate_cities={
 'Thessaloniki':'Europe', 'Geel':'Europe', 'Bern':'Europe', 'Dublin':'Europe', 'Hanover':'Europe',
 'Gurabo':'Latin America','Manati' :'Latin America', 'Panama':'Latin America', 'Lima': 'Latin America' ,'Buenos Aires': 'Latin America',
'Washington':'North America', 'Huston':'North America', 'Boston': 'North America'
 }

df_to_map['continent']= df_to_map.cities.map(Aggregate_cities)

Body:
As far as speed as concerned, agreed with @jezrael that you currently have just about the fastest solution for this problem.

However, you commented,

Would it be possible to put all the European cities in one list?

Yes, if you want to, form a dictionary with reversed key/value structure:

Aggregate_cities = {
    'Europe' : ['Thessaloniki', 'Geel', 'Bern', 'Dublin', 'Hanover'],
    'Latin Ameriac': ['Gurabo', 'Manati', 'Panama', 'Lima', 'Buenos Aires'],
    'North America' : ['Washington', 'Huston', 'Boston']
    }

Then map your Series to the reverse of this:

df_to_map['continent']= df_to_map.cities.map(
    {v: k for k, cities in Aggregate_cities.items() for v in cities})

Is this faster?  No, because your current solution doesn't require this reversal through dictionary comprehension.  But perhaps this is more readable and easier to maintain.

What you cannot do is use a list of cities as the keys in your dictionary.

Python's dictionary implementation reduces the average complexity of
  dictionary lookups to O(1) by requiring that key objects provide a
  "hash" function.

...and lists don't fulfill this requirement:

hash([1, 2, 3])
# ---------------------------------------------------------------------------
# TypeError                                 Traceback (most recent call last)
# <ipython-input-97-0b995650570c> in <module>()
# ----> 1 hash([1, 2, 3])
#
# TypeError: unhashable type: 'list'


问:
Jetty - set system property
I run webapp on Jetty. The configuration for the app come from file that lives on the same server where Jetty is running. Inside the app I rely on the system property to obtain path to the file so I can parse it. E.g.

```<code>final String loc = System.getProperty(FACTORY);
</code>```

Now I can start jetty with D switch to provide $FACTORY on the command line but I rather put it in jetty.xml if I can. I know there is <SystemProperty /> tag but that seems to just provide system value that already exists for the <Set/> tag. Can someone give me example how this can be achieved? (If it can be achieved)

答:
For the record, if you really need to do this through system properties (I did) you can do this to append for example -Drun.mode=staging to the system properties:

```<code><Call class="java.lang.System" name="setProperties">
  <Arg>
    <New class="java.util.Properties">
      <Call name="putAll">
        <Arg><Call class="java.lang.System" name="getProperties"/></Arg>
      </Call>
      <Call name="setProperty">
        <Arg>run.mode</Arg>
        <Arg>staging</Arg>
      </Call>
    </New>
  </Arg>
</Call>
</code>```

... and yes you can probably can program your application through this ;-)

Title: Jetty - set system property

Body:
I run webapp on Jetty. The configuration for the app come from file that lives on the same server where Jetty is running. Inside the app I rely on the system property to obtain path to the file so I can parse it. E.g.

final String loc = System.getProperty(FACTORY);

Now I can start jetty with D switch to provide $FACTORY on the command line but I rather put it in jetty.xml if I can. I know there is <SystemProperty /> tag but that seems to just provide system value that already exists for the <Set/> tag. Can someone give me example how this can be achieved? (If it can be achieved)

Body:
For the record, if you really need to do this through system properties (I did) you can do this to append for example -Drun.mode=staging to the system properties:

<Call class="java.lang.System" name="setProperties">
  <Arg>
    <New class="java.util.Properties">
      <Call name="putAll">
        <Arg><Call class="java.lang.System" name="getProperties"/></Arg>
      </Call>
      <Call name="setProperty">
        <Arg>run.mode</Arg>
        <Arg>staging</Arg>
      </Call>
    </New>
  </Arg>
</Call>

... and yes you can probably can program your application through this ;-)


问:
How can i Filter records on column type return by jdbcCursorItemReader and process same kind of records at the same time in spring batch
How can I fetch record for a unique I'd at a time using jdbccursoritem reader and process them and then fetch records for another id and then process.</p>

答:
This requirement goes slightly against the main idea of processing records. If your bussiness logic requires that the records of the same batch id are processed together, you can try making an enclosing class (BatchIdRecords?) that represents a batch id and includes all the records in that batch id. This way you'll have a ItemReader, and a similar processor, which can deal with them, as you want, Delete first, and then Update.

The query of the reader will have to sort by batch id, and maybe do some manual buffering (ugh) unless you can aggregate them beforehand.

This has nothing to do with spring batch configuration, though.


问:
Obj can not be resolved
```<code>public class IPAddress {
    public static void main(String[] args) throws Throwable {
        String[] cmd = {"C:\\WINDOWS\\system32\\cmd.exe","/c","start"};

        try {
            Runtime runtime = Runtime.getRuntime();
            Process p = runtime.exec(cmd);

        } catch (java.io.IOException exception) {
            System.out.println("Caught IOException: " + exception.getMessage());
        }

        String release = "ipconfig /release";
        String output1 = obj.executeCommand(release);
        String renew = "ipconfig /renew";
        String output2 = obj.executeCommand(renew);

        System.out.println(output1);
        System.out.println(output2);
    }
}
</code>```

I am making an IP Changer, and on "String output1" and "String output2" i get an error that says obj can not be resolved. I have tried resolving this but to no evail

答: You need to create an obj object. Since there isn't any obj object in your main method, it cannot find it. You need to create that object inside main method.

Title: Obj can not be resolved

Body:
public class IPAddress {
    public static void main(String[] args) throws Throwable {
        String[] cmd = {"C:\\WINDOWS\\system32\\cmd.exe","/c","start"};

        try {
            Runtime runtime = Runtime.getRuntime();
            Process p = runtime.exec(cmd);

        } catch (java.io.IOException exception) {
            System.out.println("Caught IOException: " + exception.getMessage());
        }

        String release = "ipconfig /release";
        String output1 = obj.executeCommand(release);
        String renew = "ipconfig /renew";
        String output2 = obj.executeCommand(renew);

        System.out.println(output1);
        System.out.println(output2);
    }
}

I am making an IP Changer, and on "String output1" and "String output2" i get an error that says obj can not be resolved. I have tried resolving this but to no evail


问:
How To Write Series Of Number In Excel
I want to write numbers in excel starting from 000001 till 999999

I have done like this =TEXT(A2,"000001") but i am not been able to generate series even though not able to separate this in different attributes

Further I want to distribute each number in each different cell for example like this

```<code>A           B         C        D         E         F       G

000001      0         0        0         0         0       1

000002      0         0        0         0         0       2

till

999999      9          9       9         9          9       9
</code>```

答:
Use following formuls to B1 cell and drag then right and down as needed.

```<code>=MID($A1,COLUMNS($A$1:A$1),1)
</code>```

See the screenshot.

Title: How To Write Series Of Number In Excel

Body:
I want to write numbers in excel starting from 000001 till 999999

I have done like this =TEXT(A2,"000001") but i am not been able to generate series even though not able to separate this in different attributes

Further I want to distribute each number in each different cell for example like this

A           B         C        D         E         F       G

000001      0         0        0         0         0       1

000002      0         0        0         0         0       2

till

999999      9          9       9         9          9       9

Body:
Use following formuls to B1 cell and drag then right and down as needed.

=MID($A1,COLUMNS($A$1:A$1),1)

See the screenshot.


问:
Spring constructor injection with lots of fields
I have a Spring component that has 8 members.

I am currently autowiring these 8 members with field injection.

I now want make these members private final, and do constructor injection to set them.

This is easy enough to do, but now I have a component constructor with 8 parameters.

I know I can use setter injection and set these values in an XML file, but this I don't want to do.

Are there any other alternatives?

EDIT:

This component just does a single thing. But that involves calling several other services. Hence the 8 injections

答:
Firstly, there is no alternative.

Secondly, if a contructor has 8 parameters, it is not designed  properly. I think you should rethink about the class structure and responsibility. Consider splitting the class into two or three separate beans and inject those.

If a constructor has 8 arguments, in most cases it will be vioalating SRP(Single Responsibility principle)


问:
Sending JSON to PHP via jQuery AJAX
I have looked at a bunch of questions/answers on here and none of them seem to solve my problem.  I am integrating a payment system that returns a JSON string via a JS library that I then need to parse on the server to compare the hash values to ensure that it is valid.  So I get their response and attempt to pass it via jQuery AJAX to a PHP file on the server.  The response I get from the payment system is valid JSON.  If I pass it directly the result I get on the server seems to be URL encoded.  If I JSON.stringify() it, it adds a bunch of extra quotes which results in invalid JSON.

```<code>function isValidJSON($str) {
    json_decode($str);
    return json_last_error() == JSON_ERROR_NONE;
}

$json_params = file_get_contents("php://input");
error_log($json_params);

//error_log($_POST['jsresp']);
//$respObj = json_decode(stripslashes($_POST['jsresp']));

//error_log($json_params);

if (strlen($json_params) > 0 && isValidJSON($json_params)) {
    $respObj = json_decode($json_params);
} else {
    error_log('bad json '.$json_params);
}

$result = 0;

$resp = json_encode($respObj->Response);
$hash = $respObj->Hash;
error_log($hash);
$calcHash = base64_encode(hash_hmac('sha512', $resp, $app->getSageClientSecret(), true));
error_log($calcHash);

if($hash === $calcHash) {
    $result = 1;
}

$app->updateCartResponse($_COOKIE['qid'], $result);
</code>```

And here is the jQuery AJAX call to send the data:

```<code>$(document).on('click', 'button#sps-close.sps.btn.btn-primary', function(){
    var resp = $("#resp_holder").val();
    $.ajax({
        url: "<?=$env?>sources/processors/process_hash.php",
        data: { jsresp : resp },
        type: "post",
        //dataType: "json",
        success: function( data ) {
            // nothing to do here.
        }
    });
    var url = $("#redirect_url").val();
    if(url != "") {
        location.href = $("#redirect_url").val();
    }
});
</code>```

When I do it this way, the JSON that gets to the server looks like this:

```<code>jsresp%5Bresponse%5D=%7B%22requestId%22%3A%22443594%22%2C%22gatewayResponse%22%3A%7B%22status%22%3A%22Approved%22%2C%22reference%22%3A%22EBGHNHChw0%22%2C%22message%22%3A%22APPROVED+658658%22%2C%22code%22%3A%22658658%22%2C%22cvvResult%22%3A%22P%22%2C%22avsResult%22%3A%22+%22%2C%22riskCode%22%3A%2200%22%2C%22networkId%22%3A%2210%22%2C%22isPurchaseCard%22%3Afalse%2C%22orderNumber%22%3A%22443594%22%2C%22transactionId%22%3A%22NDViMWYzNmEwNWNiOGQxZjIwOTAwNzU4MmVjYzJhMWQ%22%2C%22timestamp%22%3A%222017-11-16T23%3A17%3A12.6584893-05%3A00%22%7D%7D&jsresp%5Bhash%5D=bgd1e0Cxhj5s1FQaUFFYk7BMnSIl4Ez1jPMopZFp%2B4MyN9chFZZoo%2F3IuZPX7bbQ%2BRyaReKN1CNJXxRmjnLMRQ%3D%3D
</code>```

I don't understand what I'm doing wrong or how to get it there properly.

答:
First i will advice you to look at the value in your #resp_holder, if the value there is correct as you want it, then you can post it using anyhow you want it, json is a string, and as long as that string conforms to json standard, and they are no special characters in the it like &, then you can decode it in your php.

You can use html or json dataType to post it.

Title: Sending JSON to PHP via jQuery AJAX

Body:
I have looked at a bunch of questions/answers on here and none of them seem to solve my problem.  I am integrating a payment system that returns a JSON string via a JS library that I then need to parse on the server to compare the hash values to ensure that it is valid.  So I get their response and attempt to pass it via jQuery AJAX to a PHP file on the server.  The response I get from the payment system is valid JSON.  If I pass it directly the result I get on the server seems to be URL encoded.  If I JSON.stringify() it, it adds a bunch of extra quotes which results in invalid JSON.

function isValidJSON($str) {
    json_decode($str);
    return json_last_error() == JSON_ERROR_NONE;
}

$json_params = file_get_contents("php://input");
error_log($json_params);

//error_log($_POST['jsresp']);
//$respObj = json_decode(stripslashes($_POST['jsresp']));

//error_log($json_params);

if (strlen($json_params) > 0 && isValidJSON($json_params)) {
    $respObj = json_decode($json_params);
} else {
    error_log('bad json '.$json_params);
}

$result = 0;

$resp = json_encode($respObj->Response);
$hash = $respObj->Hash;
error_log($hash);
$calcHash = base64_encode(hash_hmac('sha512', $resp, $app->getSageClientSecret(), true));
error_log($calcHash);

if($hash === $calcHash) {
    $result = 1;
}

$app->updateCartResponse($_COOKIE['qid'], $result);

And here is the jQuery AJAX call to send the data:

$(document).on('click', 'button#sps-close.sps.btn.btn-primary', function(){
    var resp = $("#resp_holder").val();
    $.ajax({
        url: "<?=$env?>sources/processors/process_hash.php",
        data: { jsresp : resp },
        type: "post",
        //dataType: "json",
        success: function( data ) {
            // nothing to do here.
        }
    });
    var url = $("#redirect_url").val();
    if(url != "") {
        location.href = $("#redirect_url").val();
    }
});

When I do it this way, the JSON that gets to the server looks like this:

jsresp%5Bresponse%5D=%7B%22requestId%22%3A%22443594%22%2C%22gatewayResponse%22%3A%7B%22status%22%3A%22Approved%22%2C%22reference%22%3A%22EBGHNHChw0%22%2C%22message%22%3A%22APPROVED+658658%22%2C%22code%22%3A%22658658%22%2C%22cvvResult%22%3A%22P%22%2C%22avsResult%22%3A%22+%22%2C%22riskCode%22%3A%2200%22%2C%22networkId%22%3A%2210%22%2C%22isPurchaseCard%22%3Afalse%2C%22orderNumber%22%3A%22443594%22%2C%22transactionId%22%3A%22NDViMWYzNmEwNWNiOGQxZjIwOTAwNzU4MmVjYzJhMWQ%22%2C%22timestamp%22%3A%222017-11-16T23%3A17%3A12.6584893-05%3A00%22%7D%7D&jsresp%5Bhash%5D=bgd1e0Cxhj5s1FQaUFFYk7BMnSIl4Ez1jPMopZFp%2B4MyN9chFZZoo%2F3IuZPX7bbQ%2BRyaReKN1CNJXxRmjnLMRQ%3D%3D

I don't understand what I'm doing wrong or how to get it there properly.


答: Nowhere in your code have you created a obj object. This is why you are getting an error from the compiler, explaining that it does not know where it has come from.

Title: Obj can not be resolved


问:
Toggle div tag on button click
I have many buttons with id b1, b2 ... and each has a div tag after it with id q1, q2...
I want to toggle the div tag when the corresponding button is clicked. Example: When b1 is clicked q1 should toggle.
It is given here. http://upscfever.com/upsc-fever/en/topper/en-toppers.html

$(document).ready(function(){
  $(".info").hide();
  $("#b1").click(function(){
    $("#q1").toggle();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b1" type="button" class="btn btn-primary btn-block"></button>

<div id="q1" class="info"></div></code>```

But as i might have 100 of buttons, how can i do the same thing without adding click on each button?

答:
Using attribute startswith selector ^, get the id of button and get the index value from it first.

```<code>$("[id^='b']").click(function(){
    var index = this.id.match(/\d+$/)[0];
    $("#q" + index ).toggle();
});
</code>```

Demo

$(document).ready(function() {
  $(".info").hide();
  $("[id^='b']").click(function() {
    var index = this.id.match(/\d+$/)[0];
    $("#q" + index).toggle();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b1" type="button" class="btn btn-primary btn-block">Button1</button>
<div id="q1" class="info">Info1</div>

<button id="b2" type="button" class="btn btn-primary btn-block">Button2</button>
<div id="q2" class="info">Info2</div>

<button id="b3" type="button" class="btn btn-primary btn-block">Button3</button>
<div id="q3" class="info">Info3</div>

<button id="b4" type="button" class="btn btn-primary btn-block">Button4</button>
<div id="q4" class="info">Info4</div></code>```

Title: Toggle div tag on button click

Body:
I have many buttons with id b1, b2 ... and each has a div tag after it with id q1, q2...
I want to toggle the div tag when the corresponding button is clicked. Example: When b1 is clicked q1 should toggle.
It is given here. http://upscfever.com/upsc-fever/en/topper/en-toppers.html

$(document).ready(function(){
  $(".info").hide();
  $("#b1").click(function(){
    $("#q1").toggle();
  });
});

<button id="b1" type="button" class="btn btn-primary btn-block"></button>

But as i might have 100 of buttons, how can i do the same thing without adding click on each button?

Body:
Using attribute startswith selector ^, get the id of button and get the index value from it first.

$("[id^='b']").click(function(){
    var index = this.id.match(/\d+$/)[0];
    $("#q" + index ).toggle();
});

Demo

$(document).ready(function() {
  $(".info").hide();
  $("[id^='b']").click(function() {
    var index = this.id.match(/\d+$/)[0];
    $("#q" + index).toggle();
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b1" type="button" class="btn btn-primary btn-block">Button1</button>
<div id="q1" class="info">Info1</div>

<button id="b2" type="button" class="btn btn-primary btn-block">Button2</button>
<div id="q2" class="info">Info2</div>

<button id="b3" type="button" class="btn btn-primary btn-block">Button3</button>
<div id="q3" class="info">Info3</div>

<button id="b4" type="button" class="btn btn-primary btn-block">Button4</button>
<div id="q4" class="info">Info4</div>


问:
TIBCO BW5- Mavenization using maven commands
I am trying to mavenize tibco bw5 existing projects using maven commands based on https://fastconnect.github.io/tibco-factory/bw-maven-plugin/mavenization.html

According to which,

I created a folder and then excecuted : "mvn archetype:generate-DarchetypeGroupId=fr.fastconnect.factory.tibco.bw.maven -DarchetypeArtifactId=archetype-client-root-project " which creates a root folder with a root POM.xml.

Then i placed an existing bw5 project folder that contains vcrepo.dat and bw code, in the root folder and tried to mavenize the project :
mvn bw:mavenize-bw-projects -DrootProjectArtifactId=rootmavenartifact -DrootProjectGroupId=com.rootmavengroupId -DrootProjectVersion=1.0.0 -DdoIt=true

which gives me follwing error and mavenisation is not successful

```<code>[INFO] Scanning for projects...
    [INFO]
    [INFO] -------------------------------------------------------------------
    [INFO] Building Root for ClientMavenProj project 1.0-SNAPSHOT
    [INFO] ---------------------------------------------------------------------
    [INFO]
    [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ rootProject ---
    [INFO]
    [INFO] --------------------------------------------------------------------
    [INFO] Building Root for ClientMavenProj project 1.0-SNAPSHOT
    [INFO] --------------------------------------------------------------------
    [INFO]
    [INFO] --- bw-maven-plugin:2.4.1:mavenize-bw-projects (default-cli) @ rootProject ---
    [INFO] Scanning recursively 'C:\trialMaven2\rootProject' with patterns '[**/]'
    [INFO] ---
    [INFO] rootProject
    [INFO]   Location of the BW project    : tibco_practise
    [INFO]   Location of the project (POM) : C:\trialMaven2\rootProject
    [INFO]   The root project is           : com.rootmavengroupId:rootmavenartifact:1.0.0
    [INFO]   The root project location is  :
    [INFO]   Mavenized project will be     : com.rootmavengroupId:rootproject:1.0.0
    [INFO]
    **[WARNING] Mavenization failed : No common path element found for 'C:\trialMaven2\rootProject\C:\trialMaven2\rootProject' and ''**
    [INFO]
    [INFO] 1 project was found.
    **[INFO] 1 project failed the mavenization.
    [INFO] 0 project was successfully mavenized.**
    [INFO] ---------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ---------------------------------------------------------------------
    [INFO] Total time: 5.286 s
    [INFO] Finished at: 2017-11-13T21:51:41+05:30
    [INFO] Final Memory: 18M/269M
    [INFO] --------------------------------------------------------------------
</code>```

Note:Attaching root pom for reference

答:
You can use <relativePath> tag for the parent path

```<code><parent>
    <groupId>fr.fastconnect.factory.tibco</groupId>
    <artifactId>fc-tibco-factory</artifactId>
    <version>2.4.1</version>
    <relativePath>PARENT_RELATIVE_PATH</relativePath>
</parent>
</code>```

Body:
I am trying to mavenize tibco bw5 existing projects using maven commands based on https://fastconnect.github.io/tibco-factory/bw-maven-plugin/mavenization.html

According to which,

I created a folder and then excecuted : "mvn archetype:generate-DarchetypeGroupId=fr.fastconnect.factory.tibco.bw.maven -DarchetypeArtifactId=archetype-client-root-project " which creates a root folder with a root POM.xml.

Then i placed an existing bw5 project folder that contains vcrepo.dat and bw code, in the root folder and tried to mavenize the project :
mvn bw:mavenize-bw-projects -DrootProjectArtifactId=rootmavenartifact -DrootProjectGroupId=com.rootmavengroupId -DrootProjectVersion=1.0.0 -DdoIt=true

which gives me follwing error and mavenisation is not successful

[INFO] Scanning for projects...
    [INFO]
    [INFO] -------------------------------------------------------------------
    [INFO] Building Root for ClientMavenProj project 1.0-SNAPSHOT
    [INFO] ---------------------------------------------------------------------
    [INFO]
    [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ rootProject ---
    [INFO]
    [INFO] --------------------------------------------------------------------
    [INFO] Building Root for ClientMavenProj project 1.0-SNAPSHOT
    [INFO] --------------------------------------------------------------------
    [INFO]
    [INFO] --- bw-maven-plugin:2.4.1:mavenize-bw-projects (default-cli) @ rootProject ---
    [INFO] Scanning recursively 'C:\trialMaven2\rootProject' with patterns '[**/]'
    [INFO] ---
    [INFO] rootProject
    [INFO]   Location of the BW project    : tibco_practise
    [INFO]   Location of the project (POM) : C:\trialMaven2\rootProject
    [INFO]   The root project is           : com.rootmavengroupId:rootmavenartifact:1.0.0
    [INFO]   The root project location is  :
    [INFO]   Mavenized project will be     : com.rootmavengroupId:rootproject:1.0.0
    [INFO]
    **[WARNING] Mavenization failed : No common path element found for 'C:\trialMaven2\rootProject\C:\trialMaven2\rootProject' and ''**
    [INFO]
    [INFO] 1 project was found.
    **[INFO] 1 project failed the mavenization.
    [INFO] 0 project was successfully mavenized.**
    [INFO] ---------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ---------------------------------------------------------------------
    [INFO] Total time: 5.286 s
    [INFO] Finished at: 2017-11-13T21:51:41+05:30
    [INFO] Final Memory: 18M/269M
    [INFO] --------------------------------------------------------------------

Note:Attaching root pom for reference

Body:
You can use <relativePath> tag for the parent path

<parent>
    <groupId>fr.fastconnect.factory.tibco</groupId>
    <artifactId>fc-tibco-factory</artifactId>
    <version>2.4.1</version>
    <relativePath>PARENT_RELATIVE_PATH</relativePath>
</parent>


答:
Here you go with a solution

$(".info").hide();
$("button").click(function(){
  $(this).next('div.info').toggle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-primary btn-block">Button 1</button>

<div class="info">Div 1</div>
<button type="button" class="btn btn-primary btn-block">Button 2</button>

<div class="info">Div 2</div></code>```

No need to targeting using id, you can do it using jQuery .next()

Hope this will help you.

Title: Toggle div tag on button click

Body:
Here you go with a solution

$(".info").hide();
$("button").click(function(){
  $(this).next('div.info').toggle();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-primary btn-block">Button 1</button>

<div class="info">Div 1</div>
<button type="button" class="btn btn-primary btn-block">Button 2</button>

<div class="info">Div 2</div>

No need to targeting using id, you can do it using jQuery .next()

Hope this will help you.


问:
Using same column multiple times in WHERE clause
I have a following table structure.

USERS

PROPERTY_VALUE

PROPERTY_NAME

USER_PROPERTY_MAP

I am trying to retrieve user/s from the users table who have matching properties in property_value table.

A single user can have multiple properties. The example data here has 2 properties for user '1', but there can be more than 2. I want to use all those user properties in the WHERE clause.

This query works if user has a single property but it fails for more than 1 properties:

```<code>SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE (pn.id = 1 AND pv.id IN (SELECT id FROM property_value WHERE value like '101')
AND pn.id = 2 AND pv.id IN (SELECT id FROM property_value WHERE value like '102')) and u.user_name = 'user1' and u.city = 'city1'
</code>```

I understand since the query has pn.id = 1 AND pn.id = 2 it will always fail because pn.id can be either 1 or 2 but not both at the same time. So how can I re-write it to make it work for n number of properties?

In above example data there is only one user with id = 1 that has both matching properties used in the WHERE clause. The query should return a single record with all columns of the USERS table.

To clarify my requirements

I am working on an application that has a users list page on the UI listing all users in the system. This list has information like user id, user name, city etc. - all columns of the in USERS table. Users can have properties as detailed in the database model above.

The users list page also provides functionality to search users based on these properties. When searching for users with 2 properties, 'property1' and 'property2', the page should fetch and display only matching rows. Based on the test data above, only user '1' fits the bill.

A user with 4 properties including 'property1' and 'property2' qualifies. But a user with only one property 'property1' would be excluded due to the missing 'property2'.

答:
```<code>SELECT *
  FROM users u
 WHERE u.id IN(
         select m.user_id
           from property_value v
           join USER_PROPERTY_MAP m
             on v.id=m.property_value_id
          where (v.property_name_id, v.value) in( (1, '101'), (2, '102') )
          group by m.user_id
         having count(*)=2
      )
</code>```

OR

```<code>SELECT u.id
  FROM users u
 INNER JOIN user_property_map upm ON u.id = upm.user_id
 INNER JOIN property_value pv ON upm.property_value_id = pv.id
 WHERE (pv.property_name_id=1 and pv.value='101')
    OR (pv.property_name_id=2 and pv.value='102')
 GROUP BY u.id
HAVING count(*)=2
</code>```

No property_name table needed in query if propery_name_id are kown.

Body:
I have a following table structure.

USERS

PROPERTY_VALUE

PROPERTY_NAME

USER_PROPERTY_MAP

I am trying to retrieve user/s from the users table who have matching properties in property_value table.

A single user can have multiple properties. The example data here has 2 properties for user '1', but there can be more than 2. I want to use all those user properties in the WHERE clause.

This query works if user has a single property but it fails for more than 1 properties:

SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE (pn.id = 1 AND pv.id IN (SELECT id FROM property_value WHERE value like '101')
AND pn.id = 2 AND pv.id IN (SELECT id FROM property_value WHERE value like '102')) and u.user_name = 'user1' and u.city = 'city1'

I understand since the query has pn.id = 1 AND pn.id = 2 it will always fail because pn.id can be either 1 or 2 but not both at the same time. So how can I re-write it to make it work for n number of properties?

In above example data there is only one user with id = 1 that has both matching properties used in the WHERE clause. The query should return a single record with all columns of the USERS table.

To clarify my requirements

I am working on an application that has a users list page on the UI listing all users in the system. This list has information like user id, user name, city etc. - all columns of the in USERS table. Users can have properties as detailed in the database model above.

The users list page also provides functionality to search users based on these properties. When searching for users with 2 properties, 'property1' and 'property2', the page should fetch and display only matching rows. Based on the test data above, only user '1' fits the bill.

A user with 4 properties including 'property1' and 'property2' qualifies. But a user with only one property 'property1' would be excluded due to the missing 'property2'.

Body:
SELECT *
  FROM users u
 WHERE u.id IN(
         select m.user_id
           from property_value v
           join USER_PROPERTY_MAP m
             on v.id=m.property_value_id
          where (v.property_name_id, v.value) in( (1, '101'), (2, '102') )
          group by m.user_id
         having count(*)=2
      )

OR

SELECT u.id
  FROM users u
 INNER JOIN user_property_map upm ON u.id = upm.user_id
 INNER JOIN property_value pv ON upm.property_value_id = pv.id
 WHERE (pv.property_name_id=1 and pv.value='101')
    OR (pv.property_name_id=2 and pv.value='102')
 GROUP BY u.id
HAVING count(*)=2

No property_name table needed in query if propery_name_id are kown.


问:
How to access the correct `this` inside a callback
I have a constructor function which registers an event handler:

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', function () {
        alert(this.data);
    });
}

// Mock transport object
var transport = {
    on: function(event, callback) {
        setTimeout(callback, 1000);
    }
};

// called as
var obj = new MyConstructor('foo', transport);```
</div>
</div>
</p>
<p>However, I'm not able to access the <code>data</code> property of the created object inside the callback. It looks like <code>this</code> does not refer to the object that was created, but to another one.</p>
<p>I also tried to use an object method instead of an anonymous function:</p>
```function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', this.alert);
}

MyConstructor.prototype.alert = function() {
    alert(this.name);
};
```

but it exhibits the same problems.

How can I access the correct object?

答:
We can not bind this to setTimeout(), as it always executes with the global object (Window). If you want to access the this context in the callback function then by using bind() to the callback function, we can achieve it as:

```<code>setTimeout(function(){
    this.methodName();
}.bind(this), 2000);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a constructor function which registers an event handler:

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', function () {
        alert(this.data);
    });
}

// Mock transport object
var transport = {
    on: function(event, callback) {
        setTimeout(callback, 1000);
    }
};

// called as
var obj = new MyConstructor('foo', transport);

However, I'm not able to access the data property of the created object inside the callback. It looks like this does not refer to the object that was created, but to another one.

I also tried to use an object method instead of an anonymous function:

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', this.alert);
}

MyConstructor.prototype.alert = function() {
    alert(this.name);
};

but it exhibits the same problems.

How can I access the correct object?

Body:
We can not bind this to setTimeout(), as it always executes with the global object (Window). If you want to access the this context in the callback function then by using bind() to the callback function, we can achieve it as:

setTimeout(function(){
    this.methodName();
}.bind(this), 2000);


问:
Add multple maps to list in Java
I have multiple maps (like 100 or more). I want to put them to list like this:

ArrayList<HashMap> mapsList = new ArryaList(Arrays.asList(map1, map2, map3 ..., map100);

is there a way to put all this in here in one loop to avoid writing the same name one hundred times changing only number in it?

@EDIT

I have this map like this:

```<code>HashMap<String, Integer> map1 = new HashMap<>();
map1.put("x", 47);
...
nextmap here...
</code>```

答:
Use a method to generate a map, insert the value and add it in the List.

```<code>public Map<String, Integer> newMap(Values... values){
    Map<String, integer> map = new HashMap<>();
    for(Values v : values){
        map.put(v.getKey(), v.getValue());
    }
    list.add(map);

    return map;
}
</code>```

Where Values hold both key and value

```<code>class Values{
    String key;
    Integer value;

    public Values(String key, Integer value){
        ...
    }

    //getters;
}
</code>```

That way, you don't need to play with map1, map2, map3, .. but simply call that method.

```<code>newMap(new Values("x", 47), new Values("y", 12));
newMap(new Values("x", 4));
</code>```

...

Title: Add multple maps to list in Java

Body:
I have multiple maps (like 100 or more). I want to put them to list like this:

ArrayList<HashMap> mapsList = new ArryaList(Arrays.asList(map1, map2, map3 ..., map100);

is there a way to put all this in here in one loop to avoid writing the same name one hundred times changing only number in it?

@EDIT

I have this map like this:

HashMap<String, Integer> map1 = new HashMap<>();
map1.put("x", 47);
...
nextmap here...

Body:
Use a method to generate a map, insert the value and add it in the List.

public Map<String, Integer> newMap(Values... values){
    Map<String, integer> map = new HashMap<>();
    for(Values v : values){
        map.put(v.getKey(), v.getValue());
    }
    list.add(map);

    return map;
}

Where Values hold both key and value

class Values{
    String key;
    Integer value;

    public Values(String key, Integer value){
        ...
    }

    //getters;
}

That way, you don't need to play with map1, map2, map3, .. but simply call that method.

newMap(new Values("x", 47), new Values("y", 12));
newMap(new Values("x", 4));

...


问:
AngularJS - Override CSS
I've inherited an AngularJS project which uses the 3rd party grid, Ag-grid.  There is an ag-grid-style.css file that has the following:

```<code>.ag-pinned-left-header.hasCategoryCol .ag-header-cell, .ag-pinned-left-cols-viewport.hasCategoryCol .ag-row .ag-cell {
    width: calc(100% / 7) !important;
}
</code>```

This works great for the grid already in use, the grid is nicely divided into 7 columns.
My problem is I have created new code, also using ag-grid, but I need the new grid divided into 6 columns, not 7.  I end up with one extra empty column.  Using Chrome for debugging and going into the developer tools, I can see the above CSS and if I change the 7 to a 6, my grid displays perfectly.  My question is what is the easiest way to accomplish what I want?  I've been trying to adjust the styling in code but haven't succeeded yet.  Suggestions?

答:
I would simply add the modified CSS to a CSS file that renders after all other third-party library CSS files. When you have an !important that happens after another !important, the second one overrides the first. So by adding the CSS to your website it should be fine.

```<code>.ag-pinned-left-header.hasCategoryCol .ag-header-cell, .ag-pinned-left-cols-
viewport.hasCategoryCol .ag-row .ag-cell {
    width: calc(100% / 6) !important;
}
</code>```

Title: AngularJS - Override CSS

Body:
I've inherited an AngularJS project which uses the 3rd party grid, Ag-grid.  There is an ag-grid-style.css file that has the following:

.ag-pinned-left-header.hasCategoryCol .ag-header-cell, .ag-pinned-left-cols-viewport.hasCategoryCol .ag-row .ag-cell {
    width: calc(100% / 7) !important;
}

This works great for the grid already in use, the grid is nicely divided into 7 columns.
My problem is I have created new code, also using ag-grid, but I need the new grid divided into 6 columns, not 7.  I end up with one extra empty column.  Using Chrome for debugging and going into the developer tools, I can see the above CSS and if I change the 7 to a 6, my grid displays perfectly.  My question is what is the easiest way to accomplish what I want?  I've been trying to adjust the styling in code but haven't succeeded yet.  Suggestions?

Body:
I would simply add the modified CSS to a CSS file that renders after all other third-party library CSS files. When you have an !important that happens after another !important, the second one overrides the first. So by adding the CSS to your website it should be fine.

.ag-pinned-left-header.hasCategoryCol .ag-header-cell, .ag-pinned-left-cols-
viewport.hasCategoryCol .ag-row .ag-cell {
    width: calc(100% / 6) !important;
}