问:
Disable dropdown option after selecting (even for new visitors)
I'm working on a website where people can sign up for an event. We've got 8 different teams, based on superhero's. Every team should choose 1 of the 8 superheroes, but non of them should choose the same one.

Is it possible to write some code to disable an option (for every new visitor of the website) after someone has chosen that superhero?

So if 2 people has chosen a superhero, there will only be 6 choices left. These six will be visible, but non-clickable.

So my html form code is (some titles/names are Dutch;)):

```<code><form action="inschrijfformulier.php" method="post" id="cc-m-form-6876142651" target="_blank" class="cc-m-form cc-m-form-layout-1" onsubmit="javascript: setTimeout(function(){location.reload();}, 1000);return true;">
                                                <div class="cc-m-form-loading"></div>

                                                <div class="cc-m-form-view-sortable">
                                                    <div class="cc-m-form-view-element cc-m-form-select" data-action="element" required>
                                                        <label for="ma6b8be54cf86a6410">
    <div>Kies welke held jouw team is!</div>
    </label>
                                                        <div class="cc-m-form-view-input-wrapper">
                                                            <select name="teamnaam" class="cc-m-form-element-input" required>
                                                                <option value="" selected disabled hidden>Selecteer</option>
<option value="Superman">Superman</option>
<option value="Batman">Batman</option>
<option value="X-Men">X-Men</option>
<option value="MegaMindy">Mega Mindy</option>
<option value="Spiderman">Spiderman</option>
<option value="TheHulk">The Hulk</option>
<option value="HitGirl">Hit Girl</option>
<option value="Meerminman">Meerminman</option></select></div></div>
<input type="submit" value="Naar betalen" data-action="formButton">
</code>```

So if you make a selection and submit the form, it wil link to inschrijfformulie.php, this .php file contains:

```<code><?php
$name = $_POST['teamnaam'];
$email = $_POST['email'];
$rekeninghouder = $_POST['rekeninghouder'];
$aantalspelers = $_POST['aantalspelers'];
$spelernamen = $_POST['spelernamen'];
$formcontent="Teamnaam: $name \nEmail: $email \nRekeninghouder: $rekeninghouder \nAantal spelers: $aantalspelers \nSpelers: $spelernamen";
$recipient = "info@sidekickevents.nl";
$subject = "Inschrijfformulier";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header("Location: https://www.ticketkantoor.nl/shop/bubbelvoetbal");
 exit;
?>
</code>```

This makes sure that I'm getting an email with the information they fill in. This works great, I also can see which superhero they've chosen.
Hopefully someone can explain it, because I'm new to PHP!
Thanks in advance!

答:
You can use the code,</p>

```<code>$('select').change(function(){
    var value = $(this).val();
    $(this).children('option').each(function() {
        if ( $(this).val() === value ) {
             $(this).attr('disabled', true);
        }
    });
});
</code>```

Body:
I'm working on a website where people can sign up for an event. We've got 8 different teams, based on superhero's. Every team should choose 1 of the 8 superheroes, but non of them should choose the same one.

Is it possible to write some code to disable an option (for every new visitor of the website) after someone has chosen that superhero?

So if 2 people has chosen a superhero, there will only be 6 choices left. These six will be visible, but non-clickable.

So my html form code is (some titles/names are Dutch;)):

<form action="inschrijfformulier.php" method="post" id="cc-m-form-6876142651" target="_blank" class="cc-m-form cc-m-form-layout-1" onsubmit="javascript: setTimeout(function(){location.reload();}, 1000);return true;">

Kies welke held jouw team is!

                                                            <select name="teamnaam" class="cc-m-form-element-input" required>
                                                                <option value="" selected disabled hidden>Selecteer</option>
<option value="Superman">Superman</option>
<option value="Batman">Batman</option>
<option value="X-Men">X-Men</option>
<option value="MegaMindy">Mega Mindy</option>
<option value="Spiderman">Spiderman</option>
<option value="TheHulk">The Hulk</option>
<option value="HitGirl">Hit Girl</option>
<option value="Meerminman">Meerminman</option></select>

<input type="submit" value="Naar betalen" data-action="formButton">

So if you make a selection and submit the form, it wil link to inschrijfformulie.php, this .php file contains:

<?php
$name = $_POST['teamnaam'];
$email = $_POST['email'];
$rekeninghouder = $_POST['rekeninghouder'];
$aantalspelers = $_POST['aantalspelers'];
$spelernamen = $_POST['spelernamen'];
$formcontent="Teamnaam: $name \nEmail: $email \nRekeninghouder: $rekeninghouder \nAantal spelers: $aantalspelers \nSpelers: $spelernamen";
$recipient = "info@sidekickevents.nl";
$subject = "Inschrijfformulier";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header("Location: https://www.ticketkantoor.nl/shop/bubbelvoetbal");
 exit;
?>

This makes sure that I'm getting an email with the information they fill in. This works great, I also can see which superhero they've chosen.
Hopefully someone can explain it, because I'm new to PHP!
Thanks in advance!

Body:
You can use the code,

$('select').change(function(){
    var value = $(this).val();
    $(this).children('option').each(function() {
        if ( $(this).val() === value ) {
             $(this).attr('disabled', true);
        }
    });
});


来源: stackexchange

问:
Open some custom inbound ports e.g. 8077 by using 80 or 3389
I am launching one windows instance in AWS(Amazon) using Java and trying to open few inbound ports like 445, 555, 9089, 8077 for my work.

I have also tried using Security groups port opening but it is only opening the inbound ports at security group level, not at the system level.

Provide me some solution so that I can open either before launch itself or after launch is also fine.

Here is my sample code.

```<code>package com.corenttech.engine.shift;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.AvailabilityZone;
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
import com.amazonaws.services.ec2.model.CreateKeyPairResult;
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult;
import com.amazonaws.services.ec2.model.DescribeImagesResult;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest;
import com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult;
import com.amazonaws.services.ec2.model.Image;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.IpPermission;
import com.amazonaws.services.ec2.model.KeyPair;
import com.amazonaws.services.ec2.model.Placement;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.SecurityGroup;
import com.amazonaws.services.ec2.model.StartInstancesRequest;
import com.amazonaws.services.ec2.model.StopInstancesRequest;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
import com.amazonaws.services.ec2.model.TerminateInstancesResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;

public class AwsConnection {

static AmazonEC2Client ec2;
static Logger logger = Logger.getLogger(AwsConnection.class);
static String Group_name;

private AwsConnection() {

}

public static void main(String[] args) throws Exception {
    String credentialsString;
    AmazonCredentials cred = new AmazonCredentials();
    cred.setAccessKeyId("accesskey");
    cred.setSecretKey("secretKey");

    credentialsString = "accessKey = " + cred.getAccessKeyId() + "\n";
    credentialsString += "secretKey = " + cred.getSecretKey();
    logger.info("credentialString :" + credentialsString);

    InputStream inpStrm = new ByteArrayInputStream(credentialsString.getBytes());
    AWSCredentials credentials = new PropertiesCredentials(inpStrm);
    ec2 = new AmazonEC2Client(credentials);

    try {

        AuthorizeSecurityGroupIngressRequest secrtyGrp = createSecurityGroup();
        List<String> groupName = updatePortToSecurityGroup(cred, secrtyGrp);

//            listAvailableZones();
//            getAvailableImages();
//            getRunningInstances();

        /* Launching a new AMI instance*/
        List<String> runninginstanceIDs = createAMInstances("ami-76f0061f", 1, 1, "Maas", "t1.micro", "us-east-1a", groupName);

        String runningInstanceID = runninginstanceIDs.iterator().next();
        logger.info("New instance created successfully : " + runningInstanceID);

        TimeUnit.SECONDS.sleep(60);
        createTagName(runningInstanceID);
        TimeUnit.SECONDS.sleep(1);
        getRunningInstances();

    } catch (AmazonServiceException ase) {
        logger.info("Caught Exception: " + ase.getMessage());
        logger.info("Reponse Status Code: " + ase.getStatusCode());
        logger.info("Error Code: " + ase.getErrorCode());
        logger.info("Request ID: " + ase.getRequestId());

    }

}

public static AuthorizeSecurityGroupIngressRequest createSecurityGroup() {
    Group_name = "group_test" + 1; //name of the group
    CreateSecurityGroupRequest r1 = new CreateSecurityGroupRequest(Group_name, "test group"); // this is security group description
    ec2.createSecurityGroup(r1);
    AuthorizeSecurityGroupIngressRequest r2 = new AuthorizeSecurityGroupIngressRequest();
    r2.setGroupName(Group_name);
    return r2;
}

public static List<String> updatePortToSecurityGroup(AmazonCredentials cred, AuthorizeSecurityGroupIngressRequest secrtyGrp) {
    logger.info("<<Amazon updatePortToSecurityGroup start>>");
    String protocol = "tcp";
    int port = 8077;

    IpPermission perm1 = new IpPermission();
    perm1.setIpProtocol(protocol);
    perm1.setFromPort(port);
    perm1.setToPort(port);
    List<String> ipRanges = new ArrayList<>();
    ipRanges.add("0.0.0.0/0");
    perm1.setIpRanges(ipRanges);

    IpPermission permission2 = new IpPermission();
    permission2.setIpProtocol("tcp");
    permission2.setFromPort(445);
    permission2.setToPort(445);
    List<String> ipRanges2 = new ArrayList<>();
    ipRanges2.add("0.0.0.0/0");
    permission2.setIpRanges(ipRanges2);

    IpPermission permission3 = new IpPermission();
    permission3.setIpProtocol("tcp");
    permission3.setFromPort(555);
    permission3.setToPort(555);
    List<String> ipRanges3 = new ArrayList<String>();
    ipRanges3.add("0.0.0.0/0");
    permission3.setIpRanges(ipRanges3);

    IpPermission permission4 = new IpPermission();
    permission4.setIpProtocol("tcp");
    permission4.setFromPort(8080);
    permission4.setToPort(8080);
    List<String> ipRanges4 = new ArrayList<>();
    ipRanges4.add("0.0.0.0/0");
    permission4.setIpRanges(ipRanges4);

    IpPermission permission5 = new IpPermission();
    permission5.setIpProtocol("tcp");
    permission5.setFromPort(3389);
    permission5.setToPort(3389);
    List<String> ipRanges5 = new ArrayList<>();
    ipRanges5.add("0.0.0.0/0");
    permission5.setIpRanges(ipRanges5);

    IpPermission permission6 = new IpPermission();
    permission6.setIpProtocol("tcp");
    permission6.setFromPort(9089);
    permission6.setToPort(9089);
    List<String> ipRanges6 = new ArrayList<>();
    ipRanges6.add("0.0.0.0/0");
    permission6.setIpRanges(ipRanges6);

    IpPermission permission7 = new IpPermission();
    permission7.setIpProtocol("tcp");
    permission7.setFromPort(80);
    permission7.setToPort(80);
    List<String> ipRanges7 = new ArrayList<>();
    ipRanges7.add("0.0.0.0/0");
    permission7.setIpRanges(ipRanges7);

    IpPermission permission8 = new IpPermission();
    permission8.setIpProtocol("tcp");
    permission8.setFromPort(443);
    permission8.setToPort(443);
    List<String> ipRanges8 = new ArrayList<>();
    ipRanges8.add("0.0.0.0/0");
    permission8.setIpRanges(ipRanges8);

    IpPermission permission9 = new IpPermission();
    permission9.setIpProtocol("tcp");
    permission9.setFromPort(23);
    permission9.setToPort(23);
    List<String> ipRanges9 = new ArrayList<>();
    ipRanges9.add("0.0.0.0/0");
    permission9.setIpRanges(ipRanges9);

    List<IpPermission> permissions = new ArrayList<>();
    permissions.add(perm1);
    permissions.add(permission2);
    permissions.add(permission3);
    permissions.add(permission4);
    permissions.add(permission5);
    permissions.add(permission6);
    permissions.add(permission7);
    permissions.add(permission8);
    permissions.add(permission9);

    secrtyGrp.setIpPermissions(permissions);

    ec2.authorizeSecurityGroupIngress(secrtyGrp);
    List<String> groupName = new ArrayList<>();
    groupName.add(Group_name);

    logger.info("<<Amazon updatePortToSecurityGroup end>>");
    return groupName;
}

public static List<SecurityGroup> findAllSecurityGroups() {
    DescribeSecurityGroupsRequest securityRequest = new DescribeSecurityGroupsRequest();
    DescribeSecurityGroupsResult securityDescription = ec2.describeSecurityGroups(securityRequest);
    return securityDescription.getSecurityGroups();
}

/**
 * Create one or more running instances of a given AMI. If you want to lunch
 * a machine in the amazon cloud this is the method that you are looking
 * for. The key method is RunInstancesResult runInstancesRes =
 * ec2.runInstances(request); that return a unique id of the reservation for
 * retrieving the running instances. By the way if you do that you will have
 * to query the amazon APIs, it will be slower and will cost you but is good
 * to know that this information will be always there.
 *
 * @param amiId unique ID of the machine
 * @param min minimum number of machines
 * @param max maximum number of machines that you want to run
 * @param keyPairName unique id of the key pair that will be used for
 * running an instance
 * @param insType type of instance (i.e. m1.small)
 * @param availabilityZone where the instance should run
 * @param groupName
 * @return List of unique ID of running instances
 * @throws AmazonServiceException something wrong in Amazon
 * @throws Exception some communication failure
 */
public static List<String> createAMInstances(String amiId, int min, int max,
        String keyPairName, String insType, String availabilityZone, List<String> groupName)
        throws AmazonServiceException {

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

    RunInstancesRequest request = new RunInstancesRequest(amiId, min, max);
    /*Chose the type i.e. m1.small*/
    request.setInstanceType(insType);
    request.setKeyName(keyPairName);// assign Keypair name for this request
    request.setSecurityGroups(groupName);

    // Chose the zone
    Placement p = new Placement();
    p.setAvailabilityZone(availabilityZone);
    request.setPlacement(p);

    RunInstancesResult runInstancesRes = ec2.runInstances(request);
    String reservationId = runInstancesRes.getReservation().getReservationId();

    //Getting the list of running instances according with our request
    Reservation reservation = runInstancesRes.getReservation();
    List<Instance> instances = reservation.getInstances();
    if (!instances.isEmpty()) {
        Iterator<Instance> instIterator = instances.iterator();
        int count = 0;
        //getting the descriptions of the instances
        while (instIterator.hasNext()) {
            Instance runningInst = instIterator.next();
            logger.info("We just start the Instance " + count + " UniqueID: "
                    + runningInst.getInstanceId() + " ImageId " + runningInst.getImageId()
                    + " type: " + runningInst.getInstanceType() + " Started by "
                    + runningInst.getKeyName() + " Status: " + runningInst.getState().toString());
            //Unique ID of the image that is running
            String uniqueID = runningInst.getInstanceId();
            runninginstanceIDs.add(uniqueID);
            count++;
        }
    }

    //Optionally you can use the unique id of the reservation for retrieving the running instance.
    //if you do that you will have to query the amazon APIs, it will be slower and will cost you
    //but is good to know that this information will be always there.
    logger.info("reservation ID of the executed transaction: " + reservationId);
    return runninginstanceIDs;
}

/**
 * Terminate (kill) a given running instance. Note that the method returns
 * when you move from "your previous state" to "terminating" and not when
 * the machine is actually terminated.
 *
 * @param instanceId unique ID of the running instance.
 * @throws AmazonServiceException something wrong in Amazon
 * @throws AmazonServiceException some communication failure
 */
public static void terminateAMI(String instanceId) throws AmazonServiceException {
    TerminateInstancesRequest rq = new TerminateInstancesRequest();
    rq.getInstanceIds().add(instanceId);
    TerminateInstancesResult rsp = ec2.terminateInstances(rq);
    logger.info("Insance successfully terminated : " + rsp.toString());
}

public static void createTagName(String runningInstanceID) {

    List<String> resources = new LinkedList<>();
    List<Tag> tags = new LinkedList<>();
    Tag nameTag = new Tag("Name", "Ankit_Shift");

    resources.add(runningInstanceID);
    tags.add(nameTag);

    CreateTagsRequest ctr = new CreateTagsRequest(resources, tags);
    ec2.createTags(ctr);
    logger.info("Appended tag name name for the instance as " + nameTag);
}

public static void startInstance(List<String> instanceIds) {
    //start
    StartInstancesRequest startIR = new StartInstancesRequest(instanceIds);
    ec2.startInstances(startIR);
    logger.info("Instance successfully restarted.");
}

public static void stopInstance(List<String> instanceIds) {
    //stop
    StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds);
    ec2.stopInstances(stopIR);
    logger.info("Instance successfully stopped.");
}

/**
 * Get a list of the current running instances. The key method is
 * DescribeInstancesResult describeInstancesResult =
 * ec2.describeInstances(); That returns information about instances that
 * you own. Note that gives you all the reservation that are currently
 * accounted in amazon. In other words an instance that has been stopped a
 * few minute ago is still consider "running instance for amazon". To refine
 * this list you need to use the method runningInst.getState().toString()
 * that tells you if the machine is really running or is terminated or
 * stopped or stopping or terminating or pending etc..
 *
 * @return Verbose description of the running instances.
 * @throws AmazonServiceException something wrong in Amazon
 * @throws Exception some communication failure
 */
public static String getRunningInstances() throws AmazonServiceException {
    logger.info("Fetching all running instances.");
    String ret = "";
    DescribeInstancesResult describeInstancesResult = ec2.describeInstances();

    // The list of reservations containing the describes instances.
    List<Reservation> reservations = describeInstancesResult.getReservations();
    Set<Instance> instances = new HashSet<>();

    for (Reservation reservation : reservations) {
        //Add the list of Amazon EC2 instances for this reservation.
        instances.addAll(reservation.getInstances());
    }

    ret += "You have " + instances.size() + " Amazon EC2 instance(s) running.\n";
    logger.info("You have " + instances.size() + " Amazon EC2 instance(s) running.");

    if (!instances.isEmpty()) {
        Iterator<Instance> instIterator = instances.iterator();
        int count = 0;
        //getting the descriptions of our running instances
        while (instIterator.hasNext()) {
            // the method runningInst.getState().toString() tell you if the machine is really running or is terminated or stopped or stopping or terminating or pending etc..
            Instance runningInst = instIterator.next();
            ret += "Instance: " + count + ", InstanceId: " + runningInst.getInstanceId() + ", ImageId: " + runningInst.getImageId() + ", type: " + runningInst.getInstanceType() + ", Started by: " + runningInst.getKeyName() + ", Status: " + runningInst.getState().toString() + "\n";
            logger.info("Instance: " + count + ", InstanceId: " + runningInst.getInstanceId() + ", ImageId: " + runningInst.getImageId() + ", type: " + runningInst.getInstanceType() + ", Started by: " + runningInst.getKeyName() + ", Status: " + runningInst.getState().toString());
            count++;
        }
    }

    return ret;

}

/**
 * Retrieve the list of zone that can be used for running the instances with
 * the user credential
 *
 * @return verbose string describing the zones
 * @throws AmazonServiceException something wrong in Amazon
 * @throws Exception some communication failure
 */
public static String listAvailableZones() throws AmazonServiceException {
    String ret = "";
    DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
    StringBuilder sb = new StringBuilder("You have access to " + availabilityZonesResult.getAvailabilityZones().size() + " Availability Zones.\n");
    ret += sb.toString();
    logger.info(sb.toString());

    List<AvailabilityZone> availabilityZone = availabilityZonesResult.getAvailabilityZones();
    Iterator<AvailabilityZone> iterator = availabilityZone.iterator();

    int i = 0;
    while (iterator.hasNext()) {
        AvailabilityZone az = iterator.next();
        ret += "Zone " + i + " " + az.getRegionName() + " " + az.getState() + " " + az.getZoneName() + "\n";
        logger.info("Zone " + i + " " + az.getRegionName() + " " + az.getState() + " " + az.getZoneName());
        i++;
    }
    return ret;

}

/**
 * Retrieve the list of possible Amazon Machine Image (AMI) that can be
 * instantiated by the user represented in the credential loaded during the
 * init() method. All the public AMI will be retrieved so the list will be
 * long. Many of the AMI will not have a description or a name but only an
 * ID so they will be useless. The AMI "ami-11ca2d78" is a sort of default
 * machine for amazon that all the user will be able to load
 *
 * @return Verbose description of the running instances.
 * @throws AmazonServiceException something wrong in Amazon
 */
public static String getAvailableImages() throws AmazonServiceException {
    String ret = "";
    DescribeImagesResult describeImagesResult = ec2.describeImages();
    logger.info("describe image result : " + describeImagesResult);
    List<Image> listOfImages = describeImagesResult.getImages();
    Iterator<Image> listOfImagesIterator = listOfImages.iterator();
    int count = 0;
    while (listOfImagesIterator.hasNext()) {
        Image img = listOfImagesIterator.next();

        StringBuilder sb = new StringBuilder("Image " + count + " Name: " + img.getName() + " Description: " + img.getDescription() + " Id: " + img.getImageId() + "\n");
        ret += sb.toString();
        logger.info(sb.toString());
        count++;
    }

    return ret;

}

/**
 * Create a key pair for a give user. The Keys are stored in yourHome/.ec2
 * or in the place that you specify while configuring the AWS plug-in for
 * java development. Note that you can always refer to this key pair using
 * just the name as long as the keys are correctly store in you machine.
 *
 * @param keyPairName unique name of the key pair
 * @return Object representing the Key pair
 * @throws AmazonServiceException something wrong in Amazon
 * @throws AmazonServiceException some communication failure
 */
public static KeyPair createKeyPair(String keyPairName) throws AmazonServiceException {
    // Create key pair for the given user.
    // request.getSecurityGroups().add("groupname");//create security groups
    // if you want create it! the security group will be default!
    // make sure to have access to SSH port 22 on the default group on the EC2console
    CreateKeyPairRequest kpReq = new CreateKeyPairRequest();
    kpReq.setKeyName(keyPairName);
    CreateKeyPairResult kpres = ec2.createKeyPair(kpReq);
    KeyPair keyPair = kpres.getKeyPair();
    logger.info("You havekeyPair.getKeyName = " + keyPair.getKeyName() + "\nkeyPair.getKeyFingerprint()=" + keyPair.getKeyFingerprint() + "\nkeyPair.getKeyMaterial()=" + keyPair.getKeyMaterial());
    return keyPair;
}
</code>```

}

答:
You can use this (Refer the AWS Documentation) AWS userdata to run powershell commands to open ports in Windows Firewall and according to question I assume you are able to open the Security Group Rules.

Here are Powershell Command to Open port:

netsh advfirewall firewall add rule name="Open Port (your port number)" dir=in action=allow protocol=TCP localport=(your port number)

Hope it helps!

ContentLicense: CC BY-SA 3.0

Body:
I am launching one windows instance in AWS(Amazon) using Java and trying to open few inbound ports like 445, 555, 9089, 8077 for my work.

I have also tried using Security groups port opening but it is only opening the inbound ports at security group level, not at the system level.

Provide me some solution so that I can open either before launch itself or after launch is also fine.

Here is my sample code.

package com.corenttech.engine.shift;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.AvailabilityZone;
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
import com.amazonaws.services.ec2.model.CreateKeyPairResult;
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult;
import com.amazonaws.services.ec2.model.DescribeImagesResult;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest;
import com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult;
import com.amazonaws.services.ec2.model.Image;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.IpPermission;
import com.amazonaws.services.ec2.model.KeyPair;
import com.amazonaws.services.ec2.model.Placement;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.SecurityGroup;
import com.amazonaws.services.ec2.model.StartInstancesRequest;
import com.amazonaws.services.ec2.model.StopInstancesRequest;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
import com.amazonaws.services.ec2.model.TerminateInstancesResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;

public class AwsConnection {

static AmazonEC2Client ec2;
static Logger logger = Logger.getLogger(AwsConnection.class);
static String Group_name;

private AwsConnection() {

}

public static void main(String[] args) throws Exception {
    String credentialsString;
    AmazonCredentials cred = new AmazonCredentials();
    cred.setAccessKeyId("accesskey");
    cred.setSecretKey("secretKey");

    credentialsString = "accessKey = " + cred.getAccessKeyId() + "\n";
    credentialsString += "secretKey = " + cred.getSecretKey();
    logger.info("credentialString :" + credentialsString);

    InputStream inpStrm = new ByteArrayInputStream(credentialsString.getBytes());
    AWSCredentials credentials = new PropertiesCredentials(inpStrm);
    ec2 = new AmazonEC2Client(credentials);

    try {

        AuthorizeSecurityGroupIngressRequest secrtyGrp = createSecurityGroup();
        List<String> groupName = updatePortToSecurityGroup(cred, secrtyGrp);

//            listAvailableZones();
//            getAvailableImages();
//            getRunningInstances();

        /* Launching a new AMI instance*/
        List<String> runninginstanceIDs = createAMInstances("ami-76f0061f", 1, 1, "Maas", "t1.micro", "us-east-1a", groupName);

        String runningInstanceID = runninginstanceIDs.iterator().next();
        logger.info("New instance created successfully : " + runningInstanceID);

        TimeUnit.SECONDS.sleep(60);
        createTagName(runningInstanceID);
        TimeUnit.SECONDS.sleep(1);
        getRunningInstances();

    } catch (AmazonServiceException ase) {
        logger.info("Caught Exception: " + ase.getMessage());
        logger.info("Reponse Status Code: " + ase.getStatusCode());
        logger.info("Error Code: " + ase.getErrorCode());
        logger.info("Request ID: " + ase.getRequestId());

    }

}

public static AuthorizeSecurityGroupIngressRequest createSecurityGroup() {
    Group_name = "group_test" + 1; //name of the group
    CreateSecurityGroupRequest r1 = new CreateSecurityGroupRequest(Group_name, "test group"); // this is security group description
    ec2.createSecurityGroup(r1);
    AuthorizeSecurityGroupIngressRequest r2 = new AuthorizeSecurityGroupIngressRequest();
    r2.setGroupName(Group_name);
    return r2;
}

public static List<String> updatePortToSecurityGroup(AmazonCredentials cred, AuthorizeSecurityGroupIngressRequest secrtyGrp) {
    logger.info("<<Amazon updatePortToSecurityGroup start>>");
    String protocol = "tcp";
    int port = 8077;

    IpPermission perm1 = new IpPermission();
    perm1.setIpProtocol(protocol);
    perm1.setFromPort(port);
    perm1.setToPort(port);
    List<String> ipRanges = new ArrayList<>();
    ipRanges.add("0.0.0.0/0");
    perm1.setIpRanges(ipRanges);

    IpPermission permission2 = new IpPermission();
    permission2.setIpProtocol("tcp");
    permission2.setFromPort(445);
    permission2.setToPort(445);
    List<String> ipRanges2 = new ArrayList<>();
    ipRanges2.add("0.0.0.0/0");
    permission2.setIpRanges(ipRanges2);

    IpPermission permission3 = new IpPermission();
    permission3.setIpProtocol("tcp");
    permission3.setFromPort(555);
    permission3.setToPort(555);
    List<String> ipRanges3 = new ArrayList<String>();
    ipRanges3.add("0.0.0.0/0");
    permission3.setIpRanges(ipRanges3);

    IpPermission permission4 = new IpPermission();
    permission4.setIpProtocol("tcp");
    permission4.setFromPort(8080);
    permission4.setToPort(8080);
    List<String> ipRanges4 = new ArrayList<>();
    ipRanges4.add("0.0.0.0/0");
    permission4.setIpRanges(ipRanges4);

    IpPermission permission5 = new IpPermission();
    permission5.setIpProtocol("tcp");
    permission5.setFromPort(3389);
    permission5.setToPort(3389);
    List<String> ipRanges5 = new ArrayList<>();
    ipRanges5.add("0.0.0.0/0");
    permission5.setIpRanges(ipRanges5);

    IpPermission permission6 = new IpPermission();
    permission6.setIpProtocol("tcp");
    permission6.setFromPort(9089);
    permission6.setToPort(9089);
    List<String> ipRanges6 = new ArrayList<>();
    ipRanges6.add("0.0.0.0/0");
    permission6.setIpRanges(ipRanges6);

    IpPermission permission7 = new IpPermission();
    permission7.setIpProtocol("tcp");
    permission7.setFromPort(80);
    permission7.setToPort(80);
    List<String> ipRanges7 = new ArrayList<>();
    ipRanges7.add("0.0.0.0/0");
    permission7.setIpRanges(ipRanges7);

    IpPermission permission8 = new IpPermission();
    permission8.setIpProtocol("tcp");
    permission8.setFromPort(443);
    permission8.setToPort(443);
    List<String> ipRanges8 = new ArrayList<>();
    ipRanges8.add("0.0.0.0/0");
    permission8.setIpRanges(ipRanges8);

    IpPermission permission9 = new IpPermission();
    permission9.setIpProtocol("tcp");
    permission9.setFromPort(23);
    permission9.setToPort(23);
    List<String> ipRanges9 = new ArrayList<>();
    ipRanges9.add("0.0.0.0/0");
    permission9.setIpRanges(ipRanges9);

    List<IpPermission> permissions = new ArrayList<>();
    permissions.add(perm1);
    permissions.add(permission2);
    permissions.add(permission3);
    permissions.add(permission4);
    permissions.add(permission5);
    permissions.add(permission6);
    permissions.add(permission7);
    permissions.add(permission8);
    permissions.add(permission9);

    secrtyGrp.setIpPermissions(permissions);

    ec2.authorizeSecurityGroupIngress(secrtyGrp);
    List<String> groupName = new ArrayList<>();
    groupName.add(Group_name);

    logger.info("<<Amazon updatePortToSecurityGroup end>>");
    return groupName;
}

public static List<SecurityGroup> findAllSecurityGroups() {
    DescribeSecurityGroupsRequest securityRequest = new DescribeSecurityGroupsRequest();
    DescribeSecurityGroupsResult securityDescription = ec2.describeSecurityGroups(securityRequest);
    return securityDescription.getSecurityGroups();
}

/**
 * Create one or more running instances of a given AMI. If you want to lunch
 * a machine in the amazon cloud this is the method that you are looking
 * for. The key method is RunInstancesResult runInstancesRes =
 * ec2.runInstances(request); that return a unique id of the reservation for
 * retrieving the running instances. By the way if you do that you will have
 * to query the amazon APIs, it will be slower and will cost you but is good
 * to know that this information will be always there.
 *
 * @param amiId unique ID of the machine
 * @param min minimum number of machines
 * @param max maximum number of machines that you want to run
 * @param keyPairName unique id of the key pair that will be used for
 * running an instance
 * @param insType type of instance (i.e. m1.small)
 * @param availabilityZone where the instance should run
 * @param groupName
 * @return List of unique ID of running instances
 * @throws AmazonServiceException something wrong in Amazon
 * @throws Exception some communication failure
 */
public static List<String> createAMInstances(String amiId, int min, int max,
        String keyPairName, String insType, String availabilityZone, List<String> groupName)
        throws AmazonServiceException {

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

    RunInstancesRequest request = new RunInstancesRequest(amiId, min, max);
    /*Chose the type i.e. m1.small*/
    request.setInstanceType(insType);
    request.setKeyName(keyPairName);// assign Keypair name for this request
    request.setSecurityGroups(groupName);

    // Chose the zone
    Placement p = new Placement();
    p.setAvailabilityZone(availabilityZone);
    request.setPlacement(p);

    RunInstancesResult runInstancesRes = ec2.runInstances(request);
    String reservationId = runInstancesRes.getReservation().getReservationId();

    //Getting the list of running instances according with our request
    Reservation reservation = runInstancesRes.getReservation();
    List<Instance> instances = reservation.getInstances();
    if (!instances.isEmpty()) {
        Iterator<Instance> instIterator = instances.iterator();
        int count = 0;
        //getting the descriptions of the instances
        while (instIterator.hasNext()) {
            Instance runningInst = instIterator.next();
            logger.info("We just start the Instance " + count + " UniqueID: "
                    + runningInst.getInstanceId() + " ImageId " + runningInst.getImageId()
                    + " type: " + runningInst.getInstanceType() + " Started by "
                    + runningInst.getKeyName() + " Status: " + runningInst.getState().toString());
            //Unique ID of the image that is running
            String uniqueID = runningInst.getInstanceId();
            runninginstanceIDs.add(uniqueID);
            count++;
        }
    }

    //Optionally you can use the unique id of the reservation for retrieving the running instance.
    //if you do that you will have to query the amazon APIs, it will be slower and will cost you
    //but is good to know that this information will be always there.
    logger.info("reservation ID of the executed transaction: " + reservationId);
    return runninginstanceIDs;
}

/**
 * Terminate (kill) a given running instance. Note that the method returns
 * when you move from "your previous state" to "terminating" and not when
 * the machine is actually terminated.
 *
 * @param instanceId unique ID of the running instance.
 * @throws AmazonServiceException something wrong in Amazon
 * @throws AmazonServiceException some communication failure
 */
public static void terminateAMI(String instanceId) throws AmazonServiceException {
    TerminateInstancesRequest rq = new TerminateInstancesRequest();
    rq.getInstanceIds().add(instanceId);
    TerminateInstancesResult rsp = ec2.terminateInstances(rq);
    logger.info("Insance successfully terminated : " + rsp.toString());
}

public static void createTagName(String runningInstanceID) {

    List<String> resources = new LinkedList<>();
    List<Tag> tags = new LinkedList<>();
    Tag nameTag = new Tag("Name", "Ankit_Shift");

    resources.add(runningInstanceID);
    tags.add(nameTag);

    CreateTagsRequest ctr = new CreateTagsRequest(resources, tags);
    ec2.createTags(ctr);
    logger.info("Appended tag name name for the instance as " + nameTag);
}

public static void startInstance(List<String> instanceIds) {
    //start
    StartInstancesRequest startIR = new StartInstancesRequest(instanceIds);
    ec2.startInstances(startIR);
    logger.info("Instance successfully restarted.");
}

public static void stopInstance(List<String> instanceIds) {
    //stop
    StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds);
    ec2.stopInstances(stopIR);
    logger.info("Instance successfully stopped.");
}

/**
 * Get a list of the current running instances. The key method is
 * DescribeInstancesResult describeInstancesResult =
 * ec2.describeInstances(); That returns information about instances that
 * you own. Note that gives you all the reservation that are currently
 * accounted in amazon. In other words an instance that has been stopped a
 * few minute ago is still consider "running instance for amazon". To refine
 * this list you need to use the method runningInst.getState().toString()
 * that tells you if the machine is really running or is terminated or
 * stopped or stopping or terminating or pending etc..
 *
 * @return Verbose description of the running instances.
 * @throws AmazonServiceException something wrong in Amazon
 * @throws Exception some communication failure
 */
public static String getRunningInstances() throws AmazonServiceException {
    logger.info("Fetching all running instances.");
    String ret = "";
    DescribeInstancesResult describeInstancesResult = ec2.describeInstances();

    // The list of reservations containing the describes instances.
    List<Reservation> reservations = describeInstancesResult.getReservations();
    Set<Instance> instances = new HashSet<>();

    for (Reservation reservation : reservations) {
        //Add the list of Amazon EC2 instances for this reservation.
        instances.addAll(reservation.getInstances());
    }

    ret += "You have " + instances.size() + " Amazon EC2 instance(s) running.\n";
    logger.info("You have " + instances.size() + " Amazon EC2 instance(s) running.");

    if (!instances.isEmpty()) {
        Iterator<Instance> instIterator = instances.iterator();
        int count = 0;
        //getting the descriptions of our running instances
        while (instIterator.hasNext()) {
            // the method runningInst.getState().toString() tell you if the machine is really running or is terminated or stopped or stopping or terminating or pending etc..
            Instance runningInst = instIterator.next();
            ret += "Instance: " + count + ", InstanceId: " + runningInst.getInstanceId() + ", ImageId: " + runningInst.getImageId() + ", type: " + runningInst.getInstanceType() + ", Started by: " + runningInst.getKeyName() + ", Status: " + runningInst.getState().toString() + "\n";
            logger.info("Instance: " + count + ", InstanceId: " + runningInst.getInstanceId() + ", ImageId: " + runningInst.getImageId() + ", type: " + runningInst.getInstanceType() + ", Started by: " + runningInst.getKeyName() + ", Status: " + runningInst.getState().toString());
            count++;
        }
    }

    return ret;

}

/**
 * Retrieve the list of zone that can be used for running the instances with
 * the user credential
 *
 * @return verbose string describing the zones
 * @throws AmazonServiceException something wrong in Amazon
 * @throws Exception some communication failure
 */
public static String listAvailableZones() throws AmazonServiceException {
    String ret = "";
    DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
    StringBuilder sb = new StringBuilder("You have access to " + availabilityZonesResult.getAvailabilityZones().size() + " Availability Zones.\n");
    ret += sb.toString();
    logger.info(sb.toString());

    List<AvailabilityZone> availabilityZone = availabilityZonesResult.getAvailabilityZones();
    Iterator<AvailabilityZone> iterator = availabilityZone.iterator();

    int i = 0;
    while (iterator.hasNext()) {
        AvailabilityZone az = iterator.next();
        ret += "Zone " + i + " " + az.getRegionName() + " " + az.getState() + " " + az.getZoneName() + "\n";
        logger.info("Zone " + i + " " + az.getRegionName() + " " + az.getState() + " " + az.getZoneName());
        i++;
    }
    return ret;

}

/**
 * Retrieve the list of possible Amazon Machine Image (AMI) that can be
 * instantiated by the user represented in the credential loaded during the
 * init() method. All the public AMI will be retrieved so the list will be
 * long. Many of the AMI will not have a description or a name but only an
 * ID so they will be useless. The AMI "ami-11ca2d78" is a sort of default
 * machine for amazon that all the user will be able to load
 *
 * @return Verbose description of the running instances.
 * @throws AmazonServiceException something wrong in Amazon
 */
public static String getAvailableImages() throws AmazonServiceException {
    String ret = "";
    DescribeImagesResult describeImagesResult = ec2.describeImages();
    logger.info("describe image result : " + describeImagesResult);
    List<Image> listOfImages = describeImagesResult.getImages();
    Iterator<Image> listOfImagesIterator = listOfImages.iterator();
    int count = 0;
    while (listOfImagesIterator.hasNext()) {
        Image img = listOfImagesIterator.next();

        StringBuilder sb = new StringBuilder("Image " + count + " Name: " + img.getName() + " Description: " + img.getDescription() + " Id: " + img.getImageId() + "\n");
        ret += sb.toString();
        logger.info(sb.toString());
        count++;
    }

    return ret;

}

/**
 * Create a key pair for a give user. The Keys are stored in yourHome/.ec2
 * or in the place that you specify while configuring the AWS plug-in for
 * java development. Note that you can always refer to this key pair using
 * just the name as long as the keys are correctly store in you machine.
 *
 * @param keyPairName unique name of the key pair
 * @return Object representing the Key pair
 * @throws AmazonServiceException something wrong in Amazon
 * @throws AmazonServiceException some communication failure
 */
public static KeyPair createKeyPair(String keyPairName) throws AmazonServiceException {
    // Create key pair for the given user.
    // request.getSecurityGroups().add("groupname");//create security groups
    // if you want create it! the security group will be default!
    // make sure to have access to SSH port 22 on the default group on the EC2console
    CreateKeyPairRequest kpReq = new CreateKeyPairRequest();
    kpReq.setKeyName(keyPairName);
    CreateKeyPairResult kpres = ec2.createKeyPair(kpReq);
    KeyPair keyPair = kpres.getKeyPair();
    logger.info("You havekeyPair.getKeyName = " + keyPair.getKeyName() + "\nkeyPair.getKeyFingerprint()=" + keyPair.getKeyFingerprint() + "\nkeyPair.getKeyMaterial()=" + keyPair.getKeyMaterial());
    return keyPair;
}

}


问:
Visual studio IDE change references upon changing configuration
Is there a way where I can change references using the configuration manager?  I have a third party DLL which for some reason is split in two folders:  x86, x64.

example the x86 bit would be in:
c:\progra~1\myAddin\x86\someDll.dll
while the x64 would be:
c:\progra~1\myAddin\x64\someDll.dll

I would need some option from the VS IDE that when I switch to 'debug' configuration it would change to x86 and when I switch to 'release' it would change to x64 dll.

答:
Your approach is going to lead to issues. Switching between debug and release shouldn't change the platform you are targeting. You should be switching references only when the platform changes (this is the box to the right of the configuration).

I have not found a good way to manage this via the IDE, but you can easily manage this by modifying the project file directly. Take a look at Conditionally use 32/64 bit reference when building in Visual Studio for details on how to do this.


问:
Swagger editor is throwing error while specifying the response "Not a valid response definition"
I am trying to generate the API documentation using swagger editor. I specified my API specification as follow

```<code>paths:
  /opendata/v1/{index}:
    get:
      tags: [verification]
      description: Verify the person information
      parameters:
        - name: index
          in: path
          description: specific data index
          required: true
          type: string
        - name: name
          in: query
          description: name of a person
          required: false
          type: string
        - name: company name
          in: query
          description: name of a company
          required: false
          type: string

      responses:
        '200':
          description: Success
          content:
            application/json:
              schemas:
                $ref: '#/responses/200'

responses:
    '200':
      description: Success
      schema:
        type: object
        properties:
          verification:
            type: string
</code>```

But its always showing error in the editor that "Not a valid response definition". I checked the specification for response from here. What changes I should do so that error will not come.

Note: I want the response in the json form like below:

```<code>{
    verification:string
}
</code>```

答:
You are mixing OpenAPI/Swagger 2.0 and OpenAPI 3.0 syntax. Your spec seems to be swagger: '2.0', so you should use:

paths:
  /opendata/v1/{index}:
    get:
      ...

      produces:
        - application/json
      responses:
        200:
          $ref: '#/responses/200'
```

Here's a related OpenAPI/Swagger 2.0 guide: Describing Responses

Body:
I am trying to generate the API documentation using swagger editor. I specified my API specification as follow

paths:
  /opendata/v1/{index}:
    get:
      tags: [verification]
      description: Verify the person information
      parameters:
        - name: index
          in: path
          description: specific data index
          required: true
          type: string
        - name: name
          in: query
          description: name of a person
          required: false
          type: string
        - name: company name
          in: query
          description: name of a company
          required: false
          type: string

      responses:
        '200':
          description: Success
          content:
            application/json:
              schemas:
                $ref: '#/responses/200'

responses:
    '200':
      description: Success
      schema:
        type: object
        properties:
          verification:
            type: string

But its always showing error in the editor that "Not a valid response definition". I checked the specification for response from here. What changes I should do so that error will not come.

Note: I want the response in the json form like below:

{
    verification:string
}

Body:
You are mixing OpenAPI/Swagger 2.0 and OpenAPI 3.0 syntax. Your spec seems to be swagger: '2.0', so you should use:

paths:
  /opendata/v1/{index}:
    get:
      ...

      produces:
        - application/json
      responses:
        200:
          $ref: '#/responses/200'

Here's a related OpenAPI/Swagger 2.0 guide: Describing Responses


问:
Clean array indexing with arrays in numpy
I'm running into this problem over and over again, and can't seem to find a clean solution for this. So I'm trying to index an array with another array. I have a 2d numpy array. And a 1d numpy array with the same length as the 1st dimension of the 2d array I'm trying to index and the elements represent the indices of the columns I try to extract:

```<code>import numpy as np

A = np.random.rand((5,3))

B = np.asarray([2,1,2,0,1])
</code>```

The behaviour that I want is extracting for all rows the corresponding column in array B. This could be done by

```<code>C = A[np.arange(A.shape[0]),B]
</code>```

But I can imagine that there is a better way to get this behaviour. Using a : as indexing the first row gives the wrong behaviour.

If there is a cleaner way of doing this that would be great. I'm really used to this array indexing from Matlab, but maybe there is no equivalent in numpy. Using boolean indices is of course an option, but that also requires converting arrays all the time.

Body:
I'm running into this problem over and over again, and can't seem to find a clean solution for this. So I'm trying to index an array with another array. I have a 2d numpy array. And a 1d numpy array with the same length as the 1st dimension of the 2d array I'm trying to index and the elements represent the indices of the columns I try to extract:

import numpy as np

A = np.random.rand((5,3))

B = np.asarray([2,1,2,0,1])

The behaviour that I want is extracting for all rows the corresponding column in array B. This could be done by

C = A[np.arange(A.shape[0]),B]

But I can imagine that there is a better way to get this behaviour. Using a : as indexing the first row gives the wrong behaviour.

If there is a cleaner way of doing this that would be great. I'm really used to this array indexing from Matlab, but maybe there is no equivalent in numpy. Using boolean indices is of course an option, but that also requires converting arrays all the time.

Body:
I think what you look after is np.choose(B,A.T) :

In [125]: A
Out[125]:
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14]])

In [126]: B = np.asarray([2,1,2,0,1])

In [127]: np.choose(B,A.T)
Out[127]: array([ 2,  4,  8,  9, 13])


问:
Resize view to fit superview after transform
I have a innerview within a view, I have pinned innerview to view using autolayout.
Now I am rotating innerview using transform

```<code>self.innerView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))
</code>```

After transform, innerview is showing outside.

How can I fit innerview to view after transform means innerview should not go beyond view.

Please have a look at attached images.

答:
You can do it by one line code

```<code>superView.clipsToBounds = true
</code>```

superView is view that your innerView added on that

OR

You can also find out this property from storyBoard too.

Select your superView and check on Clip Subviews

Body:
I have a innerview within a view, I have pinned innerview to view using autolayout.
Now I am rotating innerview using transform

self.innerView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))

After transform, innerview is showing outside.

How can I fit innerview to view after transform means innerview should not go beyond view.

Please have a look at attached images.

Body:
You can do it by one line code

superView.clipsToBounds = true

superView is view that your innerView added on that

OR

You can also find out this property from storyBoard too.

Select your superView and check on Clip Subviews


问:
Cannot install php 7.2 on Raspbian
I cannot install php 7.2 on Raspbian.
I used the last Raspbian (Release date : 2017-11-29) with a Debian Stretch 9.1 : https://www.raspberrypi.org/downloads/raspbian/

I followed the instructions from https://www.colinodell.com/blog/2016-12/installing-php-7-1 :

```<code>apt-get install apt-transport-https lsb-release ca-certificates
wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list
apt-get update
</code>```

But when I try

```<code>apt-get install -y php7.2
</code>```

A get the below errors :

```<code>root@raspberrypi:/home/pi# apt-get install -y php7.2
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 php7.2 : Depends: libapache2-mod-php7.2 but it is not installable or
               php7.2-fpm but it is not installable or
               php7.2-cgi but it is not installable
      Depends: php7.2-common but it is not installable
E: Unable to correct problems, you have held broken packages.
</code>```

Someone can help me ?
Thanks a lot

答:
I found the reason, the package php7.1 and php7.2 isn't in the stretch repo :(.

https://raspberrypi.stackexchange.com/questions/70388/how-to-install-php-7-1

Have to wait an update ...

Title: Cannot install php 7.2 on Raspbian

Body:
I cannot install php 7.2 on Raspbian.
I used the last Raspbian (Release date : 2017-11-29) with a Debian Stretch 9.1 : https://www.raspberrypi.org/downloads/raspbian/

I followed the instructions from https://www.colinodell.com/blog/2016-12/installing-php-7-1 :

apt-get install apt-transport-https lsb-release ca-certificates
wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list
apt-get update

But when I try

apt-get install -y php7.2

A get the below errors :

root@raspberrypi:/home/pi# apt-get install -y php7.2
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 php7.2 : Depends: libapache2-mod-php7.2 but it is not installable or
               php7.2-fpm but it is not installable or
               php7.2-cgi but it is not installable
      Depends: php7.2-common but it is not installable
E: Unable to correct problems, you have held broken packages.

Someone can help me ?
Thanks a lot


问:
Openlayers 4+ using local vector tiles (.pbf) without server
I'm new in online mapping, and in the past I've created raster maps succesfully with Maperitive from osm data. It works fine from localhost/ local folder structure.  But my question: Is it possible to serve local vector maps from .pbf or geojson files without any server or mapbox stuff just like raster images? Is it possible to render without any server or api key required service in the browser directly in the client side?
If yes, could someone provide me a working example?

Thanks.

答:
Normally websites cannot access your local file system. This is to protect you and your computer from websites spying on you.

However, there are exceptions to that rule.

Websites can read files that you selected in a "upload file" input element.

A page can read file system, when it is opended from the disk

Opening an html document from the harddrive means that you simply double click it on your computer and the browser opens it. All relative links in that html document are then relative to that document.

So if you use the GeoJSON class, you can simply give it a path to files on your computer. Here is an example that reads a local file named mygeojson.geojson from a folder mysubfolder and shows it on top of a OpenStreetMap layer:

```<code>var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
    new ol.layer.Image({
      source: new ol.source.ImageVector({
        source: new ol.source.Vector({
          url: 'mysubfolder/mygeojson.geojson',
          format: new ol.format.GeoJSON()
        }),
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.6)'
          }),
          stroke: new ol.style.Stroke({
            color: '#319FD3',
            width: 1
          })
        })
      })
    })
  ],
  target: 'map',
  view: new ol.View({ center: [0, 0], zoom: 1 })
});
</code>```

Body:
Normally websites cannot access your local file system. This is to protect you and your computer from websites spying on you.

However, there are exceptions to that rule.

Websites can read files that you selected in a "upload file" input element.

A page can read file system, when it is opended from the disk

Opening an html document from the harddrive means that you simply double click it on your computer and the browser opens it. All relative links in that html document are then relative to that document.

So if you use the GeoJSON class, you can simply give it a path to files on your computer. Here is an example that reads a local file named mygeojson.geojson from a folder mysubfolder and shows it on top of a OpenStreetMap layer:

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
    new ol.layer.Image({
      source: new ol.source.ImageVector({
        source: new ol.source.Vector({
          url: 'mysubfolder/mygeojson.geojson',
          format: new ol.format.GeoJSON()
        }),
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.6)'
          }),
          stroke: new ol.style.Stroke({
            color: '#319FD3',
            width: 1
          })
        })
      })
    })
  ],
  target: 'map',
  view: new ol.View({ center: [0, 0], zoom: 1 })
});


问:
AJAX to Google Forms works everytime in Chrome but only occasionally in FF and IE11
I'm having a bit of an issue with using my AJAX code that posts to a google form, which I have developed from this site: https://wiki.base22.com/display/btg/Send+data+to+Google+docs+using+a+web+form+and+AJAX

Basically I have constructed a webpage that collects some data in a form.  When the user clicks on the "next" button it runs through some JQuery that launches the following function:

```<code>function postQuToGoogle() {
    var pathclick = $('#text').val();
    var tasknumber = $('#taskno').text();
    var identifier = $('#ident').val();
    var duration = $('#timediff').val();
    var button = press;
    var treename = TestName;

        $.ajax({
            url: "https://docs.google.com/forms/......",
            data: { "entry.1507891248": pathclick,
                    "entry.2057302526": tasknumber,
                    "entry.1920694157": identifier,
                    "entry.900973756": treename,
                    "entry.706969357": button,
                    "entry.647049842": duration
                     },
            type: "POST",
            dataType: "jsonp",
        });
}
</code>```

When I run it on Chrome it posts to the Google form every time.  When I run it on IE11 or FF (57) it only works some of the time.

I'm pretty new at coding JS and AJAX so have only learnt from what I have read on the internet.

I have run it through all three browsers with the console open to check for errors. They come up with the following every time:

Chrome's error:

Refused to execute script from 'https://docs.google.com/forms/.....' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

Firefox's errors:

The resource from “https://docs.google.com/forms/.....” was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).[Learn More]  (unknown)

Loading failed for the  with source “https://docs.google.com/forms/....”.

IE11's error:

Script from https://docs.google.com/forms/..... was blocked due to mime type mismatch

Any ideas on why Chrome does it every time but the other browsers appear to be a bit more choosy? And if there is a fix?

答:
It appears that I wasn't giving enough time for the Ajax to do it's thing.

In the main site code the postQuToGoogle function is called and then the browser is redirected to the next page.

I have now built in a two second delay after the submit button is pressed.The process goes like this now:

User presses submit button

Loader is faded in

postQuToGoogle is called

setTimeout is used to hold the page for two seconds

After two seconds the browser is directed to the next page

```<code>function loaderIn(){
  $("#loader-wrapper").fadeIn("slow");}

$("#surveypost").click(function(){
 loaderIn();
 postToGoogle();
 setTimeout(function(){
       window.location.href = "instructions.html";
 },2000);
});
</code>```

Body:
I'm having a bit of an issue with using my AJAX code that posts to a google form, which I have developed from this site: https://wiki.base22.com/display/btg/Send+data+to+Google+docs+using+a+web+form+and+AJAX

Basically I have constructed a webpage that collects some data in a form.  When the user clicks on the "next" button it runs through some JQuery that launches the following function:

function postQuToGoogle() {
    var pathclick = $('#text').val();
    var tasknumber = $('#taskno').text();
    var identifier = $('#ident').val();
    var duration = $('#timediff').val();
    var button = press;
    var treename = TestName;

        $.ajax({
            url: "https://docs.google.com/forms/......",
            data: { "entry.1507891248": pathclick,
                    "entry.2057302526": tasknumber,
                    "entry.1920694157": identifier,
                    "entry.900973756": treename,
                    "entry.706969357": button,
                    "entry.647049842": duration
                     },
            type: "POST",
            dataType: "jsonp",
        });
}

When I run it on Chrome it posts to the Google form every time.  When I run it on IE11 or FF (57) it only works some of the time.

I'm pretty new at coding JS and AJAX so have only learnt from what I have read on the internet.

I have run it through all three browsers with the console open to check for errors. They come up with the following every time:

Chrome's error:

Refused to execute script from 'https://docs.google.com/forms/.....' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

Firefox's errors:

The resource from “https://docs.google.com/forms/.....” was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).[Learn More]  (unknown)

Loading failed for the  with source “https://docs.google.com/forms/....”.

IE11's error:

Script from https://docs.google.com/forms/..... was blocked due to mime type mismatch

Any ideas on why Chrome does it every time but the other browsers appear to be a bit more choosy? And if there is a fix?

Body:
It appears that I wasn't giving enough time for the Ajax to do it's thing.

In the main site code the postQuToGoogle function is called and then the browser is redirected to the next page.

I have now built in a two second delay after the submit button is pressed.The process goes like this now:

User presses submit button

Loader is faded in

postQuToGoogle is called

setTimeout is used to hold the page for two seconds

After two seconds the browser is directed to the next page

function loaderIn(){
  $("#loader-wrapper").fadeIn("slow");}

$("#surveypost").click(function(){
 loaderIn();
 postToGoogle();
 setTimeout(function(){
       window.location.href = "instructions.html";
 },2000);
});


问:
Responsive image for recording user selection
I am wanting to allow users to click on a specific part of a photograph in a tablet/phone (via a web browser or software) and it will record their choice.

Essentially I have some aerial photographs and I want to place a regular grid (say 100m x 100m over the top). This grid would be semi-transparent, and each grid cell would be clear if not clicked ('off') and change to blue when clicked ('on'). Each grid cell would store a value if it is 'on' or 'off'.

This would preferably done using a spatially referenced geotiff image, but is not essential.

I have lots experience in GIS related software, but I am looking for a simple solution.

Is this possible?
What tools, web languages (html, java etc), or software is recomended.
Responsive image maps kind of seem relevant here but I am not sure?

答:
Tracking user interaction over an image is possible. You can overlay a grid of clickable div, and simply listen for clicks on each div.

Here is an approach where I place a 10x10 grid of div on top of an image:

https://jsfiddle.net/o31p99wh/

The key is to know the size / scale of the image, and make sure that the tiles are mapped to that. E.g. each 35 x 35px square maps to 350 x 350m.


问:
Replacing runs of zero in a vector with a fraction of the previous value
I have a vector containing zero values:

```<code>x<-c(6,0,0,4,2,0,2,2,0,0,5)
</code>```

How can I replace the zero values and the last non zero value using the number:

```<code>   last non zero value /(length of run of zero's + 1)
</code>```

As an example first three elements should be replaced by 6/3 which is 2

So afterwards the x should looks like below:

```<code>x<-c(2,2,2,4,1,1,2,0.66,0.66,0.66,5)
</code>```

Body:
I have a vector containing zero values:

x<-c(6,0,0,4,2,0,2,2,0,0,5)

How can I replace the zero values and the last non zero value using the number:

   last non zero value /(length of run of zero's + 1)

As an example first three elements should be replaced by 6/3 which is 2

So afterwards the x should looks like below:

x<-c(2,2,2,4,1,1,2,0.66,0.66,0.66,5)

Body:
This is a pretty simple one-liner with ave and using cumsum to do the grouping:

ave(x, cumsum(x > 0))
 [1] 2.0000000 2.0000000 2.0000000 4.0000000 1.0000000 1.0000000 2.0000000
 [8] 0.6666667 0.6666667 0.6666667 5.0000000


问:
Unable to find CMake in Android Studio
I need to add C/C++ code in my Android program for which I needed LLDB, CMake, and NDK. I found LLDB and NDK in SDK manager, but CMake is missing from there. I tried manually downloading it from the CMake official site and found out that for Android we need SDK customized CMake.

As you can see there is no option such as CMake.

Where do I find a version of CMake for Android?

I have tried CMake from the website and one I found in ndk-bundle/build folder, but both are giving the same error as below. What can be made out of it and how can the issue be solved?

```<code>Build command failed.

Error while executing 'C:\Users\amishr33\AppData\Local\Android\sdk\cmake\bin\cmake.exe' with arguments {-HC:\Users\amishr33\AndroidStudioProjects\MyApplication\app\src\main\jni -BC:\Users\amishr33\AndroidStudioProjects\MyApplication\app\.externalNativeBuild\cmake\debug\armeabi -GAndroid Gradle - Ninja -DANDROID_ABI=armeabi -DANDROID_NDK=C:\Users\amishr33\AppData\Local\Android\sdk\ndk-bundle -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\amishr33\AndroidStudioProjects\MyApplication\app\build\intermediates\cmake\debug\obj\armeabi -DCMAKE_BUILD_TYPE=Debug -DCMAKE_MAKE_PROGRAM=C:\Users\amishr33\AppData\Local\Android\sdk\cmake\bin\ninja.exe -DCMAKE_TOOLCHAIN_FILE=C:\Users\amishr33\AppData\Local\Android\sdk\ndk-bundle\build\cmake\android.toolchain.cmake -DANDROID_NATIVE_API_LEVEL=15 -DCMAKE_CXX_FLAGS=-std=c++11 -DANDROID_TOOLCHAIN=clang -DANDROID_STL=gnustl_static}
CMake Error: Could not create named generator Android Gradle - Ninja
Generators
  Visual Studio 15 2017 [arch] = Generates Visual Studio 2017 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 14 2015 [arch] = Generates Visual Studio 2015 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 12 2013 [arch] = Generates Visual Studio 2013 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 11 2012 [arch] = Generates Visual Studio 2012 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 10 2010 [arch] = Generates Visual Studio 2010 project files.
                                 Optional [arch] can be "Win64" or "IA64".
  Visual Studio 9 2008 [arch]  = Generates Visual Studio 2008 project files.
                                 Optional [arch] can be "Win64" or "IA64".
  Visual Studio 8 2005 [arch]  = Generates Visual Studio 2005 project files.
                                 Optional [arch] can be "Win64".
  Visual Studio 7 .NET 2003    = Deprecated.  Generates Visual Studio .NET
                                 2003 project files.
  Borland Makefiles            = Generates Borland makefiles.
  NMake Makefiles              = Generates NMake makefiles.
  NMake Makefiles JOM          = Generates JOM makefiles.
  Green Hills MULTI            = Generates Green Hills MULTI files
                                 (experimental, work-in-progress).
  MSYS Makefiles               = Generates MSYS makefiles.
  MinGW Makefiles              = Generates a make file for use with
                                 mingw32-make.
  Unix Makefiles               = Generates standard UNIX makefiles.
  Ninja                        = Generates build.ninja files.
  Watcom WMake                 = Generates Watcom WMake makefiles.
  CodeBlocks - MinGW Makefiles = Generates CodeBlocks project files.
  CodeBlocks - NMake Makefiles = Generates CodeBlocks project files.
  CodeBlocks - Ninja           = Generates CodeBlocks project files.
  CodeBlocks - Unix Makefiles  = Generates CodeBlocks project files.
  CodeLite - MinGW Makefiles   = Generates CodeLite project files.
  CodeLite - NMake Makefiles   = Generates CodeLite project files.
  CodeLite - Ninja             = Generates CodeLite project files.
  CodeLite - Unix Makefiles    = Generates CodeLite project files.
  Sublime Text 2 - MinGW Makefiles
                               = Generates Sublime Text 2 project files.
  Sublime Text 2 - NMake Makefiles
                               = Generates Sublime Text 2 project files.
  Sublime Text 2 - Ninja       = Generates Sublime Text 2 project files.
  Sublime Text 2 - Unix Makefiles
                               = Generates Sublime Text 2 project files.
  Kate - MinGW Makefiles       = Generates Kate project files.
  Kate - NMake Makefiles       = Generates Kate project files.
  Kate - Ninja                 = Generates Kate project files.
  Kate - Unix Makefiles        = Generates Kate project files.
  Eclipse CDT4 - NMake Makefiles
                               = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - MinGW Makefiles
                               = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Ninja         = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Unix Makefiles= Generates Eclipse CDT 4.0 project files.
Error:executing external native build for cmake C:\Users\amishr33\AndroidStudioProjects\MyApplication\app\src\main\jni\CMakeLists.txt
</code>```

答:
If you do the following you may get CMake without any problems:

Open the Settings (Android Studio);

Search by "Android SDK";

On the right side, go to the "SDK Tools" pallet|tab;

Check the "CMake" item on the list;

Press OK button;

Now, just wait the next century while Gradle builds, =D .

ContentLicense: CC BY-SA 4.0

Title: Unable to find CMake in Android Studio

Body:
I need to add C/C++ code in my Android program for which I needed LLDB, CMake, and NDK. I found LLDB and NDK in SDK manager, but CMake is missing from there. I tried manually downloading it from the CMake official site and found out that for Android we need SDK customized CMake.

As you can see there is no option such as CMake.

Where do I find a version of CMake for Android?

I have tried CMake from the website and one I found in ndk-bundle/build folder, but both are giving the same error as below. What can be made out of it and how can the issue be solved?

Build command failed.

Error while executing 'C:\Users\amishr33\AppData\Local\Android\sdk\cmake\bin\cmake.exe' with arguments {-HC:\Users\amishr33\AndroidStudioProjects\MyApplication\app\src\main\jni -BC:\Users\amishr33\AndroidStudioProjects\MyApplication\app\.externalNativeBuild\cmake\debug\armeabi -GAndroid Gradle - Ninja -DANDROID_ABI=armeabi -DANDROID_NDK=C:\Users\amishr33\AppData\Local\Android\sdk\ndk-bundle -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\amishr33\AndroidStudioProjects\MyApplication\app\build\intermediates\cmake\debug\obj\armeabi -DCMAKE_BUILD_TYPE=Debug -DCMAKE_MAKE_PROGRAM=C:\Users\amishr33\AppData\Local\Android\sdk\cmake\bin\ninja.exe -DCMAKE_TOOLCHAIN_FILE=C:\Users\amishr33\AppData\Local\Android\sdk\ndk-bundle\build\cmake\android.toolchain.cmake -DANDROID_NATIVE_API_LEVEL=15 -DCMAKE_CXX_FLAGS=-std=c++11 -DANDROID_TOOLCHAIN=clang -DANDROID_STL=gnustl_static}
CMake Error: Could not create named generator Android Gradle - Ninja
Generators
  Visual Studio 15 2017 [arch] = Generates Visual Studio 2017 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 14 2015 [arch] = Generates Visual Studio 2015 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 12 2013 [arch] = Generates Visual Studio 2013 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 11 2012 [arch] = Generates Visual Studio 2012 project files.
                                 Optional [arch] can be "Win64" or "ARM".
  Visual Studio 10 2010 [arch] = Generates Visual Studio 2010 project files.
                                 Optional [arch] can be "Win64" or "IA64".
  Visual Studio 9 2008 [arch]  = Generates Visual Studio 2008 project files.
                                 Optional [arch] can be "Win64" or "IA64".
  Visual Studio 8 2005 [arch]  = Generates Visual Studio 2005 project files.
                                 Optional [arch] can be "Win64".
  Visual Studio 7 .NET 2003    = Deprecated.  Generates Visual Studio .NET
                                 2003 project files.
  Borland Makefiles            = Generates Borland makefiles.
  NMake Makefiles              = Generates NMake makefiles.
  NMake Makefiles JOM          = Generates JOM makefiles.
  Green Hills MULTI            = Generates Green Hills MULTI files
                                 (experimental, work-in-progress).
  MSYS Makefiles               = Generates MSYS makefiles.
  MinGW Makefiles              = Generates a make file for use with
                                 mingw32-make.
  Unix Makefiles               = Generates standard UNIX makefiles.
  Ninja                        = Generates build.ninja files.
  Watcom WMake                 = Generates Watcom WMake makefiles.
  CodeBlocks - MinGW Makefiles = Generates CodeBlocks project files.
  CodeBlocks - NMake Makefiles = Generates CodeBlocks project files.
  CodeBlocks - Ninja           = Generates CodeBlocks project files.
  CodeBlocks - Unix Makefiles  = Generates CodeBlocks project files.
  CodeLite - MinGW Makefiles   = Generates CodeLite project files.
  CodeLite - NMake Makefiles   = Generates CodeLite project files.
  CodeLite - Ninja             = Generates CodeLite project files.
  CodeLite - Unix Makefiles    = Generates CodeLite project files.
  Sublime Text 2 - MinGW Makefiles
                               = Generates Sublime Text 2 project files.
  Sublime Text 2 - NMake Makefiles
                               = Generates Sublime Text 2 project files.
  Sublime Text 2 - Ninja       = Generates Sublime Text 2 project files.
  Sublime Text 2 - Unix Makefiles
                               = Generates Sublime Text 2 project files.
  Kate - MinGW Makefiles       = Generates Kate project files.
  Kate - NMake Makefiles       = Generates Kate project files.
  Kate - Ninja                 = Generates Kate project files.
  Kate - Unix Makefiles        = Generates Kate project files.
  Eclipse CDT4 - NMake Makefiles
                               = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - MinGW Makefiles
                               = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Ninja         = Generates Eclipse CDT 4.0 project files.
  Eclipse CDT4 - Unix Makefiles= Generates Eclipse CDT 4.0 project files.
Error:executing external native build for cmake C:\Users\amishr33\AndroidStudioProjects\MyApplication\app\src\main\jni\CMakeLists.txt


问:
How to manage methods\variables caller class?
in class standard class Dialog exist an Object declare (in classDeclaration)

```<code>Object caller;
</code>```

In this class I'm able to get the caller class name. For example:

```<code>if (caller.name() == classStr(MyCallerClass) )
{
     // manage-pass variable in caller class
}
</code>```

If I catch in the IF, I want to pass a parameter in parm method in to  MyCallerClass.

How I can pass a simple parameter? For example:

```<code>if (caller.name() == classStr(MyCallerClass) )
{
     // MyCallerClass.myParmMethod(parameter);
}
</code>```

Thanks.

答:
Just call the method:

```<code>if (caller.name() == classStr(MyCallerClass))
    caller.myParmMethod('abc');
</code>```

As caller is of type Object the compiler accepts any method name, it uses duck typing.
A run time error happens if caller does not have the method.

That said, you should not change the standard Dialog class.
You might extend the class, though this is unlikely to be the right thing.

What you should do depends on information you do not give.

Body:
in class standard class Dialog exist an Object declare (in classDeclaration)

Object caller;

In this class I'm able to get the caller class name. For example:

if (caller.name() == classStr(MyCallerClass) )
{
     // manage-pass variable in caller class
}

If I catch in the IF, I want to pass a parameter in parm method in to  MyCallerClass.

How I can pass a simple parameter? For example:

if (caller.name() == classStr(MyCallerClass) )
{
     // MyCallerClass.myParmMethod(parameter);
}

Thanks.

Body:
Just call the method:

if (caller.name() == classStr(MyCallerClass))
    caller.myParmMethod('abc');

As caller is of type Object the compiler accepts any method name, it uses duck typing.
A run time error happens if caller does not have the method.

That said, you should not change the standard Dialog class.
You might extend the class, though this is unlikely to be the right thing.

What you should do depends on information you do not give.


问:
Analysis of list elements
I have a list of strings of variable length, from which I should remove elements of a certain length ONLY IF all the elements don't have the same length.

e.g.:

```<code>my_list = ['a', 'b', 'c'] # should remains the same (all elements have the same lenght)
</code>```

but:

```<code>my_list = ['a', 'ab', 'abc', 'abcd', 'b', 'bcd'] # 'a' and 'b' because their length is <2.
</code>```

Any ideas?

答:
From what you describe, this should do what you want, assuming your threshold can defined:

```<code>my_list1 = ['a', 'b', 'c']

my_list2 = ['a', 'ab', 'abc', 'abcd', 'b', 'bcd']

my_list3 = ['ab', 'abc', 'ac', 'defe']

def check_len(lst):
    if len(lst) < 2:
        return True

    first = lst[0]

    return all(len(x) == len(first) for x in lst[1:])

def filter_lst(lst, threshold):
    if check_len(lst):
        return lst

    return list(filter(lambda x : len(x) < threshold, lst))
    # or [x for x in lst if len(x) < 2], had this before, but decided to do something different

>>> print(filter_lst(my_list1, 2))
['a', 'b', 'c']
>>> print(filter_lst(my_list2, 2))
['a', 'b']
>>> print(filter_lst(my_list3, 3))
['ab', 'ac']
</code>```

This solution follows this procedure:

Check if all the elements are of the same length, using all() for lists with length 2 or greater

If they are all the same length, whereby check_len() returns True, return the list normally, irregardless of the threshold.

Otherwise, filter() only the elements in the list that are less than < the threshold in length.

Title: Analysis of list elements

Body:
I have a list of strings of variable length, from which I should remove elements of a certain length ONLY IF all the elements don't have the same length.

e.g.:

my_list = ['a', 'b', 'c'] # should remains the same (all elements have the same lenght)

but:

my_list = ['a', 'ab', 'abc', 'abcd', 'b', 'bcd'] # 'a' and 'b' because their length is <2.

Any ideas?

Body:
From what you describe, this should do what you want, assuming your threshold can defined:

my_list1 = ['a', 'b', 'c']

my_list2 = ['a', 'ab', 'abc', 'abcd', 'b', 'bcd']

my_list3 = ['ab', 'abc', 'ac', 'defe']

def check_len(lst):
    if len(lst) < 2:
        return True

    first = lst[0]

    return all(len(x) == len(first) for x in lst[1:])

def filter_lst(lst, threshold):
    if check_len(lst):
        return lst

    return list(filter(lambda x : len(x) < threshold, lst))
    # or [x for x in lst if len(x) < 2], had this before, but decided to do something different

>>> print(filter_lst(my_list1, 2))
['a', 'b', 'c']
>>> print(filter_lst(my_list2, 2))
['a', 'b']
>>> print(filter_lst(my_list3, 3))
['ab', 'ac']

This solution follows this procedure:

Check if all the elements are of the same length, using all() for lists with length 2 or greater

If they are all the same length, whereby check_len() returns True, return the list normally, irregardless of the threshold.

Otherwise, filter() only the elements in the list that are less than < the threshold in length.


问:
How to save foreign keys (SQL)
```<code>$sql = "INSERT INTO deelnemer (Account_ID, BehaaldePunten, School_ID, Icon_ID) VALUES
          ('Account_ID', (SELECT ID FROM account WHERE Gebruikersnaam = '$name'),
          0,
          ('School_ID', (SELECT ID FROM school WHERE Naam = '$school'),
          ('Icon_ID', (SELECT ID FROM icon WHERE ID = 1))
          INNER JOIN account ON deelnemer.Account_ID = account.ID,
          INNER JOIN school ON deelnemer.School_ID = school.ID";
          $result = $connection->prepare($sql);
          $result->execute();
</code>```

Hey guys, I'm pretty new to SQL. I need to save a row which contains some foreign keys and I tried some stuff already but nothing seems to work. I hope you can help me xX

This is the error message:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MariaDB server version for the right syntax to use near 'INNER JOIN
  account ON deelnemer.Account_ID = account.ID, INNER JO' at line 6' in
  C:\xampp\htdocs\GameBattle\test\Register_Modal.php:36 Stack trace: #0
  C:\xampp\htdocs\GameBattle\test\Register_Modal.php(36):
  PDOStatement->execute() #1
  C:\xampp\htdocs\GameBattle\test\login.php(84):
  require_once('C:\xampp\htdocs...') #2 {main} thrown in
  C:\xampp\htdocs\GameBattle\test\Register_Modal.php on line 36

答:
Try to replacing  :

```<code>('Account_ID', (SELECT ID FROM account WHERE Gebruikersnaam = '$name')
          0,
          ('School_ID', (SELECT ID FROM school WHERE Naam = '$school'),
</code>```

with just :

```<code>(SELECT ID FROM account WHERE Gebruikersnaam = '$name',
          0,
 SELECT ID FROM school WHERE Naam = '$school'
etc... )
</code>```

Title: How to save foreign keys (SQL)

Body:
$sql = "INSERT INTO deelnemer (Account_ID, BehaaldePunten, School_ID, Icon_ID) VALUES
          ('Account_ID', (SELECT ID FROM account WHERE Gebruikersnaam = '$name'),
          0,
          ('School_ID', (SELECT ID FROM school WHERE Naam = '$school'),
          ('Icon_ID', (SELECT ID FROM icon WHERE ID = 1))
          INNER JOIN account ON deelnemer.Account_ID = account.ID,
          INNER JOIN school ON deelnemer.School_ID = school.ID";
          $result = $connection->prepare($sql);
          $result->execute();

Hey guys, I'm pretty new to SQL. I need to save a row which contains some foreign keys and I tried some stuff already but nothing seems to work. I hope you can help me xX

This is the error message:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MariaDB server version for the right syntax to use near 'INNER JOIN
  account ON deelnemer.Account_ID = account.ID, INNER JO' at line 6' in
  C:\xampp\htdocs\GameBattle\test\Register_Modal.php:36 Stack trace: #0
  C:\xampp\htdocs\GameBattle\test\Register_Modal.php(36):
  PDOStatement->execute() #1
  C:\xampp\htdocs\GameBattle\test\login.php(84):
  require_once('C:\xampp\htdocs...') #2 {main} thrown in
  C:\xampp\htdocs\GameBattle\test\Register_Modal.php on line 36

Body:
Try to replacing  :

('Account_ID', (SELECT ID FROM account WHERE Gebruikersnaam = '$name')
          0,
          ('School_ID', (SELECT ID FROM school WHERE Naam = '$school'),

with just :

(SELECT ID FROM account WHERE Gebruikersnaam = '$name',
          0,
 SELECT ID FROM school WHERE Naam = '$school'
etc... )


问:
Yii2 - list every post - coding error
I am new in Yii2 and I made a site where i can write posts, view them, delete them etc...

I want to list every post from a DB on one page as a "timeline"

My code does not list any error simply just show the very first record only.

Here is my code from (views) index.php

```<code>        <?php

use yii\helpers\Html;
use yii\widgets\ListView;

/* @var $this yii\web\View */
/* @var $searchModel frontend\models\search\TweetSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'My tweets';

?>
<div class="tweet-model-index">

    <h1 class="text-center"><?= Html::encode($this->title) ?></h1>

    <p class="text-center">
        <?= Html::a('New Tweet', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

    <?php

    $con = \Yii::$app->db;

    $sql = $con->createCommand("SELECT * FROM tweet ORDER BY created_at DESC");

    $tweets = $sql->queryAll();

    if(!$tweets)
        echo '<h2> This is empty </h2>';
     else{
           foreach($tweets as $tweet){
       ?>

    <hr>
    <div class="container-fluid">
        <div class="col-md-8 col-md-offset-2">
            <h2 class="text-left">
                <?php echo $tweet['tweet_title']; ?>
                <br><small>Author: <b><?php echo $tweet['author_id'];?> </b>Created at: <b><?php echo date(($tweet['created_at']));?></b>
                    <br>Updated at: <b><?php echo date(($tweet['updated_at']));?>
                </small>
            </h2>

                <p class="text-left">
                <?= Html::a('Update', ['update', 'id' => $tweet['tweet_id']], ['class' => 'btn btn-primary']) ?>
                <?= Html::a('View', ['view', 'id' => $tweet['tweet_id']], ['class' => 'btn btn-primary']) ?>
                <?= Html::a('Delete', ['delete', 'id' => $tweet['tweet_id']], [
                                        'class' => 'btn btn-danger',
                                        'data' => [
                                        'confirm' => 'Are you sure you want to delete this item?',
                                        'method' => 'post',
                                        ],
                                    ]) ?>
                </p>

        </div>

    </div>

</div>
<?php endforeach; ?>
<?php endif; ?>
</code>```

May i ask You guys, how can I count the views on each post?

I tried this on my TweetController but doesn't work.

```<code>public function actionView($id)
{
    $this->render('view',array(
        'model'=>$this->loadModel($id));
}
</code>```

答:
update from </p>

```<code>$tweets = $sql->query();
</code>```

<p>to </p>

```<code>$tweets = $sql->queryAll();
</code>```

Title: Yii2 - list every post - coding error

Body:
I am new in Yii2 and I made a site where i can write posts, view them, delete them etc...

I want to list every post from a DB on one page as a "timeline"

My code does not list any error simply just show the very first record only.

Here is my code from (views) index.php

        <?php

use yii\helpers\Html;
use yii\widgets\ListView;

/* @var $this yii\web\View */
/* @var $searchModel frontend\models\search\TweetSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'My tweets';

?>

<?= Html::encode($this->title) ?>

        <?= Html::a('New Tweet', ['create'], ['class' => 'btn btn-success']) ?>

    <?php

    $con = \Yii::$app->db;

    $sql = $con->createCommand("SELECT * FROM tweet ORDER BY created_at DESC");

    $tweets = $sql->queryAll();

    if(!$tweets)
        echo '
 This is empty
';
     else{
           foreach($tweets as $tweet){
       ?>

                <?php echo $tweet['tweet_title']; ?>

Author: <?php echo $tweet['author_id'];?> Created at: <?php echo date(($tweet['created_at']));?>

Updated at: <?php echo date(($tweet['updated_at']));?>

                <?= Html::a('Update', ['update', 'id' => $tweet['tweet_id']], ['class' => 'btn btn-primary']) ?>
                <?= Html::a('View', ['view', 'id' => $tweet['tweet_id']], ['class' => 'btn btn-primary']) ?>
                <?= Html::a('Delete', ['delete', 'id' => $tweet['tweet_id']], [
                                        'class' => 'btn btn-danger',
                                        'data' => [
                                        'confirm' => 'Are you sure you want to delete this item?',
                                        'method' => 'post',
                                        ],
                                    ]) ?>

<?php endforeach; ?>
<?php endif; ?>

May i ask You guys, how can I count the views on each post?

I tried this on my TweetController but doesn't work.

public function actionView($id)
{
    $this->render('view',array(
        'model'=>$this->loadModel($id));
}

Body:
update from

$tweets = $sql->query();

to

$tweets = $sql->queryAll();


问:
Outlook 2013/2016 Add-In: Outlook.MailItem.Copy()-method doesn't work on a active inline response item
I have a C# Outlook add-in, and on 2013 and 2016. There is a problem with the new functionality where you can reply to an email from the reading-pane.

However my add-in does some stuff which requires a copy of the MailItem. But the Copy-method gives an exception.

"This method can't be used with an inline response mail item."

I have found little info about this, other than that is not supported.

Does anyone have ideas how to get around this? One link suggested opening it first with .Display(false). However, this doesn't help. Same error is raised. Display(true) will open it in a new window and leave the old one open. The Send button won't work and it is stuck in a infinite loop somewhere. Not a working solution either.

Would appreciate any help on this.

答: Well I never got any replies, but seems like Redemption can do this with copyto()-method.</p>


问:
Pythonic type hints with pandas?
Let's take a simple function that takes a str and returns a dataframe:

```<code>import pandas as pd
def csv_to_df(path):
    return pd.read_csv(path, skiprows=1, sep='\t', comment='#')
</code>```

What is the recommended pythonic way of adding type hints to this function?

If I ask python for the type of a DataFrame it returns pandas.core.frame.DataFrame.
The following won't work though, as it'll tell me that pandas is not defined.

```<code> def csv_to_df(path: str) -> pandas.core.frame.DataFrame:
     return pd.read_csv(path, skiprows=1, sep='\t', comment='#')
</code>```

答:
Why not just use pd.DataFrame?

```<code>import pandas as pd
def csv_to_df(path: str) -> pd.DataFrame:
    return pd.read_csv(path, skiprows=1, sep='\t', comment='#')
</code>```

Result is the same:

```<code>> help(csv_to_df)
Help on function csv_to_df in module __main__:
csv_to_df(path:str) -> pandas.core.frame.DataFrame
</code>```

Title: Pythonic type hints with pandas?

Body:
Let's take a simple function that takes a str and returns a dataframe:

import pandas as pd
def csv_to_df(path):
    return pd.read_csv(path, skiprows=1, sep='\t', comment='#')

What is the recommended pythonic way of adding type hints to this function?

If I ask python for the type of a DataFrame it returns pandas.core.frame.DataFrame.
The following won't work though, as it'll tell me that pandas is not defined.

 def csv_to_df(path: str) -> pandas.core.frame.DataFrame:
     return pd.read_csv(path, skiprows=1, sep='\t', comment='#')

Body:
Why not just use pd.DataFrame?

import pandas as pd
def csv_to_df(path: str) -> pd.DataFrame:
    return pd.read_csv(path, skiprows=1, sep='\t', comment='#')

Result is the same:

> help(csv_to_df)
Help on function csv_to_df in module __main__:
csv_to_df(path:str) -> pandas.core.frame.DataFrame


问:
Update 2 tables with trigger
I have two tables:

Table Order: IDOrder (PK), ProductId, Quantity, Price

Table Product: ProductId (PK), Name,...., Quantity

I want to change quantity of product table when quantity of order table was added. But this does not work.

Here is my trigger:

```<code>CREATE TRIGGER [dbo].[trg_updatequantity]
On [dbo].[order]
FOR UPDATE
AS
    IF UPDATE(quantity)
       UPDATE product
       SET product.quantity = product.quantity - (inserted.quantity - deleted.quantity)
       FROM (deleted
       INNER JOIN inserted ON deleted.IDOrder = inserted.IDOrder)
       INNER JOIN product ON product.productId = inserted.ProductId
</code>```

答:
Try This</p>

```<code>Create trigger [dbo].[trg_updatequantity]
On [dbo].[order]
FOR INSERT
AS

update product SET quantity= a.quantity - b.quantity
from product a
inner join (
    SELECT  ProductID, SUM( ISNULL( quantity, 0))quantity
    FROM    inserted
    GROUP BY ProductID) b
ON  a.ProductID = b.ProductID
</code>```

Title: Update 2 tables with trigger

Body:
I have two tables:

Table Order: IDOrder (PK), ProductId, Quantity, Price

Table Product: ProductId (PK), Name,...., Quantity

I want to change quantity of product table when quantity of order table was added. But this does not work.

Here is my trigger:

CREATE TRIGGER [dbo].[trg_updatequantity]
On [dbo].[order]
FOR UPDATE
AS
    IF UPDATE(quantity)
       UPDATE product
       SET product.quantity = product.quantity - (inserted.quantity - deleted.quantity)
       FROM (deleted
       INNER JOIN inserted ON deleted.IDOrder = inserted.IDOrder)
       INNER JOIN product ON product.productId = inserted.ProductId

Body:
Try This

Create trigger [dbo].[trg_updatequantity]
On [dbo].[order]
FOR INSERT
AS

update product SET quantity= a.quantity - b.quantity
from product a
inner join (
    SELECT  ProductID, SUM( ISNULL( quantity, 0))quantity
    FROM    inserted
    GROUP BY ProductID) b
ON  a.ProductID = b.ProductID