text:
<?php

namespace Zend\Navigation\Page;

use Zend\Mvc\Router as MvcRouter;
use Zend\Navigation\Exception;
use Zend\Router\RouteMatch;
use Zend\Router\RouteStackInterface;

/**
 * Represents a page that is defined using controller, action, route
 * name and route params to assemble the href
 *
 * The two constants defined were originally provided via the zend-mvc class
 * ModuleRouteListener; to remove the requirement on that component, they are
 * reproduced here.
 */
class Mvc extends AbstractPage
{
    const MODULE_NAMESPACE = '__NAMESPACE__';
    const ORIGINAL_CONTROLLER = '__CONTROLLER__';

    /**
     * Action name to use when assembling URL
     *
     * @var string
     */
    protected $action;

    /**
     * Controller name to use when assembling URL
     *
     * @var string
     */
    protected $controller;

    /**
     * URL query part to use when assembling URL
     *
     * @var array|string
     */
    protected $query;

    /**
     * Params to use when assembling URL
     *
     * @see getHref()
     * @var array
     */
    protected $params = [];

    /**
     * RouteInterface name to use when assembling URL
     *
     * @see getHref()
     * @var string
     */
    protected $route;

    /**
     * Cached href
     *
     * The use of this variable minimizes execution time when getHref() is
     * called more than once during the lifetime of a request. If a property
     * is updated, the cache is invalidated.
     *
     * @var string
     */
    protected $hrefCache;

    /**
     * RouteInterface matches; used for routing parameters and testing validity
     *
     * @var RouteMatch
     */
    protected $routeMatch;

    /**
     * If true and set routeMatch than getHref will use routeMatch params
     * to assemble uri
     * @var bool
     */
    protected $useRouteMatch = false;

    /**
     * Router for assembling URLs
     *
     * @see getHref()
     * @var RouteStackInterface
     */
    protected $router = null;

    /**
     * Default router to be used if router is not given.
     *
     * @see getHref()
     *
     * @var RouteStackInterface
     */
    protected static $defaultRouter = null;

    /**
     * Default route name
     *
     * @var string
     */
    protected static $defaultRoute = null;

    // Accessors:

    /**
     * Returns whether page should be considered active or not
     *
     * This method will compare the page properties against the route matches
     * composed in the object.
     *
     * @param  bool $recursive  [optional] whether page should be considered
     *                          active if any child pages are active. Default is
     *                          false.
     * @return bool             whether page should be considered active or not
     */
    public function isActive($recursive = false)
    {
        if (! $this->active) {
            $reqParams = [];
            if ($this->routeMatch instanceof RouteMatch || $this->routeMatch instanceof MvcRouter\RouteMatch) {
                $reqParams  = $this->routeMatch->getParams();

                if (isset($reqParams[self::ORIGINAL_CONTROLLER])) {
                    $reqParams['controller'] = $reqParams[self::ORIGINAL_CONTROLLER];
                }

                $pageParams   = $this->params;
                if (null !== $this->controller) {
                    $pageParams['controller'] = $this->controller;
                }
                if (null !== $this->action) {
                    $pageParams['action'] = $this->action;
                }

                if (null !== $this->getRoute()) {
                    if ($this->routeMatch->getMatchedRouteName() === $this->getRoute()
                        && (count(array_intersect_assoc($reqParams, $pageParams)) == count($pageParams))
                    ) {
                        $this->active = true;
                        return $this->active;
                    } else {
                        return parent::isActive($recursive);
                    }
                }
            }

            $pageParams = $this->params;

            if (null !== $this->controller) {
                $pageParams['controller'] = $this->controller;
            } else {
                /**
                 * @todo In ZF1, this was configurable and pulled from the front controller
                 */
                $pageParams['controller'] = 'index';
            }

            if (null !== $this->action) {
                $pageParams['action'] = $this->action;
            } else {
                /**
                 * @todo In ZF1, this was configurable and pulled from the front controller
                 */
                $pageParams['action'] = 'index';
            }

            if (count(array_intersect_assoc($reqParams, $pageParams)) == count($pageParams)) {
                $this->active = true;
                return true;
            }
        }

        return parent::isActive($recursive);
    }

    /**
     * Returns href for this page
     *
     * This method uses {@link RouteStackInterface} to assemble
     * the href based on the page's properties.
     *
     * @see RouteStackInterface
     * @return string  page href
     * @throws Exception\DomainException if no router is set
     */
    public function getHref()
    {
        if ($this->hrefCache) {
            return $this->hrefCache;
        }

        $router = $this->router;
        if (null === $router) {
            $router = static::$defaultRouter;
        }

        if (! $router instanceof RouteStackInterface && ! $router instanceof MvcRouter\RouteStackInterface) {
            throw new Exception\DomainException(
                __METHOD__
                . ' cannot execute as no Zend\Router\RouteStackInterface instance is composed'
            );
        }

        if ($this->useRouteMatch() && $this->getRouteMatch()) {
            $rmParams = $this->getRouteMatch()->getParams();

            if (isset($rmParams[self::ORIGINAL_CONTROLLER])) {
                $rmParams['controller'] = $rmParams[self::ORIGINAL_CONTROLLER];
                unset($rmParams[self::ORIGINAL_CONTROLLER]);
            }

            if (isset($rmParams[self::MODULE_NAMESPACE])) {
                unset($rmParams[self::MODULE_NAMESPACE]);
            }

            $params = array_merge($rmParams, $this->getParams());
        } else {
            $params = $this->getParams();
        }

        if (($param = $this->getController()) !== null) {
            $params['controller'] = $param;
        }

        if (($param = $this->getAction()) !== null) {
            $params['action'] = $param;
        }

        switch (true) {
            case ($this->getRoute() !== null || static::getDefaultRoute() !== null):
                $name = ($this->getRoute() !== null) ? $this->getRoute() : static::getDefaultRoute();
                break;
            case ($this->getRouteMatch() !== null):
                $name = $this->getRouteMatch()->getMatchedRouteName();
                break;
            default:
                throw new Exception\DomainException('No route name could be found');
        }

        $options = ['name' => $name];

        // Add the fragment identifier if it is set
        $fragment = $this->getFragment();
        if (null !== $fragment) {
            $options['fragment'] = $fragment;
        }

        if (null !== ($query = $this->getQuery())) {
            $options['query'] = $query;
        }

        $url = $router->assemble($params, $options);

        return $this->hrefCache = $url;
    }

    /**
     * Sets action name to use when assembling URL
     *
     * @see getHref()
     *
     * @param  string $action             action name
     * @return Mvc   fluent interface, returns self
     * @throws Exception\InvalidArgumentException  if invalid $action is given
     */
    public function setAction($action)
    {
        if (null !== $action && ! is_string($action)) {
            throw new Exception\InvalidArgumentException(
                'Invalid argument: $action must be a string or null'
            );
        }

        $this->action    = $action;
        $this->hrefCache = null;
        return $this;
    }

    /**
     * Returns action name to use when assembling URL
     *
     * @see getHref()
     *
     * @return string|null  action name
     */
    public function getAction()
    {
        return $this->action;
    }

    /**
     * Sets controller name to use when assembling URL
     *
     * @see getHref()
     *
     * @param  string|null $controller    controller name
     * @return Mvc   fluent interface, returns self
     * @throws Exception\InvalidArgumentException  if invalid controller name is given
     */
    public function setController($controller)
    {
        if (null !== $controller && ! is_string($controller)) {
            throw new Exception\InvalidArgumentException(
                'Invalid argument: $controller must be a string or null'
            );
        }

        $this->controller = $controller;
        $this->hrefCache  = null;
        return $this;
    }

    /**
     * Returns controller name to use when assembling URL
     *
     * @see getHref()
     *
     * @return string|null  controller name or null
     */
    public function getController()
    {
        return $this->controller;
    }

    /**
     * Sets URL query part to use when assembling URL
     *
     * @see getHref()
     * @param  array|string|null $query    URL query part
     * @return self   fluent interface, returns self
     */
    public function setQuery($query)
    {
        $this->query      = $query;
        $this->hrefCache  = null;
        return $this;
    }

    /**
     * Returns URL query part to use when assembling URL
     *
     * @see getHref()
     *
     * @return array|string|null  URL query part (as an array or string) or null
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * Sets params to use when assembling URL
     *
     * @see getHref()
     * @param  array|null $params [optional] page params. Default is null
     *                            which sets no params.
     * @return Mvc  fluent interface, returns self
     */
    public function setParams(array $params = null)
    {
        $this->params = empty($params) ? [] : $params;
        $this->hrefCache = null;
        return $this;
    }

    /**
     * Returns params to use when assembling URL
     *
     * @see getHref()
     *
     * @return array  page params
     */
    public function getParams()
    {
        return $this->params;
    }

    /**
     * Sets route name to use when assembling URL
     *
     * @see getHref()
     *
     * @param  string $route Route name to use when assembling URL.
     * @return Mvc Fluent interface, returns self.
     * @throws Exception\InvalidArgumentException If invalid $route is given.
     */
    public function setRoute($route)
    {
        if (null !== $route && (! is_string($route) || strlen($route) < 1)) {
            throw new Exception\InvalidArgumentException(
                'Invalid argument: $route must be a non-empty string or null'
            );
        }

        $this->route     = $route;
        $this->hrefCache = null;
        return $this;
    }

    /**
     * Returns route name to use when assembling URL
     *
     * @see getHref()
     *
     * @return string  route name
     */
    public function getRoute()
    {
        return $this->route;
    }

    /**
     * Get the route match.
     *
     * @return RouteMatch
     */
    public function getRouteMatch()
    {
        return $this->routeMatch;
    }

    /**
     * Set route match object from which parameters will be retrieved
     *
     * @param  RouteMatch|MvcRouter\RouteMatch $matches
     * @return Mvc fluent interface, returns self
     */
    public function setRouteMatch($matches)
    {
        if (! $matches instanceof RouteMatch && ! $matches instanceof MvcRouter\RouteMatch) {
            throw new Exception\InvalidArgumentException(sprintf(
                'RouteMatch passed to %s must be either a %s or a %s instance; received %s',
                __METHOD__,
                RouteMatch::class,
                MvcRouter\RouteMatch::class,
                (is_object($router) ? get_class($router) : gettype($router))
            ));
        }
        $this->routeMatch = $matches;
        return $this;
    }

    /**
     * Get the useRouteMatch flag
     *
     * @return bool
     */
    public function useRouteMatch()
    {
        return $this->useRouteMatch;
    }

    /**
     * Set whether the page should use route match params for assembling link uri
     *
     * @see getHref()
     * @param bool $useRouteMatch [optional]
     * @return Mvc
     */
    public function setUseRouteMatch($useRouteMatch = true)
    {
        $this->useRouteMatch = (bool) $useRouteMatch;
        $this->hrefCache = null;
        return $this;
    }

    /**
     * Get the router.
     *
     * @return null|RouteStackInterface|MvcRouter\RouteStackInterface
     */
    public function getRouter()
    {
        return $this->router;
    }

    /**
     * Sets router for assembling URLs
     *
     * @see getHref()
     *
     * @param  RouteStackInterface|MvcRouter\RouteStackInterface $router Router
     * @return Mvc Fluent interface, returns self
     */
    public function setRouter($router)
    {
        if (! $router instanceof RouteStackInterface && ! $router instanceof MvcRouter\RouteStackInterface) {
            throw new Exception\InvalidArgumentException(sprintf(
                'Router passed to %s must be either a %s or a %s instance; received %s',
                __METHOD__,
                RouteStackInterface::class,
                MvcRouter\RouteStackInterface::class,
                (is_object($router) ? get_class($router) : gettype($router))
            ));
        }
        $this->router = $router;
        return $this;
    }

    /**
     * Sets the default router for assembling URLs.
     *
     * @see getHref()
     * @param  RouteStackInterface $router Router
     * @return void
     */
    public static function setDefaultRouter($router)
    {
        static::$defaultRouter = $router;
    }

    /**
     * Gets the default router for assembling URLs.
     *
     * @return RouteStackInterface
     */
    public static function getDefaultRouter()
    {
        return static::$defaultRouter;
    }

    /**
     * Set default route name
     *
     * @param string $route
     * @return void
     */
    public static function setDefaultRoute($route)
    {
        static::$defaultRoute = $route;
    }

    /**
     * Get default route name
     *
     * @return string
     */
    public static function getDefaultRoute()
    {
        return static::$defaultRoute;
    }

    // Public methods:

    /**
     * Returns an array representation of the page
     *
     * @return array  associative array containing all page properties
     */
    public function toArray()
    {
        return array_merge(
            parent::toArray(),
            [
                 'action'     => $this->getAction(),
                 'controller' => $this->getController(),
                 'params'     => $this->getParams(),
                 'route'      => $this->getRoute(),
                 'router'     => $this->getRouter(),
                 'route_match' => $this->getRouteMatch(),
            ]
        );
    }
}


text:
package org.ladanse.persistence.entity.queue;

import javax.persistence.*;
import java.sql.Timestamp;

@Entity
@Table(name = "NotificationQueueItem")
public class NotificationQueueItem
{
    private Integer id;
    private String activityType;
    private Timestamp activityOn;
    private String rawData;
    private Timestamp processedOn;
    private Integer activityBy;

    @Id
    @Column(name = "id", nullable = false)
    public Integer getId()
    {
        return id;
    }

    public NotificationQueueItem setId(Integer id)
    {
        this.id = id;
        return this;
    }

    @Basic
    @Column(name = "activityType", nullable = false, length = 255)
    public String getActivityType()
    {
        return activityType;
    }

    public NotificationQueueItem setActivityType(String activityType)
    {
        this.activityType = activityType;
        return this;
    }

    @Basic
    @Column(name = "activityOn", nullable = false)
    public Timestamp getActivityOn()
    {
        return activityOn;
    }

    public NotificationQueueItem setActivityOn(Timestamp activityOn)
    {
        this.activityOn = activityOn;
        return this;
    }

    @Basic
    @Column(name = "rawData", nullable = true, length = -1)
    public String getRawData()
    {
        return rawData;
    }

    public NotificationQueueItem setRawData(String rawData)
    {
        this.rawData = rawData;
        return this;
    }

    @Basic
    @Column(name = "processedOn", nullable = true)
    public Timestamp getProcessedOn()
    {
        return processedOn;
    }

    public NotificationQueueItem setProcessedOn(Timestamp processedOn)
    {
        this.processedOn = processedOn;
        return this;
    }

    @Basic
    @Column(name = "activityBy", nullable = true)
    public Integer getActivityBy()
    {
        return activityBy;
    }

    public NotificationQueueItem setActivityBy(Integer activityBy)
    {
        this.activityBy = activityBy;
        return this;
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace viz {

namespace mojom {
class SurfaceRangeDataView;
}

// SurfaceRange consists of two SurfaceIds representing a range of surfaces
// [start,end] ordered by SurfaceId where |start| is an optional surface
// which acts like a "fallback" surface in case it exists.
class VIZ_COMMON_EXPORT SurfaceRange {
 public:
  SurfaceRange();

  SurfaceRange(const absl::optional<SurfaceId>& start, const SurfaceId& end);

  explicit SurfaceRange(const SurfaceId& surface_id);

  SurfaceRange(const SurfaceRange& other);
  SurfaceRange& operator=(const SurfaceRange& other);

  bool operator==(const SurfaceRange& other) const;

  bool operator!=(const SurfaceRange& other) const;

  bool operator<(const SurfaceRange& other) const;

  // Check if |surface_id| falls within |this| SurfaceRange but is neither the
  // start nor end of the range. The FrameSinkId of |surface_id| must match
  // either the start or end of the range.
  bool IsInRangeExclusive(const SurfaceId& surface_id) const;

  // Check if |surface_id| falls within |this| SurfaceRange inclusive of the
  // start and end of the range. The FrameSinkId of |surface_id| must match
  // either the start or end of the range.
  bool IsInRangeInclusive(const SurfaceId& surface_id) const;

  // Returns whether the start and end of the range have differing FrameSinkIds.
  bool HasDifferentFrameSinkIds() const;

  // Returns whether the start and end of the range have different embed tokens.
  bool HasDifferentEmbedTokens() const;

  bool IsValid() const;

  const absl::optional<SurfaceId>& start() const { return start_; }

  const SurfaceId& end() const { return end_; }

  std::string ToString() const;

 private:
  friend struct mojo::StructTraits<mojom::SurfaceRangeDataView, SurfaceRange>;

  absl::optional<SurfaceId> start_;
  SurfaceId end_;
};

VIZ_COMMON_EXPORT std::ostream& operator<<(std::ostream& out,
                                           const SurfaceRange& surface_range);

}  // namespace viz

#endif  // COMPONENTS_VIZ_COMMON_SURFACES_SURFACE_RANGE_H_


text:
var config = require('../config.json');

var Redis = require('ioredis');
exports.redis = new Redis();

var Sequelize = require('sequelize');
var sequelize = new Sequelize(config.mysql.database, config.mysql.username, config.mysql.password, {
   host: config.mysql.host,
   port: config.mysql.port,
   logging: false,
   pool: {
      max: 5,
      min: 1,
      idle: 10000
   }
});

console.log('Connected to database.');

exports.posts = sequelize.define('posts', {
   postId: {type: Sequelize.TEXT, allowNull: false},
   postUrl: {type: Sequelize.TEXT, allowNull: false},
   mirror: {type: Sequelize.TEXT, allowNull: false},
   commentId: {type: Sequelize.TEXT, allowNull: false}
});

sequelize.sync();


text:
'use strict';

var Bing = require('node-bing-api')({ accKey: 'your key here' });

function imagesProcessing(db) {
    var queries = db.collection("queries");
    var queryProjection = {"_id" : false};

    this.apiResponse = function(req, res){
        var skip = 0;
        if(req.query.offset) {
            skip = parseInt(req.query.offset) * 10;
        }
         Bing.composite(req.params.url, {
          top: 10,  // Number of results (max 15 for news, max 50 if other)
          skip: skip,   // Skip first n results
          sources: "image", //Choices are web+image+video+news+spell
          newsSortBy: "Date" //Choices are Date, Relevance
        }, function(error, result, body){
           if(error) {
               throw error;
           }
           storeQueries(req);
           res.send(processResult(body));
        });
    };

    this.latestQueries = function(req, res) {

        queries.find({}, queryProjection ).sort({"when" : -1}).limit(10).toArray(function(err, documents) {
            if(err) {
               throw err;
           }
            res.send(documents);
        });

    };

    var processResult = function(body) {
        var imagesArray = [];
        var completeObj = body.d.results[0].Image;
        for(var index in completeObj) {
            var thisObject = {"url": completeObj[index].MediaUrl, "snippet" : completeObj[index].Title, "thumbnail" : completeObj[index].Thumbnail.MediaUrl, "context" : completeObj[index].SourceUrl };
            imagesArray.push(thisObject);
        }

        return imagesArray;
    };

    var storeQueries = function(req) {
        var date = new Date();
        queries.insert({"term": req.params.url, "when": date }, function (err) {
               if (err) {
                  throw err;
               }
        });
    };
}

module.exports = imagesProcessing;


text:
class AddEncryptionColumnsToPushNotificationSubscription < ActiveRecord::Migration[4.2]
  def change
    remove_column :push_notification_subscriptions, :subscription_id, :string, null: false

    add_column :push_notification_subscriptions, :endpoint, :string, null: false
    add_column :push_notification_subscriptions, :p256dh, :string, null: false
    add_column :push_notification_subscriptions, :auth, :string, null: false

    add_index :push_notification_subscriptions, [:endpoint, :p256dh, :auth], unique: true, name: 'index_push_notification_subscriptions_on_data'
  end
end


text:
jpoika-c
========

C-Sample Programs


text:
package android.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;

public final class Log {
  public static final int ASSERT = 7;
  public static final int DEBUG = 3;
  public static final int ERROR = 6;
  public static final int INFO = 4;
  public static final int VERBOSE = 2;
  public static final int WARN = 5;

  Log() {
  }

  public static int v(String tag, String msg) {
    return -1;
  }

  public static int v(String tag, String msg, Throwable tr) {
    return -1;
  }

  public static int d(String tag, String msg) {
    return -1;
  }

  public static int d(String tag, String msg, Throwable tr) {
    return -1;
  }

  public static int i(String tag, String msg) {
    return -1;
  }

  public static int i(String tag, String msg, Throwable tr) {
    return -1;
  }

  public static int w(String tag, String msg) {
    return -1;
  }

  public static int w(String tag, String msg, Throwable tr) {
    return -1;
  }

  public static boolean isLoggable(String var0, int var1) {
    return true;
  }

  public static int w(String tag, Throwable tr) {
    return -1;
  }

  public static int e(String tag, String msg) {
    return -1;
  }

  public static int e(String tag, String msg, Throwable tr) {
    return -1;
  }

  public static int wtf(String tag, String msg) {
    return -1;
  }

  public static int wtf(String tag, Throwable tr) {
    return -1;
  }

  public static int wtf(String tag, String msg, Throwable tr) {
    return -1;
  }

  public static String getStackTraceString(Throwable tr) {
    if (tr == null) {
      return "";
    }

    // This is to reduce the amount of log spew that apps do in the non-error
    // condition of the network being unavailable.
    Throwable t = tr;
    while (t != null) {
      if (t instanceof UnknownHostException) {
        return "";
      }
      t = t.getCause();
    }

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    tr.printStackTrace(pw);
    pw.flush();
    return sw.toString();
  }

  public static int println(int priority, String tag, String msg) {
    return -1;
  }
}


text:
using UnityEngine;
using System.Collections;

public class PlayVideo : MonoBehaviour {

	// Use this for initialization

	void Awake ()
	{
		((MovieTexture)guiTexture.texture).Play();

		audio.clip = ((MovieTexture)guiTexture.texture).audioClip;
		audio.Play ();
		Debug.Log ("Vid");
	}

}


text:
<?php

namespace Pterodactyl\Http\Controllers\Admin;

use Ramsey\Uuid\Uuid;
use Illuminate\Http\Request;
use Pterodactyl\Models\Nest;
use Pterodactyl\Models\Mount;
use Pterodactyl\Models\Location;
use Prologue\Alerts\AlertsMessageBag;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Http\Requests\Admin\MountFormRequest;
use Pterodactyl\Repositories\Eloquent\MountRepository;
use Pterodactyl\Contracts\Repository\NestRepositoryInterface;
use Pterodactyl\Contracts\Repository\LocationRepositoryInterface;

class MountController extends Controller
{
    /**
     * @var \Prologue\Alerts\AlertsMessageBag
     */
    protected $alert;

    /**
     * @var \Pterodactyl\Contracts\Repository\NestRepositoryInterface
     */
    protected $nestRepository;

    /**
     * @var \Pterodactyl\Contracts\Repository\LocationRepositoryInterface
     */
    protected $locationRepository;

    /**
     * @var \Pterodactyl\Repositories\Eloquent\MountRepository
     */
    protected $repository;

    /**
     * MountController constructor.
     */
    public function __construct(
        AlertsMessageBag $alert,
        NestRepositoryInterface $nestRepository,
        LocationRepositoryInterface $locationRepository,
        MountRepository $repository
    ) {
        $this->alert = $alert;
        $this->nestRepository = $nestRepository;
        $this->locationRepository = $locationRepository;
        $this->repository = $repository;
    }

    /**
     * Return the mount overview page.
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        return view('admin.mounts.index', [
            'mounts' => $this->repository->getAllWithDetails(),
        ]);
    }

    /**
     * Return the mount view page.
     *
     * @param string $id
     *
     * @return \Illuminate\View\View
     *
     * @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
     */
    public function view($id)
    {
        $nests = Nest::query()->with('eggs')->get();
        $locations = Location::query()->with('nodes')->get();

        return view('admin.mounts.view', [
            'mount' => $this->repository->getWithRelations($id),
            'nests' => $nests,
            'locations' => $locations,
        ]);
    }

    /**
     * Handle request to create new mount.
     *
     * @return \Illuminate\Http\RedirectResponse
     *
     * @throws \Throwable
     */
    public function create(MountFormRequest $request)
    {
        $model = (new Mount())->fill($request->validated());
        $model->forceFill(['uuid' => Uuid::uuid4()->toString()]);

        $model->saveOrFail();
        $mount = $model->fresh();

        $this->alert->success('Mount was created successfully.')->flash();

        return redirect()->route('admin.mounts.view', $mount->id);
    }

    /**
     * Handle request to update or delete location.
     *
     * @return \Illuminate\Http\RedirectResponse
     *
     * @throws \Throwable
     */
    public function update(MountFormRequest $request, Mount $mount)
    {
        if ($request->input('action') === 'delete') {
            return $this->delete($mount);
        }

        $mount->forceFill($request->validated())->save();

        $this->alert->success('Mount was updated successfully.')->flash();

        return redirect()->route('admin.mounts.view', $mount->id);
    }

    /**
     * Delete a location from the system.
     *
     * @return \Illuminate\Http\RedirectResponse
     *
     * @throws \Exception
     */
    public function delete(Mount $mount)
    {
        $mount->delete();

        return redirect()->route('admin.mounts');
    }

    /**
     * Adds eggs to the mount's many to many relation.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function addEggs(Request $request, Mount $mount)
    {
        $validatedData = $request->validate([
            'eggs' => 'required|exists:eggs,id',
        ]);

        $eggs = $validatedData['eggs'] ?? [];
        if (count($eggs) > 0) {
            $mount->eggs()->attach($eggs);
        }

        $this->alert->success('Mount was updated successfully.')->flash();

        return redirect()->route('admin.mounts.view', $mount->id);
    }

    /**
     * Adds nodes to the mount's many to many relation.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function addNodes(Request $request, Mount $mount)
    {
        $data = $request->validate(['nodes' => 'required|exists:nodes,id']);

        $nodes = $data['nodes'] ?? [];
        if (count($nodes) > 0) {
            $mount->nodes()->attach($nodes);
        }

        $this->alert->success('Mount was updated successfully.')->flash();

        return redirect()->route('admin.mounts.view', $mount->id);
    }

    /**
     * Deletes an egg from the mount's many to many relation.
     *
     * @return \Illuminate\Http\Response
     */
    public function deleteEgg(Mount $mount, int $egg_id)
    {
        $mount->eggs()->detach($egg_id);

        return response('', 204);
    }

    /**
     * Deletes an node from the mount's many to many relation.
     *
     * @return \Illuminate\Http\Response
     */
    public function deleteNode(Mount $mount, int $node_id)
    {
        $mount->nodes()->detach($node_id);

        return response('', 204);
    }
}


text:
using System;
using MonoTouch.UIKit;
using System.Drawing;
using MonoTouch.Foundation;
using System.Collections.Generic;

namespace MonoKit.UI.PagedViews
{
    public class MetroPage
    {
        public string Title { get; set; }
    }

    public class MetroPageView : UIView, IScrollingPageViewDelegate
    {
        private string fontStyle = "Optima-Regular";

        private float fontSize = 48;

        private ScrollingPageView pgTitle;

        private UIButton mainLabel;

        private readonly List<MetroPage> pages = new List<MetroPage>();

        private readonly List<MetroPageInstance> pageInstances = new List<MetroPageInstance>();

        public MetroPageView(RectangleF frame, IEnumerable<MetroPage> pages) : base(frame)
        {
            var f = frame;
            f.Y = 100;
            this.pgTitle = new ScrollingPageView(f, true);
            this.pgTitle.Delegate = this;
            this.pgTitle.AutoresizingMask = UIViewAutoresizing.All;
            this.AddSubview(this.pgTitle);

            this.Load(pages);
        }

        private void Load(IEnumerable<MetroPage> pages)
        {
            this.pages.AddRange(pages);
            this.pgTitle.ReloadPages();
            this.CreateButtons();
        }

        private void CreateButtons()
        {
            float left = 0;
            int index = 0;
            foreach (var page in this.pages)
            {
                var instance = new MetroPageInstance();
                instance.Button = this.CreateButton(page.Title, left, index);
                this.AddSubview(instance.Button);
                this.pageInstances.Add(instance);
                index++;
                left += instance.Button.Frame.Width;
            }
        }

        private UIButton CreateButton(string title, float left, int index)
        {
            var fnt = UIFont.FromName(this.fontStyle, this.fontSize);
            if (fnt == null)
            {
                fnt = UIFont.SystemFontOfSize(this.fontSize);
            }

            var sz = new NSString(title).StringSize(fnt);

            RectangleF frame = new RectangleF(0, 0, sz.Width + 20, sz.Height + 20);

            var label = new UILabel(frame);
            label.Text = title;
            label.Font = fnt;
            label.TextAlignment = UITextAlignment.Center;
            label.TextColor = UIColor.LightGray;

            //label.BackgroundColor = UIColor.Clear;

            frame.X = left;
            frame.Y = 0;

            var button = UIButton.FromType(UIButtonType.Custom);

            button.Frame = frame;

            button.AddSubview(label);
            //button.BackgroundColor = UIColor.Blue;
            button.TouchUpInside += HandleMainLabelhandleTouchUpInside;
            button.Tag = index;

            return button;
        }

        void HandleMainLabelhandleTouchUpInside (object sender, EventArgs e)
        {
            //this.test.TextColor = UIColor.Black;
            var newIndex = ((UIButton)sender).Tag;

            this.pgTitle.ScrollToPage(newIndex);
            this.UpdateFocusedButtonIndex(newIndex);
        }

        private void UpdateFocusedButtonIndex(int index)
        {
            foreach (var instance in this.pageInstances)
            {
                var label = (instance.Button.Subviews[0] as UILabel);
                label.TextColor = instance.Button.Tag == index ? UIColor.Black : UIColor.LightGray;
            }
        }

        public UIView CreateView(string pageTypeKey, RectangleF frame)
        {
            return new TitleView(frame);
        }

        public void UpdatePage(int index, UIView view)
        {
           (view as TitleView).TitleLabel.Text = "test page " + index.ToString();
        }

        public void PageIndexChanged(int index)
        {
            this.UpdateFocusedButtonIndex(index);
            //throw new NotImplementedException();
        }

        public string GetPageTypeKey(int index)
        {
            switch (index)
            {
                case 0:
                    return "key1";
                case 1:
                    return "key2";
                case 2:
                    return "key3";
            }

            return string.Empty;
        }

        public int PageCount
        {
            get
            {
                return this.pages.Count;
            }
        }

        private class MetroPageInstance
        {
            public UIButton Button { get; set; }

        }

    }
}


text:
require_relative '../../spec_helper'

describe GemsToPatchReconciler do
  def names_to_patches(names)
    names.map { |n| GemPatch.new(gem_name: n) }
  end

  def reconciler(vuln_names, requested_names=[])
    @vulnerable_patches = names_to_patches(Array(vuln_names))
    GemsToPatchReconciler.new(@vulnerable_patches, names_to_patches(Array(requested_names)))
  end

  it 'should do nothing if nothing requested' do
    r = reconciler('foo')
    r.reconciled_patches.length.should == 0
    # empty will signal to Bundler to update _all_
  end

  it 'should not include non-requested vulnerable gems' do
    r = reconciler('foo', 'bar')
    r.reconciled_patches.length.should == 1
    r.reconciled_patches.first.gem_name.should == 'bar'

    @vulnerable_patches.length.should == 0
  end

  it 'should include requested vulnerable gems' do
    r = reconciler('foo', %w(foo bar))
    r.reconciled_patches.length.should == 2
    r.reconciled_patches.first.gem_name.should == 'foo'
    r.reconciled_patches.last.gem_name.should == 'bar'

    @vulnerable_patches.length.should == 1
  end
end


text:
id: 273
title: Signs that App Store is getting crowded
date: 2010-02-10T22:39:49+00:00
author: Junda Ong
layout: post
guid: http://blog.just2us.com/2010/02/sign-that-app-store-is-getting-crowded/
permalink: /2010/02/sign-that-app-store-is-getting-crowded/
dsq_thread_id:
  - 65765183
arkayne-cache-post:
  - |
    |

arkayne-time-post:
  - 1400175456
categories:
  - Development
  - iPhone
tags:
  - appstore
  - market
---
txeet was released on 9 Feb 2010.

Shortly after releasing, I checked on App Store ranking and my analytic data, and I see signs that Apple's App Store is getting too crowded.

## Sign 1 – Apps cluttered in the categories, especially in Lifestyle

In just a single day, there are **18 lifestyle apps** released. These apps are ordered in alphabetical order, therefore txeet is placed quite behind, in fact it is in page 2.

To have a newly released app in page 2 is a big disappointment. One year ago, it could take 3 days before a new app gets pushed to page 2. Those were the days..

Note that page 1 has 5 charm apps (similar apps with combination of color and types…). The developer probably gonna release another 100+ apps as there are so many colors..

Page 2 has quite a lot of Girls apps, the latest trend. On first look, txeet looks bright and very out of place.

## Sign 2 – Analytics show that Android has more users

I used Flurry analytics to analyze the **number of new users** for the first few days of launch.

Android was released on Oct 18th, and the first day it gathered **620 new users**.

##

iPhone was released on Feb 9th, and the first full day it gathered **147 new users**.

##

This post will be updated when I have updated data.


text:
package io.kubernetes.client.spring.extended.manifests;

import static org.awaitility.Awaitility.await;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import io.kubernetes.client.openapi.models.V1ConfigMap;
import io.kubernetes.client.spring.extended.manifests.annotation.FromConfigMap;
import io.kubernetes.client.spring.extended.manifests.config.KubernetesManifestsProperties;
import io.kubernetes.client.spring.extended.manifests.configmaps.ConfigMapGetter;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runners.model.Statement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest("kubernetes.manifests.refreshInterval=1s")
public class KubernetesFromConfigMapTest {

  @Rule public ConfigMapResetter configMapResetter = new ConfigMapResetter();

  @SpringBootApplication
  static class App {

    @Bean
    public KubernetesFromConfigMapProcessor kubernetesFromConfigMapProcessor() {
      return new KubernetesFromConfigMapProcessor();
    }

    @Bean
    public MockAtomicConfigMapGetter mockAtomicConfigMapGetter() {
      MockAtomicConfigMapGetter atomicConfigMapGetter = new MockAtomicConfigMapGetter();
      return atomicConfigMapGetter;
    }

    @Bean
    public KubernetesFromConfigMapTest.MyBean myBean() {
      return new KubernetesFromConfigMapTest.MyBean();
    }
  }

  static class MyBean {
    @FromConfigMap(namespace = "default", name = "foo", configMapGetter = MockConfigMapGetter.class)
    private Map<String, String> staticData;

    @FromConfigMap(
        namespace = "default",
        name = "foo",
        configMapGetter = MockAtomicConfigMapGetter.class)
    private Map<String, String> dynamicData;
  }

  @Autowired private KubernetesFromConfigMapTest.MyBean myBean;

  @Autowired private MockAtomicConfigMapGetter mockAtomicConfigMapGetter;

  @Autowired private KubernetesManifestsProperties manifestsProperties;

  @Test
  public void testReadOnce() {
    assertNotNull(myBean.staticData);
    assertEquals("bar", myBean.staticData.get("foo"));
  }

  @Test
  public void testValueUpdate() throws InterruptedException {
    assertEquals(Duration.ofSeconds(1), manifestsProperties.getRefreshInterval());
    assertNotNull(myBean.dynamicData);
    assertEquals("bar1", myBean.dynamicData.get("foo"));
    mockAtomicConfigMapGetter.configMapAtomicReference.set(
        new V1ConfigMap().putDataItem("foo", "bar2"));
    await()
        .timeout(manifestsProperties.getRefreshInterval().multipliedBy(2))
        .until(() -> "bar2".equals(myBean.dynamicData.get("foo")));
  }

  @Test
  public void testKeyUpdate() throws InterruptedException {
    assertEquals(Duration.ofSeconds(1), manifestsProperties.getRefreshInterval());
    assertNotNull(myBean.dynamicData);
    assertEquals("bar1", myBean.dynamicData.get("foo"));
    mockAtomicConfigMapGetter.configMapAtomicReference.set(
        new V1ConfigMap().putDataItem("foo1", "bar"));
    await()
        .timeout(manifestsProperties.getRefreshInterval().multipliedBy(2))
        .until(
            () -> {
              return myBean.dynamicData.get("foo") == null
                  && "bar".equals(myBean.dynamicData.get("foo1"));
            });
  }

  static class MockConfigMapGetter implements ConfigMapGetter {
    @Override
    public V1ConfigMap get(String namespace, String name) {
      return new V1ConfigMap().putDataItem("foo", "bar");
    }
  }

  static class MockAtomicConfigMapGetter implements ConfigMapGetter {

    private final AtomicReference<V1ConfigMap> configMapAtomicReference = new AtomicReference<>();

    @Override
    public V1ConfigMap get(String namespace, String name) {
      return configMapAtomicReference.get();
    }
  }

  class ConfigMapResetter implements TestRule {
    @Override
    public Statement apply(Statement statement, Description description) {
      return new Statement() {
        @Override
        public void evaluate() throws Throwable {
          mockAtomicConfigMapGetter.configMapAtomicReference.set(
              new V1ConfigMap().putDataItem("foo", "bar1"));
          await().until(() -> "bar1".equals(myBean.dynamicData.get("foo")));
          statement.evaluate();
        }
      };
    }
  }
}


text:
import subprocess

document_template = r"""\documentclass{article}
\usepackage{amsmath}
\begin{document}
%s
\end{document}
"""

def latexml(math_code, reporter=None):
    """Convert LaTeX math code to MathML with LaTeXML_

    .. _LaTeXML: http://dlmf.nist.gov/LaTeXML/
    """
    p = subprocess.Popen(['latexml',
                             '-', # read from stdin
                             # '--preload=amsmath',
                             '--inputencoding=utf8',
                            ],
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            close_fds=True)
    p.stdin.write((document_template % math_code).encode('utf8'))
    p.stdin.close()
    latexml_code = p.stdout.read()
    latexml_err = p.stderr.read().decode('utf8')
    if reporter and latexml_err.find('Error') >= 0 or not latexml_code:
        reporter.error(latexml_err)

    post_p = subprocess.Popen(['latexmlpost',
                               '-',
                               '--nonumbersections',
                               '--format=xhtml',
                               # '--linelength=78', # experimental
                               '--'
                              ],
                              stdin=subprocess.PIPE,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE,
                              close_fds=True)
    post_p.stdin.write(latexml_code)
    post_p.stdin.close()
    result = post_p.stdout.read().decode('utf8')
    post_p_err = post_p.stderr.read().decode('utf8')
    if reporter and post_p_err.find('Error') >= 0 or not result:
        reporter.error(post_p_err)

    # extract MathML code:
    start,end = result.find('<math'), result.find('</math>')+7
    result = result[start:end]
    if 'class="ltx_ERROR' in result:
        raise SyntaxError(result)
    return result

def ttm(math_code, reporter=None):
    """Convert LaTeX math code to MathML with TtM_

    .. _TtM: http://hutchinson.belmont.ma.us/tth/mml/
    """
    p = subprocess.Popen(['ttm',
                          # '-i', # italic font for equations. Default roman.
                          '-u', # unicode character encoding. (Default iso-8859-1).
                          '-r', # output raw MathML (no preamble or  postlude)
                         ],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         close_fds=True)
    p.stdin.write((document_template % math_code).encode('utf8'))
    p.stdin.close()
    result = p.stdout.read()
    err = p.stderr.read().decode('utf8')
    if err.find('**** Unknown') >= 0:
        msg = '\n'.join([line for line in err.splitlines()
                         if line.startswith('****')])
        raise SyntaxError('\nMessage from external converter TtM:\n'+ msg)
    if reporter and err.find('**** Error') >= 0 or not result:
        reporter.error(err)
    start,end = result.find('<math'), result.find('</math>')+7
    result = result[start:end]
    return result

def blahtexml(math_code, inline=True, reporter=None):
    """Convert LaTeX math code to MathML with blahtexml_

    .. _blahtexml: http://gva.noekeon.org/blahtexml/
    """
    options = ['--mathml',
               '--indented',
               '--spacing', 'moderate',
               '--mathml-encoding', 'raw',
               '--other-encoding', 'raw',
               '--doctype-xhtml+mathml',
               '--annotate-TeX',
              ]
    if inline:
        mathmode_arg = ''
    else:
        mathmode_arg = 'mode="display"'
        options.append('--displaymath')

    p = subprocess.Popen(['blahtexml']+options,
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         close_fds=True)
    p.stdin.write(math_code.encode('utf8'))
    p.stdin.close()
    result = p.stdout.read().decode('utf8')
    err = p.stderr.read().decode('utf8')

    print err
    if result.find('<error>') >= 0:
        raise SyntaxError('\nMessage from external converter blahtexml:\n'
                +result[result.find('<message>')+9:result.find('</message>')])
    if reporter and (err.find('**** Error') >= 0 or not result):
        reporter.error(err)
    start,end = result.find('<markup>')+9, result.find('</markup>')
    result = ('<math xmlns="http://www.w3.org/1998/Math/MathML"%s>\n'
              '%s</math>\n') % (mathmode_arg, result[start:end])
    return result

# self-test

if __name__ == "__main__":
    example = ur'\frac{\partial \sin^2(\alpha)}{\partial \vec r} \varpi \, \text{Grüße}'
    # print latexml(example).encode('utf8')
    # print ttm(example)#.encode('utf8')
    print blahtexml(example).encode('utf8')


text:
//
//  AppDelegate.m
//  VpnTint
//
//  Created by Eric Betts on 8/15/13.
//  Copyright (c) 2013 Eric Betts. All rights reserved.
//
//__bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.
//__bridge_retained or CFBridgingRetain casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you. You are responsible for calling CFRelease or a related function to relinquish ownership of the object.
//__bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC. ARC is responsible for relinquishing ownership of the object.

#import "AppDelegate.h"
@implementation AppDelegate

NSString *const BWIconKey = @"BlackAndWhiteMenuBarIcon";
NSString *const autoStartKey = @"startAtLogin";
NSString *const ServiceIDKey = @"ActiveServiceId";
NSString *const VpnColorsKey = @"VpnColors";

float const DefaultColorAlpha = 0.3f; //Alpha of NSColors that are created from hex string

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    //Update how colors are stored:
    [self updateStoredColorFormat];

    [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:) name:NSWindowWillCloseNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveVpnEventNotification:) name:@"VpnEvent" object:nil];
    [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory]; //hide dock icon

    NSNotificationCenter *shared = [[NSWorkspace sharedWorkspace] notificationCenter];
    [shared addObserver:self selector: @selector(receiveWakeNote:) name: NSWorkspaceDidWakeNotification object: nil];
    [shared addObserver:self selector:@selector(screenWokeUp:) name: NSWorkspaceScreensDidWakeNotification object:nil];

    self.palette = @[
                     [[NSColor yellowColor] colorWithAlphaComponent:DefaultColorAlpha],
                     [[NSColor magentaColor] colorWithAlphaComponent:DefaultColorAlpha],
                     [[NSColor brownColor] colorWithAlphaComponent:DefaultColorAlpha],
                     [[NSColor cyanColor] colorWithAlphaComponent:DefaultColorAlpha],
                     [[NSColor blueColor] colorWithAlphaComponent:DefaultColorAlpha],
                     [[NSColor greenColor] colorWithAlphaComponent:DefaultColorAlpha]
                     ];
    self.icon_size = NSMakeSize(18.0, 18.0);
    self.watched_vpns = [[NSMutableArray alloc] init];
    self.selected_vpn_name = @"";

    NSColorPanel.pickerMask = NSColorPanelWheelModeMask;
    NSColorPanel.pickerMode = NSWheelModeColorPanel;

    [self addMenubarIcon];
    [self setLoginState];

    [self createVpnList];
    [self checkActiveVpns];

}

-(void)colorUpdate:(NSColorPanel*)colorPanel{
    NSColor* theColor = colorPanel.color;
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

    //NSLog(@"%s %@", __PRETTY_FUNCTION__, [theColor hexadecimalValueOfAnNSColor]);
    self.window.backgroundColor = theColor;

    //How do I figure out which one is being modified?
    NSString *vpn_name = self.selected_vpn_name;

    //Update color swatch next to menu itom
    NSMenuItem * theItem = [self.statusItem.menu itemWithTitle:vpn_name];
    theItem.image = [NSImage swatchWithColor:theColor size:self.icon_size];

    NSData *colorData=[NSArchiver archivedDataWithRootObject:theColor];
    NSDictionary *currentConfig = [prefs dictionaryForKey:VpnColorsKey];
    if (!currentConfig) currentConfig = [NSDictionary dictionary];
    NSMutableDictionary *newConfig = [currentConfig mutableCopy];
    [newConfig setObject:colorData forKey:vpn_name];
    [prefs setObject:newConfig forKey:VpnColorsKey];
    //NSLog(@"Setting user chosen color %@ for %@", [theColor hexadecimalValueOfAnNSColor], vpn_name);
    currentConfig = (NSDictionary*) newConfig;
}

-(void) readInPreferences
{
    //NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

    /*
    if([prefs floatForKey:GlobalAlphaKey]) {
        self.alpha = [prefs floatForKey:GlobalAlphaKey];
    }
    */
    //https://developer.apple.com/library/mac/documentation/cocoa/Conceptual/DrawColor/Tasks/StoringNSColorInDefaults.html#//apple_ref/doc/uid/20001693-BAJBFGED
}

- (void)addMenubarIcon
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSImage* icon = [NSApp applicationIconImage];
    if([prefs boolForKey:BWIconKey]) {
        icon = [NSImage imageNamed:@"vpn_tint_bw"];
    }
    icon.size = self.icon_size;

    if (!self.statusItem) {
        self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
        self.statusItem.menu = self.statusMenu;
    }
    self.statusItem.image = icon;
    self.statusItem.highlightMode = YES;
    self.useBWIcon.state = [prefs boolForKey:BWIconKey];
}

-(void) handleVpnMenu:(id)sender
{
    //Look up service_id of clicked item
    NSMenuItem *item = (NSMenuItem*)sender;
    NSString *service_id = (NSString*)item.representedObject;
    NSString *vpn_name = [self getServiceName:service_id];
    NSLog(@"%s: %@", __PRETTY_FUNCTION__, vpn_name);

    self.selected_vpn_name = vpn_name;

    NSColorPanel *cp = [NSColorPanel sharedColorPanel];
    cp.showsAlpha = YES;
    cp.color = [self colorOfVpn:vpn_name];
    cp.continuous = YES;
    cp.floatingPanel = NO;
    cp.worksWhenModal = NO;
    cp.target = self;
    cp.action = @selector(colorUpdate:);
    cp.hidesOnDeactivate = NO;
    [cp orderFront:self];
    [cp orderFrontRegardless];
    [[NSApplication sharedApplication] orderFrontColorPanel:nil];

}

- (void)windowWillClose:(NSNotification *)notification {
    if ([notification.object isEqual:[NSColorPanel sharedColorPanel]]) {
        NSLog(@"%s: setting color panel action", __PRETTY_FUNCTION__);
        [[NSColorPanel sharedColorPanel] setAction:nil];
        [[NSColorPanel sharedColorPanel] setTarget:nil];
        [self checkActiveVpns];
    }
}

- (void)applicationWillTerminate:(NSNotification *)aNotification
{
    NSLog(@"%s: setting color panel action", __PRETTY_FUNCTION__);
    [[NSColorPanel sharedColorPanel] setAction:nil];
    [[NSColorPanel sharedColorPanel] setTarget:nil];
}

- (void) receiveVpnEventNotification:(NSNotification *) notification
{
    NSDictionary *userInfo = notification.userInfo;
    bool newState = [userInfo[@"newState"] boolValue];
    NSString *service_id = userInfo[@"service_id"];

    NSLog(@"%s: [%@] is %@", __PRETTY_FUNCTION__, service_id, newState ? @"On" : @"Off");

    //Create native notification
    if (![service_id isEqualToString:@""]) { //blank service_id is special case
        NSString *interface = [self getServiceName:service_id];
        [self nativeNotificationFor:interface new:newState];

        //Update menu item
        [self.statusMenu itemWithTitle:[self getServiceName:service_id]].state = newState;
    }

    if(!newState) { service_id = @"";}
    //Update tint
    [self setWindowTint:service_id];
}

- (void) setWindowTint:(NSString*)service_id {
    [self.window reassert_location];
    NSColor *newColor = [self colorOfVpn:[self getServiceName:service_id]];
    self.window.backgroundColor = newColor;
    //NSLog(@"WindowTint is now %@ (alpha: %f)", [newColor hexadecimalValueOfAnNSColor], [newColor alphaComponent]);
}

#pragma mark new notification stuff #pragma mark -
-(void) createVpnList {
    SCNetworkServiceRef	service;
    SCNetworkInterfaceRef interface;
    CFStringRef interfaceType;

    SCPreferencesRef prefs = SCPreferencesCreate(NULL, CFSTR("SCNetworkConnectionCopyAvailableServices"), NULL);
    if (prefs == NULL) { return; }

	CFArrayRef services = SCNetworkServiceCopyAll(prefs);
    CFRelease(prefs);

    [self.statusMenu insertItem:[NSMenuItem separatorItem] atIndex:[self.statusMenu numberOfItems] - 1];
    [self addToMenu:@""];

	if (services) {
		long count = CFArrayGetCount(services);
        //NSLog(@"%li services", count);
		for (int i = 0; i < count; i++) {
			service = CFArrayGetValueAtIndex(services, i);
            interface = SCNetworkServiceGetInterface(service);
            if (interface == NULL) { continue; }
            interfaceType = SCNetworkInterfaceGetInterfaceType(interface);
            if (CFEqual(interfaceType, kSCNetworkInterfaceTypeIPSec) ) {
                [self watchService:service];
            } else if (CFEqual(interfaceType, kSCNetworkInterfaceTypePPP)) {
                //NB: NetworkServiceGetInterface to NetworkInterfaceGetInterface
                interface = SCNetworkInterfaceGetInterface(interface);
                interfaceType = SCNetworkInterfaceGetInterfaceType(interface);
                if (CFEqual(interfaceType, kSCNetworkInterfaceTypeL2TP) ||
                    CFEqual(interfaceType, kSCNetworkInterfaceTypePPTP) ){
                    [self watchService:service];
                }
            }
		}
        CFRelease(services);
	}

    [self.statusMenu insertItem:[NSMenuItem separatorItem] atIndex:[self.statusMenu numberOfItems] - 1];
    //NSLog(@"VPN list: %@", self.watched_vpns);
}

-(void) watchService:(SCNetworkServiceRef) service
{
    NSString *service_id = (__bridge NSString*)SCNetworkServiceGetServiceID(service);
    //NSLog(@"%s: %@", __PRETTY_FUNCTION__, service_id);
    if (![self.watched_vpns containsObject:service_id]) {
        [self.watched_vpns addObject:service_id];
        [self addToMenu:service_id];

        SCNetworkConnectionContext context = { 0, (__bridge void*)self, NULL, NULL, NULL };
        SCNetworkConnectionRef connection = SCNetworkConnectionCreateWithServiceID(NULL, (__bridge CFStringRef)(service_id), networkStateCallback, &context);
        // setup watcher
        SCNetworkConnectionSetDispatchQueue(connection, dispatch_get_current_queue());
    }
}

- (void) addToMenu:(NSString*) service_id
{
    //NSLog(@"%s: %@", __PRETTY_FUNCTION__, service_id);
    NSColor *vpnColor = [self colorOfVpn:[self getServiceName:service_id]];

    NSMenuItem *newItem = [[NSMenuItem alloc ] initWithTitle:[self getServiceName:service_id] action:@selector(handleVpnMenu:) keyEquivalent:@""];
    newItem.representedObject = service_id;

    newItem.image = [NSImage swatchWithColor:vpnColor size:self.icon_size];
    [self.statusMenu insertItem:newItem atIndex:[self.statusMenu numberOfItems] - 1];
}

-(void) checkActiveVpns
{
    NSMutableArray *active = [NSMutableArray array];
    NSDictionary *userInfo;
    for (NSString* service_id in self.watched_vpns) {
        SCNetworkConnectionContext context = { 0, (__bridge void*)self, NULL, NULL, NULL };
        SCNetworkConnectionRef connection = SCNetworkConnectionCreateWithServiceID(NULL, (__bridge CFStringRef)(service_id), networkStateCallback, &context);
        SCNetworkConnectionStatus status = SCNetworkConnectionGetStatus(connection);
        BOOL on = (status == kSCNetworkConnectionConnected || status == kSCNetworkConnectionConnecting);
        if (on) {
            [active addObject:service_id];
        }
    }

    //NSLog(@"I see %li active Vpns", [active count]);
    if ([active count] == 0) {
        userInfo = @{ @"service_id": @"", @"newState": [NSNumber numberWithBool:NO] };
        [[NSNotificationCenter defaultCenter] postNotificationName: @"VpnEvent" object:nil userInfo:userInfo];
    } else {
        userInfo = @{ @"service_id": [active objectAtIndex:0], @"newState": [NSNumber numberWithBool:YES] };
        [[NSNotificationCenter defaultCenter] postNotificationName: @"VpnEvent" object:nil userInfo:userInfo];
    }
}

void networkStateCallback(SCNetworkConnectionRef connection, SCNetworkConnectionStatus status, void *info)
{
    //AppDelegate* self = (__bridge AppDelegate*) info;
    NSString *service_id = CFBridgingRelease(SCNetworkConnectionCopyServiceID(connection)); //(__bridge_transfer NSString *)
    BOOL on = (status == kSCNetworkConnectionConnected || status == kSCNetworkConnectionConnecting);
    //NSLog(@"%s: %@, %i", __PRETTY_FUNCTION__, service_id, on);
    NSDictionary *userInfo = @{
                               @"service_id": service_id,
                               @"newState": [NSNumber numberWithBool:on]
                               };
    [[NSNotificationCenter defaultCenter] postNotificationName: @"VpnEvent" object:nil userInfo:userInfo];
}

-(NSString*) getServiceName:(NSString*) service_id
{
    //Catch off state
    if ([service_id isEqualToString:@""]) return service_id;
    //Look up name
    SCPreferencesRef prefs = SCPreferencesCreate(NULL, CFSTR("SCNetworkConnectionCopyAvailableServices"), NULL);
    SCNetworkServiceRef service = SCNetworkServiceCopy(prefs, (__bridge CFStringRef)(service_id));
    CFRelease(prefs);
    if (!service) { NSLog(@"Error in %s getting name for service_id %@", __PRETTY_FUNCTION__, service_id); return @""; }
    NSString* name = (__bridge NSString *)(SCNetworkServiceGetName(service));
    CFRelease(service);
    //NSLog(@"%s: %@ -> %@", __PRETTY_FUNCTION__, service_id, name);
    return name;
}

#pragma mark Color stuff #pragma mark -

- (NSColor*) colorOfVpn:(NSString*) vpn_name
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSDictionary *currentConfig = [prefs dictionaryForKey:VpnColorsKey];
    if (!currentConfig) currentConfig = [NSDictionary dictionary];
    NSMutableDictionary *newConfig = [currentConfig mutableCopy];

    id encodedColor = [currentConfig objectForKey:vpn_name];

    if (vpn_name && encodedColor == nil){
        //Get next color
        NSColor *newColor = self.palette[[currentConfig count] % [self.palette count]];
        //Set to clear if empty string
        if ( [vpn_name isEqualToString:@""] ) {
            newColor = [NSColor clearColor];//Default to clear, but allows it to be overridden
        }
        //Encode to NSData
        encodedColor = [NSArchiver archivedDataWithRootObject:newColor];

        //Overwrite colors dict with updated copy
        [newConfig setObject:encodedColor forKey:vpn_name];
        [prefs setObject:newConfig forKey:VpnColorsKey];
        NSLog(@"Previously unseen VPN: setting %@ for %@", newColor, vpn_name);
        currentConfig = (NSDictionary*) newConfig;
    }

    //NSLog(@"Color dictionary: %@", currentConfig);

    return (NSColor*)[NSUnarchiver unarchiveObjectWithData:encodedColor];
}

/* Update user preference dictionary from using hex string for to color to NSData. */
- (void) updateStoredColorFormat {

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSDictionary *currentConfig = [prefs dictionaryForKey:VpnColorsKey];
    if (!currentConfig) currentConfig = [NSDictionary dictionary];

    //Give us something we can work with
    NSMutableDictionary *newConfig = [currentConfig mutableCopy];

    for ( NSString *vpn_name in [newConfig allKeys]) {
        id encodedColor = [newConfig objectForKey:vpn_name];//Not sure if NSData or NSString
        if (![encodedColor isKindOfClass:[NSData class]]) {
            NSColor *vpnColor = [self colorWithHexColorString:(NSString*) encodedColor];

            NSLog(@"Updating the the color stored for %@ [%@]", vpn_name, vpnColor);
            //save it back to dictionary as NSData
            encodedColor = [NSArchiver archivedDataWithRootObject:vpnColor];
            [newConfig setObject:encodedColor forKey:vpn_name];
        }
    }

    [prefs setObject:newConfig forKey:VpnColorsKey];
}

- (NSColor*)colorWithHexColorString:(NSString*)inColorString
{
    NSColor* result = nil;
    unsigned colorCode = 0;
    unsigned char redByte, greenByte, blueByte;

    //Special case for interfaces that shouldn't tint the menu bar
    if (inColorString == nil || [inColorString isEqualToString:@""]){
        return [NSColor clearColor];
    }

    if (nil != inColorString)
    {
        NSScanner* scanner = [NSScanner scannerWithString:inColorString];
        (void) [scanner scanHexInt:&colorCode]; // ignore error
    }
    redByte = (unsigned char)(colorCode >> 16);
    greenByte = (unsigned char)(colorCode >> 8);
    blueByte = (unsigned char)(colorCode); // masks off high bits

    result = [NSColor
              colorWithCalibratedRed:(CGFloat)redByte / 0xff
              green:(CGFloat)greenByte / 0xff
              blue:(CGFloat)blueByte / 0xff
              alpha:DefaultColorAlpha];
    return result;
}

#pragma mark Handle various screen changes (sleep, new display, full screen app, etc) #pragma mark -
-(void)applicationDidChangeScreenParameters:(NSNotification*)aNotification {
    [self.window reassert_location];
}

-(void)screenWokeUp:(NSNotification*)aNotification {
    //Screen wake
    [self.window reassert_location];
}

- (void)receiveWakeNote: (NSNotification*) note {
    //System wake
    [self.window reassert_location];
    [self checkActiveVpns];
}

#pragma mark BWIcon #pragma mark -
- (IBAction)useBWIconToggle:(id)pid {
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    self.useBWIcon.state = !self.useBWIcon.state;
    [prefs setBool:self.useBWIcon.state forKey:BWIconKey];
    [self addMenubarIcon];
}

#pragma mark Adding to login #pragma mark -

- (IBAction)startAtLoginToggle:(id)pid {
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setBool:!self.startAtLogin.state forKey:autoStartKey];
    [self setLoginState];
}

- (void) setLoginState {
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    if([prefs boolForKey:autoStartKey]) {
        [self addAppAsLoginItem];
    } else {
        [self deleteAppFromLoginItem];
    }
    self.startAtLogin.state = [prefs boolForKey:autoStartKey];
}

-(void) addAppAsLoginItem{
    NSString * appPath = [[NSBundle mainBundle] bundlePath];
    NSURL *url = [NSURL fileURLWithPath:appPath];
    LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
    if (loginItems) {
        //Insert an item to the list.
        LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemLast, NULL, NULL, (__bridge CFURLRef)(url), NULL, NULL);
        if (item){
            CFRelease(item);
        }
        CFRelease(loginItems);
    }
}

-(void) deleteAppFromLoginItem{
    UInt32 seedValue;
    NSString * appPath = [[NSBundle mainBundle] bundlePath];
    NSURL *url = [NSURL fileURLWithPath:appPath];
    LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
    CFURLRef urlRef = (__bridge CFURLRef)url;

    if (loginItems) {
        NSArray  *loginItemsArray = (NSArray *)CFBridgingRelease(LSSharedFileListCopySnapshot(loginItems, &seedValue));
        for(int i = 0 ; i< [loginItemsArray count]; i++) {
            LSSharedFileListItemRef itemRef = (__bridge LSSharedFileListItemRef)([loginItemsArray objectAtIndex:i]);
            if (LSSharedFileListItemResolve(itemRef, 0, &urlRef, NULL) == noErr) {
                NSString *urlPath = [url path];
                if ([urlPath compare:appPath] == NSOrderedSame){
                    LSSharedFileListItemRemove(loginItems,itemRef);
                }
            }
        }
    }
}

#pragma mark NSUserNotificationCenterDelegate #pragma mark -
-(void) nativeNotificationFor:(NSString*)vpn_name new:(bool)state
{
    NSUserNotificationCenter* nc = [NSUserNotificationCenter defaultUserNotificationCenter];
    if(nc) {
        NSUserNotification *notification = [[NSUserNotification alloc] init];
        notification.title = vpn_name;
        notification.informativeText = [NSString stringWithFormat:@"%@ is now %@", vpn_name, state ? @"on" : @"off"];
        notification.soundName = NSUserNotificationDefaultSoundName;
        [nc deliverNotification:notification];
    }
}

- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification
{
    return YES;
}

@end


text:
<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

/**
 * Google Analytics Integration
 *
 * Allows tracking code to be inserted into store pages.
 *
 * @class   WC_Google_Analytics
 * @extends WC_Integration
 */
class WC_Google_Analytics extends WC_Integration {

	/**
	 * Init and hook in the integration.
	 *
	 * @return void
	 */
	public function __construct() {
		$this->id                    = 'google_analytics';
		$this->method_title          = __( 'Google Analytics', 'woocommerce-google-analytics-integration' );
		$this->method_description    = __( 'Google Analytics is a free service offered by Google that generates detailed statistics about the visitors to a website.', 'woocommerce-google-analytics-integration' );
		$this->dismissed_info_banner = get_option( 'woocommerce_dismissed_info_banner' );

		// Load the settings
		$this->init_form_fields();
		$this->init_settings();
		$constructor = $this->init_options();

		// Contains snippets/JS tracking code
		include_once( 'class-wc-google-analytics-js.php' );
		WC_Google_Analytics_JS::get_instance( $constructor );

		// Display an info banner on how to configure WooCommerce
		if ( is_admin() ) {
			include_once( 'class-wc-google-analytics-info-banner.php' );
			WC_Google_Analytics_Info_Banner::get_instance( $this->dismissed_info_banner, $this->ga_id );
		}

		// Admin Options
		add_filter( 'woocommerce_tracker_data', array( $this, 'track_options' ) );
		add_action( 'woocommerce_update_options_integration_google_analytics', array( $this, 'process_admin_options') );
		add_action( 'woocommerce_update_options_integration_google_analytics', array( $this, 'show_options_info') );
		add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_assets') );

		// Tracking code
		add_action( 'wp_head', array( $this, 'tracking_code_display' ), 999999 );

		// Event tracking code
		add_action( 'woocommerce_after_add_to_cart_button', array( $this, 'add_to_cart' ) );
		add_action( 'wp_footer', array( $this, 'loop_add_to_cart' ) );
		add_action( 'woocommerce_after_cart', array( $this, 'remove_from_cart' ) );
		add_action( 'woocommerce_after_mini_cart', array( $this, 'remove_from_cart' ) );
		add_filter( 'woocommerce_cart_item_remove_link', array( $this, 'remove_from_cart_attributes' ), 10, 2 );
		add_action( 'woocommerce_after_shop_loop_item', array( $this, 'listing_impression' ) );
		add_action( 'woocommerce_after_shop_loop_item', array( $this, 'listing_click' ) );
		add_action( 'woocommerce_after_single_product', array( $this, 'product_detail' ) );
		add_action( 'woocommerce_after_checkout_form', array( $this, 'checkout_process' ) );

		// utm_nooverride parameter for Google AdWords
		add_filter( 'woocommerce_get_return_url', array( $this, 'utm_nooverride' ) );
	}

	/**
	 * Loads all of our options for this plugin
	 * @return array An array of options that can be passed to other classes
	 */
	public function init_options() {
		$options = array(
			'ga_id',
			'ga_set_domain_name',
			'ga_standard_tracking_enabled',
			'ga_support_display_advertising',
			'ga_support_enhanced_link_attribution',
			'ga_use_universal_analytics',
			'ga_anonymize_enabled',
			'ga_ecommerce_tracking_enabled',
			'ga_enhanced_ecommerce_tracking_enabled',
			'ga_enhanced_remove_from_cart_enabled',
			'ga_enhanced_product_impression_enabled',
			'ga_enhanced_product_click_enabled',
			'ga_enhanced_checkout_process_enabled',
			'ga_enhanced_product_detail_view_enabled',
			'ga_event_tracking_enabled'
		);

		$constructor = array();
		foreach ( $options as $option ) {
			$constructor[ $option ] = $this->$option = $this->get_option( $option );
		}

		return $constructor;
	}

	/**
	 * Tells WooCommerce which settings to display under the "integration" tab
	 */
	public function init_form_fields() {
		$this->form_fields = array(
			'ga_id' => array(
				'title'       => __( 'Google Analytics ID', 'woocommerce-google-analytics-integration' ),
				'description' => __( 'Log into your Google Analytics account to find your ID. e.g. UA-XXXXX-X', 'woocommerce-google-analytics-integration' ),
				'type'        => 'text',
				'placeholder' => 'UA-XXXXX-X',
				'default'     => get_option( 'woocommerce_ga_id' ) // Backwards compat
			),
			'ga_set_domain_name' => array(
				'title' 			=> __( 'Set Domain Name', 'woocommerce-google-analytics-integration' ),
				'description' 		=> sprintf( __( '(Optional) Sets the _setDomainName variable. See here for more information.', 'woocommerce-google-analytics-integration' ), 'https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingSite#multipleDomains' ),
				'type' 				=> 'text',
				'default' 			=> ''
			),
			'ga_standard_tracking_enabled' => array(
				'title'         => __( 'Tracking Options', 'woocommerce-google-analytics-integration' ),
				'label'         => __( 'Enable Standard Tracking', 'woocommerce-google-analytics-integration' ),
				'description'   =>  __( 'This tracks session data such as demographics, system, etc. You don\'t need to enable this if you are using a 3rd party Google analytics plugin.', 'woocommerce-google-analytics-integration' ),
				'type'          => 'checkbox',
				'checkboxgroup' => 'start',
				'default'       => get_option( 'woocommerce_ga_standard_tracking_enabled' ) ? get_option( 'woocommerce_ga_standard_tracking_enabled' ) : 'no'  // Backwards compat
			),
			'ga_support_display_advertising' => array(
				'label'         => __( '"Display Advertising" Support', 'woocommerce-google-analytics-integration' ),
				'description'   => sprintf( __( 'Set the Google Analytics code to support Display Advertising. %sRead more about Display Advertising%s.', 'woocommerce-google-analytics-integration' ), '', '' ),
				'type'          => 'checkbox',
				'checkboxgroup' => '',
				'default'       => get_option( 'woocommerce_ga_support_display_advertising' ) ? get_option( 'woocommerce_ga_support_display_advertising' ) : 'no'  // Backwards compat
			),
			'ga_support_enhanced_link_attribution' => array(
				'label'         => __( 'Use Enhanced Link Attribution', 'woocommerce-google-analytics-integration' ),
				'description'   => sprintf( __( 'Set the Google Analytics code to support Enhanced Link Attribution. %sRead more about Enhanced Link Attribution%s.', 'woocommerce-google-analytics-integration' ), '', '' ),
				'type'          => 'checkbox',
				'checkboxgroup' => '',
				'default'       => get_option( 'woocommerce_ga_support_enhanced_link_attribution' ) ? get_option( 'woocommerce_ga_support_enhanced_link_attribution' ) : 'no'  // Backwards compat
			),
			'ga_use_universal_analytics' => array(
				'label'         => __( 'Enable Universal Analytics', 'woocommerce-google-analytics-integration' ),
				'description'   => sprintf( __( 'Uses Universal Analytics instead of Classic Google Analytics. If you have not previously used Google Analytics on this site, check this box. Otherwise, %sfollow step 1 of the Universal Analytics upgrade guide.%s Enabling this setting will take care of step 2. %sRead more about Universal Analytics%s. Universal Analytics must be enabled to enable enhanced eCommerce.', 'woocommerce-google-analytics-integration' ), '', '', '', '' ),
				'type'          => 'checkbox',
				'checkboxgroup' => '',
				'default'       => get_option( 'woocommerce_ga_use_universal_analytics' ) ? get_option( 'woocommerce_ga_use_universal_analytics' ) : 'no'  // Backwards compat
			),
			'ga_anonymize_enabled' => array(
				'label'         => __( 'Anonymize IP addresses.', 'woocommerce-google-analytics-integration' ),
				'description'   => sprintf( __( 'Enabling this option is mandatory in certain countries due to national privacy laws. %sRead more about IP Anonymization%s.', 'woocommerce-google-analytics-integration' ), '', '' ),
				'type'          => 'checkbox',
				'checkboxgroup' => '',
				'default'       => 'yes'
			),
			'ga_ecommerce_tracking_enabled' => array(
				'label' 			=> __( 'Purchase Transactions', 'woocommerce-google-analytics-integration' ),
				'description' 			=> __( 'This requires a payment gateway that redirects to the thank you/order received page after payment. Orders paid with gateways which do not do this will not be tracked.', 'woocommerce-google-analytics-integration' ),
				'type' 				=> 'checkbox',
				'checkboxgroup'		=> 'start',
				'default' 			=> get_option( 'woocommerce_ga_ecommerce_tracking_enabled' ) ? get_option( 'woocommerce_ga_ecommerce_tracking_enabled' ) : 'yes'  // Backwards compat
			),
			'ga_event_tracking_enabled' => array(
				'label' 			=> __( 'Add to Cart Events', 'woocommerce-google-analytics-integration' ),
				'type' 				=> 'checkbox',
				'checkboxgroup'		=> '',
				'default' 			=> 'yes'
			),

			'ga_enhanced_ecommerce_tracking_enabled' => array(
				'title'         => __( 'Enhanced eCommerce', 'woocommerce-google-analytics-integration' ),
				'label'         => __( 'Enable Enhanced eCommerce ', 'woocommerce-google-analytics-integration' ),
				'description'   => sprintf( __( 'Enhanced eCommerce allows you to measure more user interactions with your store, including: product impressions, product detail views, starting the checkout process, adding cart items, and removing cart items. Universal Analytics must be enabled for Enhanced eCommerce to work. Before enabling this setting, turn on Enhanced eCommerce in your Google Analytics dashboard. See here for more information.', 'woocommerce-google-analytics-integration' ), 'https://support.google.com/analytics/answer/6032539?hl=en' ),
				'type'          => 'checkbox',
				'checkboxgroup' => '',
				'default'       => 'no'
			),

			// Enhanced eCommerce Settings

			'ga_enhanced_remove_from_cart_enabled' => array(
				'label' 			=> __( 'Remove from Cart Events', 'woocommerce-google-analytics-integration' ),
				'type' 				=> 'checkbox',
				'checkboxgroup'		=> '',
				'default' 			=> 'yes',
				'class'             => 'enhanced-setting'
			),

			'ga_enhanced_product_impression_enabled' => array(
				'label' 			=> __( 'Product Impressions from Listing Pages', 'woocommerce-google-analytics-integration' ),
				'type' 				=> 'checkbox',
				'checkboxgroup'		=> '',
				'default' 			=> 'yes',
				'class'             => 'enhanced-setting'
			),

			'ga_enhanced_product_click_enabled' => array(
				'label' 			=> __( 'Product Clicks from Listing Pages', 'woocommerce-google-analytics-integration' ),
				'type' 				=> 'checkbox',
				'checkboxgroup'		=> '',
				'default' 			=> 'yes',
				'class'             => 'enhanced-setting'
			),

			'ga_enhanced_product_detail_view_enabled' => array(
				'label' 			=> __( 'Product Detail Views', 'woocommerce-google-analytics-integration' ),
				'type' 				=> 'checkbox',
				'checkboxgroup'		=> '',
				'default' 			=> 'yes',
				'class'             => 'enhanced-setting'
			),

			'ga_enhanced_checkout_process_enabled' => array(
				'label' 			=> __( 'Checkout Process Initiated', 'woocommerce-google-analytics-integration' ),
				'type' 				=> 'checkbox',
				'checkboxgroup'		=> '',
				'default' 			=> 'yes',
				'class'             => 'enhanced-setting'
			),
		);
	}

	/**
	 * Shows some additional help text after saving the Google Analytics settings
	 */
	function show_options_info() {
		$this->method_description .= "

" . __( 'Please allow Google Analytics 24 hours to start displaying results.', 'woocommerce-google-analytics-integration' ) . "

";

		if ( isset( $_REQUEST['woocommerce_google_analytics_ga_ecommerce_tracking_enabled'] ) && true === (bool) $_REQUEST['woocommerce_google_analytics_ga_ecommerce_tracking_enabled'] ) {
			$this->method_description .= "

" . __( 'Please note, for transaction tracking to work properly, you will need to use a payment gateway that redirects the customer back to a WooCommerce order received/thank you page.', 'woocommerce-google-analytics-integration' ) . "
";
		}
	}

	/**
	 * Hooks into woocommerce_tracker_data and tracks some of the analytic settings (just enabled|disabled status)
	 * only if you have opted into WooCommerce tracking
	 * http://www.woothemes.com/woocommerce/usage-tracking/
	 */
	function track_options( $data ) {
		$data['wc-google-analytics'] = array(
			'standard_tracking_enabled'   		=> $this->ga_standard_tracking_enabled,
			'support_display_advertising' 		=> $this->ga_support_display_advertising,
			'support_enhanced_link_attribution' => $this->ga_support_enhanced_link_attribution,
			'use_universal_analytics'     		=> $this->ga_use_universal_analytics,
			'anonymize_enabled'           		=> $this->ga_anonymize_enabled,
			'ecommerce_tracking_enabled'  		=> $this->ga_ecommerce_tracking_enabled,
			'event_tracking_enabled'      		=> $this->ga_event_tracking_enabled
		);
		return $data;
	}

	/**
	 *
	 */
	function load_admin_assets() {
		$screen = get_current_screen();
		if ( 'woocommerce_page_wc-settings' !== $screen->id ) {
			return;
		}

		if ( empty( $_GET['tab'] ) ) {
			return;
		}

		if ( 'integration' !== $_GET['tab'] ) {
			return;
		}

		wp_enqueue_script( 'wc-google-analytics-admin-enhanced-settings', plugins_url(  '/assets/js/admin-enhanced-settings.js', dirname(__FILE__) ) );
	}

	/**
	 * Display the tracking codes
	 * Acts as a controller to figure out which code to display
	 */
	public function tracking_code_display() {
		global $wp;
		$display_ecommerce_tracking = false;

		if ( is_admin() || current_user_can( 'manage_options' ) || ! $this->ga_id ) {
			return;
		}

		// Check if is order received page and stop when the products and not tracked
		if ( is_order_received_page() && 'yes' === $this->ga_ecommerce_tracking_enabled ) {
			$order_id = isset( $wp->query_vars['order-received'] ) ? $wp->query_vars['order-received'] : 0;
			if ( 0 < $order_id && 1 != get_post_meta( $order_id, '_ga_tracked', true ) ) {
				$display_ecommerce_tracking = true;
				echo $this->get_ecommerce_tracking_code( $order_id );
			}
		}

		if ( is_woocommerce() || is_cart() || ( is_checkout() && ! $display_ecommerce_tracking ) ) {
			$display_ecommerce_tracking = true;
			echo $this->get_standard_tracking_code();
		}

		if ( ! $display_ecommerce_tracking && 'yes' === $this->ga_standard_tracking_enabled ) {
			echo $this->get_standard_tracking_code();
		}
	}

	/**
	 * Standard Google Analytics tracking
	 */
	protected function get_standard_tracking_code() {
		return "
		" . WC_Google_Analytics_JS::get_instance()->header() . "

		";
	}

	/**
	 * eCommerce tracking
	 *
	 * @param int $order_id
	 */
	protected function get_ecommerce_tracking_code( $order_id ) {
		// Get the order and output tracking code
		$order = new WC_Order( $order_id );

		$code = WC_Google_Analytics_JS::get_instance()->load_analytics( $order );
		$code .= WC_Google_Analytics_JS::get_instance()->add_transaction( $order );

		// Mark the order as tracked
		update_post_meta( $order_id, '_ga_tracked', 1 );

		return "

		" . WC_Google_Analytics_JS::get_instance()->header() . "

		";
	}

	/**
	 * Check if tracking is disabled
	 *
	 * @param string $type The setting to check
	 *
	 * @return bool True if tracking for a certain setting is disabled
	 */
	private function disable_tracking( $type ) {
		if ( is_admin() || current_user_can( 'manage_options' ) || ( ! $this->ga_id ) || 'no' === $type ) {
			return true;
		}
	}

	/**
	 * Google Analytics event tracking for single product add to cart
	 *
	 * @return void
	 */
	public function add_to_cart() {
		if ( $this->disable_tracking( $this->ga_event_tracking_enabled ) ) {
			return;
		}
		if ( ! is_single() ) {
			return;
		}

		global $product;

		// Add single quotes to allow jQuery to be substituted into _trackEvent parameters
		$parameters = array();
		$parameters['category'] = "'" . __( 'Products', 'woocommerce-google-analytics-integration' ) . "'";
		$parameters['action']   = "'" . __( 'Add to Cart', 'woocommerce-google-analytics-integration' ) . "'";
		$parameters['label']    = "'" . esc_js( $product->get_sku() ? __( 'ID:', 'woocommerce-google-analytics-integration' ) . ' ' . $product->get_sku() : "#" . $product->get_id() ) . "'";

		if ( ! $this->disable_tracking( $this->ga_enhanced_ecommerce_tracking_enabled ) ) {
			$code = "" . WC_Google_Analytics_JS::get_instance()->tracker_var() . "( 'ec:addProduct', {";
			$code .= "'id': '" . esc_js( $product->get_sku() ? $product->get_sku() : ( '#' . $product->get_id() ) ) . "',";
			$code .= "'name': '" . esc_js( $product->get_title() ) . "',";
			$code .= "'quantity': $( 'input.qty' ).val() ? $( 'input.qty' ).val() : '1'";
			$code .= "} );";
			$parameters['enhanced'] = $code;
		}

		WC_Google_Analytics_JS::get_instance()->event_tracking_code( $parameters, '.single_add_to_cart_button' );
	}

	/**
	 * Enhanced Analytics event tracking for removing a product from the cart
	 */
	public function remove_from_cart() {
		if ( $this->disable_tracking( $this->ga_use_universal_analytics ) ) {
			return;
		}

		if ( $this->disable_tracking( $this->ga_enhanced_ecommerce_tracking_enabled ) ) {
			return;
		}

		if ( $this->disable_tracking( $this->ga_enhanced_remove_from_cart_enabled ) ) {
			return;
		}

		WC_Google_Analytics_JS::get_instance()->remove_from_cart();
	}

	/**
	 * Adds the product ID and SKU to the remove product link if not present
	 */
	public function remove_from_cart_attributes( $url, $key ) {
		if ( strpos( $url,'data-product_id' ) !== false ) {
			return $url;
		}

		$item = WC()->cart->get_cart_item( $key );
		$product = $item['data'];
		$url = str_replace( 'href=', 'data-product_id="' . esc_attr( $product->get_id() ) . '" data-product_sku="' . esc_attr( $product->get_sku() )  . '" href=', $url );
		return $url;
	}

	/**
	 * Google Analytics event tracking for loop add to cart
	 *
	 * @return void
	 */
	public function loop_add_to_cart() {
		if ( $this->disable_tracking( $this->ga_event_tracking_enabled ) ) {
			return;
		}

		// Add single quotes to allow jQuery to be substituted into _trackEvent parameters
		$parameters = array();
		$parameters['category'] = "'" . __( 'Products', 'woocommerce-google-analytics-integration' ) . "'";
		$parameters['action']   = "'" . __( 'Add to Cart', 'woocommerce-google-analytics-integration' ) . "'";
		$parameters['label']    = "($(this).data('product_sku')) ? ($(this).data('product_sku')) : ('#' + $(this).data('product_id'))"; // Product SKU or ID

		if ( ! $this->disable_tracking( $this->ga_enhanced_ecommerce_tracking_enabled ) ) {
			$code = "" . WC_Google_Analytics_JS::get_instance()->tracker_var() . "( 'ec:addProduct', {";
			$code .= "'id': ($(this).data('product_sku')) ? ($(this).data('product_sku')) : ('#' + $(this).data('product_id')),";
			$code .= "'quantity': $(this).data('quantity')";
			$code .= "} );";
			$parameters['enhanced'] = $code;
		}

		WC_Google_Analytics_JS::get_instance()->event_tracking_code( $parameters, '.add_to_cart_button:not(.product_type_variable, .product_type_grouped)' );
	}

	/**
	 * Measures a listing impression (from search results)
	 */
	public function listing_impression() {
		if ( $this->disable_tracking( $this->ga_use_universal_analytics ) ) {
			return;
		}

		if ( $this->disable_tracking( $this->ga_enhanced_ecommerce_tracking_enabled ) ) {
			return;
		}

		if ( $this->disable_tracking( $this->ga_enhanced_product_impression_enabled ) ) {
			return;
		}

		global $product, $woocommerce_loop;
		WC_Google_Analytics_JS::get_instance()->listing_impression( $product, $woocommerce_loop['loop'] );
	}

	/**
	 * Measure a product click from a listing page
	 */
	public function listing_click() {
		if ( $this->disable_tracking( $this->ga_use_universal_analytics ) ) {
			return;
		}

		if ( $this->disable_tracking( $this->ga_enhanced_ecommerce_tracking_enabled ) ) {
			return;
		}

		if ( $this->disable_tracking( $this->ga_enhanced_product_click_enabled ) ) {
			return;
		}

		global $product, $woocommerce_loop;
		WC_Google_Analytics_JS::get_instance()->listing_click( $product, $woocommerce_loop['loop'] );
	}

	/**
	 * Measure a product detail view
	 */
	public function product_detail() {
		if ( $this->disable_tracking( $this->ga_use_universal_analytics ) ) {
			return;
		}

		if ( $this->disable_tracking( $this->ga_enhanced_ecommerce_tracking_enabled ) ) {
			return;
		}

		if ( $this->disable_tracking( $this->ga_enhanced_product_detail_view_enabled ) ) {
			return;
		}

		global $product;
		WC_Google_Analytics_JS::get_instance()->product_detail( $product );
	}

	/**
	 * Tracks when the checkout form is loaded
	 */
	public function checkout_process( $checkout ) {
		if ( $this->disable_tracking( $this->ga_use_universal_analytics ) ) {
			return;
		}

		if ( $this->disable_tracking( $this->ga_enhanced_ecommerce_tracking_enabled ) ) {
			return;
		}

		if ( $this->disable_tracking( $this->ga_enhanced_checkout_process_enabled ) ) {
			return;
		}

		WC_Google_Analytics_JS::get_instance()->checkout_process( WC()->cart->get_cart() );
	}

	/**
	 * Add the utm_nooverride parameter to any return urls. This makes sure Google Adwords doesn't mistake the offsite gateway as the referrer.
	 *
	 * @param  string $return_url WooCommerce Return URL
	 *
	 * @return string URL
	 */
	public function utm_nooverride( $return_url ) {
		// We don't know if the URL already has the parameter so we should remove it just in case
		$return_url = remove_query_arg( 'utm_nooverride', $return_url );

		// Now add the utm_nooverride query arg to the URL
		$return_url = add_query_arg( 'utm_nooverride', '1', $return_url );

		return $return_url;
	}
}


text:
package com.intellij.tasks.redmine;

import com.intellij.tasks.Comment;
import com.intellij.tasks.Task;
import com.intellij.tasks.TaskRepository;
import com.intellij.tasks.TaskType;
import com.intellij.tasks.redmine.model.RedmineIssue;
import com.intellij.tasks.redmine.model.RedmineProject;
import icons.TasksCoreIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Date;

/**
 * @author Mikhail Golubev
 */
public class RedmineTask extends Task {
  private final RedmineIssue myIssue;
  private final RedmineRepository myRepository;
  /**
   * Only human-readable project name is sent with issue. Because project's identifier is more suited
   * for commit messages, it has to be extracted from cached projects. The same approach is used in
   * {@link com.intellij.tasks.gitlab.GitlabRepository}.
   */
  private final RedmineProject myProject;

  public RedmineTask(@NotNull RedmineRepository repository, @NotNull RedmineIssue issue) {
    myIssue = issue;
    myRepository = repository;
    RedmineProject project = null;
    for (RedmineProject p : repository.getProjects()) {
      if (issue.getProject() != null && p.getId() == issue.getProject().getId()) {
        project = p;
        break;
      }
    }
    myProject = project;
  }

  @NotNull
  @Override
  public String getId() {
    return String.valueOf(myIssue.getId());
  }

  @NotNull
  @Override
  public String getSummary() {
    return myIssue.getSubject();
  }

  @Nullable
  @Override
  public String getDescription() {
    return myIssue.getDescription();
  }

  @Override
  public Comment @NotNull [] getComments() {
    return Comment.EMPTY_ARRAY;
  }

  @NotNull
  @Override
  public Icon getIcon() {
    return TasksCoreIcons.Redmine;
  }

  @NotNull
  @Override
  public TaskType getType() {
    // TODO: precise mapping
    return TaskType.BUG;
  }

  @Nullable
  @Override
  public Date getUpdated() {
    return myIssue.getUpdated();
  }

  @Nullable
  @Override
  public Date getCreated() {
    return myIssue.getCreated();
  }

  @Override
  public boolean isClosed() {
    String name = myIssue.getStatus().getName();
    return name.equals("Closed") || name.equals("Resolved");
  }

  @Override
  public boolean isIssue() {
    return true;
  }

  @Nullable
  @Override
  public String getIssueUrl() {
    return myRepository.getRestApiUrl("issues", getId());
  }

  @NotNull
  @Override
  public String getNumber() {
    return getId();
  }

  @Nullable
  @Override
  public String getProject() {
    return myProject == null ? null : myProject.getIdentifier();
  }

  @Nullable
  @Override
  public TaskRepository getRepository() {
    return myRepository;
  }
}


text:
<?php

namespace Eloquent\Schemer\Constraint;

interface SchemaInterface extends ConstraintInterface
{
}


text:
<?php

namespace retailcrm\service;

class OrderManager {
    protected $api;
    protected $customer_manager;
    protected $order_converter;
    protected $corporate_customer_service;
    protected $settings_manager;

    /**
     * OrderManager constructor.
     * @param \RetailcrmProxy $proxy
     * @param CustomerManager $customer_manager
     * @param RetailcrmOrderConverter $order_converter
     * @param CorporateCustomer $corporate_customer_service
     * @param SettingsManager $settings_manager
     */
    public function __construct(
        \RetailcrmProxy $proxy,
        CustomerManager $customer_manager,
        RetailcrmOrderConverter $order_converter,
        CorporateCustomer $corporate_customer_service,
        SettingsManager $settings_manager
    ) {
        $this->api = $proxy;
        $this->customer_manager = $customer_manager;
        $this->order_converter = $order_converter;
        $this->corporate_customer_service = $corporate_customer_service;
        $this->settings_manager = $settings_manager;
    }

    /**
     * @param array $order_data
     * @param array $order_products
     * @param array $order_totals
     */
    public function createOrder($order_data, $order_products, $order_totals) {
        $order = $this->prepareOrder($order_data, $order_products, $order_totals);

        if (!isset($order['customer'])
            || (isset($order['customer']['externalId'])
                && !$this->checkExistCustomer($order['customer']['externalId']))
        ) {
            $customer = $this->customer_manager->getCustomerForOrder($order_data);
            if (!empty($customer)) {
                $order['customer'] = $customer;
            }
        }

        $order['contragent']['contragentType'] = 'individual';
        $this->handleCorporate($order, $order_data);

        return $this->api->ordersCreate($order);
    }

    /**
     * @param array $order_data
     * @param array $order_products
     * @param array $order_totals
     */
    public function editOrder($order_data, $order_products, $order_totals) {
        $order = $this->prepareOrder($order_data, $order_products, $order_totals);

        if (!isset($order['customer'])) {
            $customer = $this->customer_manager->getCustomerForOrder($order_data);
            if (!empty($customer)) {
                $order['customer'] = array(
                    'id' => $customer['id']
                );
            }
        }

        $order['contragent']['contragentType'] = 'individual';
        $this->handleCorporate($order, $order_data);

        $payments = $order['payments'];
        unset($order['payments']);

        $order_payment = $payments[0];
        $order = \retailcrm\Utils::filterRecursive($order);
        $response = $this->api->ordersEdit($order);

        if ($response && $response->isSuccessful()) {
            $this->updatePayment($order_payment, $order['externalId']);
        }
    }

    /**
     * @param array $orders
     */
    public function uploadOrders($orders) {
        $this->api->ordersUpload($orders);
    }

    /**
     * @param array $order_data array of order fields
     * @param array $order_products array of order products
     * @param array $order_totals array of order totals
     * @return array
     */
    public function prepareOrder($order_data, $order_products, $order_totals) {
        return $this->order_converter->initOrderData($order_data, $order_products, $order_totals)
            ->setOrderData()
            ->setDelivery()
            ->setItems()
            ->setPayment(false)
            ->setDiscount()
            ->setCustomFields()
            ->getOrder();
    }

    private function handleCorporate(&$order, $order_data) {
        if ($this->isCorporateOrder($order_data)
            && !empty($order['customer'])
            && $this->settings_manager->getSetting('corporate_enabled') == 1
        ) {
            $order_data['payment_company'] = htmlspecialchars_decode($order_data['payment_company']);
            $corp_customer_id = $this->corporate_customer_service->createCorporateCustomer($order_data, $order['customer']);

            if ($corp_customer_id) {
                $order = $this->order_converter->setCorporateCustomer($order, $corp_customer_id);
                $companiesResponse = $this->api->customersCorporateCompanies($corp_customer_id, array(), 1, 100, 'id');
                if ($companiesResponse && $companiesResponse->isSuccessful() && !empty($companiesResponse['companies'])) {
                    foreach ($companiesResponse['companies'] as $company) {
                        if ($company['name'] === $order_data['payment_company']) {
                            $order['company'] = array(
                                'id' => $company['id']
                            );
                        }
                    }
                }
            }
        }
    }

    /**
     * @param array $order_data array of order fields
     * @return bool
     */
    private function isCorporateOrder($order_data) {
        return !empty($order_data['payment_company']);
    }

    /**
     * @param array $order_payment
     * @param int $orderId
     */
    private function updatePayment($order_payment, $orderId) {
        $response_order = $this->api->ordersGet($orderId);

        if ($response_order && $response_order->isSuccessful()) {
            $order_info = $response_order['order'];
        }

        foreach ($order_info['payments'] as $payment_data) {
            if (isset($payment_data['externalId'])) {
                $payment = $payment_data;
            }
        }

        if (isset($payment) && $payment['type'] != $order_payment['type']) {
            $response = $this->api->ordersPaymentDelete($payment['id']);

            if ($response && $response->isSuccessful()) {
                $this->api->ordersPaymentCreate($order_payment);
            }
        } elseif (isset($payment) && $payment['type'] == $order_payment['type']) {
            $this->api->ordersPaymentEdit($order_payment);
        }
    }

    /**
     * @param string $customerExternalId Customer's external id
     *
     * @return bool
     */
    private function checkExistCustomer($customerExternalId) {
        $result = $this->api->customersGet($customerExternalId);

        return $result && $result->isSuccessful() && $result->offsetExists('customer');
    }
}