text:
.. _hardware-control:

.. code-block:: python

    from opentrons import robot
    robot.reset()

###################
Advanced Control
###################

.. note::

    The below features are designed for advanced users who wish to use the Opentrons API in their own Python environment (ie Jupyter). This page is not relevant for users only using the Opentrons App, because the features described below will not be accessible.

The robot module can be thought of as the parent for all aspects of the Opentrons API. All containers, instruments, and protocol commands are added to and controlled by robot.

.. code-block:: python

    '''
    Examples in this section require the following
    '''
    from opentrons import robot, labware, instruments

    plate = labware.load('96-flat', 'B1', 'my-plate')
    tiprack = labware.load('opentrons_96_tiprack_300ul', 'A1', 'my-rack')

    pipette = instruments.P300_Single(mount='left', tip_racks=[tiprack])

User-Specified Pause
====================

This will pause your protocol at a specific step. You can resume by pressing 'resume' in your OT App.

.. code-block:: python

    robot.pause()

Head Speed
==========

The speed of the robot's motors can be set using ``robot.head_speed()``. The units are all millimeters-per-second (mm/sec). The ``x``, ``y``, ``z``, ``a``, ``b``, ``c`` parameters set the maximum speed of the corresponding axis on Smoothie.

'x': lateral motion, 'y': front to back motion, 'z': vertical motion of the left mount, 'a': vertical motion of the right mount, 'b': plunger motor for the left pipette, 'c': plunger motor for the right pipette.

The ``combined_speed`` parameter sets the speed across all axes to either the specified value or the axis max, whichever is lower. Defaults are specified by ``DEFAULT_MAX_SPEEDS`` in `robot_configs.py`__.

__ https://github.com/Opentrons/opentrons/blob/edge/api/src/opentrons/config/robot_configs.py

.. code-block:: python

    max_speed_per_axis = {
        'x': 600, 'y': 400, 'z': 125, 'a': 125, 'b': 50, 'c': 50}
    robot.head_speed(
        combined_speed=max(max_speed_per_axis.values()),
        **max_speed_per_axis)

Homing
======

You can `home` the robot by calling ``home()``. You can also specify axes. The robot will home immdediately when this call is made.

.. code-block:: python

    robot.home()           # home the robot on all axis
    robot.home('z')        # home the Z axis only

Commands
========

When commands are called on a pipette, they are recorded on the ``robot`` in the order they are called. You can see all past executed commands by calling ``robot.commands()``, which returns a `Python list`__.

__ https://docs.python.org/3.5/tutorial/datastructures.html#more-on-lists

.. code-block:: python

    pipette.pick_up_tip(tiprack.wells('A1'))
    pipette.drop_tip(tiprack.wells('A1'))

    for c in robot.commands():
        print(c)

will print out...

.. code-block:: python

    Picking up tip <Well A1>
    Dropping tip <Well A1>

Clear Commands
==============

We can erase the robot command history by calling ``robot.clear_commands()``. Any previously created instruments and containers will still be inside robot, but the commands history is erased.

.. code-block:: python

    robot.clear_commands()
    pipette.pick_up_tip(tiprack['A1'])
    print('There is', len(robot.commands()), 'command')

    robot.clear_commands()
    print('There are now', len(robot.commands()), 'commands')

will print out...

.. code-block:: python

    There is 1 command
    There are now 0 commands

Comment
=======

You can add a custom message to the list of command descriptions you see when running ``robot.commands()``. This command is ``robot.comment()``, and it allows you to print out any information you want at the point in your protocol

.. code-block:: python

    robot.clear_commands()

    pipette.pick_up_tip(tiprack['A1'])
    robot.comment("Hello, just picked up tip A1")

    pipette.pick_up_tip(tiprack['A1'])
    robot.comment("Goodbye, just dropped tip A1")

    for c in robot.commands():
        print(c)

will print out...

.. code-block:: python

    Picking up tip <Well A1>
    Hello, just picked up tip A1
    Picking up tip <Well A1>
    Goodbye, just dropped tip A1

Get Containers
==============

When containers are loaded, they are automatically added to the ``robot``. You can see all currently held containers by calling ``robot.get_containers()``, which returns a `Python list`__.

__ https://docs.python.org/3.5/tutorial/datastructures.html#more-on-lists

.. code-block:: python

    for container in robot.get_containers():
        print(container.get_name(), container.get_type())

will print out...

.. code-block:: python

    my-rack opentrons_96_tiprack_300ul
    my-plate 96-flat

Reset
=====

Calling ``robot.reset()`` will remove everything from the robot. Any previously added containers, pipettes, or commands will be erased.

.. code-block:: python

    robot.reset()
    print(robot.get_containers())
    print(robot.commands())

will print out...

.. code-block:: python

    []
    []
    []


text:
{% extends 'home/home.html' %}
{% load static %}

{% block css %}
  <link rel="stylesheet" href="{% static 'questions/css/countdown.css' %}">
{% endblock %}

{% block content %}

Your have answered all the questions, please check back later.

Redirecting to My Profile in

{% endblock %}

{% block script %}
  {{ block.super }}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System.Collections;

namespace SpriteStudioForUnity {
	[RequireComponent(typeof(Animator))]
	public class AnimationEventListener : MonoBehaviour {
		[HideInInspector]
		public SSController controller;

		void Start ()
		{
		}

		void IntegerEvent (int val)
		{
			if (controller.OnIntegerEvent != null) {
				controller.OnIntegerEvent (val);
			}
		}

		void RectEvent (string val)
		{
			if (controller.OnRectEvent != null) {
				string[] split = val.Split (' ');
				float x = float.Parse (split [0]);
				float y = float.Parse (split [1]);
				float z = float.Parse (split [2]);
				Vector3 v = new Vector3 (x, y, z);
				controller.OnRectEvent (v);
			}
		}

		void PointEvent (string val)
		{
			if (controller.OnPointEvent != null) {
				string[] split = val.Split (' ');
				float x = float.Parse (split [0]);
				float y = float.Parse (split [1]);
				Vector2 v = new Vector2 (x, y);
				controller.OnPointEvent (v);
			}
		}

		void StringEvent (string val)
		{
			if (controller.OnStringEvent != null) {
				controller.OnStringEvent (val);
			}
		}
	}
}


text:
<?php

namespace Jmikola\AutoLogin\Http\Firewall;

use Jmikola\AutoLogin\AutoLoginEvents;
use Jmikola\AutoLogin\Authentication\Token\AutoLoginToken;
use Jmikola\AutoLogin\Event\AlreadyAuthenticatedEvent;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\Firewall\AbstractListener;

class AutoLoginListener extends AbstractListener
{
    /**
     * @var TokenStorageInterface
     */
    private $tokenStorage;

    /**
     * @var AuthenticationManagerInterface
     */
    private $authenticationManager;

    /**
     * @var string
     */
    private $providerKey;

    /**
     * @var string
     */
    private $tokenParam;

    /**
     * @var LoggerInterface|null
     */
    private $logger = null;

    /**
     * @var EventDispatcherInterface|null
     */
    private $dispatcher = null;

    /**
     * @var array
     */
    private $options;

    public function __construct(
        TokenStorageInterface $tokenStorage,
        AuthenticationManagerInterface $authenticationManager,
        string $providerKey,
        string $tokenParam,
        LoggerInterface $logger = null,
        EventDispatcherInterface $dispatcher = null,
        array $options = []
    ) {
        $this->tokenStorage = $tokenStorage;
        $this->authenticationManager = $authenticationManager;
        $this->providerKey = $providerKey;
        $this->tokenParam = $tokenParam;
        $this->logger = $logger;
        $this->dispatcher = $dispatcher;

        $this->options = $options = array_merge([
            'override_already_authenticated' => false,
        ], $options);
    }

    /**
     * {@inheritDoc}
     */
    public function supports(Request $request): ?bool
    {
        return $request->query->has($this->tokenParam) ||
            $request->attributes->has($this->tokenParam) ||
            $request->request->has($this->tokenParam);
    }

    /**
     * {@inheritDoc}
     */
    public function authenticate(RequestEvent $event)
    {
        $request = $event->getRequest();
        $tokenParam = $request->get($this->tokenParam);

        /* If the security context has a token, a user is already authenticated.
         * We will dispatch an event with the token parameter so that a listener
         * may track its usage.
         */
        if (null !== $this->tokenStorage->getToken()) {
            if (null !== $this->dispatcher) {
                $this->dispatcher->dispatch(
                    new AlreadyAuthenticatedEvent($tokenParam),
                    AutoLoginEvents::ALREADY_AUTHENTICATED
                );
            }

            /* By default, ignore the token and return; however, in some cases
             * it may be useful to override the existing token and allow the
             * AutoLogin token to be used to switch users (without requiring
             * the user to first log out).
             */
            if ( ! $this->options['override_already_authenticated']) {
                return;
            }
        }

        try {
            $token = new AutoLoginToken($this->providerKey, $tokenParam);

            /* TODO: This authentication method should be considered the same as
             * remember-me according to AuthenticationTrustResolver. That will
             * entail either refactoring to extend RememberMeToken or adding a
             * service to compose the existing AuthenticationTrustResolver and
             * implement custom logic to respect our own token class.
             */
            if ($authenticatedToken = $this->authenticationManager->authenticate($token)) {
                $this->tokenStorage->setToken($authenticatedToken);

                if (null !== $this->dispatcher) {
                    $this->dispatcher->dispatch(
                        new InteractiveLoginEvent($request, $authenticatedToken),
                        SecurityEvents::INTERACTIVE_LOGIN
                    );
                }
            }
        } catch (AuthenticationException $e) {
            if (null !== $this->logger) {
                $this->logger->warning(
                    'TokenStorage not populated with auto-login token as the '.
                    'AuthenticationManager rejected the auto-login token created '.
                    'by AutoLoginListener: '.$e->getMessage()
                );
            }
        }
    }
}


text:
resolve:
	pip install -r requirements/dev.txt --upgrade

check-style:
	flake8 --max-complexity 12 . || exit 0
	pylint --rcfile .pylintrc *.py **/*.py **/**/*.py **/**/**/*.py || exit 0

test-clean:
	coverage erase

test-unit:
	coverage run --branch --source=. `which nosetests` -v --exe -a 'unit'

test-intg:
	coverage run --branch --source=. `which nosetests` -v --exe -a 'intg'

test: | test-clean test-unit test-intg

report-coverage:
	coverage report --omit=tests/*,migrations/*

.DEFAULT_GOAL := resolve

.PHONY: resolve, check-style, report-coverage, test-clean, test-unit, test-intg, test


text:
<?php

namespace Haven\Bundle\PortfolioBundle\Lib\Handler;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class ProjectPersistenceHandler {

    protected $em;
    protected $security_context;

    public function __construct(ProjectReadHandler $read_handler, EntityManager $em, SecurityContext $security_context) {
        $this->em = $em;
        $this->security_context = $security_context;
        $this->read_handler = $read_handler;
    }

    public function batchSave($entities) {
        if ($this->security_context->isGranted('ROLE_Admin')) {
            foreach ($entities as $entity) {
                $this->em->persist($entity);
            }
            $this->em->flush();

            return true;
        }

        throw new AccessDeniedException("you.dont.have.right.for.this.action");
    }

    public function save($entity) {
        if ($this->security_context->isGranted('ROLE_Admin')) {
            $this->em->persist($entity);
            $this->em->flush();

            return true;
        }

        throw new AccessDeniedException("you.dont.have.right.for.this.action");
    }

    public function delete($id) {
        if ($this->security_context->isGranted('ROLE_Admin')) {
            $entity = $this->read_handler->get($id);
            $this->em->remove($entity);
            $this->em->flush();

            return true;
        }

        throw new AccessDeniedException("you.dont.have.right.for.this.action");
    }

}

?>


text:
const int ERROR_CODE = 0;
const int CREATE_DO_PORT = 1; // "1:<int port number>"
const int CREATE_DI_PORT = 2; // "2:<int port number>"
const int CREATE_AO_PORT = 3; // "3:<int port number>"
//const int CREATE_AI_PORT = 4;
const int DIGITAL_WRITE = 5; // "4:<int port number>:<int value>" (1-HIGH, 0 - LOW)


text:
package de.olafdietsche.android.samples.options_menu;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.util.Log;

public class MainActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_add:
			NewEntryActivity.start(this);
			return true;
		}

		return false;
	}

	private static final String TAG = MainActivity.class.getSimpleName();
}


text:
Ce repository concerne la première révision du convertisseur ADB/USB (0x1).

![Une photo très belle du PCB du convertisseur](http://tibounise.com/img/adbusb/pcb-2560.jpg)

Ce convertisseur, basé sur le firmware [tmk_keyboard](tmk/tmk_keyboard), permet de brancher un clavier ADB en USB.

Le repository contient actuellement un guide pour hacker son convertisseur. Il a été écrit avec [LaTeX](http://www.latex-project.org). Une version PDF compilée est disponible pour ceux qui n'auraient pas envie d'installer un compilateur LaTeX sur leur machine.

Il contient aussi le schéma ainsi que le typon du circuit imprimé. Ces fichiers ont étés conçus à l'aide du logiciel [CadSoft EAGLE](http://www.cadsoft.de/eagle-pcb-design-software).


text:
using System.Web.OData.Builder;
using Microsoft.OData.Edm;

namespace WebStack.QA.Test.OData.LowerCamelCase
{
    public class LowerCamelCaseEdmModel
    {
        public static IEdmModel GetConventionModel()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            EntitySetConfiguration<Employee> employees = builder.EntitySet<Employee>("Employees");
            EntityTypeConfiguration<Employee> employee = employees.EntityType;
            employee.EnumProperty<Gender>(e => e.Sex).Name = "Gender";

            employee.Collection.Function("GetEarliestTwoEmployees").ReturnsCollectionFromEntitySet<Employee>("Employees");

            var functionConfiguration = builder.Function("GetAddress");
            functionConfiguration.Parameter<int>("id");
            functionConfiguration.Returns<Address>();

            var actionConfiguration = builder.Action("SetAddress");
            actionConfiguration.Parameter<int>("id");
            actionConfiguration.Parameter<Address>("address");
            actionConfiguration.ReturnsFromEntitySet(employees);

            var resetDataSource = builder.Action("ResetDataSource");

            builder.Namespace = typeof(Employee).Namespace;
            builder.EnableLowerCamelCase();
            var edmModel = builder.GetEdmModel();
            return edmModel;
        }
    }
}


text:
using ILspect.Syntax.Expressions;
using Mono.Cecil;
using Mono.Cecil.Cil;

namespace ILspect.Syntax.Statements
{
    public class StoreParameterStatement : Statement
    {
        public ParameterReference Parameter { get; }
        public Expression Value { get; }

        public StoreParameterStatement(ParameterReference parameter, Expression value)
            : this(parameter, value, instruction: null) { }

        public StoreParameterStatement(ParameterReference parameter, Expression value, Instruction instruction) : base(instruction)
        {
            Parameter = parameter;
            Value = value;
        }

        public override string ToString()
        {
            return $"{Parameter.Name} = {Value}";
        }
    }
}


text:
This sample demonstrates how to to calculate multi-point routes and driving directions. The sample allows a user to add stops interactively, and also barriers to avoid certain roads and intersections. Users can step through the directions turn-by-turn and see it highlighted on the map.

![](image.png)
![](image2.png)
![](image3.png)
![](image4.png)


text:
import fetch from "node-fetch";
import { IWebhookConfig } from "../entities";
import { DirectEvent } from "./DirectEvent";

export class Outgoing {
  constructor(private readonly config: IWebhookConfig) {
  }

  async execute(event: DirectEvent) {
    const res  = await fetch(this.url, this.options(event));
    return await res.json();
  }

  private get url() {
    return this.config.url;
  }

  private options(event: DirectEvent) {
    return {
      method: this.method,
      headers: this.headers,
      body: JSON.stringify(event)
    };
  }

  private get method() {
    return (this.config.method || "GET").toUpperCase();
  }

  private get headers() {
    return this.config.headers;
  }
}


text:
using UnityEngine;
using System.Collections;

public class HapticClassScript : MonoBehaviour {

	public string HapticMode;
	public int ModeIndex;

	public string TouchableFace;

	public GameObject myHapticCamera;
	public GameObject workSpaceObj;
	public GameObject hapticCursor;

	//SetHapticWorkSpace Values
	public float[] myWorkSpacePosition = new float[3];
	public float[] myWorkSpaceSize = new float[3];

	public float maxPenetration;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}
}


text:
The **jsgenerator** is the third and last step of the compilation process.
It generates the final compiled template as a javascript string, using the syntax tree built previously.

## Input ##
The syntax tree, e.g.:
```
{
    "type": "template",
    "name": "test",
    "args": ["person"],
    "content": [
      {type:"element", name:"div", closed:false, attributes:[
          {name:"title", type:"text", value:"Some text"},
          {name:"id", type:"expression", "category": "objectref", "bound": true, "path": [ "person", "id" ]},
          {name:"class", type:"textblock", content:[
            {type:"expression", "category": "objectref", "bound": true, "path": [ "person", "gender" ]},
            {type:"text", value:" "},
            {type:"expression", "category": "objectref", "bound": true, "path": [ "person", "category" ]}
          ]}
      ],"content": [
        { "type": "textblock", "content": [
            {"type": "text","value": "Hello "},
            {"type": "expression", "category": "objectref", "bound": true, "path": [ "person", "name" ]},
            {"type": "text","value": "! "}
         ]}
      ]}
    ]
}
```

## Output ##
The compiled template, e.g.:
```
n.elt(  "div",
    {e1:[1,2,"person","id"],e2:[1,2,"person","gender"],e3:[1,2,"person","category"]} ,
    {"title":"Some text","id":["",1],"class":["",2," ",3]},
    0,[
        n.$text({e1:[1,2,"person","name"]},["Hello ",1,"! "])
    ]
)
```

## Algorithm ##

The first part of this step is the actual generation.
It is done thanks to the TemplateWalker class (which extend TreeWalker).
It walks the SyntaxTree built previously and manages each node with a processor, depending on its type.
Each processor generates a javascript string for the node and its children.

Once the generation is done, the resulting javascript string is validated with the *acorn* parser.


text:
<eq name="type" value="personal">

            <eq name="required" value="1">*  </eq>{$field_name}

            <textarea class="form-control" onblur="check_textarea(this,{$field_id})" require="{$required}" min_length="{$validation.min}" max_length="{$validation.max}" text_type="textarea" id="expand_{$field_id}" name="expand_{$field_id}"style="min-height: 100px;">{$field_data|htmlspecialchars}</textarea>
            <input type="hidden" class="canSubmit" id="canSubmit_{$field_id}" value="{$canSubmit}">
            <neq name="input_tips" value=""> {$input_tips}</neq>

    <else/>

        {$field_name}:

        <if condition="($field_data neq null)&&($field_data neq '')">
            {$field_data|htmlspecialchars}
            <else/>
            无
        </if>

</eq>


text:
package kubeadm

import (
	"bytes"
	"encoding/json"
	"html/template"
	"strings"

	"github.com/golang/glog"
	"github.com/pkg/errors"
	clientv1 "k8s.io/api/core/v1"
	rbacv1beta1 "k8s.io/api/rbac/v1beta1"
	apierrs "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/apis/meta/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/strategicpatch"
	"k8s.io/minikube/pkg/minikube/bootstrapper"
	"k8s.io/minikube/pkg/minikube/service"
	"k8s.io/minikube/pkg/util"
)

const (
	masterTaint = "node-role.kubernetes.io/master"
	rbacName    = "minikube-rbac"
)

var master = ""

func unmarkMaster() error {
	k8s := service.K8s
	client, err := k8s.GetCoreClient()
	if err != nil {
		return errors.Wrap(err, "getting core client")
	}
	n, err := client.Nodes().Get(master, v1.GetOptions{})
	if err != nil {
		return errors.Wrapf(err, "getting node %s", master)
	}

	oldData, err := json.Marshal(n)
	if err != nil {
		return errors.Wrap(err, "json marshalling data before patch")
	}

	newTaints := []clientv1.Taint{}
	for _, taint := range n.Spec.Taints {
		if taint.Key == masterTaint {
			continue
		}

		newTaints = append(newTaints, taint)
	}
	n.Spec.Taints = newTaints

	newData, err := json.Marshal(n)
	if err != nil {
		return errors.Wrapf(err, "json marshalling data after patch")
	}

	patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, clientv1.Node{})
	if err != nil {
		return errors.Wrap(err, "creating strategic patch")
	}

	if _, err := client.Nodes().Patch(n.Name, types.StrategicMergePatchType, patchBytes); err != nil {
		if apierrs.IsConflict(err) {
			return errors.Wrap(err, "strategic patch conflict")
		}
		return errors.Wrap(err, "applying strategic patch")
	}

	return nil
}

// elevateKubeSystemPrivileges gives the kube-system service account
// cluster admin privileges to work with RBAC.
func elevateKubeSystemPrivileges() error {
	k8s := service.K8s
	client, err := k8s.GetClientset()
	clusterRoleBinding := &rbacv1beta1.ClusterRoleBinding{
		ObjectMeta: v1.ObjectMeta{
			Name: rbacName,
		},
		Subjects: []rbacv1beta1.Subject{
			{
				Kind:      "ServiceAccount",
				Name:      "default",
				Namespace: "kube-system",
			},
		},
		RoleRef: rbacv1beta1.RoleRef{
			Kind: "ClusterRole",
			Name: "cluster-admin",
		},
	}

	if _, err := client.RbacV1beta1().ClusterRoleBindings().Get(rbacName, metav1.GetOptions{}); err == nil {
		glog.Infof("Role binding %s already exists. Skipping creation.", rbacName)
		return nil
	}
	_, err = client.RbacV1beta1().ClusterRoleBindings().Create(clusterRoleBinding)
	if err != nil {
		return errors.Wrap(err, "creating clusterrolebinding")
	}
	return nil
}

const (
	kubeconfigConf         = "kubeconfig.conf"
	kubeProxyConfigmapTmpl = `apiVersion: v1
kind: Config
clusters:
- cluster:
    certificate-authority: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
    server: https://{{.AdvertiseAddress}}:{{.APIServerPort}}
  name: default
contexts:
- context:
    cluster: default
    namespace: default
    user: default
  name: default
current-context: default
users:
- name: default
  user:
    tokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token
`
)

func restartKubeProxy(k8s bootstrapper.KubernetesConfig) error {
	client, err := util.GetClient()
	if err != nil {
		return errors.Wrap(err, "getting k8s client")
	}

	selector := labels.SelectorFromSet(labels.Set(map[string]string{"k8s-app": "kube-proxy"}))
	if err := util.WaitForPodsWithLabelRunning(client, "kube-system", selector); err != nil {
		return errors.Wrap(err, "waiting for kube-proxy to be up for configmap update")
	}

	cfgMap, err := client.CoreV1().ConfigMaps("kube-system").Get("kube-proxy", metav1.GetOptions{})
	if err != nil {
		return errors.Wrap(err, "getting kube-proxy configmap")
	}

	t := template.Must(template.New("kubeProxyTmpl").Parse(kubeProxyConfigmapTmpl))
	opts := struct {
		AdvertiseAddress string
		APIServerPort    int
	}{
		AdvertiseAddress: k8s.NodeIP,
		APIServerPort:    util.APIServerPort,
	}

	kubeconfig := bytes.Buffer{}
	if err := t.Execute(&kubeconfig, opts); err != nil {
		return errors.Wrap(err, "executing kube proxy configmap template")
	}

	if cfgMap.Data == nil {
		cfgMap.Data = map[string]string{}
	}
	cfgMap.Data[kubeconfigConf] = strings.TrimSuffix(kubeconfig.String(), "\n")

	if _, err := client.CoreV1().ConfigMaps("kube-system").Update(cfgMap); err != nil {
		return errors.Wrap(err, "updating configmap")
	}

	pods, err := client.CoreV1().Pods("kube-system").List(metav1.ListOptions{
		LabelSelector: "k8s-app=kube-proxy",
	})
	if err != nil {
		return errors.Wrap(err, "listing kube-proxy pods")
	}
	for _, pod := range pods.Items {
		if err := client.CoreV1().Pods(pod.Namespace).Delete(pod.Name, &metav1.DeleteOptions{}); err != nil {
			return errors.Wrapf(err, "deleting pod %+v", pod)
		}
	}

	return nil
}


text:
package org.kaazing.gateway.transport.http;

import static org.kaazing.gateway.transport.http.HttpHeaders.HEADER_CONTENT_LENGTH;

import java.net.URI;
import java.nio.ByteBuffer;

import org.apache.mina.core.filterchain.IoFilterChain;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;
import org.apache.mina.core.write.WriteRequestQueue;
import org.kaazing.gateway.transport.AbstractBridgeSession;
import org.kaazing.gateway.transport.BridgeConnectHandler;
import org.kaazing.gateway.transport.BridgeConnectProcessor;
import org.kaazing.gateway.transport.IoSessionAdapterEx;
import org.kaazing.gateway.transport.UpgradeFuture;
import org.kaazing.gateway.transport.http.bridge.HttpContentMessage;
import org.kaazing.gateway.transport.http.bridge.HttpRequestMessage;
import org.kaazing.gateway.transport.http.bridge.filter.HttpBuffer;
import org.kaazing.mina.core.buffer.IoBufferAllocatorEx;
import org.kaazing.mina.core.buffer.IoBufferEx;
import org.kaazing.mina.core.buffer.SimpleBufferAllocator;
import org.kaazing.mina.core.session.IoSessionEx;

public class HttpConnectProcessor extends BridgeConnectProcessor<DefaultHttpSession> {

    public static final IoBufferEx WRITE_COMPLETE = SimpleBufferAllocator.BUFFER_ALLOCATOR.wrap(ByteBuffer.allocate(0));

    protected void finishConnect(DefaultHttpSession session) {
        // GET methods implicitly have no payload
        // when payload is empty, proactively send the request start
        // as there will be no subsequent writes to trigger the send
        boolean isChunked = "chunked".equals(session.getWriteHeader("Transfer-Encoding"));
        if (session.getMethod() == HttpMethod.GET || "0".equals(session.getWriteHeader(HEADER_CONTENT_LENGTH)) || isChunked) {
            URI resource = session.getRemoteAddress().getResource();

            // create HttpRequestMessage
            HttpRequestMessage httpRequest = new HttpRequestMessage();
            httpRequest.setMethod(session.getMethod());
            httpRequest.setRequestURI(session.getRequestURI());
            httpRequest.setVersion(session.getVersion());
            httpRequest.setParameters(session.getParameters());

            // default headers
            httpRequest.setHeader("User-Agent", "Kaazing Gateway");
            // TODO: strip port if default
            httpRequest.setHeader("Host", resource.getAuthority());

            // override headers
            httpRequest.putHeaders(session.getWriteHeaders());

            httpRequest.setCookies(session.getWriteCookies());

            if (isChunked) {
                IoBufferAllocatorEx<? extends HttpBuffer> allocator = session.getBufferAllocator();
                HttpBuffer unsharedEmpty = allocator.wrap(allocator.allocate(0));
                HttpContentMessage flush = new HttpContentMessage(unsharedEmpty, false);
                httpRequest.setContent(flush);
            }

            session.commit();

            IoSession parent = session.getParent();
            parent.write(httpRequest);
        }
    }

    @Override
    protected void flushInternal(final DefaultHttpSession session) {
        IoFilterChain filterChain = session.getFilterChain();
        WriteRequestQueue writeRequestQueue = session.getWriteRequestQueue();
        do {
            WriteRequest request = writeRequestQueue.poll(session);
            if (request == null) {
                break;
            }
            Object message = request.getMessage();
            if (message instanceof IoBufferEx) {
                IoBufferEx buf = (IoBufferEx) message;
                try {
                    // flush the buffer out to the parent
                    IoSessionEx parent = session.getParent();
                    if (parent.isClosing()) {
                        // TODO: throw write to close session exception
                        break;
                    }

                    // hold current remaining bytes so we know how much was written
                    int remaining = buf.remaining();

                    if (remaining == 0 && buf != WRITE_COMPLETE) {
                        throw new IllegalStateException("Unexpected empty buffer");
                    }

                    // TODO: may want to fragment outbound buffer here in the future
                    if (session.isCommitting()) {
                        // create HttpContentMessage
                        HttpContentMessage content = new HttpContentMessage(buf, buf == WRITE_COMPLETE);
                        flushNowInternal(parent, content, buf, filterChain, request);
                    }
                    else {
                        // create HttpRequestMessage
                        HttpRequestMessage httpRequest = new HttpRequestMessage();
                        httpRequest.setMethod(session.getMethod());
                        httpRequest.setRequestURI(session.getRequestURI());
                        httpRequest.setVersion(session.getVersion());

                        // default headers
                        httpRequest.setHeader("User-Agent", "Kaazing Gateway");

                        // override headers
                        httpRequest.putHeaders(session.getWriteHeaders());
                        httpRequest.setHeader("Host", session.getRemoteAddress().getResource().getAuthority());

                        httpRequest.setCookies(session.getWriteCookies());

                        // wrap buffer and add it to response
                        HttpContentMessage content = new HttpContentMessage(buf, buf == WRITE_COMPLETE);
                        httpRequest.setContent(content);

                        session.commit();

                        flushNowInternal(parent, httpRequest, buf, filterChain, request);
                    }

                    // increment session written bytes
                    int written = remaining;
                    session.increaseWrittenBytes(written, System.currentTimeMillis());
                }
                catch (Exception e) {
                    request.getFuture().setException(e);
                }
            } else {
                throw new IllegalStateException("Don't know how to handle message of type '" + message.getClass().getName()
                        + "'.  Are you missing a protocol encoder?");
            }
        } while (true);
    }

    @Override
    protected void removeInternal(DefaultHttpSession httpSession) {
        // Make sure the closeFuture fires now since the listener on the CloseFuture
        // is where the decision to upgrade or not occurs.
        httpSession.getCloseFuture().setClosed();

        IoHandler upgradeHandler = httpSession.getUpgradeHandler();
        if (upgradeHandler == null) {
            // TODO: implement support for HTTP/1.1 persistent connections
            IoSession parent = httpSession.getParent();
            if ("chunked".equals(httpSession.getWriteHeader("Transfer-Encoding"))) {
                IoBufferAllocatorEx<? extends HttpBuffer> allocator = httpSession.getBufferAllocator();
                HttpBuffer unsharedEmpty = allocator.wrap(allocator.allocate(0));
                HttpContentMessage message = new HttpContentMessage(unsharedEmpty, true);
                parent.write(message);
            }

            super.removeInternal(httpSession);
        } else {
            final UpgradeFuture upgradeFuture = httpSession.getUpgradeFuture();
            IoSessionEx parent = httpSession.getParent();
            try {
                if (parent instanceof AbstractBridgeSession<?, ?>) {
                    // this occurs for https
                    AbstractBridgeSession<?, ?> bridgeSession = (AbstractBridgeSession<?, ?>) parent;
                    IoHandler oldHandler = bridgeSession.getHandler();
                    oldHandler.sessionClosed(parent);
                    bridgeSession.setHandler(upgradeHandler);
                } else if (parent instanceof IoSessionAdapterEx) {
                    IoSessionAdapterEx bridgeSession = (IoSessionAdapterEx) parent;
                    IoHandler oldHandler = bridgeSession.getHandler();
                    oldHandler.sessionClosed(parent);
                    bridgeSession.setHandler(upgradeHandler);
                }
                else {
                    // this occurs for http
                    IoHandler oldHandler = (IoHandler) parent.getAttribute(BridgeConnectHandler.DELEGATE_KEY);
                    oldHandler.sessionClosed(parent);
                    parent.setAttribute(BridgeConnectHandler.DELEGATE_KEY, upgradeHandler);
                }
                upgradeFuture.setUpgraded();
                upgradeHandler.sessionOpened(parent);
            } catch (Exception e) {
                throw new RuntimeException("Error during http connector upgrade.", e);
            }
        }
    }
}


text:
'use strict';
/* Controllers */
angular.module('myApp.transactionControlers', [])
  .controller('TransactionsController', ['$scope', '$http', 'UserDataService','ConstantProvider',
    function($scope, $http, UserDataService,ConstantProvider) {
      $http.get(ConstantProvider.getApiPath()+'transaction/from/' + localStorage.getItem("username")).success(function(data) {

        $scope.transitionState = "active";

        // show items others want from me
        function kompress() {

          var kompressed = {};

          for (var num in data[0]) {
            for (var key in data[0][num]) {
              if (typeof kompressed[key] == "undefined") {

                kompressed[key] = [{
                  "name": data[0][num][key],
                  "status": "" + data[1][num].isapproved
                }];
              } else {
                kompressed[key].push({
                  "name": data[0][num][key],
                  "status": "" + data[1][num].isapproved
                });
              }
            }
          }
          return kompressed;
        }

        // items contains persons + items that request from you
        $scope.items = kompress();

        // get size of transaction object
        var transactionLenght = 0,key;

        for (key in $scope.items) {
  // --------------------------- show gray area on the right if items are accepted --------------------------- //
          if ($scope.items.hasOwnProperty(key))
          transactionLenght++;
        }

        if (transactionLenght == 0){
          $scope.notification = "You dont have any running transactions at the moment";
          $scope.hint = "why dont you take a look in";
          $scope.showTip = true;
        }
        else
        {
          $scope.wizardCount ="1";
          $scope.wizardMessage = "Click >> button left below in transaction field to select some items you like to have";
          $scope.hasWizard =true;
        }

    // --------------------------- all Wizard notifications are emitted by children and inserted in scope.wizard ---------------------------//

      $scope.$on('child', function (event, data){
        $scope.wizardCount = data.count;
        $scope.wizardMessage = data.message;

          // highlight buttons when going tru wizard

          if($scope.wizardCount =="3") // highlight middle transaction button
          {
            $scope.transaction_wizard ="transaction-button-wizard";
          }

          // if we have to set middle button to waiting state

          if($scope.data="waiting")
          {
              $scope.$broadcast('parent', 'waiting');
          }

      });

      });
    }
  ])
  .controller('TransactionLibraryController', ['$scope', '$http', 'HttpConnectorService','ConstantProvider',
    function($scope, $http, HttpConnectorService,ConstantProvider) {

      // hide mid buttons in case user is waiting for another for approval

      //  -------------------------- show all incoming requests -------------------------- //

      $scope.selectedItems = [];
      $scope.instruction = "Select some items, you would like to borrow";
      $scope.over = false;

      // -------------------------- populating left side of transaction when needed --------------------------//
      var name_of_person_that_request = ($scope.key);
      var my_name = localStorage.getItem("username");

      $http.get(ConstantProvider.getApiPath()+'collection').success(function(data) {

        localStorage.setItem("collection", data.collection);
        var all_items = data.collection;
        processCollectionData(all_items);
        $scope.buttonsHeight = $scope.height;
      });

      function processCollectionData(all_items) {
        var new_array = [];

        for (var i = 0; i < all_items.length; i++) {
          if (all_items[i].requestedFrom == my_name && all_items[i].owner == name_of_person_that_request) {
            new_array.push(all_items[i]);
          }
        }

        $scope.requestedArray = new_array;

      // ------------------------------- if other approved transaction, make field on the left gray --------------------------//

        if($scope.requestedArray.length>0)
        {
           if ($scope.requestedArray[0].approval==1){
              $scope.isApprovedFromOtherSide = "transaction-accepted";
              localStorage.setItem("transaction",[0,1]);

              $scope.$emit('child', {count:"4", message:$scope.key +' approved transaction, now it is your turn, click on middle button to finialize'});
              $scope.button_show=true;
            }
        }
      }

      //  ----------------------------------- open library in transactions ----------------------------------- //

      $scope.openLibrary = function(data) {

        var tmp_name=data;

      // emit notification to root controller, so it sets scope.wizard to data

        $scope.$emit('child', {count:"2", message:'select some items from '+tmp_name});

        var name = data;
        $http.get(ConstantProvider.getApiPath()+'collection/' + data).success(function(data) {
          $scope.libraryOpen = true;

          var filtered_array = [];

          for (var i = 0; i < data.collection.length; i++) {
            if (data.collection[i].status != 0) {
              filtered_array.push(data.collection[i]);
            }
          }

          $scope.library = filtered_array;

          //  ----------- add item from library to transaction list ----------- /

          $scope.addItem = function($event, index) {

            $scope.$emit('child', {count:"3", message:'click red button in middle of transaction element to confirm your choice and send request to '+tmp_name});

            $event.preventDefault();
            // if no items are yet in the box
            if ($scope.requestedArray.length == 0) {
              $scope.selectedItems.push($scope.library[index]);
            }
            // if there are some items in the box
            if ($scope.requestedArray.length != 0) {
              $scope.requestedArray.push($scope.library[index]);
            }
            // remove this item from library array
            $scope.library.splice(index, 1);
            $scope.instruction = "Borrowing from " + name + ":";
          };

          //  ----------- remove item from transaction and push to library ----------- //

          $scope.removeItem = function($event, index) {
            $event.preventDefault();
            // if no items are yet in the box
            if ($scope.requestedArray.length == 0) {
              $scope.library.push($scope.selectedItems[index]);
              $scope.selectedItems.splice(index, 1);
            }
            // if there are some items in the box
            if ($scope.requestedArray.length != 0) {
              $scope.library.push($scope.requestedArray[index]);
              $scope.requestedArray.splice(index, 1);
            }
            if ($scope.selectedItems.length == 0) {
              $scope.wizardMessage = "Click >> button left below in transaction field to select some items you like to have";
            }
          };
        });
      };

      //  ----------------------------------- close library in transactions ----------------------------------- //

      $scope.closeLibrary = function(data) {
        $scope.libraryOpen = false;
      };

      //  ----------------------------------------- initiate swap --------------------------------------------- //

      $scope.initSwap = function(data) {

        var _my_requests = {};
        var _my_requested_names = [];

        if ($scope.requestedArray.length == 0) {
          _my_requests = $scope.selectedItems;
        } else {
          _my_requests = $scope.requestedArray;
        }

        for (var i = 0; i < _my_requests.length; i++) {
          _my_requested_names.push(_my_requests[i].name)
        }

        var transaction_data = {
          "requestor": localStorage.getItem("username"),
          "from": $scope.key,
          "names": _my_requested_names
        };

        HttpConnectorService.initTransaction(transaction_data, function(data) {
          if (data = "ok") {
            $scope.button_show=true
          }

        });
      };

      //  ----------------------------------------- approve swap, change row Approved from to 1 --------------------------------------------- //

      $scope.upproveSwap = function() {

        // change visual aspect of transaction row
        // only visually approve mine side of transaction
        $scope.isApprovedFromMineSide = "transaction-accepted";

        var data = {
          user: localStorage.getItem("username"),
          requestedItems: JSON.stringify($scope.value)
        }

        $http({
          method: 'PUT',
          url: ConstantProvider.getApiPath()+'/transaction/approval/',
          data: data,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          }
        }).success(function() {
            $scope.$emit('child', {count:"4", message:'now just wait for reply'});
        })
      }
    }
  ]).controller('transactionItemController', ['$scope', 'HttpConnectorService',
    function($scope, HttpConnectorService) {

      $scope.visible = true;

      $scope.showItemMenu = function($event) {
        $event.preventDefault();
        $scope.visible = false;
      }
      $scope.removeFromBorrow = function($event, $index, item, requestor) {
        $event.preventDefault();
        var _data = {
          "itemRequestor": requestor,
          "itemName": item
        }

        HttpConnectorService.removeItem(_data, function() {
          $scope.value.splice($index, 1);
        });
      }
      $scope.close = function($event) {
        $event.preventDefault();
        $scope.visible = true;
      }

          if ($scope.value[0].status==1){
            $scope.isApprovedFromMineSide = "transaction-accepted";

            $scope.$emit('child', {count:"4", message:'wait untill '+$scope.key+ ' will approve his part'});
            $scope.$emit('child', 'waiting');
      }
    }
  ]).controller('borrowController', ['$scope', 'HttpConnectorService',
    function($scope, HttpConnectorService) {

      $scope.whatClassIsIt = function(itm) {
        var _cls;
        if (itm.status == 1) {
          // show normal
          _cls = "list-group-item";
        } else {
          // show grey
          _cls = "list-group-item-borrowed";
        }
        return _cls;
      }

      $scope.checkSwapReady = function(itm) {
        if (itm.status == 1) {
          // show normal
          $scope.isswappable = true;
        } else {
          // show grey
          $scope.isswappable = false;
        }

        return $scope.isswappable;
      }
    }
  ]);


text:
using System;

using Grpc.Core.Utils;

namespace Grpc.Core
{
    /// <summary>
    /// A port exposed by a server.
    /// </summary>
    public class ServerPort
    {
        /// <summary>
        /// Pass this value as port to have the server choose an unused listening port for you.
        /// Ports added to a server will contain the bound port in their <see cref="BoundPort"/> property.
        /// </summary>
        public const int PickUnused = 0;

        readonly string host;
        readonly int port;
        readonly ServerCredentials credentials;
        readonly int boundPort;

        /// <summary>
        /// Creates a new port on which server should listen.
        /// </summary>
        /// <returns>The port on which server will be listening.</returns>
        /// <param name="host">the host</param>
        /// <param name="port">the port. If zero, an unused port is chosen automatically.</param>
        /// <param name="credentials">credentials to use to secure this port.</param>
        public ServerPort(string host, int port, ServerCredentials credentials)
        {
            this.host = GrpcPreconditions.CheckNotNull(host, "host");
            this.port = port;
            this.credentials = GrpcPreconditions.CheckNotNull(credentials, "credentials");
        }

        /// <summary>
        /// Creates a port from an existing <c>ServerPort</c> instance and boundPort value.
        /// </summary>
        internal ServerPort(ServerPort serverPort, int boundPort)
        {
            this.host = serverPort.host;
            this.port = serverPort.port;
            this.credentials = serverPort.credentials;
            this.boundPort = boundPort;
        }

        /// <value>The host.</value>
        public string Host
        {
            get
            {
                return host;
            }
        }

        /// <value>The port.</value>
        public int Port
        {
            get
            {
                return port;
            }
        }

        /// <value>The server credentials.</value>
        public ServerCredentials Credentials
        {
            get
            {
                return credentials;
            }
        }

        /// <value>
        /// The port actually bound by the server. This is useful if you let server
        /// pick port automatically. <see cref="PickUnused"/>
        /// </value>
        public int BoundPort
        {
            get
            {
                return boundPort;
            }
        }
    }
}


text:
package org.qi4j.library.shiro.authc;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.qi4j.library.shiro.Shiro;
import org.qi4j.library.shiro.crypto.HashFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class SecureHashCredentialsMatcher
        implements CredentialsMatcher
{

    private static final Logger LOGGER = LoggerFactory.getLogger( Shiro.LOGGER_NAME );

    public boolean doCredentialsMatch( AuthenticationToken token, AuthenticationInfo info )
    {
        UsernamePasswordToken usernamePasswordToken = ( UsernamePasswordToken ) token;
        SecureHashAuthenticationInfo secureHashAuthInfo = ( SecureHashAuthenticationInfo ) info;

        String tokenHash = HashFactory.create( secureHashAuthInfo.getSecureHash().hashAlgorithm().get(),
                                               usernamePasswordToken.getPassword(),
                                               secureHashAuthInfo.getSecureHash().salt().get(),
                                               secureHashAuthInfo.getSecureHash().hashIterations().get() ).toBase64();
        String authInfoHash = secureHashAuthInfo.getSecureHash().hash().get();

        LOGGER.debug( "tokenHash: {}", tokenHash );
        LOGGER.debug( "authInfoHash: {}", authInfoHash );

        return tokenHash.equals( authInfoHash );

    }

}


text:
namespace PatientManagement.Administration {
    export namespace SergenService {
        export const baseUrl = 'Administration/Sergen';

        export declare function ListConnections(request: Serenity.ServiceRequest, onSuccess?: (response: Serenity.ListResponse<SergenConnection>) => void, opt?: Q.ServiceOptions<any>): JQueryXHR;
        export declare function ListTables(request: SergenListTablesRequest, onSuccess?: (response: Serenity.ListResponse<SergenTable>) => void, opt?: Q.ServiceOptions<any>): JQueryXHR;
        export declare function Generate(request: SergenGenerateRequest, onSuccess?: (response: Serenity.ServiceResponse) => void, opt?: Q.ServiceOptions<any>): JQueryXHR;

        export declare const enum Methods {
            ListConnections = "Administration/Sergen/ListConnections",
            ListTables = "Administration/Sergen/ListTables",
            Generate = "Administration/Sergen/Generate"
        }

        [
            'ListConnections',
            'ListTables',
            'Generate'
        ].forEach(x => {
            (<any>SergenService)[x] = function (r, s, o) {
                return Q.serviceRequest(baseUrl + '/' + x, r, s, o);
            };
        });
    }
}


text:
namespace Mylib {

using Chrono::Date;

class Invalid_ISBN { };  // to throw in case ISBN is not valid

enum class Genre {
    fiction, nonfiction, periodical, biography, children
};

// Genre operators
ostream& operator<<(ostream& os, Genre g);

class Book {
public:
    Book(string isbn, string title, string author, Date copyright, Genre genre);

    // modifying function members
    void check_out() { co = true; }
    void check_in() { co = false; }

    // non-modifying function members
    const string& isbn() const { return id; }
    const string& title() const { return tit; }
    const string& author() const { return auth; }
    const Date& copyright() const { return cright; }
    const Genre genre() const { return gen; }
    const bool checked_out() const { return co; }
private:
    string id;
    string tit;
    string auth;
    Date cright;
    Genre gen;
    bool co;
};

// Book helper functions
bool is_isbn(const string& isbn);
void print(ostream& os, const Book& book);

// Book operators
bool operator==(const Book& a, const Book& b);
bool operator!=(const Book& a, const Book& b);
ostream& operator<<(ostream& os, const Book& book);

class Patron {
public:
    Patron(string name, string card_number);

    // modifying function members
    void set_fees(double fees);

    // non-modifying function members
    const string& name() const { return n; }
    const string& card_number() const { return id; }
    const double fees() const { return f; }
private:
    string n;       // User's name
    string id;      // Card number
    double f;          // Fees
};

// Patron helper functions
bool owes_fees(const Patron& p);

// Patron operators
ostream& operator<<(ostream& os, const Patron& p);

} // namespace Mylib

#endif


text:
package org.ohmage.reminders.glue;

import android.content.Context;
import android.content.Intent;

import org.ohmage.reminders.types.location.LocTrigTracingSettActivity;

/*
 * APIs exported from location triggers. This class
 * exports interfaces which can be used by the clients
 * to directly interact with location based triggers
 * (without going through the framework).
 */
public class LocationTriggerAPI {

    /*
     * Launch the activity with the location tracing settings.
     */
    public static void launchLocationTracingSettingsActivity(Context context) {

        context.startActivity(new Intent(context,
                LocTrigTracingSettActivity.class));
    }
}


text:
git checkout gh-pages
rm -rf _*
touch .nojekyll
git checkout master docs hurray logo.png favicon.ico
make html -C ./docs
mv ./docs/_build/html/* ./
rm -rf ./docs
git add -A
git commit -m "publishing updated github pages..."
git push origin gh-pages

git checkout master


text: This is fucking system of APOC  in your second version


text:
import { injectable } from 'inversify';

import { Responder } from '../responder';

export type RegistrationType = 'hear' | 'respond';

export interface Registration {
    type: RegistrationType;
    test: RegExp;
    callback: (resp: Responder, match: RegExpMatchArray) => Promise<void>;
}

@injectable()
export default abstract class Feature {
    public abstract setup(): Iterable<Registration>;

    // eslint-disable-next-line class-methods-use-this
    protected hear(test: RegExp, callback: (resp: Responder, match: RegExpMatchArray) => Promise<void>): Registration {
        return { type: 'hear', test, callback };
    }

    // eslint-disable-next-line class-methods-use-this
    protected respond(
        test: RegExp,
        callback: (resp: Responder, match: RegExpMatchArray) => Promise<void>,
    ): Registration {
        return { type: 'respond', test, callback };
    }
}


text:
package example;

import static org.junit.jupiter.api.Assertions.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.inject.Named;

import org.junit.jupiter.api.Test;

class AnnotationSerializeTest {

	@Named("foobar")
	Object obj;

	@Test
	void test() throws Exception {
		final Named named = getClass().getDeclaredField("obj").getAnnotation(Named.class);

		final ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
			oos.writeObject(named);
			oos.flush();
		}

		Named deserialized;
		final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
		try (ObjectInputStream ois = new ObjectInputStream(bais)) {
			deserialized = (Named) ois.readObject();
		}

		assertEquals(named, deserialized);
	}
}


text:
namespace Google.Cloud.Dataplex.V1.Snippets
{
    // [START dataplex_v1_generated_DataplexService_CancelJob_async_flattened_resourceNames]
    using System.Threading.Tasks;
    using gcdv = Google.Cloud.Dataplex.V1;

    public sealed partial class GeneratedDataplexServiceClientSnippets
    {
        /// <summary>Snippet for CancelJobAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task CancelJobResourceNamesAsync()
        {
            // Create client
            DataplexServiceClient dataplexServiceClient = await DataplexServiceClient.CreateAsync();
            // Initialize request argument(s)
            JobName name = JobName.FromProjectLocationLakeTaskJob("[PROJECT]", "[LOCATION]", "[LAKE]", "[TASK]", "[JOB]");
            // Make the request
            await dataplexServiceClient.CancelJobAsync(name);
        }
    }
    // [END dataplex_v1_generated_DataplexService_CancelJob_async_flattened_resourceNames]
}


text:
require 'spec_helper'
require 'thrift/types/value'
require 'thrift/types/known/any'

describe 'Thrift::Types::Known::Any' do
  describe 'encode' do
    let(:codec) { '' }

    shared_examples 'idempotent' do
      it 'should be idempotent' do
        Thrift::Types::Known::Any.from_object(obj, codec).to_object.should == obj
      end
    end

    subject { Thrift::Types::Known::Any.from_object(obj, codec) }

    context 'thrift struct' do
      let(:obj) { Thrift::Types::Value.from_object("foo") }

      it { subject.type.should == 'thrift/types.value.Value' }
      it { subject.value.should == '{"2":{"str":"foo"}}' }

      include_examples 'idempotent'

      context 'yaml only' do
        let(:codec) { 'yaml' }

        it { subject.type.should == 'thrift-yaml/types.value.Value' }
        it { subject.value.should == "string_value: foo\n" }

        include_examples 'idempotent'
      end

      context 'json only' do
        let(:codec) { 'json' }

        it { subject.type.should == 'thrift-json/types.value.Value' }
        it { subject.value.should == '{"string_value":"foo"}' }

        include_examples 'idempotent'
      end
    end
  end
end


text:
$set 3 #Configmenu

$ #ConfigOptions
# Opciones de Configuración
$ #FocusModel
# Modelo del Foco
$ #WindowPlacement
# Ubicación de las Ventanas
$ #ImageDithering
# Simulación Ordenada de Colores en Imágenes
$ #OpaqueMove
# Movimiento Opaco de Ventanas
$ #FullMax
# Maximización Total
$ #FocusNew
# Enfocar Nuevas Ventanas
$ #FocusLast
# Enfocar la Ultima Ventana en el Escritorio
$ #DisableBindings
# Deshabilitar Enlaces con Bloq Despl
$ #ClickToFocus
# Click Para Enfocar
$ #SloppyFocus
# Foco Sigue Al Mouse
$ #AutoRaise
# Elevar Automáticamente
$ #ClickRaise
# Click Para Elevar
$ #SmartRows
# Ubicación Inteligente (Filas)
$ #SmartCols
# Ubicación Inteligente (Columnas)
$ #Cascade
# Ubicación en Cascada
$ #LeftRight
# Izquierda A Derecha
$ #RightLeft
# Derecha A Izquierda
$ #TopBottom
# De Arriba Abajo
$ #BottomTop
# De Abajo Arriba
$ #NoDithering
# Do not dither images
$ #OrderedDithering
# Use fast dither
$ #FloydSteinbergDithering
# Use high-quality dither


text:
package org.springframework.boot;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.util.concurrent.Callable;

import org.apache.commons.logging.Log;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

/**
 * Logs application information on startup.
 *
 * @author Phillip Webb
 * @author Dave Syer
 */
class StartupInfoLogger {

	private final Class<?> sourceClass;

	StartupInfoLogger(Class<?> sourceClass) {
		this.sourceClass = sourceClass;
	}

	public void logStarting(Log log) {
		Assert.notNull(log, "Log must not be null");
		if (log.isInfoEnabled()) {
			log.info(getStartupMessage());
		}
		if (log.isDebugEnabled()) {
			log.debug(getRunningMessage());
		}
	}

	public void logStarted(Log log, StopWatch stopWatch) {
		if (log.isInfoEnabled()) {
			log.info(getStartedMessage(stopWatch));
		}
	}

	private String getStartupMessage() {
		StringBuilder message = new StringBuilder();
		message.append("Starting ");
		message.append(getApplicationName());
		message.append(getVersion(this.sourceClass));
		message.append(getOn());
		message.append(getPid());
		message.append(getContext());
		return message.toString();
	}

	private StringBuilder getRunningMessage() {
		StringBuilder message = new StringBuilder();
		message.append("Running with Spring Boot");
		message.append(getVersion(getClass()));
		message.append(", Spring");
		message.append(getVersion(ApplicationContext.class));
		return message;
	}

	private StringBuilder getStartedMessage(StopWatch stopWatch) {
		StringBuilder message = new StringBuilder();
		message.append("Started ");
		message.append(getApplicationName());
		message.append(" in ");
		message.append(stopWatch.getTotalTimeSeconds());
		try {
			double uptime = ManagementFactory.getRuntimeMXBean().getUptime() / 1000.0;
			message.append(" seconds (JVM running for " + uptime + ")");
		}
		catch (Throwable ex) {
			// No JVM time available
		}
		return message;
	}

	private String getApplicationName() {
		return (this.sourceClass != null ? ClassUtils.getShortName(this.sourceClass)
				: "application");
	}

	private String getVersion(final Class<?> source) {
		return getValue(" v", new Callable<Object>() {
			@Override
			public Object call() throws Exception {
				return source.getPackage().getImplementationVersion();
			}
		}, "");
	}

	private String getOn() {
		return getValue(" on ", new Callable<Object>() {
			@Override
			public Object call() throws Exception {
				return InetAddress.getLocalHost().getHostName();
			}
		});
	}

	private String getPid() {
		return getValue(" with PID ", new Callable<Object>() {
			@Override
			public Object call() throws Exception {
				return System.getProperty("PID");
			}
		});
	}

	private String getContext() {
		String startedBy = getValue("started by ", new Callable<Object>() {
			@Override
			public Object call() throws Exception {
				return System.getProperty("user.name");
			}
		});
		String in = getValue("in ", new Callable<Object>() {
			@Override
			public Object call() throws Exception {
				return System.getProperty("user.dir");
			}
		});
		ApplicationHome home = new ApplicationHome(this.sourceClass);
		String path = (home.getSource() == null ? ""
				: home.getSource().getAbsolutePath());
		if (startedBy == null && path == null) {
			return "";
		}
		if (StringUtils.hasLength(startedBy) && StringUtils.hasLength(path)) {
			startedBy = " " + startedBy;
		}
		if (StringUtils.hasLength(in) && StringUtils.hasLength(startedBy)) {
			in = " " + in;
		}
		return " (" + path + startedBy + in + ")";
	}

	private String getValue(String prefix, Callable<Object> call) {
		return getValue(prefix, call, "");
	}

	private String getValue(String prefix, Callable<Object> call, String defaultValue) {
		try {
			Object value = call.call();
			if (value != null && StringUtils.hasLength(value.toString())) {
				return prefix + value;
			}
		}
		catch (Exception ex) {
			// Swallow and continue
		}
		return defaultValue;
	}

}


text:
from django.contrib import admin
from polls.models import Poll, Choice

class ChoiceInline (admin.TabularInline):
	model = Choice
	extra = 3

class PollAdmin(admin.ModelAdmin):
	fieldsets = [
			(None,		{'fields':['question']}),
			('Date information',	{'fields':['pub_date'], 'classes':['collapse']}),
			]
	inlines = [ChoiceInline]
	list_display=('question','pub_date','was_published_recently')
	list_filter=['pub_date']
	search_fields=['question']
	date_hierarchy='pub_date'

admin.site.register(Poll,PollAdmin)


text:
package org.derric_lang.validator.interpreter.structure;

import java.util.Map;

public class Fac extends ValueExpression {

	private final ValueExpression _l;
	private final ValueExpression _r;

	public Fac(ValueExpression l, ValueExpression r) {
		_l = l;
		_r = r;
	}

	@Override
	public Object eval(Map<String, Type> globals, Map<String, Type> locals) {
		return (Long)_l.eval(globals, locals) * (Long)_r.eval(globals, locals);
	}

}


text:
<?php
# MantisBT - A PHP based bugtracking system

# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MantisBT.  If not, see <http://www.gnu.org/licenses/>.

require_once( 'core.php' );

plugin_require_api( 'core/graph_api.php' );

access_ensure_project_level( config_get( 'view_summary_threshold' ) );

layout_page_header();

layout_page_begin( 'summary_page.php' );

print_summary_menu( 'summary_page.php' );
print_summary_submenu();

$t_series_name = lang_get( 'bugs' );
$t_metrics = create_bug_enum_summary( lang_get( 'severity_enum_string' ), 'severity' );
?>

                    <?php echo plugin_lang_get( 'graph_imp_severity_title' ) ?>

                <?php graph_bar( $t_metrics, lang_get( 'by_severity' ), $t_series_name ); ?>

                <?php graph_pie( $t_metrics, plugin_lang_get( 'by_severity_pct' ) ); ?>

<?php
layout_page_end();


text:
import os
import sys

from PyQt4.QtCore import (Qt, SIGNAL,QUrl)
from PyQt4.QtGui import (QApplication, QDialog, QHBoxLayout, QVBoxLayout,
        QListWidget, QListWidgetItem, QSplitter, QTableWidget, QPushButton,QGraphicsView)
from PyQt4 import QtDeclarative

import geigerWrap
import workflowManager

class Form(QDialog):

    # Define the main user interface
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        # Create widgets
        self.button = QPushButton("Run Geiger Script")
        self.quitbutton = QPushButton("Quit")
        wf_manager = workflowManager.workflowManager()

        # change to directory where the code is stored, so we can reference the
        # qml directory using a relative pathname.
        # TODO: pack files into Qt resources eventually instead of absolute pathnames
        os.chdir("/Users/clisle/Projects/Arbor/code/exploration/ArborUsingPyQt")
        self.mapview = QtDeclarative.QDeclarativeView()
        self.mapview.setSource(QUrl.fromLocalFile("arbor-ui.qml"))
        self.mapview.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)

        self.mapview.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)

        # install the Python workflowManager definition as a property in the QML context
        # so it can be referenced in the context and slots of the class can be invoked through QML
        self.mapview.rootContext().setContextProperty('workflowmgr', wf_manager)

        # as part of initialization, have the workflowMgr dig around in the QML hierarchy,
        # discover the workflow and save a private handle to the workflow so we can manage
        # the workflow UI canvas from the logic side.

        #save pointer to the view. It is needed to instantiate new objects
        wf_manager.saveViewObject(self.mapview)

        wf_manager.findAndSaveWorkspaceFromRoot(self.mapview.rootObject())

        # Create layout and add widgets
        layout = QVBoxLayout()
        layout.addWidget(self.button)
        layout.addWidget(self.mapview)
        layout.addWidget(self.quitbutton)
        # Set dialog layout
        self.setLayout(layout)
        # Add button signal to greetings slot
        self.button.clicked.connect(self.greetings)
        self.quitbutton.clicked.connect(self.quitprogram)

    # Initialize the Geiger module under R
    def greetings(self):
        print ("Running Geiger Init...")
        geigerWrap.gw_InitGeiger()
        print ("Finished Geiger Init...")

    # Closeout any leftover processes and interfaces, then quit
    def quitprogram(self):
        print ("Safe Closeout...")
        geigerWrap.gw_ShutdownGeiger()
        quit()

if __name__ == '__main__':
    # Create the Qt Application
    app = QApplication(sys.argv)
    # Create and show the form
    form = Form()
    # the window opens up really tiny without this, because QML size wasn't set
    form.setMinimumSize(800,600)
    form.show()
    # Run the main Qt loop
    sys.exit(app.exec_())


text:
layout: model
title: Legal Zero-shot NER
author: John Snow Labs
name: legner_roberta_zeroshot
date: 2022-09-02
tags: [en, legal, ner, zero, shot, zeroshot, licensed]
task: Named Entity Recognition
language: en
edition: Legal NLP 1.0.0
spark_version: 3.0
supported: true
recommended: true
annotator: ZeroShotNER
article_header:
  type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

This model is trained to carry out a Zero-Shot Named Entity Recognition (NER) approach, detecting any kind of entities with no training dataset, just tje pretrained RoBERTa embeddings (included in the model) and some examples.

## Predicted Entities

{:.btn-box}
[Live Demo](https://demo.johnsnowlabs.com/legal/LEGNER_ZEROSHOT/){:.button.button-orange}
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/legal/models/legner_roberta_zeroshot_en_1.0.0_3.2_1662113815288.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}

```python
documentAssembler = nlp.DocumentAssembler()\
  .setInputCol("text")\
  .setOutputCol("document")

sparktokenizer = nlp.Tokenizer()\
  .setInputCols("document")\
  .setOutputCol("token")

zero_shot_ner = legal.ZeroShotNerModel.pretrained("legner_roberta_zeroshot", "en", "legal/models")\
    .setInputCols(["document", "token"])\
    .setOutputCol("zero_shot_ner")\
    .setEntityDefinitions(
        {
            "DATE": ['When was the company acquisition?', 'When was the company purchase agreement?', "When was the agreement?"],
            "ORG": ["Which company?"],
            "STATE": ["Which state?"],
            "AGREEMENT": ["What kind of agreement?"],
            "LICENSE": ["What kind of license?"],
            "LICENSE_RECIPIENT": ["To whom the license is granted?"]
        })

nerconverter = nlp.NerConverter()\
  .setInputCols(["document", "token", "zero_shot_ner"])\
  .setOutputCol("ner_chunk")

pipeline =  Pipeline(stages=[
  documentAssembler,
  sparktokenizer,
  zero_shot_ner,
  nerconverter,
    ]
)

sample_text = ["In March 2012, as part of a longer-term strategy, the Company acquired Vertro, Inc., which owned and operated the ALOT product portfolio.",
              "In February 2017, the Company entered into an asset purchase agreement with NetSeer, Inc.",
              "This INTELLECTUAL PROPERTY AGREEMENT, dated as of December 31, 2018 (the 'Effective Date') is entered into by and between Armstrong Flooring, Inc., a Delaware corporation ('Seller') and AFI Licensing LLC, a Delaware company('Licensing')"
              "The Company hereby grants to Seller a perpetual, non- exclusive, royalty-free license"]

p_model = pipeline.fit(spark.createDataFrame([[""]]).toDF("text"))

res = p_model.transform(spark.createDataFrame(sample_text, StringType()).toDF("text"))

res.select(F.explode(F.arrays_zip(res.ner_chunk.result, res.ner_chunk.begin, res.ner_chunk.end, res.ner_chunk.metadata)).alias("cols")) \
   .select(F.expr("cols['0']").alias("chunk"),
           F.expr("cols['3']['entity']").alias("ner_label"))\
   .filter("ner_label!='O'")\
   .show(truncate=False)
```

</div>

## Results

```bash
+---------------------------------------+-----------------+
|chunk                                  |ner_label        |
+---------------------------------------+-----------------+
|March 2012                             |DATE             |
|Vertro, Inc                            |ORG              |
|February 2017                          |DATE             |
|asset purchase agreement               |AGREEMENT        |
|NetSeer                                |ORG              |
|INTELLECTUAL PROPERTY AGREEMENT        |AGREEMENT        |
|December 31, 2018                      |DATE             |
|Armstrong Flooring                     |ORG              |
|Delaware                               |STATE            |
|AFI Licensing LLC                      |ORG              |
|Delaware                               |ORG              |
|Seller                                 |LICENSE_RECIPIENT|
|perpetual, non- exclusive, royalty-free|LICENSE          |
+---------------------------------------+-----------------+
```

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|legner_roberta_zeroshot|
|Type:|legal|
|Compatibility:|Legal NLP 1.0.0+|
|License:|Licensed|
|Edition:|Official|
|Input Labels:|[document_question, document_context]|
|Output Labels:|[answer]|
|Language:|en|
|Size:|460.2 MB|
|Case sensitive:|true|
|Max sentence length:|512|

## References

Legal Roberta Embeddings


text:
import datetime
import csv
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.models import User
from django_pandas.io import read_frame, pd
# from wye.base.constants import WorkshopStatus
from wye.workshops.models import Workshop
from wye.profiles.models import Profile

@login_required
def index(request):
    context_dict = {}
    if not request.user.is_staff:
        template_name = '403.html'
        return render(request, template_name, context_dict)

    workshops = Workshop.objects.filter(is_active=True)
    dataframe = read_frame(workshops, fieldnames=[
        'requester__location__state__name',
        'presenter__id',
        'presenter__first_name',
        'presenter__last_name',
        'workshop_level',
        'no_of_participants',
        'expected_date'])

    # State Based workshop plot
    location = dataframe
    location.dropna(subset=['presenter__id'], inplace=True)
    # location['presenter__id'] = location['presenter__id'].astype(int)
    location_based_sum = location.requester__location__state__name.value_counts()
    location_list = []
    for loc, count in location_based_sum.to_dict().items():
        location_list.append(
            {"label": loc, "values": count})
    context_dict['location'] = location_list
    # Top 10 tutors
    top_tutor_data = dataframe
    presenter_count = top_tutor_data.groupby('presenter__id').count()
    top_tutor_data.drop_duplicates(subset=['presenter__id'], inplace=True)
    top_tutor_data.index = top_tutor_data.presenter__id
    top_tutor_data.drop(["presenter__id"], axis=1, inplace=True)
    presenter_count.drop([
        'presenter__last_name', 'workshop_level',
        'requester__location__state__name',
        'no_of_participants',
        'expected_date'], axis=1, inplace=True)
    presenter_count.rename(columns={
        'presenter__first_name': 'conducted_workshop_count'}, inplace=True)
    t = top_tutor_data.join(presenter_count)
    top_ten_tutors = t.groupby('workshop_level')[
        'conducted_workshop_count'].nlargest(10)
    top_ten_tutors = dataframe.join(top_ten_tutors)
    top_ten_tutors.rename(
        columns={'presenter__first_name': 'first_name',
                 'presenter__last_name': 'last_name'
                 }, inplace=True)
    # Create list of dict as required by nd3 library
    d = {}
    data = []
    for index, row in top_ten_tutors.iterrows():
        d.setdefault(row.workshop_level, [])
        d[row.workshop_level].append(
            {'x': '{} {}'.format(row.first_name, row.last_name),
             'y': row.conducted_workshop_count})
    for k, v in d.items():
        data.append({'key': k, 'values': v})
    context_dict['workshop_tutor'] = data

    time_series = read_frame(workshops, fieldnames=[
        'no_of_participants', 'expected_date'])
    # print(time_series)
    time_series['no_of_participants'] = pd.to_numeric(
        time_series['no_of_participants'])
    time_series = time_series.groupby(
        'expected_date')[['no_of_participants']].agg('sum')
    time_series.fillna(0, inplace=True)
    time_series.index = pd.to_datetime(time_series.index)
    resampled = time_series.resample('M').sum()
    resampled.fillna(0, inplace=True)
    # month_list = []
    t = resampled.groupby([(resampled.index.year),
                           (resampled.index.month)]).sum()
    d = {}
    month_dict = {
        1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr',
        5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug',
        9: 'Sept', 10: 'Oct', 11: 'Nov', 12: 'Dec'}
    for index, row in t.to_dict()['no_of_participants'].items():
        d.setdefault(index[0], [])
        d[index[0]].insert(
            index[1] - 1, {'x': month_dict.get(index[1]), 'y': row})

    ret = []
    for index, row in d.items():
        ret.append({"key": index, "values": row})
    context_dict['line_graph'] = ret
    years = [('all', 'All')]
    for y in range(2016, int(datetime.datetime.today().strftime('%Y')) + 1):
        years.append((y, y))
    context_dict['years'] = years

    template_name = 'reports/index.html'
    return render(request, template_name, context_dict)

# @login_required
# def index_old(request):
#     context_dict = {}
#     if not request.user.is_staff:
#         template_name = '403.html'
#         return render(request, template_name, context_dict)

#     workshops = Workshop.objects.filter(is_active=True)
#     context_dict['workshops'] = {
#         'completed': workshops.filter(status=WorkshopStatus.COMPLETED).count(),
#         'drafted': workshops.filter(status=WorkshopStatus.DRAFT).count(),
#         'hold': workshops.filter(status=WorkshopStatus.HOLD).count(),
#         'feedback_pending': workshops.filter(
#             status=WorkshopStatus.FEEDBACK_PENDING).count(),
#     }
#     workshop_finished = workshops.filter(
#         status__in=[WorkshopStatus.COMPLETED,
#                     WorkshopStatus.FEEDBACK_PENDING])
#     tutors_dict = {}
#     tutors = [
#         user for w in workshop_finished for user in w.presenter.all()]
#     for tutor in tutors:
#         tutors_dict[tutor.id] = [
#             tutor.username,
#             tutor.first_name,
#             tutor.last_name,
#             tutor.profile.get_workshop_completed_count]
#     context_dict['tutors'] = tutors_dict
#     org_dict = {}
#     orgs = [
#         w.requester for w in workshop_finished]
#     for org in orgs:
#         if org.id in org_dict:
#             count = org_dict[org.id][1] + 1
#         else:
#             count = 1
#         org_dict[org.id] = [org.name, count, org.location.name]

#     context_dict['orgs'] = org_dict
#     template_name = 'reports/index.html'
#     years = [('all', 'All')]
#     for y in range(2016, int(datetime.datetime.today().strftime('%Y')) + 1):
#         years.append((y, y))
#     context_dict['years'] = years
#     return render(request, template_name, context_dict)

@login_required
def get_tutor_college_poc_csv(request):
    # if not request.user.is_staff:
    #     template_name = '403.html'
    #     return render(request, template_name, {})
    usertype = request.POST['usertype']
    year = request.POST['years']
    workshops = Workshop.objects.filter(is_active=True)
    if year != 'all':
        workshops = workshops.filter(expected_date__year=year)

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="workshops.csv"'
    writer = csv.writer(response)
    csv_titles = ['Worshop Id', 'Workshop Date', 'Location', 'College']
    if usertype == 'tutor':
        csv_titles.extend(['Presenter Name', 'Presenter Email'])
    elif usertype == 'poc':
        csv_titles.extend(['College POC Name', 'College POC Email'])
    else:
        csv_titles.extend(['Presenter Name', 'Presenter Email'])
        csv_titles.extend(['College POC Name', 'College POC Email'])
    writer.writerow(csv_titles)

    for obj in workshops:
        row = [
            obj.id, obj.expected_date,
            obj.location.name, obj.requester.name]
        if usertype == 'tutor':
            for u in obj.presenter.all():
                row.append("{} {}".format(u.first_name, u.last_name))
                row.append("{}".format(u.email))
        elif usertype == 'poc':
            for u in obj.requester.user.all():
                row.append("{} {}".format(u.first_name, u.last_name))
                row.append("{}".format(u.email))
        else:
            for u in obj.presenter.all():
                row.append("{} {}".format(u.first_name, u.last_name))
                row.append("{}".format(u.email))
            for u in obj.requester.user.all():
                row.append("{} {}".format(u.first_name, u.last_name))
                row.append("{}".format(u.email))
        writer.writerow(row)
    return response

@login_required
def get_all_user_info(request):
    users = User.objects.all()
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="all_users.csv"'
    writer = csv.writer(response)
    csv_titles = [
        'User Id', 'First Name', 'Last Name', 'Email', 'Is Active',
        'Is Presenter', 'Is POC', 'Is Organiser']
    writer.writerow(csv_titles)
    for obj in users:
        try:
            row = [
                obj.id,
                obj.first_name,
                obj.last_name,
                obj.email,
                obj.is_active,
                Profile.is_presenter(obj),
                Profile.is_coordinator(obj),
                Profile.is_organiser(obj)]
            writer.writerow(row)
        except Exception:
            pass
    return response


text:
<?xml version="1.0" encoding="utf-8"?>

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:context="tie.hackathon.travelguide.destinations.description.FinalCityInfo">

        <ImageView
            android:id="@+id/image"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:contentDescription="@string/empty_description"
            android:scaleType="centerCrop"
            android:src="@drawable/delhi" />

        <TextView
            android:id="@+id/head"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:fontFamily="sans-serif-bold"
            android:padding="10dp"
            android:text="@string/sample_state"
            android:textColor="#000000"
            android:textSize="25sp"
            android:textStyle="bold" />

        <com.ms.square.android.expandabletextview.ExpandableTextView
            android:id="@+id/expand_text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/sample_string"
            expandableTextView:animDuration="200"
            expandableTextView:maxCollapsedLines="4">

            <TextView
                android:id="@id/expandable_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:textColor="#666666"
                android:textSize="16sp" />

            <ImageButton
                android:id="@id/expand_collapse"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right|bottom"
                android:background="@android:color/transparent"
                android:contentDescription="@string/empty_description"
                android:padding="16dp" />
        </com.ms.square.android.expandabletextview.ExpandableTextView>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/shadow_1"
            android:backgroundTint="#000000"
            android:orientation="horizontal">

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/icon"
                    android:layout_width="70dp"
                    android:layout_height="70dp"
                    android:layout_gravity="center_vertical"
                    android:contentDescription="@string/empty_description"
                    android:src="@drawable/ic_cloud_black_48dp" />

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_marginStart="10dp"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/temp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_margin="5dp"
                        android:text="@string/max_text"
                        android:textAppearance="?android:attr/textAppearanceSmall"
                        android:textSize="15sp"
                        android:textStyle="bold" />

                    <LinearLayout
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:orientation="horizontal">

                        <TextView
                            android:id="@+id/humidit"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_margin="5dp"
                            android:layout_weight="1.0"
                            android:text="@string/min_text"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:textSize="15sp"
                            android:textStyle="bold" />

                        <TextView
                            android:id="@+id/weatherinfo"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_margin="5dp"
                            android:layout_weight="1.0"
                            android:text="@string/min_text"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:textSize="15sp"
                            android:textStyle="bold" />

                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <LinearLayout
                android:id="@+id/funfact"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1.0"
                android:background="@drawable/shadow_1"
                android:backgroundTint="#000000"
                android:orientation="horizontal"
                android:padding="20dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:contentDescription="@string/empty_description"
                    android:src="@drawable/funfact" />

                <TextView
                    android:id="@+id/fftext"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_margin="5dp"
                    android:text="@string/fun_facts"
                    android:textColor="#000000"
                    android:textSize="18sp" />

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <LinearLayout

                android:id="@+id/hangout"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1.0"
                android:background="@drawable/shadow_1"
                android:backgroundTint="#000000"
                android:orientation="horizontal"
                android:padding="20dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:contentDescription="@string/empty_description"
                    android:src="@drawable/hangout" />

                <TextView
                    android:id="@+id/hgtext"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_margin="5dp"
                    android:text="Hangout"
                    android:textColor="#000000"
                    android:textSize="18sp" />

            </LinearLayout>

            <LinearLayout

                android:id="@+id/monu"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1.0"
                android:background="@drawable/shadow_1"
                android:backgroundTint="#000000"
                android:orientation="horizontal"
                android:padding="20dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:contentDescription="@string/empty_description"
                    android:src="@drawable/monuments" />

                <TextView
                    android:id="@+id/mntext"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_margin="5dp"
                    android:text="Monuments"
                    android:textColor="#000000"
                    android:textSize="18sp" />

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <LinearLayout
                android:id="@+id/shoppp"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1.0"
                android:background="@drawable/shadow_1"
                android:backgroundTint="#000000"
                android:orientation="horizontal"
                android:padding="20dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:contentDescription="@string/empty_description"
                    android:src="@drawable/shopping" />

                <TextView
                    android:id="@+id/shtext"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_margin="5dp"
                    android:text="Shopping"
                    android:textColor="#000000"
                    android:textSize="18sp" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/restau"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1.0"
                android:background="@drawable/shadow_1"
                android:backgroundTint="#000000"
                android:orientation="horizontal"
                android:padding="20dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:contentDescription="@string/empty_description"
                    android:src="@drawable/restaurant" />

                <TextView
                    android:id="@+id/rstext"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_margin="5dp"
                    android:text="Restaurants"
                    android:textColor="#000000"
                    android:textSize="18sp" />

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <LinearLayout
                android:id="@+id/trends"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1.0"
                android:background="@drawable/shadow_1"
                android:backgroundTint="#000000"
                android:orientation="horizontal"
                android:padding="20dp">

                <ImageView
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:contentDescription="@string/empty_description"
                    android:src="@drawable/twitter" />

                <TextView
                    android:id="@+id/cttext"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_margin="5dp"
                    android:text="City Trends"
                    android:textColor="#000000"
                    android:textSize="18sp" />

            </LinearLayout>
        </LinearLayout>

    </LinearLayout>
</ScrollView>


text:
/**
 * Created by me664 on 11/24/14.
 */
jQuery(document).ready(function($){

    $('.st_post_select').each(function(){
        var me=$(this);
        $(this).select2({
            placeholder: me.data('placeholder'),
            minimumInputLength:2,
            ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
                url: ajaxurl,
                dataType: 'json',
                quietMillis: 250,
                data: function (term, page) {
                    return {
                        q: term, // search term,
                        action:'st_post_select',
                        post_type:me.data('post-type'),
                        author : me.data('author')
                    };
                },
                results: function (data, page) { // parse the results into the format expected by Select2.
                    // since we are using custom formatting functions we do not need to alter the remote JSON data
                    return { results: data.items };
                },
                cache: true
            },
            initSelection: function(element, callback) {
                // the input tag has a value attribute preloaded that points to a preselected repository's id
                // this function resolves that id attribute to an object that select2 can render
                // using its formatResult renderer - that way the repository name is shown preselected
                var id = $(element).val();
                if (id !== "") {
                    var data={
                        id:id,
                        name:$(element).data('pl-name'),
                        description:$(element).data('pl-desc')
                    };
                    callback(data);
                }
            },
            formatResult: function(state){
                if (!state.id) return state.name; // optgroup
                return state.name+'
'+state.description+'
';
            },
            formatSelection: function(state){
                if (!state.id) return state.name; // optgroup
                return state.name+'
'+state.description+'
';
            },
            escapeMarkup: function(m) { return m; }
        });
    });
});