text:
var IN_NODE = false
  , IN_WORKER = typeof importScripts !== 'undefined'

if(typeof module === 'undefined') {
  // noop
} else {
  IN_NODE = true
  ContextObject = require('./context_object')
}

var DELETION_FLAG = -1

function Context(uuid, definition_class) {
  this.uuid = uuid

  this.id_counter = 0

  this.objects = {}

  this.definition_class = definition_class
}

Context.prototype.clean = function() {
  for(var key in this.objects) {
    this.objects[key].__dirty__ = {}
  }
}

Context.prototype.create_object = function(definition) {
  var id = ++this.id_counter
    , uuid = this.uuid+':'+id
    , obj

  obj = new ContextObject(definition, uuid)
  this.objects[uuid] = obj
  return obj
}

Context.prototype.recv_object = function(definition_id, uuid) {
  obj = new ContextObject((this.definition_class || Definition).lookup(definition_id), uuid)
  this.objects[uuid] = obj
  return obj
}

Context.prototype.pretty = function() {
  var self = this
  return Object.keys(self.objects).map(function(key) {
    var out = self.objects[key].pretty()
    out.ID = key
    return out
  })
}

Context.prototype.create_full_update = function() {
  var payload = {}
    , def
    , deleted
    , item

  for(var i = 0, all=Object.keys(this.objects), len = all.length; item=this.objects[all[i]], i < len; ++i) {
    def = item.__definition__

    deleted = item.__deleted__
    if(!deleted)
      payload[all[i]] = [item.__definition__.id, item.send_update(true)]
  }

  return payload
}

Context.prototype.create_update = function(for_context, full) {
  if(full) return this.create_full_update()

  var payload = {}
    , def
    , deleted
    , item
    , valid = false

  for(var i = 0, all=Object.keys(this.objects), len = all.length; item=this.objects[all[i]], i < len; ++i) {
    def = item.__definition__

    deleted = item.__deleted__
    if(def.is_authoritative(this, for_context)) {
      if(deleted) {
        payload[all[i]] = [item.__definition__.id, DELETION_FLAG]
        valid = true
      } else {
        var item_update = item.send_update()
        if(item_update.length) {
          payload[all[i]] = [item.__definition__.id, item_update]
          valid = true
        }
      }

    }
    if(deleted) {
      delete this.objects[all[i]]
    }
  }
  if(!valid) return

  return payload
}

Context.prototype.recv_update = function(payload, from_context) {
  for(var i = 0, all=Object.keys(payload), len = all.length, key; key = all[i], i < len; ++i) {
    var def = (this.definition_class || Definition).lookup(payload[key][0])

    // only apply updates from authoritative contexts.
    if(from_context === this || def.is_authoritative(from_context, this)) {
      if(!this.objects[key]) {
        // create a new object matching the incoming uuid, looking up the definition in the process
        this.recv_object(payload[key][0], key)
      }
      if(payload[key][1] === DELETION_FLAG) {
        // mark for deletion. will be deleted on the next update.
        this.objects[key].__deleted__ = true
      } else {
        this.objects[key].recv_update(payload[key][1], from_context)
      }
    }
  }
}

Context.prototype.find = function(name) {
  var self = this
    , out = []
  Object.keys(self.objects).forEach(function(key) {
    if(self.objects[key].__definition__.id === name)
      out.push(self.objects[key])
  })
  return out
}

Context.current = function() {
  return this.__context__
}

Context.set = function(ctxt) {
  this.__context__ = ctxt
}

if(typeof module !== 'undefined') {
  module.exports = Context
}


text:
package com.intel.analytics.bigdl.dllib.utils.tf.loaders

import com.intel.analytics.bigdl.dllib.tensor.Tensor
import com.intel.analytics.bigdl.dllib.utils.T
import com.intel.analytics.bigdl.dllib.utils.serializer.ModuleSerializationTest

import scala.util.Random

class MeanLoadTFSerialTest extends ModuleSerializationTest {
  override def test(): Unit = {
    val meanLoadTF = new MeanLoadTF[Float]("Float", false).setName("meanLoadTF")
    val input = T(Tensor[Float](1, 2).apply1(_ => Random.nextFloat()),
      Tensor[Int](T(1, 1)))
    runSerializationTest(meanLoadTF, input)
  }
}

redpajama_set_name: RedPajamaGithub


text:
* [Tips for negotiating salary and startup for newly-hired tenure-track faculty](https://dynamicecology.wordpress.com/2017/03/01/tips-for-negotiating-salary-and-startup-for-newly-hired-tenure-track-faculty/)

* [Ten Simple Rules to becoming a principal investigator](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1007448)

Some resources for faculty postion application and grants writing.

* [A list of publicly available grant proposals in the biological sciences](https://jabberwocky.weecology.org/2012/08/10/a-list-of-publicly-available-grant-proposals-in-the-biological-sciences/)

* [My faculty job application materials](http://pgbovine.net/faculty-job-application-materials.htm) from Philip J Guo, a faculty at UCSD.

* [applying for a faculty position](http://effortreport.libsyn.com/15-applying-for-a-faculty-position) by Roger Peng.

* [How to Turn A "Good" Proposal Into An "Excellent" Proposal in Eight Admittedly Arduous Steps](https://hopejahrensurecanwrite.com/2014/06/02/how-to-turn-a-good-proposal-into-an-excellent-proposal-in-eight-admittedly-arduous-steps/)

* [Ten simple rules for structuring papers](http://biorxiv.org/content/early/2016/11/28/088278)
* [open grant](https://www.ogrants.org/) find other people's grants.

* [The CommKit](http://mitcommlab.mit.edu/broad/use-the-commkit/) is a collection of guides to successful communication in the biological sciences, written by the BRCL Fellows.

*

In 2004, my postdoc advisor @DaphnePreuss asked me to write a 1page paper writing guide for the lab, from an advisee point of view (udpated) pic.twitter.com/9akUIOjtNs
— Ravi Palanivelu (@rpalaniveluaz) March 6, 2017

![](https://github.com/crazyhottommy/The-world-of-faculty/blob/master/paper-writing-guide.jpg)

### Stay in the current of literatures.

* [Pubchase](https://www.pubchase.com/)
* [SciReader](http://www.scireader.org)
* [meta](https://meta.org/)
* [citeulike](http://www.citeulike.org/)
* [semanticscholoar](https://www.semanticscholar.org/) managed by Allen Institute for Artificial Intelligence
.
### submit to journals and funding agencies

* [writing in sciences stanford online course](https://www.coursera.org/learn/sciwrite/)
* [AuthorArranger: Conquer journal title pages in seconds](https://authorarranger.nci.nih.gov/#/)
* [typeset](https://www.typeset.io/) Adhering to fuzzy journal guidelines is every researcher's nightmare. Not anymore!
Introducing Typeset - an intelligent editor that lets you automatically format or re-format to over 14,000 journals with 100% compliance. No fuss. And that's just the beginning...
* [NIH grant podcasts](https://grants.nih.gov/news/virtual-learning/podcasts.htm)
* [how to write a K99](https://k99.sbamin.com/) by Samir Amin (my good buddy). Go and check out this treasure.
* [seeking the k99](https://timoast.github.io/blog/seeking-the-k99/) a blog post by Tim Stuart.
* [citeomatic](http://labs.semanticscholar.org/citeomatic/) find other relative citations you may miss.

* How to write a proposal

![](https://github.com/crazyhottommy/The-world-of-faculty/blob/master/proposal.jpg)

* [cocites](http://www.cocites.com/)
* [connected papers](https://www.connectedpapers.com/)
* [Citeomatic](http://labs.semanticscholar.org/citeomatic/)  finds new citations for you.
* [Ten simple rules for structuring papers](http://www.biorxiv.org/content/early/2017/05/23/088278)
* [NIC guide](https://www.niaid.nih.gov/grants-contracts/write-research-plan)
* [Thoughts on reviewing NIH proposals: What is the difference between a 2.0 and 3.0 in initial score?](http://mistressoftheanimals.scientopia.org/2018/02/10/thoughts-on-reviewing-nih-proposals-what-is-the-difference-between-a-2-0-and-3-0-in-initial-score/) a blog post.

* [ZoteroBib](https://zbib.org/) is a free service that helps you quickly create a bibliography in any citation style.

* [How to craft a figure legend for scientific papers](https://blog.bioturing.com/2018/05/10/how-to-craft-a-figure-legend-for-scientific-papers/)

### Time planning
* [Time is Citations: How I Plan My Days](https://olgabotvinnik.com/blog/time-is-citations/) A post by Olga Botvinnik in  UCSD on how she manages her day. I learned a lot!

* [how to manage a lab](http://www.labmanager.com/management-tips)

### review a paper

* https://github.com/jtleek/reviews by Jeff Leek.
* [A Guide to Responding to Scientific Peer Review](https://jef.works/blog/2020/06/17/responding-to-scientific-peer-review/) by Jean Fan.

### Data plan
* ["All you need to know about data management plans"](https://zenodo.org/record/803756#.WWelz9PyvUo) - workshop for Principal Investigators in Bioinformatics
### Teaching
* [How to Teach Programming (And Other Things)](http://third-bit.com/2017/05/31/how-to-teach-programming.html) by Greg Wilson.
* [Teaching Tech Together](http://teachtogether.tech/) by Greg Wilson as well.

### fundings

* [Early Career Funding, Awards, and Other Funding](https://docs.google.com/spreadsheets/d/1H1aj--VUYr7eMFk_T7x0Oh985LqbyyscXg2wAAevDnU/edit#gid=0)
* https://ecrcentral.org/resources
* [Funding schemes for postdoctoral fellowships](https://asntech.github.io/postdoc-funding-schemes/)
* [Postdoctoral Funding Opportunities by Johns Hopkins](https://research.jhu.edu/rdt/funding-opportunities/postdoctoral/)
* [Early Career Funding Opportunities by Johns Hopkins](https://research.jhu.edu/rdt/funding-opportunities/early-career/)

### manage a lab

* [Ten quick tips for making things findable](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1008469)
* [Making experimental data tables in the life sciences more FAIR: a pragmatic approach](https://academic.oup.com/gigascience/article/9/12/giaa144/6034785)
* protocols: https://www.protocols.io/
* [electronic lab notebooks review by Harvard HMS](https://datamanagement.hms.harvard.edu/electronic-lab-notebooks)
* [Rspace](https://www.researchspace.com/) Next-gen Elab notebook.
* [How to grow a healthy lab](https://www.nature.com/collections/pmlcrkkyyq)  Nature collections
* [Bench Sci](https://www.benchsci.com/) Run Successful Experiments with the Right Antibody. Let our AI decode the literature to provide antibody usage data that's unbiased and experiment-specific

### collabration

* Rule #1: Say no unless you are excited. ---Credits to Shirley Liu and Stan Gu.
* [The ASCCR Frame for Learning Essential Collaboration Skills](https://www.semanticscholar.org/paper/Essential-Collaboration-Skills%3A-The-ASCCR-Frame-for-Vance-Smith/8ddb0800fbf0a43e343809f9df92fe622b25f3f5)

### recruiting

### training

* [Ten simple rules for making training materials FAIR](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1007854)

### conferences

* [Conferences & Schools 2019](https://generegulation.org/conferences-2019/)
* [conferences by nextgenseek](http://nextgenseek.com/ngs-conferences/)

###  collaborative writing

* [Synchronized editing: the future of collaborative writing](https://www.nature.com/articles/d41586-020-00916-6)
* [manuscripts](https://www.manuscripts.io/about/)
* [Open collaborative writing with Manubot](https://manubot.org/)
* google doc + paperpile

### digital tools for organizing a computational biology lab

collected from this twitter thread https://twitter.com/tangming2005/status/1230568527033012225

* [basecamp](https://basecamp.com/) for tracking progress of projects. Github integration using [zapier](https://zapier.com/home)

"We use Basecamp in my lab, with GitHub integration via Zapier" -- Naupaka Zimmerman

"We use basecamp at HBC, it helps to track progress, n communicate with collaborator. For code tracking we use github. Though for my personal use, I hv jupyter notebook for code, Evernote for docs,and full Analysis I build docker for each project. This gives me peace" -- Preeti Aahir

* [github + zenhub](https://www.zenhub.com/) project management for github.
"We're trying out gitbook for the group documentation and working policies, etc. In addition, we use @ZenHub
 because of its tight GitHub integration to track projects" -- Moritz E. Beber

* [trello](https://trello.com/en-US) group working, organize projects.

"I use Trello for organisation and push my collaborators to use it. It helps keeping tasks, code, input, output & comments organised. We have common conda envs on the cluster and a place to store scripts. GitHub would be better for scripts but it's a lot to learn for some people."

"But I think that everything could be moved to @trello with a github integration and links to input data on shared folders on the HPC (so that large files are not stored on the Trello boards). Also it's free (compared to http://Monday.com)."

--Gautier Richard

* [Notion](https://www.notion.so/) All-in-one workspace.
"We have a general lab section with boards for expectations, on boarding, and getting started with the HPC. Each trainee then has their own long term goals boards and separate projects board." -- Nicholas Mancuso

* [github wiki](https://help.github.com/en/github/building-a-strong-community/about-wikis) for documenting projects.

"Recently commenced attempt at this is to use a github repo with the wiki as the guide (onboard routines), and possibly the repo itself for useful scripts" --Kieran Campbell

* [gitbook](https://www.gitbook.com/) for other documenting purposes. onboard routine: e.g. HPC setup. pipeline running.

"We're trying out gitbook for the group documentation and working policies, etc. In addition, we use @ZenHub
 because of its tight GitHub integration to track projects" -- Moritz E. Beber

* [electronic lab notebooks](https://datamanagement.hms.harvard.edu/electronic-lab-notebooks) wetlab usage as well.

* [knowlege repo from airbnb](https://github.com/airbnb/knowledge-repo)
"We are deploying airbnb's knowledge repo as proof of concept and are enjoying it so far. Let me know what you think!" -- An Hoang.

* [discord to replace slack?](https://discordapp.com/)

* [super-productivity](https://github.com/johannesjo/super-productivity) Free to do list & time tracker for programmers & designers with Jira integration.
read https://bioinformaticsworkbook.org/projectManagement/Intro_projectManagement
and https://olgabotvinnik.com/blog/time-is-citations/

* [The Beginner's Guide To Scrum And Agile Project Management](https://blog.trello.com/beginners-guide-scrum-and-agile-project-management)


text:
"""Tests for the Abode light device."""
from unittest.mock import patch

from homeassistant.components.abode import ATTR_DEVICE_ID
from homeassistant.components.light import (
    ATTR_BRIGHTNESS,
    ATTR_COLOR_TEMP,
    ATTR_RGB_COLOR,
    DOMAIN as LIGHT_DOMAIN,
)
from homeassistant.const import (
    ATTR_ENTITY_ID,
    ATTR_FRIENDLY_NAME,
    ATTR_SUPPORTED_FEATURES,
    SERVICE_TURN_OFF,
    SERVICE_TURN_ON,
    STATE_ON,
)

from .common import setup_platform

DEVICE_ID = "light.living_room_lamp"

async def test_entity_registry(hass):
    """Tests that the devices are registered in the entity registry."""
    await setup_platform(hass, LIGHT_DOMAIN)
    entity_registry = await hass.helpers.entity_registry.async_get_registry()

    entry = entity_registry.async_get(DEVICE_ID)
    assert entry.unique_id == "741385f4388b2637df4c6b398fe50581"

async def test_attributes(hass):
    """Test the light attributes are correct."""
    await setup_platform(hass, LIGHT_DOMAIN)

    state = hass.states.get(DEVICE_ID)
    assert state.state == STATE_ON
    assert state.attributes.get(ATTR_BRIGHTNESS) == 204
    assert state.attributes.get(ATTR_RGB_COLOR) == (0, 63, 255)
    assert state.attributes.get(ATTR_COLOR_TEMP) == 280
    assert state.attributes.get(ATTR_DEVICE_ID) == "ZB:db5b1a"
    assert not state.attributes.get("battery_low")
    assert not state.attributes.get("no_response")
    assert state.attributes.get("device_type") == "RGB Dimmer"
    assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Living Room Lamp"
    assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 19

async def test_switch_off(hass):
    """Test the light can be turned off."""
    await setup_platform(hass, LIGHT_DOMAIN)

    with patch("abodepy.AbodeLight.switch_off") as mock_switch_off:
        assert await hass.services.async_call(
            LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: DEVICE_ID}, blocking=True
        )
        await hass.async_block_till_done()
        mock_switch_off.assert_called_once()

async def test_switch_on(hass):
    """Test the light can be turned on."""
    await setup_platform(hass, LIGHT_DOMAIN)

    with patch("abodepy.AbodeLight.switch_on") as mock_switch_on:
        await hass.services.async_call(
            LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: DEVICE_ID}, blocking=True
        )
        await hass.async_block_till_done()
        mock_switch_on.assert_called_once()

async def test_set_brightness(hass):
    """Test the brightness can be set."""
    await setup_platform(hass, LIGHT_DOMAIN)

    with patch("abodepy.AbodeLight.set_level") as mock_set_level:
        await hass.services.async_call(
            LIGHT_DOMAIN,
            SERVICE_TURN_ON,
            {ATTR_ENTITY_ID: DEVICE_ID, "brightness": 100},
            blocking=True,
        )
        await hass.async_block_till_done()
        # Brightness is converted in abode.light.AbodeLight.turn_on
        mock_set_level.assert_called_once_with(39)

async def test_set_color(hass):
    """Test the color can be set."""
    await setup_platform(hass, LIGHT_DOMAIN)

    with patch("abodepy.AbodeLight.set_color") as mock_set_color:
        await hass.services.async_call(
            LIGHT_DOMAIN,
            SERVICE_TURN_ON,
            {ATTR_ENTITY_ID: DEVICE_ID, "hs_color": [240, 100]},
            blocking=True,
        )
        await hass.async_block_till_done()
        mock_set_color.assert_called_once_with((240.0, 100.0))

async def test_set_color_temp(hass):
    """Test the color temp can be set."""
    await setup_platform(hass, LIGHT_DOMAIN)

    with patch("abodepy.AbodeLight.set_color_temp") as mock_set_color_temp:
        await hass.services.async_call(
            LIGHT_DOMAIN,
            SERVICE_TURN_ON,
            {ATTR_ENTITY_ID: DEVICE_ID, "color_temp": 309},
            blocking=True,
        )
        await hass.async_block_till_done()
        # Color temp is converted in abode.light.AbodeLight.turn_on
        mock_set_color_temp.assert_called_once_with(3236)


text:
package gov.hhs.fha.nhinc.adapter.deferred.queue.gui;

import com.sun.webui.jsf.model.Option;
import gov.hhs.fha.nhinc.asyncmsgs.model.AsyncMsgRecord;
import com.sun.rave.web.ui.appbase.AbstractSessionBean;
import java.util.ArrayList;
import java.util.List;
import javax.faces.FacesException;

/**
 *
 * @author richard.ettema
 */
public class UserSession extends AbstractSessionBean {

    private String authToken;

    public String getAuthToken() {
        return authToken;
    }

    public void setAuthToken(String authToken) {
        this.authToken = authToken;
    }

    private boolean authenticationServiceAvail;

    public boolean isAuthenticationServiceAvail() {
        return authenticationServiceAvail;
    }

    public void setAuthenticationServiceAvail(boolean authenticationServiceAvail) {
        this.authenticationServiceAvail = authenticationServiceAvail;
    }

    private void _init() throws Exception {
    }

    /** Creates a new instance of UserSession */
    public UserSession() {
    }

    /**
     *

     * This method is called when this bean is initially added to session scope. Typically, this occurs as a result of
     * evaluating a value binding or method binding expression, which utilizes the managed bean facility to instantiate
     * this bean and store it into session scope.
     *

     *
     *

     * You may customize this method to initialize and cache data values or resources that are required for the lifetime
     * of a particular user session.
     *

     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("UserSession Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
    }

    /**
     *

     * This method is called when the session containing it is about to be passivated. Typically, this occurs in a
     * distributed servlet container when the session is about to be transferred to a different container instance,
     * after which the activate() method will be called to indicate that the transfer is complete.
     *

     *
     *

     * You may customize this method to release references to session data or resources that can not be serialized with
     * the session itself.
     *

     */
    @Override
    public void passivate() {
    }

    /**
     *

     * This method is called when the session containing it was reactivated.
     *

     *
     *

     * You may customize this method to reacquire references to session data or resources that could not be serialized
     * with the session itself.
     *

     */
    @Override
    public void activate() {
    }

    /**
     *

     * This method is called when this bean is removed from session scope. Typically, this occurs as a result of the
     * session timing out or being terminated by the application.
     *

     *
     *

     * You may customize this method to clean up resources allocated during the execution of the init()
     * method, or at any later time during the lifetime of the application.
     *

     */
    @Override
    public void destroy() {
    }

    private List<AsyncMsgRecord> processQueueResults;
    private List<AsyncMsgRecord> unProcessQueueResults;
    private List<Option> statusItems;

    public List<AsyncMsgRecord> getProcessQueueResults() {
        if (processQueueResults == null) {
            processQueueResults = new ArrayList<AsyncMsgRecord>();
        }
        return processQueueResults;
    }

    public void setProcessQueueResults(List<AsyncMsgRecord> processQueueResults) {
        this.processQueueResults = processQueueResults;
    }

    public List<AsyncMsgRecord> getUnProcessQueueResults() {
        if (unProcessQueueResults == null) {
            unProcessQueueResults = new ArrayList<AsyncMsgRecord>();
        }
        return unProcessQueueResults;
    }

    public void setUnProcessQueueResults(List<AsyncMsgRecord> unProcessQueueResults) {
        this.unProcessQueueResults = unProcessQueueResults;
    }

    public List<Option> getStatusItems() {
        if (statusItems == null) {
            statusItems = new ArrayList<Option>();
        }
        return statusItems;
    }

    public void setStatusItems(List<Option> statusItems) {
        this.statusItems = statusItems;
    }
}


text:
from __future__ import unicode_literals

import struct

from c1218.errors import C1218ReadTableError, C1218WriteTableError
from c1219.constants import C1219_METER_MODE_NAMES, C1219_PROC_RESULT_CODES
from c1219.errors import C1219ProcedureError
from termineter.module import TermineterModuleOptical

class Module(TermineterModuleOptical):
	def __init__(self, *args, **kwargs):
		TermineterModuleOptical.__init__(self, *args, **kwargs)
		self.author = ['Spencer McIntyre']
		self.description = 'Change the Meter\'s Operating Mode'
		self.detailed_description = 'Change the operating mode of the meter. Accepted values for MODE are METERING, TEST, METERSHOP, and FACTORY.'
		self.options.add_string('MODE', 'the mode to set the meter to', True)

	def run(self):
		conn = self.frmwk.serial_connection
		logger = self.logger
		mode = self.options['MODE']
		mode = mode.upper()
		mode = mode.replace('_', '')
		mode = mode.replace(' ', '')
		if mode[-4:] == 'MODE':
			mode = mode[:-4]
		mode_dict = C1219_METER_MODE_NAMES
		if not mode in mode_dict:
			self.frmwk.print_error('unknown mode, please use METERING, TEST, METERSHOP, or FACTORY')
			return

		logger.info('setting mode to: ' + mode)
		self.frmwk.print_status('Setting Mode To: ' + mode)

		mode = mode_dict[mode]
		try:
			result_code, response_data = conn.run_procedure(6, False, struct.pack('B', mode))
		except C1218ReadTableError as error:
			self.frmwk.print_exception(error)
			return
		except C1218WriteTableError as error:
			if error.code == 4:  # onp/operation not possible
				self.frmwk.print_error('Meter responded that it can not set the mode to the desired type')
			else:
				self.frmwk.print_exception(error)
			return
		except C1219ProcedureError as error:
			self.frmwk.print_exception(error)
			return

		if result_code < 2:
			self.frmwk.print_good(C1219_PROC_RESULT_CODES[result_code])
		else:
			self.frmwk.print_error(C1219_PROC_RESULT_CODES.get(result_code, "Unknown status code: {0}".format(result_code)))


text:
import re
import os
import functools
import pkg_resources

from pkgtools.pypi import PyPIXmlRpc

from pyg.vcs import vcs
from pyg.log import logger
from pyg.req import Requirement
from pyg.pack import Packer
from pyg.freeze import freeze, list_releases, site_info
from pyg.core import PygError, Version, args_manager
from pyg.inst import Installer, Uninstaller, Updater, Bundler
from pyg.utils import TempDir, is_installed, unpack
from pyg.web import ReqManager

def check_permissions(dir):
    if not os.path.exists(dir):
        logger.fatal('Error: installation directory {0} does not exist', dir, exc=PygError)
    try:
        path = os.path.join(dir, 'pyg-permissions-test.pth')
        with open(path, 'w'):
            pass
        os.remove(path)
    ## FIXME: Do we need OSError too?
    except (IOError, OSError):
        return False
    else:
        return True

def check_and_exit():
    dir = os.path.abspath(args_manager['install']['install_dir'])
    if not check_permissions(dir):
        logger.exit('''Pyg cannot create new files in the installation directory.
Installation directory was:

    {0}

Perhaps your account does not have write access to this directory?  If the
installation directory is a system-owned directory, you may need to sign in
as the administrator or "root" account.  If you do not have administrative
access to this machine, you may wish to choose a different installation
directory, preferably one that is listed in your PYTHONPATH environment
variable.

If you need further information about Pyg command-line options visit:

    http://pyg.readthedocs.org/en/latest/cmdline.html
or
    http://pyg-installer.co.nr
'''.format(dir))

def _install_package_from_name(package, ignore=False):
    if os.path.exists(package) and not ignore:
        path = os.path.abspath(package)
        logger.info('Installing {0}', path)
        if os.path.isfile(path):
            return Installer.from_file(path)
        elif os.path.isdir(path):
            if not os.path.exists(os.path.join(path, 'setup.py')):
                raise PygError('{0} must contain the setup.py file', path)
            return Installer.from_dir(path)
        else:
            raise PygError('Cannot install the package: {0} is neither a file nor a directory', path)
    if package.startswith(('http://', 'https://')):
        return Installer.from_url(package)
    for s in ('git+', 'hg+', 'bzr+', 'svn+'):
        if package.startswith(s):
            with TempDir() as tempdir:
                return vcs(package, tempdir).install()
    return Installer(package).install()

def install_func(packname, req_file, editable, ignore):
    check_and_exit()
    if editable:
        if len(packname) > 1:
            logger.error('Error: Unable to install multiple packages in editable mode')
            return
        package = packname[0]
        if os.path.exists(os.path.abspath(package)):
            package = 'dir+{0}#egg={1}'.format(os.path.abspath(package),
                                               os.path.basename(package))
        return vcs(package).develop()
    if req_file:
        logger.info('Installing from requirements file')
        for rq in req_file:
            Installer.from_req_file(os.path.abspath(rq))
        return
    if packname:
        for package in packname:
            _install_package_from_name(package, ignore)

def remove_func(packname, req_file, yes, info, local):
    uninstaller = functools.partial(Uninstaller, yes=yes, local=local)
    if info:
        for p in packname:
            logger.info('{0}:', p)
            files = uninstaller(p).find_files()
            logger.indent = 8
            for path in files:
                logger.info(path)
            logger.indent = 0
        return
    check_and_exit()
    ## Little Easter egg...
    if len(packname) == 1 and packname[0] == 'yourself':
        return uninstaller('pyg').uninstall()
    if req_file:
        with open(os.path.abspath(req_file)) as f:
            for line in f:
                try:
                    uninstaller(line.strip()).uninstall()
                except PygError:
                    continue
    for p in packname:
        try:
            uninstaller(p).uninstall()
        except PygError:
            continue

def check_func(name, info=False):
    INFO = '{0.project_name} - {0.version}\nInstalled in {0.location}'
    if not info:
        logger.info(is_installed(name))
        return
    if info:
        try:
            dist = pkg_resources.get_distribution(name)
            logger.info(INFO.format(dist))
        except pkg_resources.DistributionNotFound:
            logger.info(False)

def site_func(count, no_info, file):
    f = freeze()
    if count:
        logger.info(str(len(f)))
        return
    f = '\n'.join(f)
    if not no_info:
        f = site_info() + f
    if file:
        with open(os.path.abspath(file), 'w') as req_file:
            req_file.write(f)
    return logger.info(f)

def list_func(name):
    res = []
    for v, inst in list_releases(name):
        if inst:
            res.append(v + '\tinstalled')
        else:
            res.append(v)
    return logger.info('\n'.join(res))

def search_func(query, exact, show_all_version, max_num):
    def _pypi_order(item):
        # this is the old implementation, that looks buggy (try on "sphinx")
        return item['_pypi_ordering']

    def _pkgresources_order(item):
        return (item[0],) +  item[2].v

    res = sorted(PyPIXmlRpc(index_url=args_manager['install']['index_url']).search({'name': query, 'summary': query}, 'or'))
    processed = {}
    for release in res:
        name, version, summary = release['name'], Version(release['version']), release['summary']

        ## We have already parsed a different version
        if name in processed:
            if show_all_version:
                processed[name].append((version, summary))
            elif version > processed[name][0][0]:
                processed[name] = [(version, summary)]
            continue
        ## This is the first time
        processed[name] = [(version, summary)]

    pattern = re.compile('$|'.join(query) + '$')
    results = []
    for name, values in processed.iteritems():
        try:
            _installed = Version(pkg_resources.get_distribution(name).version)
        except pkg_resources.DistributionNotFound:
            _installed = None
        except Exception:
            logger.warn('WARN: Cannot get package data for {0!r}', name)
            _installed = None
        if exact:
            if pattern.match(name) is None:
                continue

        for version in values:
            if not _installed:
                dec = ''
            elif _installed == version[0]:
                dec = '@'
            else:
                dec = '*'
            results.append((name, dec, version[0], version[1]))

    results = sorted(results, key=_pkgresources_order)
    results = results[:max_num or len(results)]
    output = '\n'.join('{0}  {1}{2} - {3}'.format(name, dec, version, summary) for name, dec, version, summary in results)
    return logger.info(output)

def download_func(args):
    pref = None
    if args.prefer:
        pref = ['.' + args.prefer.strip('.')]
    name = args.packname
    dest = args_manager['download']['download_dir']
    unpk = args_manager['download']['unpack']
    downloader = ReqManager(Requirement(name), pref)
    if args_manager['download']['dry']:
        res = downloader.download(None)
    else:
        res = downloader.download(dest)

    if args_manager['download']['md5']:
        for dl in res:
            logger.info('%(url)s md5: %(hash)s'%dl)
    if downloader.downloaded_name is None:
        logger.fatal('Error: Did not find any files for {0}', name, exc=PygError)
    if unpk:
        path = os.path.abspath(downloader.downloaded_name)
        logger.info('Unpacking {0} to {1}', os.path.basename(path), os.getcwd())
        unpack(path)

def update_func():
    check_and_exit()
    up = Updater()
    up.update()

def bundle_func(packages, bundlename, exclude, req_file, develop):
    def get_reqs(path):
        path = os.path.abspath(path)
        reqs = set()
        with open(path) as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith('#'):
                    continue
                reqs.add(line)
        return reqs
    if not packages and not req_file:
        logger.fatal('Error: You must specify at least one package', exc=PygError)
    reqs = []
    if req_file:
        reqs = [Requirement(r) for f in req_file for r in get_reqs(f)]
    exclude = [Requirement(r) for r in (exclude or [])]
    bundlename = os.path.abspath(bundlename)
    dest, bundlename = os.path.dirname(bundlename), os.path.basename(bundlename)
    b = Bundler(map(Requirement, packages) + reqs, bundlename, exclude, use_develop=develop)
    b.bundle(dest=dest)

def pack_func(package, packname, exclude, use_develop):
    packname = os.path.abspath(packname)
    dest, packname = os.path.dirname(packname), os.path.basename(packname)
    exclude = [Requirement(r) for r in (exclude or [])]
    Packer(Requirement(package), packname, dest).gen_pack(exclude, use_develop)

def completion_func(commands, file):
    code = '''_pyg()
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts=%r
    COMPREPLY=($(compgen -W "${opts}" -- "${cur}"))
}

complete -o default -F _pyg pyg'''

    code %= ' '.join(commands)

    if not file:
        return logger.info(code)

    dir = os.path.dirname(file)
    # permissions test
    try:
        path = os.path.join(dir, 'pyg-test')
        with open(path, 'w') as f:
            f.write('pyg test')
        os.remove(path)
    except IOError:
        logger.fatal('Pyg cannot write files into {0}.\nTry to run it with root privileges.', dir, exc=PygError)

    with open(file, 'a') as f:
        f.write('\n{0}\n'.format(code))
    os.system('source %s' % (file))

def shell_func():
    check_and_exit()

    from pyg.parser.shell import PygShell
    PygShell().cmdloop()


text:
namespace base {
namespace sequence_manager {

// TaskTimeObserver provides an API for observing completion of tasks.
class TaskTimeObserver {
 public:
  TaskTimeObserver() = default;
  TaskTimeObserver(const TaskTimeObserver&) = delete;
  TaskTimeObserver& operator=(const TaskTimeObserver&) = delete;
  virtual ~TaskTimeObserver() = default;

  // To be called when task is about to start.
  virtual void WillProcessTask(TimeTicks start_time) = 0;

  // To be called when task is completed.
  virtual void DidProcessTask(TimeTicks start_time, TimeTicks end_time) = 0;
};

}  // namespace sequence_manager
}  // namespace base

#endif  // BASE_TASK_SEQUENCE_MANAGER_TASK_TIME_OBSERVER_H_


text:
<dependencies>
  <androidPackages>
    <androidPackage spec="com.google.ads.mediation:verizonmedia:1.14.0.1">
      <repositories>
        <repository>https://artifactory.verizonmedia.com/artifactory/maven/</repository>
        <repository>https://dl.google.com/dl/android/maven2/</repository>
      </repositories>
    </androidPackage>
  </androidPackages>

  <iosPods>
    <iosPod name="GoogleMobileAdsMediationVerizonMedia" version="1.14.1.1">
      <sources>
        <source>https://github.com/CocoaPods/Specs</source>
      </sources>
    </iosPod>
  </iosPods>
</dependencies>


text:
package edu.usu.sdl.describe.model;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
 *
 * @author dshurtleff
 */
@Root(name = "HandlingAssertion",  strict = false)
public class HandlingAssertion
{
	@Attribute(required = false)
	private String scope;

	@Element(name = "HandlingStatement", required = false)
	private HandlingStatement handlingStatement;

	public HandlingAssertion()
	{
	}

	public HandlingStatement getHandlingStatement()
	{
		return handlingStatement;
	}

	public void setHandlingStatement(HandlingStatement handlingStatement)
	{
		this.handlingStatement = handlingStatement;
	}

	public String getScope()
	{
		return scope;
	}

	public void setScope(String scope)
	{
		this.scope = scope;
	}

}


text:
"use strict";

class StatTracker {

    constructor(statService) {
        this.statService = statService;
    }

    message(message) {

        if (!message.subtype && message.text) {
            this.statService.addMessage(message.user);
        }
    }

    reaction(reaction) {

        if (reaction.item_user !== reaction.user) {
            this.statService.addReaction(reaction.item_user);
        }
    }
}

const RTM_EVENTS = require('@slack/client').RTM_EVENTS;

module.exports = {
    name: 'statTracker',
    dependencies: ['statService'],
    factory: statService => new StatTracker(statService),
    events: [
        {
            name: RTM_EVENTS.MESSAGE,
            invoker: (statTracker, message) => statTracker.message(message)
        },
        {
            name: RTM_EVENTS.REACTION_ADDED,
            invoker: (statTracker, reaction) => statTracker.reaction(reaction)
        }
    ],
    author: 'chriscaruso'
};


text:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

/* Standard header files */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>

/* CPE */
#include <cpe_name.h>
#include <cpe_dict.h>
#include <cpe_lang.h>
#include <oscap_source.h>

#include "oscap-tool.h"

static struct oscap_module* CPE_SUBMODULES[];
bool getopt_cpe(int argc, char **argv, struct oscap_action *action);
int app_cpe_check(const struct oscap_action *action);
int app_cpe_match(const struct oscap_action *action);
int app_cpe_validate(const struct oscap_action *action);

struct oscap_module OSCAP_CPE_MODULE = {
    .name = "cpe",
    .parent = &OSCAP_ROOT_MODULE,
    .summary = "Common Platform Enumeration",
    .submodules = CPE_SUBMODULES
};

static struct oscap_module CPE_MATCH_MODULE = {
    .name = "match",
    .parent = &OSCAP_CPE_MODULE,
    .summary = "Match CPE name against provided dictionary",
    .usage = "name dictionary.xml",
    .help = NULL,
    .opt_parser = getopt_cpe,
    .func = app_cpe_match
};

static struct oscap_module CPE_CHECK_MODULE = {
    .name = "check",
    .parent = &OSCAP_CPE_MODULE,
    .summary = "Check if CPE name is valid",
    .usage = "name",
    .help = NULL,
    .opt_parser = getopt_cpe,
    .func = app_cpe_check
};

static struct oscap_module CPE_VALIDATE_XML = {
    .name = "validate-xml",
    .parent = &OSCAP_CPE_MODULE,
    .summary = "Validate CPE Dictionary content",
    .usage = "cpe-dict.xml",
    .help = NULL,
    .opt_parser = getopt_cpe,
    .func = app_cpe_validate
};

static struct oscap_module CPE_VALIDATE = {
    .name = "validate",
    .parent = &OSCAP_CPE_MODULE,
    .summary = "Validate CPE Dictionary content",
    .usage = "cpe-dict.xml",
    .help = NULL,
    .opt_parser = getopt_cpe,
    .func = app_cpe_validate
};

static struct oscap_module* CPE_SUBMODULES[] = {
    &CPE_MATCH_MODULE,
    &CPE_CHECK_MODULE,
    &CPE_VALIDATE,
    &CPE_VALIDATE_XML,
    NULL
};

bool getopt_cpe(int argc, char **argv, struct oscap_action *action) {

	if( (action->module == &CPE_MATCH_MODULE) ) {
		if(  argc != 5 ) {
			oscap_module_usage(action->module, stderr, "Wrong number of parameters.\n");
			return false;
		}
		action->cpe_action = malloc(sizeof(struct cpe_action));
		action->cpe_action->name=argv[3];
		action->cpe_action->dict=argv[4];
	}

	if( (action->module == &CPE_CHECK_MODULE)) {
		if( argc != 4 ) {
			oscap_module_usage(action->module, stderr, "Wrong number of parameters.\n");
			return false;
		}
		action->cpe_action = malloc(sizeof(struct cpe_action));
		action->cpe_action->name=argv[3];
	}

	if ((action->module == &CPE_VALIDATE) || action->module == &CPE_VALIDATE_XML) {
		if( argc != 4 ) {
			oscap_module_usage(action->module, stderr, "Wrong number of parameters.\n");
			return false;
		}

		action->cpe_action = malloc(sizeof(struct cpe_action));
		action->cpe_action->dict=argv[3];
	}

	return true;
}

int app_cpe_check(const struct oscap_action *action) {
	int ret;

	if (!cpe_name_check(action->cpe_action->name)) {
		fprintf(stdout,"'%s' is NOT Valid CPE name.\n", action->cpe_action->name);
		ret = OSCAP_FAIL;
	}
	else {
		fprintf(stdout,"'%s' is Valid CPE name.\n", action->cpe_action->name);
		ret = OSCAP_OK;
	}
	free(action->cpe_action);
	return ret;
}

int app_cpe_match(const struct oscap_action *action) {

	int ret;
	struct cpe_name *candidate_cpe = NULL;
        struct cpe_dict_model *dict = NULL;

	struct oscap_source *source = NULL;

        /* is CPE well formated? */
        if( ! cpe_name_check(action->cpe_action->name) ) {
                fprintf(stdout, "%s is not in valid CPE format.\n", action->cpe_action->name);
		ret = OSCAP_ERROR;
                goto clean;
        }
        candidate_cpe = cpe_name_new(action->cpe_action->name);

        /* load dictionary */
	source = oscap_source_new_from_file(action->cpe_action->dict);
	if( (dict = cpe_dict_model_import_source(source)) == NULL ) {
                fprintf(stdout, "can't load CPE dictionary from: %s.\n", action->cpe_action->dict);
		ret = OSCAP_ERROR;
                goto clean;
        }

	/* matching */
        if( cpe_name_match_dict(candidate_cpe, dict) ) {
        	fprintf(stdout, "The exact CPE match is found.\n");
		ret = OSCAP_OK;
	}
        else {
                fprintf(stdout, "No match found.\n");
		ret = OSCAP_FAIL;
	}

        /* clean up */
clean:
        cpe_name_free(candidate_cpe);
        cpe_dict_model_free(dict);
	free(action->cpe_action);
	oscap_source_free(source);
	return ret;
}

int app_cpe_validate(const struct oscap_action *action) {

	int ret;
	int result;

	struct oscap_source *source = oscap_source_new_from_file(action->cpe_action->dict);
	ret = oscap_source_validate(source, reporter, (void *) action);
	oscap_source_free(source);

	if (ret==-1) {
		result=OSCAP_ERROR;
		goto cleanup;
	}
	else if (ret==1) {
		result=OSCAP_FAIL;
	}
	else {
		result=OSCAP_OK;
	}

cleanup:
	if (oscap_err())
		fprintf(stderr, "%s %s\n", OSCAP_ERR_MSG, oscap_err_desc());

	free(action->cpe_action);
	return result;
}


text:
package ai.elimu.model.analytics;

import ai.elimu.model.content.Word;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;

@Entity
public class WordLearningEvent extends LearningEvent {

    @ManyToOne
    private Word word;

    /**
     * A Word's text value is used as a fall-back if the Android application did not use a Word ID.
     */
//    @NotNull
    private String wordText;

    public Word getWord() {
        return word;
    }

    public void setWord(Word word) {
        this.word = word;
    }

    public String getWordText() {
        return wordText;
    }

    public void setWordText(String wordText) {
        this.wordText = wordText;
    }
}


text:
user=`whoami`
syncTo="/Users/${user}/Dropbox/ReadingList"
tmpFolder="/tmp/com.adamfaeth.readinglist/"

# Paths to papers libraries
library="/Users/${user}/Documents"
papers2="Papers2"
p2Lib="$library/$papers2/Library.papers2/Database.papersdb"

# Get flagged papers from the databases
p2Query="SELECT PDF.path FROM Publication INNER JOIN PDF on PDF.object_id=Publication.rowid  where Publication.flagged > 0;"

# fetch flagged papers and prepend absolute paths
if [ -f "$p2Lib" ]
then
    listTwo=$(sqlite3 -list "$p2Lib" "$p2Query" )
    if [ "$listTwo" ]
    then
    	listTwo=$(echo "$listTwo" | while read line; do echo "$papers2/$line"; done)
    fi
fi

# create a temp dir of symlinks so rysnc will delete items that were removed
mkdir -p "$tmpFolder"
mkdir -p "$syncTo"

echo "$listTwo" | while read pdf
do
    if [ "$pdf" ]
        then
        # ${##*/} is a glob that matches the filename and extension in a path
        ln -sf "$library/$pdf" "$tmpFolder/${pdf##*/}"
    fi
done

# use -l to copy the link and -L to copy original linked file
rsync -al --delete "$tmpFolder" "$syncTo"

rm -rf "$tmpFolder"

echo "Finished syncing papers to Dropbox/ReadingList."


text:
using System;
using System.Threading.Tasks;
using System.Windows;

namespace eStation.Views.Journals
{

    internal partial class JournalView
    {
        public JournalView()
        {
            InitializeComponent();

            Task.Run(async () => await Refresh(DateTime.Today.AddMonths(-1), DateTime.Today));
        }

        public async Task Refresh(DateTime fromDate, DateTime toDate)
        {
            await _FUEL_PERIOD.Refresh(fromDate, toDate)
            .ContinueWith(task => _OIL_PERIOD.Refresh(fromDate, toDate))
            .ContinueWith(task => _FINANCE_CARD.Refresh(fromDate: fromDate, toDate: toDate));
        }

        private async void BACK_BUTTON_OnClick(object sender, RoutedEventArgs e)
                => await Dispatcher.BeginInvoke(new Action(() => { NavigationService?.GoBack(); }));

        private async void FuelPeriodCard_OnSelectionChanged(object sender, EventArgs e)
                => await _FUELS_SALES.Refresh(_FUEL_PERIOD.SelectedFuels, _FUEL_PERIOD.FromDate,_FUEL_PERIOD.ToDate);

        private async void OilPeriodCard_OnSelectionChanged(object sender, EventArgs e)
                => await _CHART_OIL_SALE.Refresh(_OIL_PERIOD.SelectedOils, _OIL_PERIOD.FromDate, _OIL_PERIOD.ToDate);

        private async void CaisseDetails_OnDateSelectionChanged(object sender, EventArgs e)
                => await _TRANS_CARD.Refresh(_FINANCE_CARD.FromDate, _FINANCE_CARD.ToDate);

        private async void CaisseTransactions_OnRefreshed(object sender, EventArgs e)
                =>await _FINANCE_CARD.Refresh(false);

    }
}


text:
<!DOCTYPE html>

<title>OffscreenCanvas test: 2d.text.draw.fontface.repeat</title>

2d.text.draw.fontface.repeat

Draw with the font immediately, then wait a bit until and draw again. (This crashes some version of WebKit.)


text:
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName       = "Wire Graphics Tablet"
ENT.WireDebugName	= "Graphics Tablet"
ENT.Author = "greenarrow"
ENT.Editable = true

ENT.workingDistance = 64

local SCREEN_CURSOR = false -- (0, 0) is top left, (1, 1) is bottom right
local GRAPH_CURSOR = true -- (0, 0) is center, (1, 1) is top right

function ENT:SetupDataTables()
	self:NetworkVar("Bool", 0, "DrawBackground", { KeyName = "DrawBackground",
		Edit = { type = "Boolean", title = "#Tool_wire_graphics_tablet_mode", order = 1 } })
	self:NetworkVar("Bool", 1, "CursorMode", { KeyName = "CursorMode",
		Edit = { type = "Boolean", title = "#Tool_wire_graphics_tablet_draw_background", order = 2 } })
end

if CLIENT then
	function ENT:Initialize()
		self.GPU = WireGPU(self, true)
	end

	function ENT:OnRemove()
		self.GPU:Finalize()
	end

	local function cut_rect(x1,y1,w1,h1,x2,y2,w2,h2)
		local x,y = x1>x2 and x1 or x2, y1>y2 and y1 or y2
		local right1,bottom1,right2,bottom2 = x1+w1,y1+h1, x2+w2,y2+h2
		local w,h = (right1<right2 and right1 or right2)-x, (bottom1<bottom2 and bottom1 or bottom2)-y
		return x,y,w,h
	end

	function ENT:Draw()
		self:DrawModel()

		local draw_background = self:GetDrawBackground()
		self.GPU:RenderToWorld(nil, 512, function(x, y, w, h, monitor, pos, ang, res)
			if draw_background then
				surface.SetDrawColor(0, 0, 0, 255)
				surface.DrawRect(x, y, w, h)
			end

			local ply = LocalPlayer()
			local trace = ply:GetEyeTraceNoCursor()
			local ent = trace.Entity
			if ent:IsValid() then
				local dist = trace.Normal:Dot(trace.HitNormal)*trace.Fraction*-16384
				dist = math.max(dist, trace.Fraction*16384-ent:BoundingRadius())
				--WireLib.hud_debug(""..dist, true)

				if dist < self.workingDistance and ent == self.GPU.Entity then
					local cpos = WorldToLocal(trace.HitPos, Angle(), pos, ang)

					local cx = 0.5+cpos.x/(res*w)
					local cy = 0.5-cpos.y/(res*h)

					if cx >= 0 and cy >= 0 and cx <= 1 and cy <= 1 then
						surface.SetDrawColor(255, 255, 255, 255)
						--surface.SetTexture(surface.GetTextureID("gui/arrow"))
						--surface.DrawTexturedRectRotated(x+cx*w+11,y+cy*h+11,32,32,45)

						local curSize = 16
						local curWidth = 2
						local midX, midY = x+cx*w,y+cy*h

						local x1,y1,w1,h1 = cut_rect(midX - curSize, midY - curWidth, curSize * 2, curWidth * 2,x,y,w,h)
						local x2,y2,w2,h2 = cut_rect(midX - curWidth, midY - curSize, curWidth * 2, curSize * 2,x,y,w,h)
						surface.DrawRect(x1,y1,w1,h1)
						surface.DrawRect(x2,y2,w2,h2)
					end
				end
			end
		end, draw_background and nil or 0.1)
		Wire_Render(self)
	end

	return  -- No more client
end

-- Server

function ENT:Initialize()
	self:PhysicsInit( SOLID_VPHYSICS )
	self:SetMoveType( MOVETYPE_VPHYSICS )
	self:SetSolid( SOLID_VPHYSICS )
	self.Outputs = Wire_CreateOutputs(self, { "X", "Y", "Use", "OnScreen" })

	Wire_TriggerOutput(self, "X", 0)
	Wire_TriggerOutput(self, "Y", 0)
	Wire_TriggerOutput(self, "Use", 0)
	Wire_TriggerOutput(self, "OnScreen", 0)

	self.lastOnscreen = 0
	self.lastX = 0
	self.lastY = 0
	self.lastClick = 0
end

function ENT:Think()
	self.BaseClass.Think(self)
	local onScreen = 0
	local clickActive = 0

	local GPUEntity = self.GPUEntity or self
	local model = GPUEntity:GetModel()
	local monitor = WireGPU_Monitors[model]
	local ang = GPUEntity:LocalToWorldAngles(monitor.rot)
	local pos = GPUEntity:LocalToWorld(monitor.offset)
	local h = 512
	local w = h/monitor.RatioX
	local x = -w/2
	local y = -h/2

	for _,ply in pairs(player.GetAll()) do
		local trace = ply:GetEyeTraceNoCursor()
		local ent = trace.Entity
		if ent:IsValid() then
			local dist = trace.Normal:Dot(trace.HitNormal)*trace.Fraction*-16384
			dist = math.max(dist, trace.Fraction*16384-ent:BoundingRadius())

			if dist < 64 and ent == GPUEntity then
				if ply:KeyDown(IN_ATTACK) or ply:KeyDown(IN_USE) then
					clickActive = 1
				end
				local cpos = WorldToLocal(trace.HitPos, Angle(), pos, ang)

				local cx = 0.5+cpos.x/(monitor.RS*w)
				local cy = 0.5-cpos.y/(monitor.RS*h)

				if (cx >= 0 and cy >= 0 and cx <= 1 and cy <= 1) then
					onScreen = 1
					if (cx ~= self.lastX or cy ~= self.lastY) then
						self.lastX = cx
						self.lastY = cy
						if self:GetCursorMode() == GRAPH_CURSOR then
							cx = cx * 2 - 1
							cy = -(cy * 2 - 1)
						end
						Wire_TriggerOutput(self, "X", cx)
						Wire_TriggerOutput(self, "Y", cy)
						self:ShowOutput(cx, cy, clickActive, 1)
					end
				end
			end
		end
	end

	if (onScreen ~= self.lastOnScreen) then
		Wire_TriggerOutput(self, "OnScreen", onScreen)
		self:ShowOutput(self.lastX, self.lastY, self.lastClick, onScreen)
		self.lastOnScreen = onScreen
	end

	if (clickActive ~= self.lastClick) then
		Wire_TriggerOutput(self, "Use", clickActive)
		self:ShowOutput(self.lastX, self.lastY, clickActive, self.lastOnScreen)
		self.lastClick = clickActive
	end

	self:NextThink(CurTime()+0.08)
	return true
end

function ENT:ShowOutput(cx, cy, activeval, osval)
	self:SetOverlayText(string.format("X = %f, Y = %f, Use = %d, On Screen = %d\n", cx, cy, activeval, osval))
end

function ENT:OnRestore()
	self.BaseClass.OnRestore(self)
	Wire_AdjustOutputs(self, { "X", "Y", "Use", "OnScreen" })
end

-- only needed for legacy dupes
function ENT:Setup(gmode, draw_background)
	if gmode ~= nil then self:SetCursorMode(gmode) end
	if draw_background ~= nil then self:SetDrawBackground(draw_background) end
end

duplicator.RegisterEntityClass("gmod_wire_graphics_tablet", WireLib.MakeWireEnt, "Data", "gmode", "draw_background")


text:
package com.linecorp.armeria.server.jetty;

import static java.util.Objects.requireNonNull;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import java.util.function.Function;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.RequestLog;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.SessionIdManager;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.util.component.Container;
import org.eclipse.jetty.util.component.LifeCycle;

import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import com.linecorp.armeria.common.annotation.Nullable;

/**
 * Builds a {@link JettyService}. Use {@link JettyService#of(Server)} if you have a configured Jetty
 * {@link Server} instance.
 */
public final class JettyServiceBuilder {

    private final ImmutableMap.Builder<String, Object> attrs = ImmutableMap.builder();
    private final ImmutableList.Builder<Bean> beans = ImmutableList.builder();
    private final ImmutableList.Builder<HandlerWrapper> handlerWrappers = ImmutableList.builder();
    private final ImmutableList.Builder<Container.Listener> eventListeners = ImmutableList.builder();
    private final ImmutableList.Builder<LifeCycle.Listener> lifeCycleListeners = ImmutableList.builder();
    private final ImmutableList.Builder<Consumer<? super Server>> customizers = ImmutableList.builder();

    @Nullable
    private String hostname;
    @Nullable
    private Boolean dumpAfterStart;
    @Nullable
    private Boolean dumpBeforeStop;
    @Nullable
    private Handler handler;
    @Nullable
    private RequestLog requestLog;
    @Nullable
    private Function<? super Server, ? extends SessionIdManager> sessionIdManagerFactory;
    @Nullable
    private Long stopTimeoutMillis;
    private boolean tlsReverseDnsLookup;

    JettyServiceBuilder() {}

    /**
     * Sets the default hostname of the Jetty {@link Server}.
     */
    public JettyServiceBuilder hostname(String hostname) {
        this.hostname = requireNonNull(hostname, "hostname");
        return this;
    }

    /**
     * Puts the specified attribute into the Jetty {@link Server}.
     *
     * @see Server#setAttribute(String, Object)
     */
    public JettyServiceBuilder attr(String name, Object attribute) {
        attrs.put(requireNonNull(name, "name"), requireNonNull(attribute, "attribute"));
        return this;
    }

    /**
     * Adds the specified bean to the Jetty {@link Server}.
     *
     * @see Server#addBean(Object)
     */
    public JettyServiceBuilder bean(Object bean) {
        beans.add(new Bean(bean, null));
        return this;
    }

    /**
     * Adds the specified bean to the Jetty {@link Server}.
     *
     * @see Server#addBean(Object, boolean)
     */
    public JettyServiceBuilder bean(Object bean, boolean managed) {
        beans.add(new Bean(bean, managed));
        return this;
    }

    /**
     * Sets whether the Jetty {@link Server} needs to dump its configuration after it started up.
     *
     * @see Server#setDumpAfterStart(boolean)
     */
    public JettyServiceBuilder dumpAfterStart(boolean dumpAfterStart) {
        this.dumpAfterStart = dumpAfterStart;
        return this;
    }

    /**
     * Sets whether the Jetty {@link Server} needs to dump its configuration before it shuts down.
     *
     * @see Server#setDumpBeforeStop(boolean)
     */
    public JettyServiceBuilder dumpBeforeStop(boolean dumpBeforeStop) {
        this.dumpBeforeStop = dumpBeforeStop;
        return this;
    }

    /**
     * Sets the {@link Handler} of the Jetty {@link Server}.
     *
     * @see Server#setHandler(Handler)
     */
    public JettyServiceBuilder handler(Handler handler) {
        this.handler = requireNonNull(handler, "handler");
        return this;
    }

    /**
     * Adds the specified {@link HandlerWrapper} to the Jetty {@link Server}.
     *
     * @see Server#insertHandler(HandlerWrapper)
     */
    public JettyServiceBuilder handlerWrapper(HandlerWrapper handlerWrapper) {
        handlerWrappers.add(requireNonNull(handlerWrapper, "handlerWrapper"));
        return this;
    }

    /**
     * Adds the specified {@link HttpConfiguration} to the Jetty {@link Server}.
     * This method is a type-safe alias of {@link #bean(Object)}.
     */
    public JettyServiceBuilder httpConfiguration(HttpConfiguration httpConfiguration) {
        return bean(httpConfiguration);
    }

    /**
     * Sets the {@link RequestLog} of the Jetty {@link Server}.
     *
     * @see Server#setRequestLog(RequestLog)
     */
    public JettyServiceBuilder requestLog(RequestLog requestLog) {
        this.requestLog = requireNonNull(requestLog, "requestLog");
        return this;
    }

    /**
     * Sets the {@link SessionIdManager} of the Jetty {@link Server}. This method is a shortcut for:
     *
{@code
     * sessionIdManagerFactory(server -> sessionIdManager);
     * }

     *
     * @see Server#setSessionIdManager(SessionIdManager)
     */
    public JettyServiceBuilder sessionIdManager(SessionIdManager sessionIdManager) {
        requireNonNull(sessionIdManager, "sessionIdManager");
        return sessionIdManagerFactory(server -> sessionIdManager);
    }

    /**
     * Sets the factory that creates a new instance of {@link SessionIdManager} for the Jetty {@link Server}.
     *
     * @see Server#setSessionIdManager(SessionIdManager)
     */
    public JettyServiceBuilder sessionIdManagerFactory(
            Function<? super Server, ? extends SessionIdManager> sessionIdManagerFactory) {
        requireNonNull(sessionIdManagerFactory, "sessionIdManagerFactory");
        this.sessionIdManagerFactory = sessionIdManagerFactory;
        return this;
    }

    /**
     * Sets the graceful stop time of the {@link Server#stop()} in milliseconds.
     *
     * @see Server#setStopTimeout(long)
     */
    public JettyServiceBuilder stopTimeoutMillis(long stopTimeoutMillis) {
        this.stopTimeoutMillis = stopTimeoutMillis;
        return this;
    }

    /**
     * Adds the specified event listener to the Jetty {@link Server}.
     */
    public JettyServiceBuilder eventListener(Container.Listener eventListener) {
        eventListeners.add(requireNonNull(eventListener, "eventListener"));
        return this;
    }

    /**
     * Adds the specified life cycle listener to the Jetty {@link Server}.
     */
    public JettyServiceBuilder lifeCycleListener(LifeCycle.Listener lifeCycleListener) {
        lifeCycleListeners.add(requireNonNull(lifeCycleListener, "lifeCycleListener"));
        return this;
    }

    /**
     * Sets whether Jetty has to perform reverse DNS lookup for the remote IP address on a TLS connection.
     * By default, this flag is disabled because it is known to cause performance issues when the DNS server
     * is not responsive enough. However, you might want to take the risk and enable it if you want the same
     * behavior with Jetty 9.3 when mTLS is enabled.
     *
     * @see Jetty issue #1235
     * @see Jetty commit de7c146
     */
    public JettyServiceBuilder tlsReverseDnsLookup(boolean tlsReverseDnsLookup) {
        this.tlsReverseDnsLookup = tlsReverseDnsLookup;
        return this;
    }

    /**
     * Adds a {@link Consumer} that performs additional configuration operations against
     * the Jetty {@link Server} created by a {@link JettyService}.
     */
    public JettyServiceBuilder customizer(Consumer<? super Server> customizer) {
        customizers.add(requireNonNull(customizer, "customizer"));
        return this;
    }

    /**
     * Adds a {@link Consumer} that performs additional configuration operations against
     * the Jetty {@link Server} created by a {@link JettyService}.
     *
     * @deprecated Use {@link #customizer(Consumer)}.
     */
    @Deprecated
    public JettyServiceBuilder configurator(Consumer<? super Server> configurator) {
        return customizer(requireNonNull(configurator, "configurator"));
    }

    /**
     * Returns a newly-created {@link JettyService} based on the properties of this builder.
     */
    public JettyService build() {
        // Make a copy of the properties that's used in `serverFactory` so that any further modification of
        // this builder doesn't affect the built server.
        final Boolean dumpAfterStart = this.dumpAfterStart;
        final Boolean dumpBeforeStop = this.dumpBeforeStop;
        final Long stopTimeoutMillis = this.stopTimeoutMillis;
        final Handler handler = this.handler;
        final RequestLog requestLog = this.requestLog;
        final Function<? super Server, ? extends SessionIdManager> sessionIdManagerFactory =
                this.sessionIdManagerFactory;
        final Map<String, Object> attrs = this.attrs.build();
        final List<Bean> beans = this.beans.build();
        final List<HandlerWrapper> handlerWrappers = this.handlerWrappers.build();
        final List<Container.Listener> eventListeners = this.eventListeners.build();
        final List<LifeCycle.Listener> lifeCycleListeners = this.lifeCycleListeners.build();
        final List<Consumer<? super Server>> customizers = this.customizers.build();

        final Function<ScheduledExecutorService, Server> serverFactory = blockingTaskExecutor -> {
            final Server server = new Server(new ArmeriaThreadPool(blockingTaskExecutor));

            if (dumpAfterStart != null) {
                server.setDumpAfterStart(dumpAfterStart);
            }
            if (dumpBeforeStop != null) {
                server.setDumpBeforeStop(dumpBeforeStop);
            }
            if (stopTimeoutMillis != null) {
                server.setStopTimeout(stopTimeoutMillis);
            }

            if (handler != null) {
                server.setHandler(handler);
            }
            if (requestLog != null) {
                server.setRequestLog(requestLog);
            }
            if (sessionIdManagerFactory != null) {
                server.setSessionIdManager(sessionIdManagerFactory.apply(server));
            }

            handlerWrappers.forEach(server::insertHandler);
            attrs.forEach(server::setAttribute);
            beans.forEach(bean -> {
                final Boolean managed = bean.isManaged();
                if (managed == null) {
                    server.addBean(bean.bean());
                } else {
                    server.addBean(bean.bean(), managed);
                }
            });

            eventListeners.forEach(server::addEventListener);
            lifeCycleListeners.forEach(server::addLifeCycleListener);

            customizers.forEach(c -> c.accept(server));

            return server;
        };

        final Consumer<Server> postStopTask = server -> {
            try {
                JettyService.logger.info("Destroying an embedded Jetty: {}", server);
                server.destroy();
            } catch (Exception e) {
                JettyService.logger.warn("Failed to destroy an embedded Jetty: {}", server, e);
            }
        };

        return new JettyService(hostname, tlsReverseDnsLookup, serverFactory, postStopTask);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                          .omitNullValues()
                          .add("hostname", hostname)
                          .add("dumpAfterStart", dumpAfterStart)
                          .add("dumpBeforeStop", dumpBeforeStop)
                          .add("stopTimeoutMillis", stopTimeoutMillis)
                          .add("handler", handler)
                          .add("requestLog", requestLog)
                          .add("sessionIdManagerFactory", sessionIdManagerFactory)
                          .add("attrs", attrs)
                          .add("beans", beans)
                          .add("handlerWrappers", handlerWrappers)
                          .add("eventListeners", eventListeners)
                          .add("lifeCycleListeners", lifeCycleListeners)
                          .add("tlsReverseDnsLookup", tlsReverseDnsLookup)
                          .add("customizers", customizers)
                          .toString();
    }

    static final class Bean {

        private final Object bean;
        @Nullable
        private final Boolean managed;

        Bean(Object bean, @Nullable Boolean managed) {
            this.bean = requireNonNull(bean, "bean");
            this.managed = managed;
        }

        Object bean() {
            return bean;
        }

        @Nullable
        Boolean isManaged() {
            return managed;
        }

        @Override
        public String toString() {
            final String mode = managed != null ? managed ? "managed" : "unmanaged"
                                                : "auto";
            return "(" + bean + ", " + mode + ')';
        }
    }
}


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UploadingComponent
 *
 * @author db2admin
 */
App::uses('Component', 'Controller');
class UploadingComponent extends Component {
    public function uploadImage($files,$imagePath)
    {
        $imagePath=$this->webroot.$imagePath;
        $image=$files['image_url']['tmp_name'];
        $fileName='';
            if ($image!='')
            {

 		$filename = stripslashes($files['image_url']['name']);
               $arrFile=preg_split('/\./', $filename);
  		$extension = $arrFile[count($arrFile)-1];
 		$extension = strtolower($extension);
 		if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
 		{
 			//echo '<script>window.location="item.php?ext_error"</script>';
			exit;
 		}
 		else
 		{
 			if(($extension == "jpg") || ($extension == "jpeg"))
			{
				$src = imagecreatefromjpeg($image);
			}
			if($extension == "png")
			{
				$src = imagecreatefrompng($image);
			}
			if($extension == "gif")
			{
				$src = imagecreatefromgif($image);
			}

			$size=filesize($files['image_url']['tmp_name']);
			if ($size > 100*1024*1024)
			{
				echo '<script>window.location="?size_error"</script>';
				exit;
			}

			$image_name=time().'.'.$extension;
			list($width,$height)=getimagesize($image);
			/*================== Large Image =================*/

			$image_name=time().'.'.$extension;

			$filename = $imagePath.$image_name;
                        move_uploaded_file($_FILES["image_url"]["tmp_name"],$filename);
                    }
            }
            return $filename;
    }
}

?>


text:
"""This dag only runs some simple tasks to test Airflow's task execution."""
from datetime import datetime, timedelta

from airflow.models.dag import DAG
from airflow.operators.dummy import DummyOperator
from airflow.utils.dates import days_ago

now = datetime.now()
now_to_the_hour = (now - timedelta(0, 0, 0, 0, 0, 3)).replace(minute=0, second=0, microsecond=0)
START_DATE = now_to_the_hour
DAG_NAME = 'test_dag_v1'

default_args = {'owner': 'airflow', 'depends_on_past': True, 'start_date': days_ago(2)}
dag = DAG(DAG_NAME, schedule_interval='*/10 * * * *', default_args=default_args)

run_this_1 = DummyOperator(task_id='run_this_1', dag=dag)
run_this_2 = DummyOperator(task_id='run_this_2', dag=dag)
run_this_2.set_upstream(run_this_1)
run_this_3 = DummyOperator(task_id='run_this_3', dag=dag)
run_this_3.set_upstream(run_this_2)


text:
namespace Stact.Specs.Channels
{
	using System;

	using Internal;
	using Stact;
	using Magnum.Extensions;
	using NUnit.Framework;
	using Magnum.TestFramework;

	[TestFixture]
	public class Binding_an_action_queue_channel_to_a_method
	{
		[Test]
		public void Should_call_the_consumer_method()
		{
			var actor = new SomeActorInstance();

			var message = new MyMessage();

			actor.MessageChannel.Send(message);

			actor.Future.WaitUntilCompleted(1.Seconds()).ShouldBeTrue();
			actor.Future.Value.ShouldEqual(message);
		}

		[Test]
		public void Should_call_the_consumer_anonymous_method()
		{
			var actor = new SomeActorInstance();

			var message = new MyMessage();

			actor.LambdaMessageChannel.Send(message);

			actor.Future.WaitUntilCompleted(1.Seconds()).ShouldBeTrue();
			actor.Future.Value.ShouldEqual(message);
		}
	}

	public class SomeActorInstance
	{
		private readonly Future<MyMessage> _future;
		private readonly PoolFiber _fiber;

		public SomeActorInstance()
		{
			_fiber = new PoolFiber();
			_future = new Future<MyMessage>();

			MessageChannel = new ConsumerChannel<MyMessage>(_fiber, Consume);
			LambdaMessageChannel = new ConsumerChannel<MyMessage>(_fiber, message => _future.Complete(message));
		}

		public Future<MyMessage> Future
		{
			get { return _future; }
		}

		public Channel<MyMessage> MessageChannel { get; private set; }
		public Channel<MyMessage> LambdaMessageChannel { get; private set; }

		private void Consume(MyMessage message)
		{
			_future.Complete(message);
		}
	}

	public class MyMessage
	{
		public Guid Id { get; set; }
	}
}


text:
package gov.va.escreening.controller.dashboard;

import gov.va.escreening.delegate.CreateAssessmentDelegate;
import gov.va.escreening.dto.SelectVeteranResultDto;
import gov.va.escreening.form.CreateVeteranFormBean;
import gov.va.escreening.form.SelectVeteranFormBean;
import gov.va.escreening.security.CurrentUser;
import gov.va.escreening.security.EscreenUser;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/dashboard")
public class SelectVeteranController {

    private static final Logger logger = LoggerFactory.getLogger(SelectVeteranController.class);

    private CreateAssessmentDelegate createAssessmentDelegate;

    @Autowired
    public void setCreateAssessmentDelegate(CreateAssessmentDelegate createAssessmentDelegate) {
        this.createAssessmentDelegate = createAssessmentDelegate;
    }

    public SelectVeteranController() {
        // Default constructor.
    }

    /**
     * Returns the backing bean for the form.
     *
     * @return
     */
    @ModelAttribute
    public SelectVeteranFormBean getSelectVeteranFormBean() {
        logger.trace("Creating new SelectVeteranFormBean");
        return new SelectVeteranFormBean();
    }

    /**
     * Initialize and setup page.
     *
     * @param selectVeteranFormBean
     * @param model
     * @return
     */
    @RequestMapping(value = "/selectVeteran", method = RequestMethod.GET)
    public String setUpPageSelectVeteran(HttpServletRequest request, @CurrentUser EscreenUser escreenUser,
                                         @ModelAttribute SelectVeteranFormBean selectVeteranFormBean, Model model) {

        model.addAttribute("isPostBack", false);
        model.addAttribute("isCprsVerified", escreenUser.getCprsVerified());
        accomodateCreateVeteranFormBeamFromSearchResult(request, selectVeteranFormBean, model);

        return "dashboard/selectVeteran";
    }

    private void accomodateCreateVeteranFormBeamFromSearchResult(HttpServletRequest request, SelectVeteranFormBean selectVeteranFormBean, Model model) {
        HttpSession session = request.getSession();
        String lastName = (String) session.getAttribute("lastName");
        String ssnLastFour = (String) session.getAttribute("ssnLastFour");
        boolean updateCreateVeteranFormBean = false;

        if (lastName != null) {
            selectVeteranFormBean.setLastName(lastName);
            session.removeAttribute("lastName");
            updateCreateVeteranFormBean = true;
        }
        if (ssnLastFour != null) {
            selectVeteranFormBean.setSsnLastFour(ssnLastFour);
            session.removeAttribute("ssnLastFour");
            updateCreateVeteranFormBean = true;
        }
        if (updateCreateVeteranFormBean) {
            model.addAttribute("selectVeteranFormBean", selectVeteranFormBean);

            // also add the search result previously displayed
            model.addAttribute("searchResultList", session.getAttribute("searchResultList"));
            model.addAttribute("searchResultListSize", session.getAttribute("searchResultListSize"));

            model.addAttribute("isPostBack", true);
        }
    }

    /**
     * Process search request.
     *
     * @param selectVeteranFormBean
     * @param result
     * @param model
     * @param escreenUser
     * @return
     */
    @RequestMapping(value = "/selectVeteran", method = RequestMethod.POST, params = "searchButton")
    public String searchPageSelectVeteran(HttpServletRequest request, @Valid @ModelAttribute SelectVeteranFormBean selectVeteranFormBean,
                                          BindingResult result, Model model, @CurrentUser EscreenUser escreenUser) {

        logger.trace(selectVeteranFormBean.toString());

        // If there is an error, return the same view.
        if (result.hasErrors()) {
            model.addAttribute("isCprsVerified", escreenUser.getCprsVerified());
            model.addAttribute("isPostBack", true);
            return "dashboard/selectVeteran";
        }

        List<SelectVeteranResultDto> searchResultList = createAssessmentDelegate.searchVeterans(escreenUser,
                selectVeteranFormBean.getLastName(), selectVeteranFormBean.getSsnLastFour());

        if (searchResultList == null) {
            searchResultList = new ArrayList<SelectVeteranResultDto>();
        }

        {
            // save the search result in Session Cache so it is available when user presses cancel button
            request.getSession().setAttribute("searchResultList", searchResultList);
            request.getSession().setAttribute("searchResultListSize", searchResultList.size());
        }

        model.addAttribute("isCprsVerified", escreenUser.getCprsVerified());
        model.addAttribute("isPostBack", true);
        model.addAttribute("searchResultList", searchResultList);
        model.addAttribute("searchResultListSize", searchResultList.size());

        return "dashboard/selectVeteran";
    }

    /**
     * Redirects user to Create New Veteran page.
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/selectVeteran", method = RequestMethod.POST, params = "createButton")
    public String createPageSelectVeteran(HttpServletRequest request, @Valid @ModelAttribute SelectVeteranFormBean selectVeteranFormBean,
                                          BindingResult result, Model model, @CurrentUser EscreenUser escreenUser) {

        request.getSession().setAttribute("lastName", selectVeteranFormBean.getLastName());
        request.getSession().setAttribute("ssnLastFour", selectVeteranFormBean.getSsnLastFour());

        return "redirect:/dashboard/createVeteran";
    }
}


text:
package ch.mlutz.plugins.t4e.tapestry.element;

/**
 * Models a Tapestry parameter used for pages, components, services, etc.
 *
 * @author mlutz
 *
 */
public class Parameter {

	private String name;

	private ParameterType type;

	private ParameterDirection direction;

	private boolean required;

	private Object defaultValue;

	private IComponent parent;

	public Parameter(String name, ParameterType type) {
		super();
		this.name = name;
		this.type = type;
	}

	public Parameter(String name, ParameterType type,
			ParameterDirection direction, boolean required,
			Object defaultValue) {
		super();
		this.name = name;
		this.type = type;
		this.direction = direction;
		this.required = required;
		this.defaultValue = defaultValue;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((defaultValue == null) ? 0 : defaultValue.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + (required ? 1231 : 1237);
		result = prime * result + ((type == null) ? 0 : type.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof Parameter)) {
			return false;
		}
		Parameter other = (Parameter) obj;
		if (defaultValue == null) {
			if (other.defaultValue != null) {
				return false;
			}
		} else if (!defaultValue.equals(other.defaultValue)) {
			return false;
		}
		if (name == null) {
			if (other.name != null) {
				return false;
			}
		} else if (!name.equals(other.name)) {
			return false;
		}
		if (required != other.required) {
			return false;
		}
		if (type != other.type) {
			return false;
		}
		return true;
	}

	// getters and setters

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public ParameterType getType() {
		return type;
	}

	public void setType(ParameterType type) {
		this.type = type;
	}

	public boolean isRequired() {
		return required;
	}

	public void setRequired(boolean required) {
		this.required = required;
	}

	public Object getDefaultValue() {
		return defaultValue;
	}

	public void setDefaultValue(Object defaultValue) {
		this.defaultValue = defaultValue;
	}

	public ParameterDirection getDirection() {
		return direction;
	}

	public void setDirection(ParameterDirection direction) {
		this.direction = direction;
	}

	public IComponent getParent() {
		return parent;
	}

	public void setParent(IComponent parent) {
		this.parent = parent;
	}
}


text:
layout: post
title: "nova compute创建虚拟机分配network"
description: ""
category: articles
tags: [Nova, Network]
---
## nova-compute创建虚拟机分配network过程 ##
在/nova/compute/manager.py中:

    def _build_instance(self, context, request_spec, filter_properties,
            requested_networks, injected_files, admin_password, is_first_time,
            node, instance, image_meta, legacy_bdm_in_spec):
        context = context.elevated()

        ...

        try:
            limits = filter_properties.get('limits', {})
            with rt.instance_claim(context, instance, limits):
                macs = self.driver.macs_for_instance(instance)
                dhcp_options = self.driver.dhcp_options_for_instance(instance)

                network_info = self._allocate_network(context, instance,
                        requested_networks, macs, security_groups,
                        dhcp_options)

        ...

        return instance, network_info

通过_allocate_network(),创建必要的port和security group。

        def _allocate_network(self, context, instance, requested_networks, macs,
                          security_groups, dhcp_options):
        """Start network allocation asynchronously.  Return an instance
        of NetworkInfoAsyncWrapper that can be used to retrieve the
        allocated networks when the operation has finished.
        """
        # NOTE(comstud): Since we're allocating networks asynchronously,
        # this task state has little meaning, as we won't be in this
        # state for very long.
        instance = self._instance_update(context, instance['uuid'],
                                         vm_state=vm_states.BUILDING,
                                         task_state=task_states.NETWORKING,
                                         expected_task_state=[None])
        is_vpn = pipelib.is_vpn_image(instance['image_ref'])
        return network_model.NetworkInfoAsyncWrapper(
                self._allocate_network_async, context, instance,
                requested_networks, macs, security_groups, is_vpn,
                dhcp_options)

network_model.NetworkInfoAsyncWrapper()创建一个异步的wrapper,返回执行_allocate_network_async()的结果。

    def _allocate_network_async(self, context, instance, requested_networks,
                                macs, security_groups, is_vpn, dhcp_options):

        ...

        for attempt in range(1, attempts + 1):
            try:
                nwinfo = self.network_api.allocate_for_instance(
                        context, instance, vpn=is_vpn,
                        requested_networks=requested_networks,
                        macs=macs,
                        security_groups=security_groups,
                        dhcp_options=dhcp_options)

        ...
最后通过network_api.allocate_for_instance()里执行操作。
allocate_for_instance()在/nova/network/neutronv2/api.py中:

    def allocate_for_instance(self, context, instance, **kwargs):

        ...

        if requested_networks:
            for network_id, fixed_ip, port_id in requested_networks:
                if port_id:
                    port = neutron.show_port(port_id)['port']
                    if port.get('device_id'):
                        raise exception.PortInUse(port_id=port_id)
                    if hypervisor_macs is not None:
                        if port['mac_address'] not in hypervisor_macs:
                            raise exception.PortNotUsable(port_id=port_id,
                                instance=instance['display_name'])
                        else:
                            available_macs.discard(port['mac_address'])
                    network_id = port['network_id']
                    ports[network_id] = port
                elif fixed_ip and network_id:
                    fixed_ips[network_id] = fixed_ip
                if network_id:
                    net_ids.append(network_id)

        ...

        touched_port_ids = []
        created_port_ids = []
        for network in nets:
            if (security_groups and not (
                    network['subnets']
                    and network.get('port_security_enabled', True))):

                raise exception.SecurityGroupCannotBeApplied()
            network_id = network['id']
            zone = 'compute:%s' % instance['availability_zone']
            port_req_body = {'port': {'device_id': instance['uuid'],
                                      'device_owner': zone}}
            try:
                port = ports.get(network_id)
                self._populate_neutron_extension_values(instance,
                                                        port_req_body)
                # Requires admin creds to set port bindings
                port_client = (neutron if not
                               self._has_port_binding_extension() else
                               neutronv2.get_client(context, admin=True))
                if port:
                    port_client.update_port(port['id'], port_req_body)
                    touched_port_ids.append(port['id'])
                else:
                    //创建port
                    created_port_ids.append(self._create_port(
                            port_client, instance, network_id,
                            port_req_body, fixed_ips.get(network_id),
                            security_group_ids, available_macs, dhcp_opts))

           ...

        nw_info = self.get_instance_nw_info(context, instance, networks=nets)
        return network_model.NetworkInfo([port for port in nw_info
                                          if port['id'] in created_port_ids +
                                                           touched_port_ids])


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../cl_sys/constant.CL_INVALID_WORK_GROUP_SIZE.html">

Redirecting to ../../cl_sys/constant.CL_INVALID_WORK_GROUP_SIZE.html...


text:
package appaloosa_store.com.appaloosa_android_tools.analytics;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;

import appaloosa_store.com.appaloosa_android_tools.Appaloosa;
import appaloosa_store.com.appaloosa_android_tools.analytics.callback.handler.ActivityLifeCycleHandler;
import appaloosa_store.com.appaloosa_android_tools.analytics.callback.handler.AnalyticsBatchingHandler;
import appaloosa_store.com.appaloosa_android_tools.analytics.db.AnalyticsDb;
import appaloosa_store.com.appaloosa_android_tools.analytics.model.ApplicationEvent;
import appaloosa_store.com.appaloosa_android_tools.analytics.services.AnalyticsServices;
import appaloosa_store.com.appaloosa_android_tools.utils.DeviceUtils;

public class AppaloosaAnalytics {

    public static final String ANALYTICS_LOG_TAG = "APPALOOSA_ANALYTICS";

    private static AnalyticsDb analyticsDb;
    private static AnalyticsBatchingHandler batchingHandler;
    private static boolean isInit;
    private static String analyticsEndpoint;
    private static BroadcastReceiver broadcastReceiver;
    private static boolean alreadyStarted;

    public static void initialize() {
        batchingHandler = new AnalyticsBatchingHandler();
        analyticsDb = new AnalyticsDb(Appaloosa.getApplicationContext(), batchingHandler);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                batchingHandler.updateNetworkStatus(
                        !DeviceUtils.getActiveNetwork().equals(DeviceUtils.NO_ACTIVE_NETWORK)
                );
            }
        };
        isInit = true;
        start();
    }

    private static void start() {
        if(isInit && batchingHandler != null && analyticsEndpoint != null && !alreadyStarted) {
            alreadyStarted = true;
            registerConnectivityStatusListener();
            AnalyticsServices.registerEvent(new ApplicationEvent());
            Appaloosa.getApplication().registerActivityLifecycleCallbacks(new ActivityLifeCycleHandler());
        }
    }

    public static AnalyticsDb getAnalyticsDb() {
        return analyticsDb;
    }

    public static String getAnalyticsEndpoint() {
        return analyticsEndpoint;
    }

    public static void setAnalyticsEndpoint(String analyticsEndpoint) {
        AppaloosaAnalytics.analyticsEndpoint = analyticsEndpoint;
        start();
    }

    private static void registerConnectivityStatusListener() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        Appaloosa.getApplicationContext().registerReceiver(broadcastReceiver, filter);
    }

}


text:
layout: page
title: "Donna Funghar Louie"
comments: true
description: "blanks"
keywords: "Donna Funghar Louie,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Arts and Sciences

**Classes taught**: EBIO 1210, EBIO 1220, IPHY 2420, IPHY 3420

#### EBIO 1210: GENERAL BIOLOGY 1 GT-SC1

**Terms taught**: Fall 2006, Fall 2007, Fall 2008

**Instructor rating**: 4.93

**Standard deviation in instructor rating**: 0.07

**Average grade** (4.0 scale): 2.7

**Standard deviation in grades** (4.0 scale): 0.23

**Average workload** (raw): 2.79

**Standard deviation in workload** (raw): 0.09

#### EBIO 1220: GENERAL BIOLOGY 2 GT-SC1

**Terms taught**: Spring 2007

**Instructor rating**: 5.7

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.24

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 3.4

**Standard deviation in workload** (raw): 0.0

#### IPHY 2420: Nutrition for Health and Performance

**Terms taught**: Fall 2011, Fall 2011, Fall 2011, Fall 2011, Spring 2012, Spring 2012, Spring 2012, Spring 2012, Fall 2012, Fall 2012, Fall 2012, Fall 2012, Spring 2013, Spring 2013, Spring 2013, Spring 2013, Fall 2013, Fall 2013, Fall 2013, Fall 2013, Spring 2014, Spring 2014, Spring 2014, Spring 2014, Fall 2014, Fall 2014, Fall 2014, Fall 2014, Spring 2015, Spring 2015, Spring 2015, Spring 2015, Fall 2015, Fall 2015, Fall 2015, Fall 2015, Spring 2016, Spring 2016, Spring 2016, Spring 2016, Fall 2016, Fall 2016, Fall 2016, Fall 2016, Spring 2017, Spring 2017, Spring 2017, Spring 2017

**Instructor rating**: 5.2

**Standard deviation in instructor rating**: 0.6

**Average grade** (4.0 scale): 3.2

**Standard deviation in grades** (4.0 scale): 0.22

**Average workload** (raw): 2.61

**Standard deviation in workload** (raw): 0.28

#### IPHY 3420: Nutrition, Health, and Performance

**Terms taught**: Spring 2008, Fall 2008, Spring 2009, Spring 2009, Spring 2009, Fall 2009, Fall 2009, Spring 2010, Spring 2010, Spring 2010, Fall 2010, Fall 2010, Fall 2010, Spring 2011, Spring 2011, Spring 2011

**Instructor rating**: 4.44

**Standard deviation in instructor rating**: 0.45

**Average grade** (4.0 scale): 2.82

**Standard deviation in grades** (4.0 scale): 0.23

**Average workload** (raw): 2.7

**Standard deviation in workload** (raw): 0.34


text:
package eu.ehealth.db.xsd;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *

 * Clase Java para Consulter complex type.
 *
 *

 * El siguiente fragmento de esquema especifica el contenido que se espera que
 * haya en esta clase.
 *
 *

 * <complexType name="Consulter">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="phone" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="email" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Consulter", propOrder = { "name", "phone", "email" })
public class Consulter
{

	@XmlElement(required = true)
	protected String name;
	@XmlElement(required = true)
	protected String phone;
	@XmlElement(required = true)
	protected String email;

	/**
	 * Obtiene el valor de la propiedad name.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getName()
	{
		return name;
	}

	/**
	 * Define el valor de la propiedad name.
	 *
	 * @param value allowed object is {@link String }
	 *
	 */
	public void setName(String value)
	{
		this.name = value;
	}

	/**
	 * Obtiene el valor de la propiedad phone.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getPhone()
	{
		return phone;
	}

	/**
	 * Define el valor de la propiedad phone.
	 *
	 * @param value allowed object is {@link String }
	 *
	 */
	public void setPhone(String value)
	{
		this.phone = value;
	}

	/**
	 * Obtiene el valor de la propiedad email.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getEmail()
	{
		return email;
	}

	/**
	 * Define el valor de la propiedad email.
	 *
	 * @param value allowed object is {@link String }
	 *
	 */
	public void setEmail(String value)
	{
		this.email = value;
	}

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp.Structure.MetadataAsSource
{
    internal class MetadataRegionDirectiveStructureProvider : AbstractSyntaxNodeStructureProvider<RegionDirectiveTriviaSyntax>
    {
        private static string GetBannerText(DirectiveTriviaSyntax simpleDirective)
        {
            var kw = simpleDirective.DirectiveNameToken;
            var prefixLength = simpleDirective.HashToken.Span.Length + kw.Span.Length;
            var text = simpleDirective.ToString().Substring(prefixLength).Trim();

            if (text.Length == 0)
            {
                return simpleDirective.HashToken.ToString() + kw.ToString();
            }
            else
            {
                return text;
            }
        }

        protected override void CollectBlockSpans(
            RegionDirectiveTriviaSyntax regionDirective,
            ArrayBuilder<BlockSpan> spans,
            OptionSet options,
            CancellationToken cancellationToken)
        {
            var match = regionDirective.GetMatchingDirective(cancellationToken);
            if (match != null)
            {
                spans.Add(new BlockSpan(
                    isCollapsible: true,
                    textSpan: TextSpan.FromBounds(regionDirective.SpanStart, match.Span.End),
                    type: BlockTypes.PreprocessorRegion,
                    bannerText: GetBannerText(regionDirective),
                    autoCollapse: true));
            }
        }

        protected override bool SupportedInWorkspaceKind(string kind)
        {
            return kind == WorkspaceKind.MetadataAsSource;
        }
    }
}


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
  // Override point for customization after application launch.
  self.window.backgroundColor = [UIColor whiteColor];
  self.window.rootViewController = [RootViewController new];
  [self.window makeKeyAndVisible];

  return YES;
}

- (void)applicationWillTerminate:(UIApplication *)application {
  // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  // Saves changes in the application's managed object context before the application terminates.
  [[DataController instance] saveContext];
}

@end