Q:

Doctrine 2 perform insert, update on entity locally but fails without error on staging

I have an entity called DoerTrip

namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Doer Trip
 *
 * @ORM\Table(name="doer_trip")
 * @ORM\Entity
 */
class DoerTrip extends AbstractEntity
{
const STATUS_PUBLISHED = 1;
const STATUS_UNPUBLISHED = 0;

/**
 * @var integer
 *
 * @ORM\Column(name="`id`", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
protected $id;

/**
 * @var \Application\Entity\Doer
 *
 * @ORM\ManyToOne(targetEntity="Doer")
 * @ORM\JoinColumn(name="`doer_id`", referencedColumnName="id")
 */
protected $doer; // inversedBy="trips"

/**
 * @var \Application\Entity\Trip
 *
 * @ORM\ManyToOne(targetEntity="Trip")
 * @ORM\JoinColumn(name="`trip_id`", referencedColumnName="id")
 */
protected $trip; //inversedBy="doers"

/**
 * @var bool
 *
 * @ORM\Column(name="`published`", type="boolean")
 */
protected $published;

/**
 * @var string
 *
 * @ORM\Column(name="`comment`", type="text")
 */
protected $comment;

/**
 * @var integer
 *
 * @ORM\Column(name="`target_sum`", type="integer")
 */
protected $targetSum;

public function __construct()
{
    $this->published = false;
}
/**
 * @param string $comment
 * @return $this
 */
public function setComment($comment)
{
    $this->comment = $comment;
    return $this;
}

/**
 * @return string
 */
public function getComment()
{
    return $this->comment;
}

/**
 * @param \Application\Entity\Doer $doer
 * @return $this
 */
public function setDoer(Doer $doer)
{
    $this->doer = $doer;
    return $this;
}

/**
 * @return \Application\Entity\Doer
 */
public function getDoer()
{
    return $this->doer;
}

/**
 * @param int $id
 * @return $this
 */
public function setId($id)
{
    $this->id = $id;
    return $this;
}

/**
 * @return int
 */
public function getId()
{
    return $this->id;
}

/**
 * @param boolean $published
 * @return $this
 */
public function setPublished($published)
{
    $this->published = $published;
    return $this;
}

/**
 * @return boolean
 */
public function getPublished()
{
    return $this->published;
}

/**
 * @param \Application\Entity\Trip $trip
 * @return $this
 */
public function setTrip(Trip $trip)
{
    $this->trip = $trip;
    return $this;
}

/**
 * @return \Application\Entity\Trip
 */
public function getTrip()
{
    return $this->trip;
}

/**
 * @param int $targetSum
 * @return $this
 */
public function setTargetSum($targetSum)
{
    $this->targetSum = $targetSum;
    return $this;
}

/**
 * @return int
 */
public function getTargetSum()
{
    return (null !== $this->targetSum) ? $this->targetSum : $this->getTrip()->getTargetAmount();
}
}

here Trip Entity:

 namespace Application\Entity;

 use Doctrine\Common\Collections\ArrayCollection;
 use Doctrine\Common\Collections\Collection;
 use Doctrine\ORM\Mapping as ORM;
 use Zend\Validator\IsInstanceOf;

 /**
  * Trip
  *
  * @ORM\Table(name="trip")
  * @ORM\Entity
 */
 class Trip extends AbstractEntity
 {
  const STATUS_ACTIVE = 'active';
  const STATUS_INACTIVE = 'inactive';
  const STATUS_BANNED = 'banned';

  /**
   * @var string
   *
   * @ORM\Column(name="name", type="string", length=255)
 */
protected $name;
/**
 * @var Collection
 *
 * @ORM\ManyToMany(targetEntity="Media", cascade={"remove"}, orphanRemoval=true)
 * @ORM\JoinTable(name="trip_media",
 * joinColumns={@ORM\JoinColumn(name="trip_id", referencedColumnName="id")},
 * inverseJoinColumns={@ORM\JoinColumn(name="file_id", referencedColumnName="id", unique=true)}
 * )
 */
protected $media;

/**
 * @var \Application\Entity\Media
 *
 * @ORM\OneToOne(targetEntity="Media", mappedBy="trip", cascade={"persist", "remove"})
 * @ORM\JoinColumn(name="main_media_id", referencedColumnName="id")
 */
protected $mainMedia;

/**
 * @var string
 *
 * @ORM\Column(name="api_key", type="string", length=255)
 */
protected $apiKey;

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

/**
 * @var \DateTime
 *
 * @ORM\Column(name="departure_date", type="date", nullable=true)
 */
protected $departureDate;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="due_date", type="date", nullable=true)
 */
protected $dueDate;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="return_date", type="date", nullable=true)
 */
protected $returnDate;

/**
 * @var string
 *
 * @ORM\Column(name="description", type="text", nullable=true)
 */
protected $description;

/**
 * @var string
 *
 * @ORM\Column(name="target_amount", type="integer")
 */
protected $targetAmount;

/**
 * @var Collection
 *
 * @ORM\OneToMany(targetEntity="DoerTrip", mappedBy="trip", cascade={"persist","remove"}, orphanRemoval=true)
 */
protected $doers;

/**
 * @var Organization
 *
 * @ORM\ManyToOne(targetEntity="Organization", inversedBy="trips")
 * @ORM\JoinColumn(name="organization_id", referencedColumnName="id")
 */
protected $organization;

/**
 * @var Cause
 *
 * @ORM\OneToOne(targetEntity="Cause", inversedBy="trips")
 * @ORM\JoinColumn(name="cause_id", referencedColumnName="id", onDelete="SET NULL")
 */
protected $cause;

/**
 * @var integer
 *
 * @ORM\Column(name="status", type="string" ,columnDefinition="ENUM('active', 'inactive', 'banned')")
 */
protected $status;
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
protected $id;

/**
 * @var Transaction
 *
 * @ORM\OneToMany(targetEntity="Transaction", mappedBy="trip", cascade={"remove"}, orphanRemoval=true)
 */
protected $transactions;

/**
 * @param Organization $organization
 * @return $this
 */
public function setOrganization(Organization $organization)
{
    $this->organization = $organization;
    return $this;
}

/**
 * @return Organization
 */
public function getOrganization()
{
    return $this->organization;
}

public function __construct()
{
    $this->doers = new ArrayCollection();
    $this->media = new ArrayCollection();
    $this->status = self::STATUS_ACTIVE;
    $this->transactions = new ArrayCollection();
    $this->targetAmount = 0;
    $this->description = '';
}

/**
 * @param string $apiKey
 * @return $this
 */
public function setApiKey($apiKey)
{
    $this->apiKey = $apiKey;
    return $this;
}

/**
 * @return string
 */
public function getApiKey()
{
    return $this->apiKey;
}

/**
 * @param string $country
 * @return $this
 */
public function setCountry($country)
{
    $this->country = $country;
    return $this;
}

/**
 * @return string
 */
public function getCountry()
{
    return $this->country;
}

/**
 * @param string $description
 * @return $this
 */
public function setDescription($description)
{
    $this->description = $description;
    return $this;
}

/**
 * @return string
 */
public function getDescription()
{
    return $this->description;
}

/**
 * @param \DateTime $dueDate
 * @return $this
 */
public function setDueDate(\DateTime $dueDate)
{
    $this->dueDate = $dueDate;
    return $this;
}

/**
 * @return \DateTime
 */
public function getDueDate()
{
    return $this->dueDate;
}

/**
 * @param int $id
 * @return $this
 */
public function setId($id)
{
    $this->id = $id;
    return $this;
}

/**
 * @return int
 */
public function getId()
{
    return $this->id;
}

/**
 * @param \DateTime $departureDate
 * @return $this
 */
public function setDepartureDate(\DateTime $departureDate)
{
    $this->departureDate = $departureDate;
    return $this;
}

/**
 * @return \DateTime
 */
public function getDepartureDate()
{
    return $this->departureDate;
}

/**
 * @param string $targetAmount
 * @return $this
 */
public function setTargetAmount($targetAmount)
{
    $this->targetAmount = $targetAmount;
    return $this;
}

/**
 * @return string
 */
public function getTargetAmount()
{
    return $this->targetAmount;
}

/**
 * @param string $name
 * @return $this
 */
public function setName($name)
{
    $this->name = $name;
    return $this;
}

/**
 * @return string
 */
public function getName()
{
    return $this->name;
}

/**
 * @param int $status
 * @return $this
 */
public function setStatus($status)
{
    $this->status = $status;
    return $this;
}

/**
 * @return int
 */
public function getStatus()
{
    return $this->status;
}

/**
 * @param \Application\Entity\Cause $cause
 * @return $this
 */
public function setCause($cause)
{
    $this->cause = $cause;
    return $this;
}

/**
 * @return \Application\Entity\Cause
 */
public function getCause()
{
    return $this->cause;
}

/**
 * @param \Doctrine\Common\Collections\Collection $media
 * @return $this
 */
public function setMedia($media)
{
    $this->media = $media;
    return $this;
}

/**
 * @return \Doctrine\Common\Collections\Collection
 */
public function getMedia()
{
    return $this->media;
}

/**
 * @param \Application\Entity\DoerTrip $doer
 * @return $this
 */
public function addDoer(DoerTrip $doer)
{
    $this->doers->add($doer);
    $doer->setTrip($this);
    return $this;
}

/**
 * @param Collection $doers
 * @return $this
 */
public function setDoers(Collection $doers)
{
    $this->doers = $doers;
    return $this;
}

/**
 * @return Collection
 */
public function getDoers()
{
    return $this->doers;
}

/**
 * @param \Application\Entity\DoerTrip $doer
 * @return $this
 */
public function removeDoer(DoerTrip $doer)
{
    $this->doers->removeElement($doer);
    return $this;
}

/**
 * @param \Doctrine\Common\Collections\Collection $transactions
 * @return $this
 */
public function setTransactions($transactions)
{
    $this->transactions = $transactions;
    return $this;
}

/**
 * @return \Doctrine\Common\Collections\Collection
 */
public function getTransactions()
{
    return $this->transactions;
}

/**
 * @param array $data
 * @return $this
 */
public function populate(array $data)
{
    if (!empty($data['departureDate']) && !$data['departureDate'] instanceof \DateTime) {
        $data['departureDate'] = new \DateTime($data['departureDate']);
    }
    if (!empty($data['dueDate']) && !$data['dueDate'] instanceof \DateTime) {
        $data['dueDate'] = new \DateTime($data['dueDate']);
    }

    if (!empty($data['returnDate']) && !$data['returnDate'] instanceof \DateTime) {
        $data['returnDate'] = new \DateTime($data['returnDate']);
    }
    parent::populate($data);
    return $this;
}

/**
 * @param \DateTime $returnDate
 * @return $this
 */
public function setReturnDate(\DateTime $returnDate)
{
    $this->returnDate = $returnDate;
    return $this;
}

/**
 * @return \DateTime
 */
public function getReturnDate()
{
    return $this->returnDate;
}

/**
 * @param \Application\Entity\Media $mainMedia
 * @return $this
 */
public function setMainMedia($mainMedia)
{
    $this->mainMedia = $mainMedia;
    return $this;
}

/**
 * @return \Application\Entity\Media
 */
public function getMainMedia()
{
    return $this->mainMedia;
}

/**
 * @param Media $media
 * @return bool
 */
public function hasMedia(Media $media)
{
    return $this->getMedia()->contains($media);
}

/**
 * @param \Application\Entity\Media $media
 * @return $this
 */
public function addMedia(Media $media)
{
    $this->media->add($media);
    return $this;
}

/**
 * @param \Application\Entity\Media $media
 * @return $this
 */
public function removeMedia(Media $media)
{
    $this->media->removeElement($media);
    return $this;
}

}

Here is Doer Entity

namespace Application\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Zend\Validator\IsInstanceOf;

/**
 * Trip
 *
 * @ORM\Table(name="trip")
 * @ORM\Entity
*/
class Trip extends AbstractEntity
{
const STATUS_ACTIVE = 'active';
const STATUS_INACTIVE = 'inactive';
const STATUS_BANNED = 'banned';

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=255)
 */
protected $name;
/**
 * @var Collection
 *
 * @ORM\ManyToMany(targetEntity="Media", cascade={"remove"}, orphanRemoval=true)
 * @ORM\JoinTable(name="trip_media",
 * joinColumns={@ORM\JoinColumn(name="trip_id", referencedColumnName="id")},
 * inverseJoinColumns={@ORM\JoinColumn(name="file_id", referencedColumnName="id", unique=true)}
 * )
 */
protected $media;

/**
 * @var \Application\Entity\Media
 *
 * @ORM\OneToOne(targetEntity="Media", mappedBy="trip", cascade={"persist", "remove"})
 * @ORM\JoinColumn(name="main_media_id", referencedColumnName="id")
 */
protected $mainMedia;

/**
 * @var string
 *
 * @ORM\Column(name="api_key", type="string", length=255)
 */
protected $apiKey;

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

/**
 * @var \DateTime
 *
 * @ORM\Column(name="departure_date", type="date", nullable=true)
 */
protected $departureDate;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="due_date", type="date", nullable=true)
 */
protected $dueDate;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="return_date", type="date", nullable=true)
 */
protected $returnDate;

/**
 * @var string
 *
 * @ORM\Column(name="description", type="text", nullable=true)
 */
protected $description;

/**
 * @var string
 *
 * @ORM\Column(name="target_amount", type="integer")
 */
protected $targetAmount;

/**
 * @var Collection
 *
 * @ORM\OneToMany(targetEntity="DoerTrip", mappedBy="trip", cascade={"persist","remove"}, orphanRemoval=true)
 */
protected $doers;

/**
 * @var Organization
 *
 * @ORM\ManyToOne(targetEntity="Organization", inversedBy="trips")
 * @ORM\JoinColumn(name="organization_id", referencedColumnName="id")
 */
protected $organization;

/**
 * @var Cause
 *
 * @ORM\OneToOne(targetEntity="Cause", inversedBy="trips")
 * @ORM\JoinColumn(name="cause_id", referencedColumnName="id", onDelete="SET NULL")
 */
protected $cause;

/**
 * @var integer
 *
 * @ORM\Column(name="status", type="string" ,columnDefinition="ENUM('active', 'inactive', 'banned')")
 */
protected $status;
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
protected $id;

/**
 * @var Transaction
 *
 * @ORM\OneToMany(targetEntity="Transaction", mappedBy="trip", cascade={"remove"}, orphanRemoval=true)
 */
protected $transactions;

/**
 * @param Organization $organization
 * @return $this
 */
public function setOrganization(Organization $organization)
{
    $this->organization = $organization;
    return $this;
}

/**
 * @return Organization
 */
public function getOrganization()
{
    return $this->organization;
}

public function __construct()
{
    $this->doers = new ArrayCollection();
    $this->media = new ArrayCollection();
    $this->status = self::STATUS_ACTIVE;
    $this->transactions = new ArrayCollection();
    $this->targetAmount = 0;
    $this->description = '';
}

/**
 * @param string $apiKey
 * @return $this
 */
public function setApiKey($apiKey)
{
    $this->apiKey = $apiKey;
    return $this;
}

/**
 * @return string
 */
public function getApiKey()
{
    return $this->apiKey;
}

/**
 * @param string $country
 * @return $this
 */
public function setCountry($country)
{
    $this->country = $country;
    return $this;
}

/**
 * @return string
 */
public function getCountry()
{
    return $this->country;
}

/**
 * @param string $description
 * @return $this
 */
public function setDescription($description)
{
    $this->description = $description;
    return $this;
}

/**
 * @return string
 */
public function getDescription()
{
    return $this->description;
}

/**
 * @param \DateTime $dueDate
 * @return $this
 */
public function setDueDate(\DateTime $dueDate)
{
    $this->dueDate = $dueDate;
    return $this;
}

/**
 * @return \DateTime
 */
public function getDueDate()
{
    return $this->dueDate;
}

/**
 * @param int $id
 * @return $this
 */
public function setId($id)
{
    $this->id = $id;
    return $this;
}

/**
 * @return int
 */
public function getId()
{
    return $this->id;
}

/**
 * @param \DateTime $departureDate
 * @return $this
 */
public function setDepartureDate(\DateTime $departureDate)
{
    $this->departureDate = $departureDate;
    return $this;
}

/**
 * @return \DateTime
 */
public function getDepartureDate()
{
    return $this->departureDate;
}

/**
 * @param string $targetAmount
 * @return $this
 */
public function setTargetAmount($targetAmount)
{
    $this->targetAmount = $targetAmount;
    return $this;
}

/**
 * @return string
 */
public function getTargetAmount()
{
    return $this->targetAmount;
}

/**
 * @param string $name
 * @return $this
 */
public function setName($name)
{
    $this->name = $name;
    return $this;
}

/**
 * @return string
 */
public function getName()
{
    return $this->name;
}

/**
 * @param int $status
 * @return $this
 */
public function setStatus($status)
{
    $this->status = $status;
    return $this;
}

/**
 * @return int
 */
public function getStatus()
{
    return $this->status;
}

/**
 * @param \Application\Entity\Cause $cause
 * @return $this
 */
public function setCause($cause)
{
    $this->cause = $cause;
    return $this;
}

/**
 * @return \Application\Entity\Cause
 */
public function getCause()
{
    return $this->cause;
}

/**
 * @param \Doctrine\Common\Collections\Collection $media
 * @return $this
 */
public function setMedia($media)
{
    $this->media = $media;
    return $this;
}

/**
 * @return \Doctrine\Common\Collections\Collection
 */
public function getMedia()
{
    return $this->media;
}

/**
 * @param \Application\Entity\DoerTrip $doer
 * @return $this
 */
public function addDoer(DoerTrip $doer)
{
    $this->doers->add($doer);
    $doer->setTrip($this);
    return $this;
}

/**
 * @param Collection $doers
 * @return $this
 */
public function setDoers(Collection $doers)
{
    $this->doers = $doers;
    return $this;
}

/**
 * @return Collection
 */
public function getDoers()
{
    return $this->doers;
}

/**
 * @param \Application\Entity\DoerTrip $doer
 * @return $this
 */
public function removeDoer(DoerTrip $doer)
{
    $this->doers->removeElement($doer);
    return $this;
}

/**
 * @param \Doctrine\Common\Collections\Collection $transactions
 * @return $this
 */
public function setTransactions($transactions)
{
    $this->transactions = $transactions;
    return $this;
}

/**
 * @return \Doctrine\Common\Collections\Collection
 */
public function getTransactions()
{
    return $this->transactions;
}

/**
 * @param array $data
 * @return $this
 */
public function populate(array $data)
{
    if (!empty($data['departureDate']) && !$data['departureDate'] instanceof \DateTime) {
        $data['departureDate'] = new \DateTime($data['departureDate']);
    }
    if (!empty($data['dueDate']) && !$data['dueDate'] instanceof \DateTime) {
        $data['dueDate'] = new \DateTime($data['dueDate']);
    }

    if (!empty($data['returnDate']) && !$data['returnDate'] instanceof \DateTime) {
        $data['returnDate'] = new \DateTime($data['returnDate']);
    }
    parent::populate($data);
    return $this;
}

/**
 * @param \DateTime $returnDate
 * @return $this
 */
public function setReturnDate(\DateTime $returnDate)
{
    $this->returnDate = $returnDate;
    return $this;
}

/**
 * @return \DateTime
 */
public function getReturnDate()
{
    return $this->returnDate;
}

/**
 * @param \Application\Entity\Media $mainMedia
 * @return $this
 */
public function setMainMedia($mainMedia)
{
    $this->mainMedia = $mainMedia;
    return $this;
}

/**
 * @return \Application\Entity\Media
 */
public function getMainMedia()
{
    return $this->mainMedia;
}

/**
 * @param Media $media
 * @return bool
 */
public function hasMedia(Media $media)
{
    return $this->getMedia()->contains($media);
}

/**
 * @param \Application\Entity\Media $media
 * @return $this
 */
public function addMedia(Media $media)
{
    $this->media->add($media);
    return $this;
}

/**
 * @param \Application\Entity\Media $media
 * @return $this
 */
public function removeMedia(Media $media)
{
    $this->media->removeElement($media);
    return $this;
}
}

I perform this sample of code:
 $doerTrip = new DoerTrip();
 $doerTrip->setDoer($doer)->setTrip($trip);
 $em->persist($doerTrip);
 $em->flush();

locally it works (on Windows). But on staging (Ubuntu) new record is not created and I don't get any errors. Update of the entity DoerTrip on staging doesn't work too.
If I perform insert with the  help of connection something like this
     $stmt = $conn->prepare('INSERT INTO doer_trip (...) VALUES (?,?,?,?,?)');
     $stmt->bindParam(1, $param);
      ...

everything works fine.
When using ORM in SQL Logger I can see
START TRANSACTION;
INSERT INTO doer_trip (...) VALUES (?,?,?,?,?)
COMMIT;

but new record is not created on staging.
locally everything works fine.
I don't know maybe it depends on MySQL configuration.
I have no idea.
Here my doer_trip table
CREATE TABLE `doer_trip` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`doer_id` INT(11) NOT NULL,
`trip_id` INT(11) UNSIGNED NOT NULL,
`published` INT(1) UNSIGNED NOT NULL DEFAULT '0',
`comment` TEXT NULL,
`target_sum` INT(10) UNSIGNED NULL DEFAULT NULL,
PRIMARY KEY (`id`),
INDEX `doer_id` (`doer_id`),
INDEX `trip_id` (`trip_id`),
UNIQUE INDEX `doer_iduniq` (`doer_id`, `trip_id`),
CONSTRAINT `FK_doer_trip_trip` FOREIGN KEY (`trip_id`) REFERENCES `trip` (`id`),
CONSTRAINT `FK_doer_trip_doer` FOREIGN KEY (`doer_id`) REFERENCES `doer` (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=41

A:

The problem was in
/**
 * @var bool
 *
 * @ORM\Column(name="`published`", type="boolean")
 */
protected $published;

If I set type to integer like this
/**
 * @var integer
 *
 * @ORM\Column(name="`published`", type="integer")
 */
protected $published;

Everything work fine. But why it works fine on my local environment???


Q:

Should I Print the Exception Stack Trace?

How inefficient is it to get the stack trace for an exception?  I know it's costly, but how costly?  Should they definitely not be used in production environment?

A:

In a production environment, it's helpful to log the stack trace so the user can find it when they contact tech support.  Printing stack trace in place of an understandable (by the typical user) message should be avoided.
You shouldn't be concerned with the efficiency of exceptional blocks of code.  Error recovery is the most important thing here.

A:

If exceptions are on your critical path, you've already got performance issues. Getting the stack trace to track down the exception is crucial, IMO.

A:

My question is why are you caring about performance when something has unexpectedly gone wrong? At this point the sanity of your application is in question so who cares if it's fast?


Q:

Dockerfileのダイエット方法を教えて下さい

Dockerfileで実行できるコマンド数を減らす方法に関して、なにか知ってれば教えて下さい。
自分の場合、下記のようにコマンドまとめたりして頑張ってるのですが、他なにかいい手段ありますか？
RUN \
yum -y update; \
yum install httpd....

A:

基本的に、Optimizing Docker Imagesこのページでまとめられているのが有力なものです。
以下では、これに加えて私がイメージを作る際に周囲からもらったアドバイスや試してみたことなども含めて書いてみます。
可能な限り、必要最小限のサイズのイメージからスタートする
上記ページにも記載があるように、例えばUbuntuよりもDebianを使います。私の場合は趣味的にはUbuntuが好きなのですが、配布用のDockerイメージはDebianのwheezyベースなどで作っています。上記ページにもあるように、これだけで100MBぐらい違ったりします。
RUNでのコマンドをチェーンさせてステージ数を減らす
torusさんの回答にあるものです。DockerではRUNの単位でファイルシステムの更新をおこなうので、仮にあるステージで大きなファイルを追加、その後のステージで当該ファイルを削除しても容量は食いっぱなしとなります。
私が過去に作ったものでは、あるソフトウェアのソースを拾ってきてmake && make install、その後にソース一式を削除するところまでをひとつにチェーンさせることで容量削減できました。
不要な中間ファイルは削除する
私がイメージを作成していた時に指摘をもらったものなのですが、/usr/local/src以下にあるソースを拾ってきて、それをmake && make installしたままソースコードを残していたことがありました。
これは、ソースを残しておいたほうが何かといじりやすいと考えての対応でした。さらに言うと、あるソースのスナップショットではなく丸ごとgit cloneしていました。これは様々な実験をおこなう際には便利ですし開発環境のDockerイメージを提供しようという際には良いのです。しかしバイナリ配布でサクッと導入してもらえるようなイメージの構築においてはただの無駄ということで納得しました。
ソースはmake installが終わったら消しましょう。ソースが本当に必要な人は、Dockerfileをforkして自前でなんとかしてくれます多分。
GitHubからソースを拾ってくるものについて、なるべくgit cloneしない
もっと言うと、不要ならgitコマンドをインストールしない(いくらgitのない世界が不安で仕方なくても)。
これも私がとあるイメージを作成していた時にもらった指摘に関するものです。
GitHubで配布されているコードを使ったビルドをおこなうならひとまずgit cloneしてくるのが普通だろうという開発脳なのですが、Dockerのイメージを作る際には「えっ、ほんとにgitいる?」と疑うのが肝心です。
Debianでgit-coreパッケージをインストールするだけでも数十MBの追加容量が必要となるので、指定リリースの*.tar.gzファイルを拾ってきて展開すれば十分なケースではgitのインストールすら避けるのが良いでしょう。
繰り返しとなりますが、チーム用などに開発用環境を用意する際は別です。
特に事情がなければディストリビューションのバイナリ配布物を利用する
ソフトウェアパッケージのビルドには多くの追加パッケージが必要です。gcc、libstdc++6-dev、make、autotools、cmakeなどなど。build-essentialをえいやっと追加すると一気にディスク容量が膨らみます。
というわけで、もし特殊な事情がなければ、なるべくディストリビューションの提供するバイナリ配布物を使うようにDockerfileを記述すべきです。
しかし、ディストリビューションの公式パッケージに入っていないものやバージョンが古いもの・互換性のないものなどについては仕方ありません。なるべく追加容量が最小限で済むように留意しつつ、パッケージをインストールしましょう。
イメージビルド中の多階層ディレクトリに対するchownを避ける
Dockerfile Golf (or optimizing the Docker build process)で紹介されていました。
これもDockerの構造がステージごとにファイルシステム状態を記録することに関連します。このblogでは、特定ディレクトリへのchownをビルドフェーズでおこなったところ、72MBもの容量増につながったという話が紹介されています。
代替策として、chownをCOMMANDでの起動シーケンスへと移動したということです。なかなか難しいですね。
ONBUILDを利用して一部処理をイメージ実行時へ逃がす
利用できるシーンが一定限られますが、例えば「あるシステムの実行のために大量の静的ファイル(しかもそれなりに頻繁な更新がおこなわれる)を拾ってくる必要がある」といった場合に有効です。
コンテナの一部として頻繁な更新のおこなわれるファイル群を利用する場合、それらが更新される都度Docker Hubでのビルドをおこなうのはあまり効率的と言えません。
そこで用意されているのがONBUILDコマンドです。RUNコマンドがイメージ生成時に実行されるコマンドであるのに対して、ONBUILDコマンド(マニュアル)は当該処理をコンテナ生成時まで後回しするものです。
番外編: 既存の巨大イメージをダイエットする
基本的にはDockerfileを編集してイメージ作り工程を改善するお話ですが、仮にDockerfileへアクセスできなくてもとれる策がこれです(これも上記ページで紹介されています)。
実行中のコンテナを指定して
docker export <container id> | docker import - <new image name>
で、イメージのビルド時にステージごとに生成されたレイヤがごっそり統合されます。結果として、ベースイメージからの差分保持すらされなくなるため、場合によっては当該イメージ単体のサイズは増えるかもしれません。
他方、パフォーマンス面では実行時にアクセスするfsレイヤを減らせるのでファイルI/O面は多少有利になるかもしれません。
メリットとデメリットを把握して利用する必要のある策です。


Q:

$F(f)\subset F(x)$ is an algebraic extension of degree $\max(p,q)$ if $f$ is non constant quotient polynomial

Let $F$ be a field, with $f=a/b\in F(x)$ the quotient of coprime polynomials $a,b\in F[x]$ of degree $p$ and $q$ respectively.

How do I prove that if $f$ is not constant, then $F(f)\subset F(x)$ is an algebraic extension of degree $\max(p,q)$?

I honestly have no idea how to approach this problem, maybe someone can give me a push in the right direction?

A:

Let $f(x) = t$. Then you can think of your extension as $F(t) \subset F(t)[x]/(a(x)-tb(x))$. I can elaborate more but you should try finishing the proof from here on.


Q:

Can you receive eggs from Pokestops with a full bag?

Is it possible to receive an egg from a Pokestop when your bag is at or above its capacity, but there is room for additional eggs?
I tried this 6 or 7 times today while I only had 5 eggs, and did not get any, but this could have just been bad luck.

A:

From my own personal experience you cannot receives eggs from pokestops if your item inventory is full even if you have less than 9 eggs in your pokemon inventory. Some cursory searching doesn't show anyone who has been able to receive eggs when inventory is full.
Source: Personal experience and here


Q:

Google Plus SignIn calls getting queued up

I am trying to user google+ login in my backbone js app. The user flow is that

User clicks on a login button
This will open a bootstrap ( thttp://twitter.github.io/bootstrap/ ) modal with the google+ sign in button ( along with facebook login, etc )
The user has to explicitly click on the g+ sign in button to log into my site.

To prevent automatic g+ SignIn what I do is display a custom g+ signin button and onclick I use the "gapi.signin.render" api with that custom signin button as the container. This works fine the very first time the signin button is clicked, but if the user logs out and tries to relogin nothing happens in the first click, but on the second click the g+ signin is triggered twice and increases by 1 everytime the user logs out and relogs in. And each time the g+ signin is triggered only on the second click. Note that my app is a single page app so there are no reloads between the logout and login. If I reload the site then again it works the first time and the issues is back for the subsequent sign ins.
Note: The modal( and its DOM ) I use for displaying the g+ Sign in buttons is removed after every successfull login and recreated everytime the user clicks on the main login button. I notice that after the successfull login the iframes created by g+ sign in button are still around and may be interfering when I recreate the modal again and invoke the "gapi.signin.render" api call.
The code I use is
In the backbone view, the render method has
render: function() {
        var thisV = this;
        _.defer(function(){
            gapi.signin.render('gSignIn', {
              'callback': thisV.gPlusLoginCB,
              'clientid': "clientID",
              'requestvisibleactions': "http://schemas.google.com/AddActivity",
              'scope': "https://www.googleapis.com/auth/plus.login",
              'theme': 'dark',
              'cookiepolicy': "single_host_origin"
            });
        });
    }

And in the html template I have
<button id="gSignIn" class="btn gplogin">
      <i class="icon-google-plus"></i>Login
</button>

Any thoughts on how why the G+ Sign In calls are getting queued up or how to implement my scenario ?
Thanks

A:

Sorry that so late. I just had the exact same issue.
When I moved the creation of the options object out of the function everything worked fine:
var options = {
                  'callback': thisV.gPlusLoginCB,
                  'clientid': "clientID",
                  'requestvisibleactions': "http://schemas.google.com/AddActivity",
                  'scope': "https://www.googleapis.com/auth/plus.login",
                  'theme': 'dark',
                  'cookiepolicy': "single_host_origin"
                }

/**

/**

/**

    render: function() {
            var thisV = this;
            _.defer(function(){
                gapi.signin.render('gSignIn', options );
            });
        }


Q:

Difference in $interpolate between AngularJS 1.0 and 1.2

I'm writing a filter to format addresses in a single line. The object that will be passed into the filter has the format:
{
  Line1: "123 Main St.",
  Line2: "Apartment 2", // Optional
  City: "Chicago",
  State: "IL",
  Zip: "60623"
}

I have the following so far:
angular.module('myApp')
  .filter('address', function ($interpolate) {
    return function (input, template) {

      if (input === null || !angular.isDefined(input)) {
        return input;
      }

      // template is optional. If not provided, use the following
      if(!template) {
        template = '{{Line1}}, {{Line2 ? Line2 + \', \' : \'\'}}{{City}} {{State}} {{Zip}}';
      }

      try {
        var parsedTemplate = $interpolate(template);
      } catch (e) {
        console.log(parsedTemplate, template, input, e)
        return input;
      }

      // Compile the template in the context of the input object
      return parsedTemplate(input);
    };
  });

In Angular 1.2 this works fine. However, in Angular 1.0 it fails with the error Error: Lexer Error: Unexpected next character  at columns 6-6 [?] in expression [Line2 ? Line2 + ', ' : '']. My thought is Angular 1.0 doesn't support the ternary operator $interpolated expressions, but I couldn't find any documentation suggesting that support was added in Angular 1.2.
Is there a way to use the ternary operator in Angular 1.0, and if not how can I get around that restriction?
(Bonus points - where in the documentation does it mention this change, or which commit in the Angular git repo made the change?)

A:

I realized that before I upgraded to 1.1.5, my workaround to using a ternary operator in interpolated expressions was to use && and || (like someCondition && TruthyResult || FalseyResult) to effectively get the same result. Here's how you'd apply it to your code:
template = '{{Line1}}, {{Line2 && (Line2 + \', \') || \'\'}}{{City}} {{State}} {{Zip}}';

DEMO: http://jsfiddle.net/f9n6r/
The only problem with this setup is if the the TruthyResult doesn't actually return something truthy, the FalseyResult will be returned (just the nature of using && and || like this, compared to the ternary operator). In your code though, (Line2 + \', \') will never be falsey because of the \', \', so it won't be a problem here. But in a more general case, it could be.


Q:

How to clean a specific index array?

I want to clean a specific index of array, in particular I've 3 index:
0:
   Appointments
   Unavailables
1:
   Appointments
   Unavailables
2:
   Appointments
   Unavailables

Now I want maintain the first appointments as 0 index. So this is my code:
foreach($appointments as $key => value)
{
   if($key != 0)
   {
      unset($appointments[$key]['appointments']);
   }
}

but unset delete also the key so the final result that I get is:
0:
   Appointments
   Unavailables
1:
   Unavailables
2:
   Unavailables

I want maintain the appointments object, just I need to empty it's content. How I can achieve this result?

A:

Instead of unsetting it just set it equal to an empty array:
$appointments[$key]['appointments'] = []
If it is an object as you state instead of an array, create a new one:
$appointments[$key]['appointments'] = new MyAppointmentObject;


Q:

How do I play an Ogg/Vorbis sound on IOS using OpenAL?

I'd like to play an Ogg/Vorbis sound file on an IOS device using OpenAL for its low-latency.
I have code that compiles and deploys onto an iPhone 6 but I'm getting no sound. I'm using virtually the same code that plays fine on Windows so I'm stuck here.
Code to load ogg:
#ifdef __APPLE__
#include <OpenAL/alc.h>
#include <OpenAL/al.h>
#include <UIKit/UIKit.h>
#else
#include <AL/al.h>
#include <AL/alc.h>
#endif
#include <vorbis/vorbisfile.h>
#define READ_BUFFER_SIZE 4096

static int endian = 2;

int load_ogg(const char* file_path, std::vector<char>* buffer, int* num_channels, int* freq)
{
    char readbuf[READ_BUFFER_SIZE];
    FILE* fp;
#ifdef __APPLE__
    char bundle_path[512];
    strcpy(bundle_path, file_path);
    char* p = bundle_path;
    while(*p != '.' && *p != 0)
        p++;
    *p = 0;
    NSString* path = [[NSBundle mainBundle] pathForResource: [NSString stringWithCString:bundle_path encoding:NSUTF8StringEncoding] ofType: @"ogg"];
    strcpy(bundle_path, path.UTF8String);
    fp = fopen(bundle_path, "rb");
#else
    fp = fopen(file_path, "rb");
#endif
    if(fp == NULL)
    {
        fflog_print("Load ogg failed - File not found.\n");
        return 1;
    }
    if(endian == 2)
    {
        uint32_t num = 0x01010000;
        uint8_t* p = (uint8_t*)#
        endian = *p;
    }
    OggVorbis_File ogg_file;
    vorbis_info* info;
    ov_open(fp, &ogg_file, NULL, 0);
    info = ov_info(&ogg_file, -1);
    *num_channels = info->channels;
    *freq = (int)info->rate;
    int bit_stream;
    int bytes;
    while(1)
    {
        bytes = ov_read(&ogg_file, readbuf, READ_BUFFER_SIZE, endian, 2, 1, &bit_stream);
        if(bytes > 0)
        {
            int starting_index = buffer->size();
            buffer->resize(buffer->size()+bytes);
            memcpy(&(*buffer)[starting_index], readbuf, bytes);
        }
        else
        {
            if(bytes < 0)
                fflog_print("read error.\n");
            break;
        }
    }
    ov_clear(&ogg_file);
    return 0;
}

Relevant code snippet that runs the above code:
ALCdevice* device = alcOpenDevice(NULL);
if(!device)
{
    fflog_print("device not found.\n");
    return NULL;
}
ALCcontext* context = alcCreateContext(device, NULL);
if(!alcMakeContextCurrent(context))
{
    fflog_print("Failed to make context current.\n");
    return NULL;
}
ALuint source;
alGenSources(1, &source);
//alListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f);
alSource3f(source, AL_POSITION, 0, 0, 0);
alSource3f(source, AL_VELOCITY, 0, 0, 0);
ALuint buffer;
alGenBuffers((ALuint)1, &buffer);
std::vector<char> oggbuffer;
int num_channels;
int freq;
fflog_print("loading music.ogg\n");
if(load_ogg("music.ogg", &oggbuffer, &num_channels, &freq))
{
    fflog_print("Failed to load ogg data.\n");
    return NULL;
}
fflog_print("finished loading music.ogg.\n");
ALenum format;
if(num_channels == 1)
    format = AL_FORMAT_MONO16;
else
    format = AL_FORMAT_STEREO16;
fflog_print("oggbuffer size=%d, freq=%d\n", (int)oggbuffer.size(), freq);
alBufferData(buffer, format, &oggbuffer[0], (ALsizei)oggbuffer.size(), freq);
alSourcei(source, AL_BUFFER, buffer);
alSourcePlay(source);

Why is there no sound playing on the device?

A:

Turns out I missed the step where I need to use AudioSessionInitialize to setup my audio session prior to opening an OpenAL device.
I had to add this before 'ALCdevice* device = alcOpenDevice(NULL);'
AudioSessionInitialize(NULL, NULL, NULL, NULL);
UInt32 session_category = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(session_category), &session_category);
AudioSessionSetActive(true);


Q:

Msys Git Merge Tool Command Options Issue

I'm using msys Git for source control on a Windows machine and I'm trying to figure out how to get my merge tool, WinMerge, to work with Git.
I've followed the instructions on this blog to the best of my ability since it's the closest I've found to what I'm trying to do. Basically what I did was:
Modify my .gitconfig file to include the following:

[merge]
    tool = winmerge

[mergetool "winmerge"]
    cmd = \"C:\\Program Files (x86)\\WinMerge\\WinMergeU.exe\" "$PWD/$LOCAL" "$PWD/$REMOTE" "$PWD/$MERGED"
        trustExitCode = false
    keepBackup = false

This is almost working. When I try to run the merge tool from Git, WinMerge gives me an error saying it can't find the paths of the files, which makes complete sense since the paths it is looking for are:

C:\MY\WORKING\DIRECTORY\-e
C:\MY\WORKING\DIRECTORY\-ub

It looks like Git is passing options into the merge tool instead of the local & remote file names that I would expect to get passed if everything was working correctly.
I've searched online for Git's merge documentation, but I can't seem to find anything related to what I'm trying to do. My guess is that the solution will be one of the following:

Change the $LOCAL & $REMOTE variables to the correct values, assuming $LOCAL & $REMOTE are incorrect.
Write a .bat script to call WinMergeU, and handle the arguments Git sends to the merge tool within the logic of my .bat script.

A:

If you look at the file that is conflicted, you'll notice the standard Theirs >>>>>>> and <<<<<< Mine markers. WinMerge understands these as merge conflicts, so it does not need 'Theirs' and 'Mine' to be specified explicitly; it just needs to be told which file it is that has the conflict markers.

We know the file in the working directory contains the markers.
It makes sense that the file we are merging to will also be this file - we also know that git mergetool makes the $MERGED variable available that names that file.
[mergetool "winmerge"]
    cmd = 'C:/Program Files/WinMerge/WinMergeU.exe' \"$MERGED\"

This is all you need to hook git up with WinMerge for merge/conflict resolution; no scripts or command-line switches needed. Refer to the 3rd command-line form in the docs (linked by the OP, above) and the explanation of conflictfile argument.

A:

From WinMerge Command line manual:
cmd = \"C:\\Program Files (x86)\\WinMerge\\WinMergeU.exe /ub /e \"
cmd = \"C:\\Program Files (x86)\\WinMerge\\WinMergeU.exe /u /e \"

(/u is the new /ub with latest WinMerge)
might work better as a command in your mergetool section.
However, you might have to wrap this call in a script, as described in this SO answer.
Extract adapted to merge.tool:

Practical case for configuring mergetool with your custom diff tool:

C:\myGitRepo>git config --global merge.tool winmerge
C:\myGitRepo>git config --global mergetool.winmerge.cmd "winmerge.sh \"$LOCAL\" \"$REMOTE\""
C:\myGitRepo>git config --global mergetool.prompt false

With winmerge.sh stored in a directory part of your PATH:
#!/bin/sh
echo Launching WinMergeU.exe: $1 $2
"C:/Program Files/WinMerge/WinMergeU.exe" -e -ub "$1" "$2"

If you have another tool (kdiff3, P4Diff, ...), create another shell script, and the appropriate mergetool.myMergeTool.cmd config directive.
  Then you can easily switch tools with the merge.tool config.

A:

[mergetool "winmerge"]
    cmd = winmergeu -e -ub -wl -dl "Remote" -dr "Local" "$PWD/$REMOTE" "$PWD/$LOCAL" "$PWD/$MERGED"
    keepBackup = false

If you look inside C:\Program Files\Git\share\git-gui\lib\mergetool.tcl it has syntax for common merge tools.
I'm still trying to figure out how to invoke mergetool directly from Git GUI...


Q:

Looping through array and appending every even item to new array

I am trying to loop through an array, adding every other item to a new array.
def yes_no(arr)
  i = 0
  new_array = []
  while i != arr.size
    arr.select.each_with_index {|value , index| index.even?}
    new_array << value
    i += 1
  end
  new_array
end

The code is supposed to return a new array with values by their order. For:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

it should return:
[1, 3, 5, 7, 9, 2, 6, 10, 8, 4]

The first value of the initial array is always taken. I believe I have the correct logic with my code, but I need some help completing this problem.
Here is another example:
 arr = ['this', 'code', 'is', 'right', 'the']
 // returns ['this', 'is', 'the', 'right', 'code']

A:

I'm not sure how to fix your code, but here's another way to get the expected result:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

new_array = []

until arr.empty?
  new_array << arr.shift
  arr.rotate!
end

new_array
#=> [1, 3, 5, 7, 9, 2, 6, 10, 8, 4]

Note that arr is being modified, you might want to dup it.


Q:

Error with creating a game launcher

I'm making a simple java game and trying to implement a launcher at the beginning of the game.
For example, a JFrame with a button in it that starts my application when it's pressed.
What I'm trying to do is have the main method call a separate class that opens a JFrame, and an ActionListener for the JButton that calls new Cliker(); when it's called.
However, when new Cliker(); is called outside of the main method, it opens the game JFrame, but not the JPanel.
Why is this error happening, and how could I fix it? I am relatively new to programming so I apologize in advance for any unclear points about this question or my program.
I would greatly appreciate your help. If you need any more classes to help answer my question, just ask, or if you have any other questions feel free to let me know.
package com.Cliker;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import com.Cliker.Accessories.Music;

public class Cliker extends JFrame {

private static final long serialVersionUID = 1L;

int score = 0;

JButton ball = new JButton(new ImageIcon("res/textures/ball/ball.PNG"));
JFrame gameFrame = new JFrame("Cliker v1.0");

public static void main(String[] args){
    new Cliker();
}

public Cliker() {

    gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gameFrame.add(new MyPanel());
    gameFrame.pack();
    gameFrame.setVisible(true);
    gameFrame.setResizable(false);
    gameFrame.setLocationRelativeTo(null);

    ClikerGame play = new ClikerGame();
    play.run(this);

}

class MyPanel extends JPanel implements MouseListener {

    private static final long serialVersionUID = 1L;

    public MyPanel() {

        setBackground(Color.CYAN);

        ball.addMouseListener(new MouseListener() {

            @Override
            public void mousePressed(MouseEvent e) {
                if (e.getSource() == ball) {
                    score++;
                    Music.music(4);
                    repaint();

                }

            }

            @Override
            public void mouseClicked(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }
        });
        ball.setBorder(null);

        add(ball);
        addMouseListener(this);

    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setFont(new Font("Fixedsys", Font.BOLD, 30));
        g.setColor(Color.BLACK);
        g.drawString(String.valueOf(score), getWidth() / 2, 40);

    }

    public Dimension getPreferredSize() {
        return new Dimension(700, 500);
    }

    @Override
    public void mousePressed(MouseEvent e) {
        if (e.getSource() == this) {

            this.setBackground(Color.RED);

            gameFrame.setVisible(false);

            ClikerEndGame sendData = new ClikerEndGame();

            try {

                sendData.finish(score);

            } catch (Exception e1) {
                JOptionPane.showInputDialog(null,"The game has encountered an error. Error code: 001");
                e1.printStackTrace();
            }

        }

    }

    @Override
    public void mouseClicked(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent arg0) {

    }
}

}

Next Class
package com.Cliker;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import com.Cliker.Accessories.Music;

 public class ClikerGame implements Runnable {

 private int x, y, xa = 2, ya = 2;

public void run(Cliker panel) {

    JButton ball = panel.ball;

    Music.music(2);

    while (true) {
        try {
            x += xa;
            y += ya;
            if (x < 0 || x > 700 - 20 ) {

                Music.music(1);

                xa = -xa;
            }

            else if (y < 0 || y > 500 - 20 ){

                Music.music(1);

                ya = -ya;

            }

            Thread.sleep(15);

            ball.setBounds(x,y,30,30);
        } catch (Exception e) {
                JOptionPane.showMessageDialog(null,"Error 1");

        }

    }
}
public void run() {
    this.run();

}

}

A:

Basically, you're violating the single thread rules of Swing, the ClikerGame is running a while-loop which is blocking the Event Dispatching Thread, preventing it from processing new events, including paint events.
The reason that it works from main, is main isn't called from within the EDT, basically, it was a fluke.  When you call new Clicker() from within the ActionListener of your JButton however, you are running from within the context of the EDT, hence your problem.
Take a look at Initial Threads and Concurrency in Swing for more details.
The "immediate" solution might look like using a Thread, but this would also violate the single rules of Swing, as Swing is not thread safe and you should never update the UI from outside the context of the EDT.
A better solution might be to use a Swing Timer to act as a pseudo loop instead.  This is notified, at regular intervals, withing the context of the EDT
Maybe, something like...
public class ClikerGame {

    private int x, y, xa = 2, ya = 2;
    private Clicker clicker;

    private Timer timer;

    public ClikerGame(Clicker clicker) {
        this.clicker = clicker;

        timer = new Timer(15, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    x += xa;
                    y += ya;
                    if (x < 0 || x > 700 - 20) {

                        Music.music(1);

                        xa = -xa;
                    } else if (y < 0 || y > 500 - 20) {

                        Music.music(1);

                        ya = -ya;

                    }

                    Thread.sleep(15);

                    clicker.ball.setBounds(x, y, 30, 30);
                    clicker.ball.getParent().repaint();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Error 1");

                }
            }
        });
    }

    public void start() {
        if (!timer.isRunning()) {
            Music.music(2);
            timer.start();
        }
    }

    public void stop() {
        timer.stop();
        // Stop the music
    }
}


Q:

How to specify resolution of a plot?

Suppose I need to plot Sin function:
Plot[Sin[x ], {x, -10 , 10 }]

Now I need to specify the resolution of the plot. I tried by using list Plot
ListPlot[Table[Sin[x ], {x, -10, 10, 0.01}], Joined -> True]

But here the x axis is different. In this case it plots from 0 to 20.
Now I have two questions,

How to plot a function giving the specifications
Is there any way to use ListPlot and get the axis as (-10,10).

Thanks in advance

A:

The reason ListPlot gives you 1 to 20 on the x-axis is that you've only specified y-values in the table. Try:
ListPlot[
  Table[
    {x, Sin[x]},
    {x, -10, 10, 0.1}
  ]
]

ListPlot expects data to be pairs of {x, y} coordinates. If they are not, it will assign the numbers 1 through n to the x-coordinate.
For using Plot, the "resolution" of the plot can be changed by adjusting PlotPoints and MaxRecursion. This code shows what happens as you change those values. The black points are the points that Plot is using to draw the curve. Of course, in your final plot you probably won't want to show those black dots. They will only show up if you have some specification for Mesh.
TableForm[
  Table[
    Plot[
      Sin[x],
      {x, -10, 10},
      Mesh -> All,
      MeshStyle -> Directive[AbsolutePointSize[3], Black],
      PlotPoints -> i,
      MaxRecursion -> j
    ],
    {i, 2, 18, 4},
    {j, 1, 5, 1}
  ],
  TableHeadings -> {
    Table[Rotate["PlotPoints \[Rule] " <> ToString[i], \[Pi]/2], {i, 2, 18, 4}],
    Table["Max Recursion \[Rule] " <> ToString[j], {j, 1, 5, 1}]
  }
]


Q:

How can Matt Murdock read something that isn't written in Braille?

In Daredevil season one episode nine(Speak of the Devil) Matt visits a warehouse on Pier 81. There's a map on a table in the warehouse, and Matt runs his fingers across it and appears to be reading it. However, the map's not written in Braille, so how is he able to do this?

A:

In the comic books, it has sometimes been stated that his super-senses are so incredible that his hypersensitive fingertips can easily detect the difference between paper-with-ink-printed-on-it and paper-without-ink-on-it. After years of practice, he can quickly recognize familiar words with a sweep of his fingertips across each line of text. (I'm not sure I have any comic books in which he navigates that way by touching a printed map, but I wouldn't be surprised if it's happened at least once or twice when the plot required it.)
I Googled just now, and found an online scan of a few panels which show Matt doing this with an ordinary newspaper he picks up.


Q:

jQuery Post blob object gives Uncaught TypeError: Illegal invocation

I am trying to post a file using jQuery post, and get TypeError: Illegal invocation
function fbUpload(token){
  var dataURL = canvas.toDataURL('image/jpeg', 1.0)
  var blob = dataURItoBlob(dataURL)

  $.post( "https://graph.facebook.com/me/photos", {
    'access_token': token,
    'source': blob
  }, function( data ) {
    console.log(data);
  });
}

Could it be because of the 'blob'?
This is working fine:
function fbUpload(token){
  var dataURL = canvas.toDataURL('image/jpeg', 1.0)
  var blob = dataURItoBlob(dataURL)
  var formData = new FormData()
  formData.append('access_token', token)
  formData.append('source', blob)

  var xhr = new XMLHttpRequest();
  xhr.open( 'POST', 'https://graph.facebook.com/me/photos', true )
  xhr.onload = xhr.onerror = function() {
    console.log( xhr.responseText )
  };
  xhr.send( formData )
}

A:

You need to use $.ajax and provide the FormData object to the data parameter. $.post only takes data as a string or as a plain object. Try this:
function fbUpload(token){
    var dataURL = canvas.toDataURL('image/jpeg', 1.0)
    var blob = dataURItoBlob(dataURL)
    var formData = new FormData()
    formData.append('access_token', token)
    formData.append('source', blob)

    $.ajax({
        url: "https://graph.facebook.com/me/photos",
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(data) {
            console.log(data);
        }
    });
}


Q:

pgf tikz for LaTeX how can I use x and y coordinates with node

I have the following rectangle:
\begin{tikzpicture}
\draw[thin] (0,0) -- (7,0) -- (7,5) -- (7,5) -- (0,5) -- (0,0);
\end{tikzpicture}

and I want to put a text label for the width and height of the rectangle using node. But don't know how to specify the x, y coordinates for the text label.
Can I use x,y coordinates with node?

A:

You can do that using the at (x, y) syntax:
\begin{tikzpicture}
  \draw[thin] (0,0) -- (7,0) -- (7,5) -- (7,5) -- (0,5) -- (0,0);
  \node at (3.5, -0.5) {7cm};
  \node at (-0.5, 2.5) {5cm};
\end{tikzpicture}


Q:

FormFlow disable switching between fields when user submits field name as value

We are using FormFlow in our bot. FormFlow has a feature that allows a user to type the name of the field and it switches to the given field. Let's say we have a model class like this
    public class SampleModelClass
    {
        public string FirstField { get; set; }
        public string SecondField { get; set; }
    }

When the user is asked to enter FirstField there is a possibility that the user can actually type "first field" which results in asking the question for the FirstField again. Is there any way to disable this and take "first field" as the value of FirstField? Renaming FirstField would work, but we are looking for a better solution

A:

When the user is asked to enter FirstField there is a possibility that the user can actually type "first field" which results in asking the question for the FirstField again. Is there any way to disable this and take "first field" as the value of FirstField? Renaming FirstField would work, but we are looking for a better solution

You can try to use the Terms attribute (with a regular expression) to define the list of terms that are used to match user input to a field or a value in a field, the following sample is for your reference.
[Serializable]
public class SampleModelClass
{
    [Terms(@"^[.*]$")]
    public string FirstField { get; set; }

    [Terms(@"^[.*]$")]
    public string SecondField { get; set; }

    public static IForm<SampleModelClass> BuildForm()
    {
        return new FormBuilder<SampleModelClass>()
                .Message(async (state) => { return new PromptAttribute($"Welcome to the form bot!"); })
                .Build();

    }
}

Test result:


Q:

split large csv text file based on column value

I have CSV files that have multiple columns that are sorted.  For instance, I might have lines like this:
19980102,,PLXS,10032,Q,A,,,15.12500,15.00000,15.12500,2
19980105,,PLXS,10032,Q,A,,,14.93750,14.75000,14.93750,2
19980106,,PLXS,10032,Q,A,,,14.56250,14.56250,14.87500,2
20111222,,PCP,63830,N,A,,,164.07001,164.09000,164.12000,1
20111223,,PCP,63830,N,A,,,164.53000,164.53000,164.55000,1
20111227,,PCP,63830,N,A,,,165.69000,165.61000,165.64000,1

I would like to divide up the file based on the 3rd column, e.g. put PLXS and PCP entries into their own files called PLXS.csv and PCP.csv.  Because the file happens to be pre-sorted, all of the PLXS entries are before the PCP entries and so on.
I generally end up doing things like this in C++ since that's the language I know the best, but in this case, my input CSV file is several gigabytes and too large to load into memory in C++.
Can somebody show how this can be accomplished?  Perl/Python/php/bash solutions are all okay, they just need to be able to handle the huge file without excessive memory usage.

A:

Here's an old school one liner for you (just replace the >> with > to truncate the output files each run):
awk -F, '{print >> ($3".csv")}' input.csv

Due to popular demand (and an itch I just had), I've also written a version that will duplicate the header lines to all files:
awk -F, 'NR==1 {h=$0; next} {f=$3".csv"} !($3 in p) {p[$3]; print h > f} {print >> f}' input.csv

But you could just start with this and finish with the first awk:
HDR=$(head -1 input.csv); for fn in $(tail -n+2 input.csv | cut -f3 -d, | sort -u); do echo $HDR > $fn.csv; done

Most modern systems have the awk binary included, but if you don't have it, you can find an exe at Gawk for Windows

A:

C++ is fine if you know it best.  Why would you try to load the entire file into memory anyways?
Since the output is dependent upon the column being read you could easily store buffers for output files and stuff the record into the appropriate file as you process, cleaning as you go to keep the memory footprint relatively small.
I do this (albeit in java) when needing to take massive extracts from a database.  The records are pushed into a file buffer stream and anything in the memory is cleaned up so the footprint of the program never grows beyond what it initially starts out at.
Fly by the seat of my pants pseudo-code:

Create a list to hold your output file buffers
Open stream on file and begin reading in the contents one line at a time
Did we encounter a record that has an open file stream for it's content type yet?

Yes -

Get the stored file stream
store the record into that file
flush the stream

No -

create a stream and save it to our list of streams
store the record on the stream
flush the stream

Rinse repeat...

Basically continuing this processing until we're at the end of the file.
Since we never store more than pointers to the streams and we're flushing as soon as we write to the streams we don't ever hold anything resident in the memory of the application other than one record from the input file.  Thus the footprint is kept managable.


Q:

binding a property from Window to DataTrigger of a DataGridCell

i have a boolean property and i want to binding it to datatrigger
 but my codes not work
i tried this:
public event PropertyChangedEventHandler PropertyChanged;
private bool _IsExist;

public bool IsExist
{
    get
    {
        return _IsExist;
    }
    set
    {
        _IsExist = value;
        NotifyPropertyChanged("IsExist");
    }
}

private void NotifyPropertyChanged(string prop)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(prop));
    }
}

and this way i can add items to datagrid and check if mypath exist or not so i need change property based on mypath exist or not
foreach (var i in parsedValues)
{
    if (Directory.Exists(MyPath)
    {
        IsExist = true;
    }
    else
    {
        IsExist = false;
    }
    datagrid.Items.Add(i);
}

and this is my xaml
<DataGridTemplateColumn Header="دانلود">
  <DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
          <Button Click="Button_Click">
              <Button.Style>
                  <Style TargetType="Button">
                      <Setter Property="Content" Value="دانلود"/>
                      <Style.Triggers>
                          <DataTrigger Binding="{Binding IsExist}" Value="True">
                              <Setter Property="Content" Value="مشاهده"/>
                          </DataTrigger>
                      </Style.Triggers>
                  </Style>
              </Button.Style>
          </Button>
      </DataTemplate>
  </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

A:

DataGridTemplateColumn.CellTemplate looks for binding path inside of each item. So if your windows has the property, you simply can't access it like Binding="{Binding IsExist}". This will only look into the DataContext of each item from the ItemsSource of the DataGrid.
You need to tell XAML to look for the path in the Window not the cell:
Binding="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=IsExist}"

This way, it goes up in the hierarchy until it reaches the first element with the type of Window and looks there for the given path.


Q:

What's the advantage of the infantry column formation in the Napoleonic Wars?

In movies/books set in the Napoleonic Wars, the British are normally deployed into lines and the French into columns. The columns are usually the advancing ones, charging into the line as the line hold their ground and fire volleys at the advancing column. In the movies it's always depicted that this situation benefits the British, because they outshoot the column (the whole line can shoot vs just the front rank or the outer edge of the column), and they don't have to move (meaning they can reload easily and faster). Not to mention that it seems scarier to be in the front rank of a column.
The result is normally the French getting slaughtered before they even reach the line, or when they arrive they would be so outnumbered that it becomes an unbalanced melee. Well, to be fair of course English-speaking movies tend to show British victories.
Actual history reading seems to confirm that the French indeed liked fighting in columns, but why did they do this when it seems obvious that the line is more advantageous? The only advantage I can think is probably faster speed (because less files to harmonize), but I don't think this justifies the greatly reduced firepower.
And why is it in the movies the French seems to be the one attacking and the British standing their ground? How would the French deploy if they're the defending side? Is there a good example of a French victory using this kind of setting?

A:

What you are referring to is commonly known as the "French Column". I suppose it shouldn't be surprising that English movies and the English version of Wikipedia are pretty dismissive of it. After all, that was the opinion of everyone's favorite English General, Wellington. And he was certainly able to back it up.
The first thing you have to realize is that Napoleonic-era unit tactics were not all about math. Getting the maximum possible fire on your opponent is important, but it isn't the only factor.
The greatest goal is to remove the enemy units from action. Now a unit (regiment, battalion, etc) obviously can be removed from action without killing every single person in that unit. How bad do you have to hurt them? That depends on oodles of factors (eg: training, experience, casualties, etc) that are often wound up into a big ball called "morale".
So a lot of Napoleanic-era tactics that may not make a lot of sense mathematically make a lot of sense when you factor in morale. For instance, the volley. Mathematically you'd be better off letting every man fire as fast as he possibly can, rather than making them all wait on a signal. However, there's a huge difference to the opposing unit whether your buddies around you are dying in dribs and drabs here and there, or in great big groups all at once. Volleys hit like a hammer rather than a steady rain.
The idea behind a French Column isn't to pour a lot of fire into the opposing unit. Instead, it is to concentrate the entire efforts of your unit into a small area (usually in the middle) of the enemy unit. The folks in the rest of the enemy unit may feel safer, but anyone at the point of impact looking at an entire French Column 50 or so men wide and hundreds deep making a beeline straight at their part of the line has a pretty good idea they are gonna die. A sensible human being (aka: all but the incredibly well-trained) looking at that will do whatever they can to get out of the way.
If you can break the enemy line there, you break their unit in two. If you then keep coming, you will suddenly have your whole unit in the middle of theirs, able to fire on all of them effectively in a line while they have found themselves in a column (assuming they don't just rout). The key to being able to do this is training and speed, and early on nobody could match Napoleon in these two qualities. It was almost like a Calvary charge for him, but done with infantry.
Here's a passage taken from a fan of the formation in Eric Flint's 1824: The Arkansas War (a work of alternative history):

The term "column" was a misnomer, he now realized, applied to the
  fighting formation of the French armies of the Revolution. This bore
  no resemblance at all to a long, slender line of men marching down a
  road.
It was more like a sledgehammer. Or perhaps a very blunt spear. Fifty
  men across, at the front, firing as they came, with the rest of the
  regiment in close support. The formation relied on speed and impact,
  more like a cavalry charge than anything else Sam could think of.
Watching it in action, he could now understand why the formation had
  eventually been abandoned. Very well trained and disciplined
  professional armies, formed into lines, could bring too much fire to
  bear on the front of the column. Hundreds of men against fifty.
But that presupposed the sort of professional armies trained and led
  by generals like the Duke of Wellington...

A:

Napoleon loved forward momentum - and he got it with the heavy column. The formation forced his infantry forward, the front ranks constantly pushed to the fore by the ranks behind them, and made opponents break formation to get the hell out of the way. This worked, because Napoleon was an artilleryman - he would disrupt opposing line formations with artillery barrage and cavalry, and once an infantry column broke through, it was all but over for the opposing forces. Napoleon's genius was knowing the soft spot to send his columns towards, and how to best support the attack.
Bear in mind that the "attack column" wasn't like a marching column or even an infantry square. The peleton, which translates as "platoon" or "rank", was either 80 men wide and 9 deep, or 40 men wide and 18 deep, and was the base unit of maneuver. So look at it more as successive waves of dense line formations. Once they're through the opposing line, peletons can wheel right or left to deliver flanking fire.
Wellington went with a much thinner line, and relied on carefully chosen terrain, cavalry and counter-artillery to disrupt French artillery support. Retreat and redeploy was a common British tactic, changing the shape of the line, bending but never breaking. The British are never shown as retreating in historical fiction because they're supposed to be the "Good Guys" in most english-language media - nevertheless C.S. Forrester had a fantastic depiction of a typical British retreat, organized and in good order while under heavy fire, in his Hornblower series. (Marines rather than infantry, but you get a good idea how this was drilled and practiced.) The other trick was to break French discipline with a two-volleys-and-bayonet-charge drill which caused the front of the attack column to break ranks, to rush to engage the enemy, which left them helpless to respond to flanking fire and too disorganized to take advantage of their break-through or allow the rest of the column to engage.

A:

The first thing to remember is that Napoleon prized speed over everything else.  Most of his campaigns he faced much larger armies led by different nations and leaders.  When Napoleon arrived the opposing armies would be near one another but not yet (His apposing armies were separated due to forage and supply needs, or were traveling to meet one another at a rally point.)  Napoleon would then force march his army to meet one of these separated enemy armies.  Once he arrived there he needed to attack and destroy that army immediately before the other allied army could bring reinforcements and overwhelm him.  He did this in such battles as Montenotte, Ulm, Jena, Ligny (the battle before Waterloo).
Once he got on the battle field he usually attacked the center of the enemy, his troops advancing in the French column.  This allowed the troops to move more quickly only pausing a moment to slightly widen and then continue to march forward.  They didn’t have to pause to redress their lines at any point.  There is a great web site that explains it better than I can. http://www.napolun.com/mirror/napoleonistyka.atspace.com/infantry_tactics_4.htm
But as others have said the intent of the French column was to hit the center with a hammer blow.
The third thing to remember is that Napoleon’s armies were international and not very well trained.  The French didn’t spend the time the British did to train troops to fire 3 shots a second.  They didn’t train for months to perfect the complicated maneuvers needed to go from column to line under fire and under speed.   According to La Grande Armee by Blond in 1809 the Grande Armee numbered 350,000 troops, 80% of which were French troops.  By 1812 the 400,000 Grande Armee only 33% of them were French soldiers.   Some of these troops, and officers did not even speak French.  It would be too difficult to give multiple complicated orders versus just saying see their center go right for it as fast as you can.  The British could train their troops so thoroughly because their army was so small; which is why it needed to be as tough as it could be.  The French also could not afford to waste powder by constantly training them how to fire faster.  Napoleon on the other hand knew he had a much larger man power base than any other single country; he could afford to waste his soldiers for a victory.
Some people would say this shows the genius of Wellington to use his men to the maximum of their ability; and Napoleon lacked genius because he was so willing to sacrifice them.  To me it says that both of them realized their own situation and tried to maximize it as best as they could.  Napoleon believed in speed, Wellington in terrain.  I had also wondered why the French used the column attack, and I spent a lot of time researching different ideas on it.  But speed and undertrained and international army seemed to be the most common answer to why the column was used.


Q:

Disabling TLS 1.1 in node.js?

I am currently experiencing a known problem with OpenSSL on Ubuntu 12.04. This problem is already fixed in Debian and I'm expecting it to be fixed soon in Ubuntu too. However, in the mean time I would need a workaround.
So is it possible to disable TLS1 in Node and have something equivalent to tls1 switch:
openssl s_client -tls1 -connect evernote.com:443

Here is a simple Node.js script to replicate the problem (on Ubuntu 12.04 w/ OpenSSL 1.0.1)
var https = require('https');
https.get({
    host: 'www.evernote.com',
    path: '/',
    port: 443
  }, function (res) {
    console.log('Success!');
  });

A:

Judging from the documentation and the sources (1, 2), it should be possible to pass an options object to request that contains something like
options = { secureProtocol: 'TLSv1_method' }

in order to use TLSv1 (and just that) for this particular connection.
The default is to use OpenSSL's SSLv23_method, which means to use the highest TLS/SSL version that is possibly understood by both parties.
Although possible in OpenSSL itself, it is not possible to blacklist a particular TLS version (as in "use the highest version possible, but never this one") in node.js as far as I can see, the necessary flags to do so are not exported in node.js itself.


Q:

Running Total and Integer Value Allocation

I need to be able to determine the remaining amount of point allocation for each row. Let me explain the following query:
Variables

@allocated int --> already allocated points
@to_allocate int --> the point that we need to allocate now

View "audits"

ts --> date on which the points were collected
points --> the amount of points collected

So far, I have only been able to get proper results when the data in "audits" is something like this:
This works
IF OBJECT_ID('audits') IS NOT NULL
DROP VIEW audits;

GO

CREATE VIEW audits
AS
SELECT '2000-1-1' AS ts, 10 AS points UNION ALL
SELECT '2000-1-2' AS ts, 12 AS points UNION ALL
SELECT '2000-1-3' AS ts, 123 AS points UNION ALL
SELECT '2000-1-4' AS ts, 100 AS points;

GO

Does not work
CREATE VIEW audits
AS
SELECT '2000-1-1' AS ts, 106 AS points UNION ALL
SELECT '2000-1-2' AS ts, 12 AS points UNION ALL
SELECT '2000-1-3' AS ts, 123 AS points UNION ALL
SELECT '2000-1-4' AS ts, 100 AS points;

GO

Query
DECLARE @to_allocate int = 92;
DECLARE @allocated int = 4;

WITH result
AS
(
    SELECT
        ts,
        points,
        SUM(points) OVER(ORDER BY ts) AS total
    FROM audits
),
points
AS
(
    SELECT
        ts,
        points,
        total,
        CASE
            WHEN @to_allocate > total - @allocated THEN total - @allocated
            ELSE @to_allocate - SUM(total - @allocated)
                                OVER(ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)
        END as result
    FROM result
)
SELECT * FROM points
WHERE result > 0;

Desired Output for "Does not work" data
Please note that the value in result column should not be greater than point of the corresponding row. Therefore,

when @to_allocate is 92

when @to_allocate is 200

I can solve this issue by using temporary tables and loops but that's something that I don't want to do because it prevents me to use this on a function. Any help or pointing me to the right direction will be appreciated.

A:

Something like this?
DECLARE @to_allocate int = 200
DECLARE @allocated int = 4

select *,
  points -
  case when total < @allocated then points
       when prev < @allocated then @allocated - prev
       else 0
  end -
  case when total > @to_allocate + @allocated
       then total - @to_allocate - @allocated
       else 0
  end

from
(
  select *, lag(total, 1, 0) over (order by ts asc) as prev
  from
  (
      select *, sum(points) over (order by ts asc) as total from audits
  ) X
) X
where prev < @to_allocate + @allocated

SQL Fiddle
I made the assumption that @allocated must remove values from more than just the first row, although your examples only had that.


Q:

Combining two ng-repeats in a table

I want do use two different ng-repeat loops in a table to kind of group different obejcts with each other but don't know really how to do it.
My code right now:
...

        {{ person1.address }}
        {{ person1.city}}
        {{ person1.email}}

        {{partner2.address }}
        {{partner2.city}}
        {{partner2.email}}

...

The result/table i'm aiming for:
person1[1].address   |    person1[1].city    | person1[1].email
---------------------------------------------------------------
person2[1].address   |    person2[1].city    | person2[1].email
---------------------------------------------------------------
person1[2].address   |    person1[2].city    | person1[2].email
---------------------------------------------------------------
person2[2].address   |    person2[2].city    | person2[2].email
---------------------------------------------------------------

That is, i'd like to the ng-repeat to out put person1[1] and person2[1] before putting out person1[2].
Is the solution to add an outer array, containing my two current arrays or are there any better solution?
best regards

A:

Assuming you could ensure that your array had no null values and were the same length, you could use this technique:
Create a new array initialized to the length of the two other arrays and iterate on this to get $index.
Put your ng-repeat on the body ( you can have multiple body elements in a table).
You'd get something like this:
var counterArray = new Array(array1.length);

        {{ Array1[$index].address }}
        {{ Array1[$index].city}}
        {{ Array1[$index].email}}

        {{ Array2[$index].address }}
        {{ Array2[$index].city}}
        {{ Array2[$index].email}}

It might be safer to use a getter function on those arrays also:
getData(index,array,value)

Where you can prevent any null errors from occurring.


Q:

Magento 2.1.1 An error occured on the server please try again at checkout

for a while we've been getting an error when checking out with Braintree using a sandbox account. we simply get the error
'An error has occurred on the server, please try again"
The error occurs when hitting the checkout button
I've tried removing the table prefix and running the SQL fix but the error still persists. There is nothing incorrect in the Braintree configuration as the dummy payments are being sent and verified in the sandbox account & our host confirms there are no server errors causing it so it must be a Mage issue.
We're at a point now where we are totally flumuxed on the issue...

A:

To know the exact reason why it is happening so, please open below file:
vendor/magento/module-checkout/Model/PaymentInformationManagement.php
than comment out the try, catch and put code to place order directly as below:
Replace below function
public function savePaymentInformationAndPlaceOrder(
    $cartId,
    \Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
    \Magento\Quote\Api\Data\AddressInterface $billingAddress = null
) {
    $this->savePaymentInformation($cartId, $paymentMethod, $billingAddress);
    try {
        $orderId = $this->cartManagement->placeOrder($cartId);
    } catch (\Exception $e) {
        //var_dump($e);
        throw new CouldNotSaveException(
            __('An error occurred on the server. Please try to place the order again.'),
            $e
        );
    }
    return $orderId;
}

To
public function savePaymentInformationAndPlaceOrder(
    $cartId,
    \Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
    \Magento\Quote\Api\Data\AddressInterface $billingAddress = null
) {
    $this->savePaymentInformation($cartId, $paymentMethod, $billingAddress);
    //try {
        $orderId = $this->cartManagement->placeOrder($cartId);
    /*} catch (\Exception $e) {
        //var_dump($e);
        throw new CouldNotSaveException(
            __('An error occurred on the server. Please try to place the order again.'),
            $e
        );
    }*/
    return $orderId;
}

Now, try to place order again. You will be able to see the detailed error in log file or may be in console.


Q:

Embedding ASPX in ASP page

I have an ASPX based component which I'd need to inlude into a plain ASP based
script. Scenario is, that I'm working within an LMS system (Angel to be exact)
and I wan't to create a new nugget within that framework. An Angel nugget is
pretty much what a portlet is in the Java world.
Now, the nugget spec. states that my starting point has to be a file called
default.asp. What I'd like to do is:

read relevant data from ASP session
pass data to ASPX component
have ASPX do it's job and display the results

My problem is that I fail to run / display my ASPX component without
using an iframe, which I want to avoid since that crushes the layout /
design of my nugget.
Is there a way to get this done properly or do I have to rewrite my
component in ASP to get this going?
Note: the component performs
web service queries and such and I'd like to avoid rewriting that.

A:

Why don't you grab the .aspx content from the .asp page using the MSXML object?

url = "http://www.yoururl.com/YourPage.aspx?relevantData=YourRelevantData"
Set xml = Server.CreateObject("Msxml2.SERVERXMLHTTP")
xml.Open "GET",url,False
xml.send
html = xml.ResponseText
Set xml = Nothing
Response.Write(html)


Q:

Hudson Doesn't Seem to Run Process.Start Correctly

For a project I have to start an application in C#, rip out the AutomationElement tree related to the process, and then close the application and output the tree. I'm doing this by opening the application using Process.Start. Then I'm finding the AutomationElements related to the spawned process and walking the tree using a combination of TreeWalker and AutomationElement's FindFirst and FindAll methods.
This runs fine on my computer and runs correctly using NUnit locally. It also runs on the other people in my groups computers. The problem is that it never runs on our central testing server that's running Hudson. After some hours of debugging, I had a test on Hudson start the application and then print the first level of the AutomationTree. On my computer, this prints all of the windows I have on my desktop. On Hudson, this only prints the Desktop.
Thinking there might be multiple desktops, I tried using TreeWalker's GetNextSibling function on the RootElement. It still only reported one desktop.
Here's the code I'm using to start a process.
public bool connect(string[] args)
{
    if (this.process != null) {
        Console.WriteLine("ERROR: Process already connected");
        return false;
    }

    if (!File.Exists(sApplicationPath)) {
        Console.WriteLine(sApplicationPath + " does not exist");
        return false;
    }

    // Turn the command arguments into a single string
    string arguments = "";
    foreach (string arg in args) {
        arguments += arg + " ";
    }

    try {
        // Start the application
        ProcessStartInfo processStartInfo =
            new ProcessStartInfo(sApplicationPath);
        processStartInfo.Arguments = arguments;
        this.process = Process.Start(processStartInfo);

        // Must be a positive integer (non-zero)
        if ( !( iInitialDelay > 0 )  ) {
            Console.WriteLine("Invalid initial delay. " +
                              "Defaulting to 5 seconds.");
            this.iInitialDelay = 5000;
        }

        Thread.Sleep(this.iInitialDelay);
    } catch (Exception ex) {
        Console.WriteLine("WGApplication.connect: " + ex.Message);
        return false;
    }

    // Check if the process still exists
    try {
        /** This part does not return an error, so I think that means the process exists and is started */
        Process check = Process.GetProcessById(process.Id);
    } catch (ArgumentException ex) {
        Console.WriteLine("The process expired before connection was complete");
        Console.WriteLine("Make sure the process is not open anywhere else");
        Console.WriteLine("and that it is able to execute on the host machine.");
        return false;
    }

    // Check if the base automation element exists to verify open
    AutomationElement rootWindow =
        AutomationElement.RootElement.FindChildProcessById(process.Id);
    /** This part returns null, so it can't find the window associated with this process id */

    if (this.process == null) {
        return false;
    } else if (rootWindow == null) {
        // A root window with this process id has not been found
        Console.WriteLine("Cannot find the root window of the created " +
                          "process. Unknown error.");
        return false;
    } else {
        // Everything is good to go
        return true;
    }
}

sApplicationPath is set to the absolute path of the executable. iInitialDelay is a delay to make sure the application has time to start. I'm running this on 'C:\Windows\System32\notepad.exe' on Windows Vista SP2 and compiling it with the v3.5 C# compiler.
FindChildProcessById is defined as follows:
public static AutomationElement FindChildProcessById(
    this AutomationElement element, int processId)
{
    var result = element.FindChildByCondition(
        new PropertyCondition(AutomationElement.ProcessIdProperty,
                              processId));

    return result;
}

Remember that this compiles and works on my computer. My test program on Hudson said that the RootElement had no children at all.
So I start the application, confirm it exists, and then I can't find any windows associated with the process. I can't find any windows associated with anything except the desktop.
Is this a problem with Hudson? Does Hudson work in some specific way that this code wouldn't work on it? Is it a problem with my code? The Hudson server is running on a Windows Server 2003 computer. Any help would be appreciated. I know this is a very specific problem which is a reason why I can't find any solutions online.

A:

Is Hudson running as a service?  If so, it may not have the necessary rights to show windows.


Q:

Rails subscription limitations

I have an application with set limits on subscription attributes i/e a user can have five projects for subscription A but have ten for subscription B
At present I run a check on there current usage when linking to the create action and if they are over there limit I do not display the link to create a new project. On the view (for the new project ) I again run the check (in a helper) to see if they can create a new project and if they are not I display a message stating so and a little upgrade link.
Is this a secure method of stopping a user bypassing there subscription attribute limitations ?
What about direct PUT requests etc ?

A:

You can also validate that the user's subscription allows starting a new project when a new project is created. This guarantee that even if they posted directly to the new_project_path they would get an error.
class Project

  belongs_to :user

  validate_on_create :subscription_allows_new_project

  def subscription_allows_new_project
    unless self.user.subscription.max_projects > self.user.projects.count
      errors.add_to_base("Project limit reached, please upgrade today!")
    end
  end

end


Q:

Failing to trigger checked event on checkboxes

I have hierarchy which i need to bind to checkbox for parent and checkboxlist for 1 level children.
Somehow i cannot get to checkboxes(CheckBoxParent_CheckedChanged),checkboxlist's (CheckBoxListChildren_SelectedIndexChanged) select events, without UpdatePanel as well.
Working on it for 4 hours without any result, why i can't enter event when i check some checkbox ?
What am I doing wrong ?
Thanks
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ListViewCategories.DataSource = CategoryManager.ListHierarchy();
        ListViewCategories.DataBind();
    }
}

protected void CheckBoxParent_CheckedChanged(object sender, EventArgs e)
{
    if (((CheckBox)sender).Checked)
    {

    }
    else
    {
    }
}

protected void CheckBoxListChildren_SelectedIndexChanged(object sender, EventArgs e)
{
    if (((CheckBoxList)sender).SelectedItem != null)
    {

    }
    else
    {
    }
}

  <asp:UpdatePanel ID="UpdatePanelCategories" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
       <ContentTemplate>
            <asp:ListView ID="ListViewCategories" runat="server">
                <LayoutTemplate>

                </LayoutTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBoxParent" runat="server" Text='<%# Eval("Key.Name") %>' OnCheckedChanged="CheckBoxParent_CheckedChanged" />

                    <asp:CheckBoxList ID="CheckBoxListChildren" runat="server" OnSelectedIndexChanged="CheckBoxListChildren_SelectedIndexChanged" RepeatDirection="Horizontal" DataSource='<%# DataBinder.Eval(Container.DataItem, "Value") %>' DataTextField="Name"></asp:CheckBoxList>

                </ItemTemplate>
            </asp:ListView>
       </ContentTemplate>
   </asp:UpdatePanel>

A:

Put the "AutoPostBack" of CheckBox to true.


Q:

Visualforce Page and Visual Flow - Back and forth redirection - Solution?

I have a visual flow that is started on a click of Custom button.  This flow is embedded in a visualforce page (standard way of using flows).
Now, in one of the steps in the flow, I want to redirect the user to a New Visualforce page (this page has the functionality of File Upload).  In this page, the user will upload file (creates a uppload record).  Then can the user be redirected back to THAT step in the flow where he left and continue with the remaning steps in the flow?
What is the feasible solution for this requirement.
So, in short, it is something like below.
Flow step1 ==> flow step 2 ==> Visualforce Page(upload file) ==> flow step 3 ==> finish flow.
EDIT:  All this can be solved, if there is File Upload option in flow! #JustAThought

A:

you can redirect like this:
<flow:interview name="CrossSell" interview="{!theInterview}" finishLocation="{!finishLocation}">
public PageReference getfinishLocation() {
    return new PageReference('/apex/some-fileuploadpage');
}

after upload, as a work around,  you can start another flow instead.


Q:

Referencing a cell in Excel using values from other cells

I would like to know if it is possible to reference a cell in Excel depending on the value of another cell.
Example

I have a cell, let's say A1 where I have the row number that I want to use (e.g., the content of A1 is 42)
I want to compute the sum of column B from row 1 to the row corresponding to the number given in A1. Something like =SUM( B1:B<NUMBER_IN_A1> )

Is there any way?

A:

Use & to create the cell coordinates, access them using INDIRECT().
=SUM(INDIRECT("B1:B" & A1))

A:

INDEX is normally preferable to INDIRECT, where possible. You don't have to "hardcode" the column, and it's not (as) volatile.
=SUM(B1:INDEX(B:B,A1))

See the documentation for more details on usage.


Q:

AsyncTask error Android App crashes

My oncreate code:
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.board);
    ArrayList<String> passing = new ArrayList<String>();
  new AsyncTaskParseJson().execute();

}

Here is my code:
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
    final String TAG = "AsyncTaskParseJson.java";
    String yourJsonStringUrl = "my url here";
    JSONArray dataJsonArr = null;

    @Override
    protected void onPreExecute() {}

    @SuppressWarnings("null")
    @Override
     public String doInBackground(String... arg0) {

        final String[] values = null;
         try {

             // instantiate our json parser
             JsonParser jParser = new JsonParser();

             // get json string from url
             JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

             // get the array of users
             dataJsonArr = json.getJSONArray("response");

             // loop through all users
             for (int i = 1; i < dataJsonArr.length(); i++) {

                 JSONObject c = dataJsonArr.getJSONObject(i);
                 String text = c.getString("text");
                values[i]=text;
             }
          //   ArrayAdapter<String> adapter = new ArrayAdapter<String>(Board.this,R.layout.item, R.id.label, values);
          //   list1.setAdapter(adapter);

         }
         catch (JSONException e) {
             e.printStackTrace();
         }

         return null;
     }

     @Override
     protected void onPostExecute(String strFromDoInBg) {}

 }

So, it's starts activity when I comment the section values[i] like this:
      //values[i]=text;

BUT when it's not commented, app just crashes. I want to doInBackground to return String[] array, how I do that?

A:

You need to have
 values = new String[dataJsonArr.length()];

Also note the commented lines are in doInbackground. But you can't update ui from a background thread. So the below should go to onPostExecute.
 //   ArrayAdapter<String> adapter = new ArrayAdapter<String>(Board.this,R.layout.item, R.id.label, values);
 //   list1.setAdapter(adapter);

Instead of using a String array it is better to use a ArrayList<String>
You need to change the args type also
public class AsyncTaskParseJson extends AsyncTask<String, String, ArrayList<String>> {

Then
 @Override
 public  ArrayList<String> doInBackground(String... arg0) {

    ArrayList<String> values = new ArrayList<String>();
     try {

         // instantiate our json parser
         JsonParser jParser = new JsonParser();

         // get json string from url
         JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

         // get the array of users
         dataJsonArr = json.getJSONArray("response");

         // loop through all users
         for (int i = 1; i < dataJsonArr.length(); i++) {

             JSONObject c = dataJsonArr.getJSONObject(i);
             String text = c.getString("text");
             values.add(text);
         }
     }
     catch (JSONException e) {
         e.printStackTrace();
     }

     return values;
 }

Then
 @Override
 protected void onPostExecute(ArrayList<String> result) {
  super.onPostExecute(result);
   ArrayAdapter<String> adapter = new ArrayAdapter<String>(Board.this,R.layout.item, R.id.label, result);
   list1.setAdapter(adapter);
 }

Also make sure list1 is initialized before you setAdapter to it coz i do not see the code where list1 is initialized.


Q:

Python replace substring that has some variable component

I have the following string:
Billy got score of 2 and Tommy got score of 3

I want to split on score of <some number> so that I get
["Billy got","Tommy got"]

How can I do such a split in python? I tried
input.split("score of \d")

but that does not work. However, if I do
input.split("score of")

then I get
["Billy got "," 2 and Tommy got "," 3"]

Update:
Thanks for the answer to the original post. I have a follow up.
What if i want to replace score of 2 with score of 2$ ? meaning whenever i see score of <some number> just add a character $ after the number

A:

Well the reason why this does not work is because str.split expects a string as pattern: it is not interpreted as a regex.
You can however use re.split:
import re

result = re.split(r'score of \d+(?: and )?',input)

You also should add the optional (?: and )? to remove the and combinator. Furthermore this answer uses \d+ (with a +) such that multi-digit scores are also parsed correctly (like "Tommy got score of 23").
In the interpreter:
$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> input="Billy got score of 2 and Tommy got score of 3"
>>> import re
>>> re.split(r'score of \d+(?:\s*and\s*)?',input)
['Billy got ', 'Tommy got ', '']


Q:

Cant access server media files in django + angular project

Because I wanted to do my routing in angular side I have added this url in my urls.py:
url(r'^.*$', Home.as_view(), name='home'),

in which my home view I just specify my base.html:
class Home(TemplateView):
    template_name = "base.html"

So that I can specify my <ng-view></ng-view> in base.html
Now my issues the requests to get pictures in server side like localhost:8000/media/uploaded_pic.png
are going to the defined url for Home.
How can I overcome this issue?
Thank you.

A:

you need to set static and media urls in your settings file so your server knows to handle them differently:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

Your catch all route for your app template needs to always come last, so to make this work during development, you need to make sure to insert your media url patterns before the final catch all that serves the template.
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [ url(r'^.*$', Home.as_view(), name='home'),]

More: https://docs.djangoproject.com/en/1.11/howto/static-files/
my personal take: I consider my API layer and my client layer as wholly seperate entities always.  My client is just a consumer of my API, so I serve my client app completely separately from my API.


Q:

Switch among states in ui-router without clicks

I am new to angular and ui-router.
I have implemented some sample like this.
    $stateProvider
    .state('route1', {
        url: "/route1",
        templateUrl: "route1.html"
    })

    .state('route2', {
        url: "/route2",
        templateUrl: "route2.html"
    })

This is working fine, but it requires a click.
What I am going to do is, the pages will automatically change among different states.
And it would start the loop from the first page if it reached the end.
Just like a slider.
How can I accomplish that?

A:

It's possible to change state via $state.go('route1') (see docs http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state). So in your controller you can use, f.e. $timeout and change state.


Q:

Child state not Inheriting resolved dependencies from parent state

Here is my code
$stateProvider
        .state('admin', {
            abstract: true,
            templateUrl: "views/common/content.html",
            resolve: {
                channel: function($stateParams){
                    return $stateParams.id
                }
            }
        })
        .state('admin.dash',{
            url: "/dash",
            templateUrl: "views/admin/admin_dash.html"
       })

and i have many controllers for this admin_dash.html view using ng-controller. And in any of these controllers (child) i am not able to inject 'channel' which is the resolved dependency of the parent state, which should be inherited.

A:

The resolve injectables will not be available to any old ng-controller, but only to the controller specified to the state.
E.g.
$stateProvider
    .state('admin', {
        abstract: true,
        templateUrl: "views/common/content.html",
        resolve: {
            channel: function($stateParams){
                return $stateParams.id
            }
        }
    })
    .state('admin.dash',{
        url: "/dash",
        templateUrl: "views/admin/admin_dash.html",
        // Injectable here
        controller: function(channel, $rootScope) {
            console.log('Received channel from parent resolve:', channel);
            // If need for ng-controller bound controllers...
            $rootScope.channel = channel;
        }
    })


Q:

How do I see which LLVM library have to link with to resolve PassManagerBuilder::addGlobalExtension()?

How do I see which LLVM library have to link with to resolve PassManagerBuilder::addGlobalExtension()?
I've already included llvm_map_components_to_libnames(llvm_libs support core irreader) in the CMakeLists.txt.
However, I still get a link error for the symbol above.
In general, how to I look up which libraries I need to include to resolve certain symbols?

A:

The method PassManagerBuilder::addGlobalExtension() declared and defined in
include/llvm/Transforms/IPO/PassManagerBuilder.h and lib/Transforms/IPO/PassManagerBuilder.cpp respectively. Live it in library libLLVMipo.a, hence you need add to llvm_map_components_to_libnames the string ipo:
llvm_map_components_to_libnames(llvm_libs ipo ...)