text:
#ifndef SVGImageForContainer_h
#define SVGImageForContainer_h

#include "core/svg/graphics/SVGImage.h"
#include "platform/geometry/FloatRect.h"
#include "platform/geometry/FloatSize.h"
#include "platform/graphics/Image.h"
#include "platform/weborigin/KURL.h"

namespace blink {

class SVGImageForContainer final : public Image {
    USING_FAST_MALLOC(SVGImageForContainer);
public:
    static PassRefPtr<SVGImageForContainer> create(SVGImage* image, const IntSize& containerSize, float zoom, const KURL& url)
    {
        FloatSize containerSizeWithoutZoom(containerSize);
        containerSizeWithoutZoom.scale(1 / zoom);
        return adoptRef(new SVGImageForContainer(image, containerSizeWithoutZoom, zoom, url));
    }

    IntSize size() const override;

    bool usesContainerSize() const override { return m_image->usesContainerSize(); }
    bool hasRelativeWidth() const override { return m_image->hasRelativeWidth(); }
    bool hasRelativeHeight() const override { return m_image->hasRelativeHeight(); }
    void computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio) override
    {
        m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
    }

    void draw(SkCanvas*, const SkPaint&, const FloatRect&, const FloatRect&, RespectImageOrientationEnum, ImageClampingMode) override;

    void drawPattern(GraphicsContext*, const FloatRect&, const FloatSize&, const FloatPoint&, SkXfermode::Mode, const FloatRect&, const FloatSize& repeatSpacing) override;

    // FIXME: Implement this to be less conservative.
    bool currentFrameKnownToBeOpaque(MetadataMode = UseCurrentMetadata) override { return false; }

    PassRefPtr<SkImage> imageForCurrentFrame() override;

private:
    SVGImageForContainer(SVGImage* image, const FloatSize& containerSize, float zoom, const KURL& url)
        : m_image(image)
        , m_containerSize(containerSize)
        , m_zoom(zoom)
        , m_url(url)
    {
    }

    void destroyDecodedData(bool) override { }

    SVGImage* m_image;
    const FloatSize m_containerSize;
    const float m_zoom;
    const KURL m_url;
};
}

#endif // SVGImageForContainer_h

redpajama_set_name: RedPajamaGithub


text:
package blended.updater.config.util

import java.io._
import java.util.regex.{Matcher, Pattern}

import scala.io.Source
import scala.util.Try

class PlaceholderProcessor(props : Map[String, String], openSeq : String, closeSeq : String, escapeChar : Char = '\\', failOnMissing : Boolean) {

  private[this] val pattern2 = Pattern.compile(s"^\\Q${openSeq}\\E(.*?)\\Q${closeSeq}\\E")

  def process(in : InputStream, out : OutputStream) : Try[Unit] = Try {
    val is = new LineNumberReader(new InputStreamReader(in))
    val ps = new PrintStream(new BufferedOutputStream(out))

    try {
      Iterator.continually(is.readLine()).takeWhile(_ != null).map { line =>
        process(line).get
      } foreach { line =>
        ps.println(line)
      }
    } finally {
      ps.flush()
      ps.close()
    }
  }

  def process(in : File, out : File) : Try[File] = Try {
    val ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(out)))
    try {
      Source.fromFile(in).getLines().map { line =>
        process(line).get
      }.foreach { line =>
        ps.println(line)
      }
    } finally {
      ps.flush()
      ps.close()
    }
    out
  }

  def process(in : String) : Try[String] = Try {
    val sb = new StringBuffer()
    var escaped = false
    var toProcess : String = in

    while (!toProcess.isEmpty()) {
      val head = toProcess.head
      if (escaped) {
        sb.append(head)
        escaped = false
        toProcess = toProcess.tail
      } else if (head == escapeChar) {
        escaped = true
        toProcess = toProcess.tail
      } else {
        val m = pattern2.matcher(toProcess)
        if (m.find()) {
          val variable = m.group(1)
          val replacement = props.get(variable).getOrElse {
            if (failOnMissing) sys.error(s"No property found to replace: ${openSeq}${variable}${closeSeq}")
            else m.group(0)
          }
          m.appendReplacement(sb, Matcher.quoteReplacement(replacement))
          val newTail = new StringBuffer()
          m.appendTail(newTail)
          toProcess = newTail.toString()
        } else {
          sb.append(head)
          toProcess = toProcess.tail
        }
      }
    }
    sb.toString()
  }
}


text:
package FunctionalProgramming.Lab;

import java.util.Arrays;
import java.util.Scanner;
import java.util.function.UnaryOperator;

public class AddVAT {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        UnaryOperator<Double> vatAdder = val -> val * 1.2;

        String[] values = Arrays.stream(scanner.nextLine().split(", "))
                .map(e -> String.format("%.2f", vatAdder.apply(Double.parseDouble(e))))
                .toArray(String[]::new);

       System.out.printf("Prices with VAT: %n%s", String.join("\n", values));
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>View Sources</title>
    <link href="/struts2-showcase-2.0.6/styles/main.css" rel="stylesheet" type="text/css" media="all"/>
    <link href="/struts2-showcase-2.0.6/struts/niftycorners/niftyCorners.css" rel="stylesheet" type="text/css"/>
    <link href="/struts2-showcase-2.0.6/struts/niftycorners/niftyPrint.css" rel="stylesheet" type="text/css" media="print"/>

<link rel="stylesheet" href="/struts2-showcase-2.0.6/struts/xhtml/styles.css" type="text/css"/>

    <link rel="stylesheet" type="text/css" href="/struts2-showcase-2.0.6/struts/tabs.css?config=jar%3Afile%3A%2FC%3A%2Fmol%2Ftools%2Fjakarta-tomcat-5.0.30%2Fwebapps%2Fstruts2-showcase-2.0.6%2FWEB-INF%2Flib%2Fstruts2-config-browser-plugin-2.0.6.jar%21%2Fstruts-plugin.xml%3A25&page=%2Fconfig-browser%2F%2Fconfig-browser%2FactionNames.ftl&className=org.apache.struts2.config_browser.ActionNamesAction">
    <link rel="stylesheet" type="text/css" href="/struts2-showcase-2.0.6/struts/niftycorners/niftyCorners.css?config=jar%3Afile%3A%2FC%3A%2Fmol%2Ftools%2Fjakarta-tomcat-5.0.30%2Fwebapps%2Fstruts2-showcase-2.0.6%2FWEB-INF%2Flib%2Fstruts2-config-browser-plugin-2.0.6.jar%21%2Fstruts-plugin.xml%3A25&page=%2Fconfig-browser%2F%2Fconfig-browser%2FactionNames.ftl&className=org.apache.struts2.config_browser.ActionNamesAction">
    <link rel="stylesheet" type="text/css" href="/struts2-showcase-2.0.6/struts/niftycorners/niftyPrint.css?config=jar%3Afile%3A%2FC%3A%2Fmol%2Ftools%2Fjakarta-tomcat-5.0.30%2Fwebapps%2Fstruts2-showcase-2.0.6%2FWEB-INF%2Flib%2Fstruts2-config-browser-plugin-2.0.6.jar%21%2Fstruts-plugin.xml%3A25&page=%2Fconfig-browser%2F%2Fconfig-browser%2FactionNames.ftl&className=org.apache.struts2.config_browser.ActionNamesAction" media="print">

Struts Showcase

2007/04/06 03:17:42

View Sources

/actionNames.ftl

jar:file:/C:/mol/tools/jakarta-tomcat-5.0.30/webapps/struts2-showcase-2.0.6/WEB-INF/lib/struts2-config-browser-plugin-2.0.6.jar!/struts-plugin.xml

15:
16:         <global-results>
17:             <result name="error" type="freemarker">/config-browser/error.ftl</result>
18:             <result name="input" type="freemarker">/config-browser/error.ftl</result>
19:         </global-results>
20:
21:         <action name="index">
22:             <result type="redirect-action">actionNames</result>
23:         </action>
24:
25:         <action name="actionNames" class="org.apache.struts2.config_browser.ActionNamesAction">
26:             <result type="freemarker" name="success">/config-browser/actionNames.ftl</result>
27:         </action>
28:
29:         <action name="showConfig" class="org.apache.struts2.config_browser.ShowConfigAction">
30:             <result type="freemarker" name="success">/config-browser/showConfig.ftl</result>
31:         </action>
32:
33:         <action name="showValidators" class="org.apache.struts2.config_browser.ListValidatorsAction">
34:             <result name="error" type="freemarker">/config-browser/simple-error.ftl</result>
35:             <result name="input" type="freemarker">/config-browser/simple-error.ftl</result>

/org/apache/struts2/config_browser/ActionNamesAction.java

Navigation

Home

Ajax

Ajax Chat

Action Chaining

Config Browser

Conversion

CRUD

Execute & Wait

File Download

File Upload

Freemarker

Hangman

JavaServer Faces

Person Manager

Tags

Tiles

Token

Validation

Help

        View Sources

Copyright © 2003-2007 The Apache Software Foundation.


text:
/**
 * Github Burndown
 */

var Client = require('github'),
    readline = require('readline'),
    async = require('async'),
    flatfile = require('flat-file-db'),
    moment = require('moment'),
    Table = require('cli-table');

var db = flatfile.sync('cache.db');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

var github = new Client({
    debug: false,
    version: "3.0.0"
});

var debug = false;

/**
 * Set these values based on project specific
 * details.
 */

var project = {
  repo: 'Fortune-Gate',    // repo name
  user: 'clevertech',      // user/organization
  milestone: 'Sprint 19',  // current milestone
  startDate: '2015-5-15'   // milestone start date (YYYY-MM-DD)
}

function fetchGithub() {
  var page = 1;

  rl.question("GitHub user name: ", function(answer) {
    hidden("Password: ", function(answer2) {
      github.authenticate({
          type: "basic",
          username: answer,
          password: answer2
      });

      var issues = [];
      var lastLength = 0;

      github.issues.getAllMilestones({repo: project.repo, user: project.user, state: 'open'}, function(errM, milestones) {
        var milestone = null;

        milestones.forEach(function(m) {
          if(m.title === project.milestone)
            milestone = m;
        });

        async.forever(
          function(callback) {
            github.issues.repoIssues({repo: project.repo, user: project.user, state: 'all', milestone: milestone.number, per_page: 100, page: page++}, function(err, res) {
              if(!res) return callback(new Error('Empty response.'));
              if(!res.length) return callback(new Error('Empty response.'));

              issues = issues.concat(res);

              console.log('.')

              if(res.length < 100) return callback(new Error('Empty response.'));

                callback(err);

            });
          }, function(err) {
            // done
            console.log('Done fetching.')

            db.put('issues', issues);
            processTickets(issues);

        });
      });

      rl.close();
    });
  });
}

function flattenLabels(issue) {
  var labels = [];

  issue.labels.forEach(function(label) {
    labels.push(label.name)
  });

  return labels;
}

function getHours(issue) {
  var hours = 0;

  issue.labels.forEach(function(label) {
    switch(label.name) {
    case 'est-64': hours += 64; break;
    case 'est-32': hours += 32; break;
    case 'est-16': hours += 16; break;
    case 'est-8': hours  += 8; break;
    case 'est-4': hours  += 4; break;
    case 'est-2': hours  += 2; break;
    case 'est-1': hours  += 1; break;
    }
  });

  return hours;
}

function getBusinessDays(start, end) {
  var first = start.clone().endOf('week');
  var last = end.clone().startOf('week');
  var days = last.diff(first,'days') * 5 / 7;
  var wfirst = first.day() - start.day();
  if(start.day() == 0) --wfirst;
  var wlast = end.day() - last.day();
  if(end.day() == 6) --wlast;
  return wfirst + days + wlast;
  return 1;
}

function addBusinessDays(date, days) {
  date = moment(date); // use a clone
  while (days > 0) {
    date = date.add(1, 'days');
    // decrease "days" only if it's a weekday.
    if (date.isoWeekday() !== 6 && date.isoWeekday() !== 7) {
      days -= 1;
    }
  }
  return date;
}

function processTickets(issues) {
  var stats = {
    open: 0,
    closed: 0,
    test: 0,
    new: 0,
    inProgress: 0,
    hoursOpen: 0,
    hoursNew: 0,
    hoursClosed: 0,
    hoursInProgress: 0,
    hoursTest: 0,
    todayClosed: 0,
    todayTest: 0
  }

  issues.forEach(function(issue) {

    issue.labelList = flattenLabels(issue);
    issue.hours = getHours(issue);

    if(issue.state === 'open'){

      if(issue.labelList.indexOf('stt-test') !== -1) {
        stats.test++;
        stats.hoursTest += issue.hours;
      }else{
        stats.open++;
        stats.hoursOpen += issue.hours;
      }

      if(issue.labelList.indexOf('stt-new') !== -1) {
        stats.new++;
        stats.hoursNew += issue.hours;
      }

      if(issue.labelList.indexOf('stt-in-progress') !== -1) {
        stats.inProgress++;
        stats.hoursInProgress += issue.hours;
      }
    }else{
      stats.closed++;
      stats.hoursClosed += issue.hours;
    }
  });

  var startDate = moment(project.startDate, 'YYYY-MM-DD');
  var workedDays = getBusinessDays(startDate, moment());

  var rate1 = {}, rate2 = {}, rate3 = {};

  rate1.burndownRate = (stats.hoursClosed + stats.hoursTest + stats.hoursInProgress) / workedDays;
  rate1.endDate = addBusinessDays(moment(), stats.hoursOpen / rate1.burndownRate);

  rate2.burndownRate = (stats.hoursClosed + stats.hoursTest) / workedDays;
  rate2.endDate = addBusinessDays(moment(), stats.hoursOpen / rate2.burndownRate);

  rate3.burndownRate = (stats.hoursClosed) / workedDays;
  rate3.endDate = addBusinessDays(moment(), stats.hoursOpen / rate3.burndownRate);

  // draw table

  var table = new Table({
      head: ['Tickets', ''],
      colWidths: [30, 45]
  });

  table.push(
      ['Open', stats.open + ' tickets (' + stats.hoursOpen + 'h)'],
      //['New', stats.new + ' tickets (' + stats.hoursNew + 'h)'],
    ['In Progress', stats.inProgress + ' tickets (' + stats.hoursInProgress + 'h)'],
    ['Test', stats.test + ' tickets (' + stats.hoursTest + 'h)'],
    ['Closed', stats.closed + ' tickets (' + stats.hoursClosed + 'h)']
  );

  console.log('```');
  console.log(table.toString());
  console.log('```');
  console.log('');

  table.push(
    ['Worked days', workedDays],
    ['Test + Closed',               'End: ' + rate2.endDate.format('MMMM Do, YYYY') +
                    ' (at ' + rate2.burndownRate.toFixed(2) + 'h/day' + ')'],
    ['Closed',                      'End: ' + rate3.endDate.format('MMMM Do, YYYY') +
                    ' (at ' + rate3.burndownRate.toFixed(2) + 'h/day' + ')']
  );

  console.log('```');
  console.log(table.toString());
  console.log('```');
}

function hidden(query, callback) {
  var stdin = process.openStdin();
  process.stdin.on("data", function(char) {
    char = char + "";
    switch (char) {
      case "\n":
      case "\r":
      case "\u0004":
        stdin.pause();
        break;
      default:
        process.stdout.write("\033[2K\033[200D" + query + Array(rl.line.length+1).join("*"));
        break;
    }
  });

  rl.question(query, function(value) {
    rl.history = rl.history.slice(1);
    callback(value);
  });
}

var cachedIssues = db.get('issues');

if(!cachedIssues || !debug)
  fetchGithub();
else
  processTickets(cachedIssues);


text:
<?php
/**
 * The following variables are available in this template:
 * - $this: the CrudCode object
 */
?>
<?php
echo "<?php\n";
$label=$this->pluralize($this->class2name($this->modelClass));
echo "\$this->pageCaption='Manage $label';
\$this->pageTitle=Yii::app()->name . ' - ' . \$this->pageCaption;
\$this->pageDescription='Administer all ".strtolower($label)."';
\$this->breadcrumbs=array(
	'$label'=>array('index'),
	'Manage',
);\n";
?>

$this->menu=array(
	array('label'=>'List <?php echo $label; ?>', 'url'=>array('index')),
	array('label'=>'Create <?php echo $this->modelClass; ?>', 'url'=>array('create')),
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
	$('.search-form').toggle();
	return false;
});
$('.search-form form').submit(function(){
	$.fn.yiiGridView.update('<?php echo $this->class2id($this->modelClass); ?>-grid', {
		data: $(this).serialize()
	});
	return false;
});
");
?>

You may optionally enter a comparison operator (<, <=, >, >=, <>
or =) at the beginning of each of your search values to specify how the comparison should be done.

<?php echo "<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>"; ?>

<?php echo "<?php \$this->renderPartial('_search',array(
	'model'=>\$model,
)); ?>\n"; ?>

<?php echo "<?php"; ?> $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'<?php echo $this->class2id($this->modelClass); ?>-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'cssFile'=>Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.bootstrap-theme.widgets.assets')).'/gridview/styles.css',
	'itemsCssClass'=>'zebra-striped',
	'columns'=>array(
<?php
$count=0;
foreach($this->tableSchema->columns as $column)
{
	if(++$count==7)
		echo "\t\t/*\n";
	echo "\t\t'".$column->name."',\n";
}
if($count>=7)
	echo "\t\t*/\n";
?>
		array(
			'class'=>'CButtonColumn',
		),
	),
)); ?>


text:
layout: page
title: DeleteUserSelfError
number: 22
categories: [AvaTax Error Codes]
disqus: 1
---

## Summary

A user account may not call DELETE on the user itself.

## Example

```json
{
  "code": "DeleteUserSelfError",
  "target": "Unknown",
  "details": [
    {
      "code": "DeleteUserSelfError",
      "number": 22,
      "message": "Profile can't be deleted.",
      "description": "You can't delete your own profile. Contact your account administrator for help. -0-",
      "faultCode": "Client",
      "helpLink": "http://developer.avalara.com/avatax/errors/DeleteUserSelfError",
      "severity": "Error"
    }
  ]
}
```

## Explanation

As a user that has successfully authenticated against AvaTax, you may not call DELETE on your own user object.  To delete this user, please use different account credentials.


text:
package org.dcm4chex.archive.web.maverick;

import org.dcm4chex.archive.ejb.interfaces.ContentEdit;
import org.dcm4chex.archive.ejb.interfaces.ContentEditHome;
import org.dcm4chex.archive.util.EJBHomeFactory;
import org.dcm4chex.archive.web.maverick.model.PatientModel;

/**
 * @author umberto.cappellini@tiani.com
 */
public class PatientUpdateCtrl extends Dcm4JbossController {
    private int pk;

    private String patientID = "";

    private String issuerOfPatientID = "";

    private String patientName = "";

    private String patientSex = "";

    private String patientBirthDate = "";

    private String submit = null;

    private String cancel = null;

    protected String perform() throws Exception {
        if (submit != null)
            if (pk == -1)
                executeCreate();
            else
                executeUpdate();
        return SUCCESS;
    }

    private void executeCreate() {
        try {
	        PatientModel pat = new PatientModel();
	        pat.setPk(-1);
	        pat.setSpecificCharacterSet("ISO_IR 100");
	        pat.setPatientID(patientID);
	        pat.setIssuerOfPatientID(issuerOfPatientID);
	        pat.setPatientSex(patientSex);
	        pat.setPatientName(patientName);
	        pat.setPatientBirthDate(patientBirthDate);
	        ContentEdit ce = lookupContentEdit();
	        ce.createPatient(pat.toDataset());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private ContentEdit lookupContentEdit() throws Exception {
        ContentEditHome home = (ContentEditHome) EJBHomeFactory.getFactory()
                .lookup(ContentEditHome.class, ContentEditHome.JNDI_NAME);
        return home.create();
    }

    private void executeUpdate() {
        try {
            PatientModel pat = FolderForm.getFolderForm(
                    getCtx().getRequest()).getPatientByPk(pk);
            pat.setPatientSex(patientSex);
            pat.setPatientName(patientName);

            pat.setPatientBirthDate(patientBirthDate);
            //updating data model
            ContentEdit ce = lookupContentEdit();
            ce.updatePatient(pat.toDataset());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public final void setIssuerOfPatientID(String issuerOfPatientID) {
        this.issuerOfPatientID = issuerOfPatientID.trim();
    }

    public final void setPatientID(String patientID) {
        this.patientID = patientID.trim();
    }

    public final void setPatientName(String patientName) {
        this.patientName = patientName.trim();
    }

    public final void setPatientSex(String patientSex) {
        this.patientSex = patientSex.trim();
    }

    public final void setPatientBirthDate(String date) {
        this.patientBirthDate = date.trim();
    }

    public final void setPk(int pk) {
        this.pk = pk;
    }

    public final void setSubmit(String update) {
        this.submit = update;
    }

    public final void setCancel(String cancel) {
        this.cancel = cancel;
    }
}


text:
/*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';

// Add button to task detail view
togglbutton.render('[id^=taskview_task_]:not(.toggl)', {observe: true}, function (elem) {
  var link,
    titleElem   = $('h3 > span.title.ng-binding', elem),
    projectElem = $('div > div.item.project.ng-binding', elem),
    description = !!titleElem ? titleElem.textContent : '',
    project = !!projectElem ? projectElem.textContent : '',
    firstOp;

  if (project !== '') {
    project = project.substring(1);  // remove '#'
  }

  link = togglbutton.createTimerLink({
    className: 'doit',
    description: description,
    projectName: project
  });

  firstOp = $('li.task-op').children[0];
  $('li.task-op').insertBefore(link, firstOp);
});

// Add button to popup form ( like when editing project )
togglbutton.render('#taskform > div > div.taskform-main:not(.toggl)', {observe: true}, function (elem) {
  var link,
    titleElem   = $('li.meta.task-title > div > div > div.textarea-tmp', elem),
    projectElem = $('li.meta.task-project.smart > div > div > ul > li.token > div', elem),
    description = !!titleElem ? titleElem.textContent : '',
    project = !!projectElem ? projectElem.textContent : '';

  link = togglbutton.createTimerLink({
    className: 'doit',
    description: description,
    projectName: project
  });

  titleElem.parentElement.appendChild(link);
});

// Add button to tasks in the list
togglbutton.render('li.task:not(.toggl)', {observe: true}, function (elem) {
  var link,
    titleElem   = $('div.title > a.link-title', elem),
    projectElem = $('div.title > a.project', elem),
    description = !!titleElem ? titleElem.textContent : '',
    project,
    projectHeader = $('#project_info:not(.ng-hide)');

  if (!!projectHeader) {
    project = document.querySelector("#project_info span.title").textContent;
  } else {
    project = !!projectElem ? projectElem.textContent : '';
    if (project !== '') {
      project = project.substring(1);  // remove '#'
    }
  }

  link = togglbutton.createTimerLink({
    className: 'doit',
    buttonType: 'minimal',
    description: description,
    projectName: project
  });

  titleElem.parentElement.appendChild(link);
});


text:
package org.genericsystem.kernel;

import org.genericsystem.api.core.annotations.Components;
import org.genericsystem.api.core.annotations.SystemGeneric;
import org.genericsystem.api.core.annotations.constraints.InstanceValueGenerator;
import org.genericsystem.common.Generic;
import org.genericsystem.defaults.IntSequenceGenerator;
import org.genericsystem.defaults.IntSequenceGenerator.StringSequenceGenerator;
import org.testng.annotations.Test;

@Test
public class SequenceTest extends AbstractTest {

	public void testFindSequence() {
		Engine root = new Engine();
		Generic sequence = root.getSequence();
		assert sequence != null;
		assert sequence.getMeta() == root.getMetaAttribute();
		assert sequence.getComponents().contains(root);
	}

	public void testStringAutoIncrementGenerator() {
		// Root root = new Root(Car.class);
		// Generic car = root.find(Car.class);
		// Generic myBmw = car.addGenerateInstance();
		// assert myBmw.getValue() instanceof String;
		// assert ((String) myBmw.getValue()).contains(Car.class.getSimpleName());

		Engine root = new Engine(Car.class);
		Generic car = root.find(Car.class);
		Generic myBmw = car.addInstance(null);
		assert myBmw.getValue() instanceof String;
		assert ((String) myBmw.getValue()).contains(Car.class.getSimpleName());
	}

	public void testIntAutoIncrementGenerator() {
		Engine root = new Engine(CarInt.class);
		Generic car = root.find(CarInt.class);
		Generic myBmw = car.addInstance(null);
		assert myBmw.getValue() instanceof Integer;
		assert ((Integer) myBmw.getValue()) == 0;
	}

	public void testHolderIntAutoIncrementGenerator() {
		Engine root = new Engine(Id.class);
		Generic id = root.find(Id.class);
		Generic vehicle = root.find(Vehicle.class);
		Generic myVehicle = vehicle.addInstance("myVehicle");
		Generic myVehicleId = id.addInstance(null, myVehicle);
		assert myVehicleId.getValue() instanceof Integer;
		assert ((Integer) myVehicleId.getValue()) == 0;
		Generic myVehicleId2 = id.addInstance(null, myVehicle);
		assert ((Integer) myVehicleId2.getValue()) == 1;
	}

	@SystemGeneric
	@InstanceValueGenerator(StringSequenceGenerator.class)
	public static class Car {

	}

	@SystemGeneric
	@InstanceValueGenerator(IntSequenceGenerator.class)
	public static class CarInt {

	}

	@SystemGeneric
	public static class Vehicle {

	}

	@SystemGeneric
	@Components(Vehicle.class)
	@InstanceValueGenerator(IntSequenceGenerator.class)
	public static class Id {

	}

}


text:
const keySecret = "pk_test_6pRNASCoBOKtIshFeQd4XMUh"
const Stripe = require("stripe")(keySecret);

module.exports.show = function(req, res) {
	res.render('payment');
};

module.exports.pay = function(req, res) {
	// Set your Stripe publishable API key here
	// Stripe.setPublishableKey('pk_test_6pRNASCoBOKtIshFeQd4XMUh');
	// var Stripe = Stripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh');

	$(function() {
	    var $form = $('#payment-form');
	    $form.submit(function(event){
	        // Disable the submit button to prevent repeated clicks:
	        $form.find('.submit').prop('disabled', true).html('Please wait...');

	        // Request a token from Stripe:
	        Stripe.card.createToken($form, stripeResponseHandler);

	        // Prevent the form from being submitted:
	        return false;
	    });

	    // Format the card number
	    $('#number').payment('formatCardNumber');
	});

	function stripeResponseHandler(status, response){
	    var $form = $('#payment-form');

	    // Clear any existing errors
	    $form.find('.has-error').removeClass('has-error')

	    if (response.error){
	        // Show the errors on the form
	        $form.find('.payment-errors').text(response.error.message).addClass('alert alert-danger');
	        $form.find('#' + response.error.param).parents('.form-group').addClass('has-error');
	        $form.find('button').prop('disabled', false).text('Pay $20'); // Re-enable submission and change amount to db call
	    } else { // Token was created!
	            // Get the token ID:
	        var token = response.id;

	        // Insert the token into the form so it gets submitted to the server:
	        $form.append($('<input type="hidden" name="stripeToken" />').val(token));

	        // Submit the form:
	        $form.get(0).submit();
	    }
	}
};


text:
<?php

/**
 * Zend_Sniffs_Files_LineEndingsSniff.
 *
 * Checks that the file does not end with a closing tag.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @author    Marc McIntyre <mmcintyre@squiz.net>
 * @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
 * @version   Release: 1.4.3
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class Zend_Sniffs_Files_ClosingTagSniff implements PHP_CodeSniffer_Sniff
{

    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @return array
     */
    public function register()
    {
        return array(T_CLOSE_TAG);

    }//end register()

    /**
     * Processes this sniff, when one of its tokens is encountered.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
     * @param int                  $stackPtr  The position of the current token in
     *                                        the stack passed in $tokens.
     *
     * @return void
     */
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        $next = $phpcsFile->findNext(T_INLINE_HTML, ($stackPtr + 1), null, true);
        if ($next !== false) {
            return;
        }

        // We've found the last closing tag in the file so the only thing
        // potentially remaining is inline HTML. Now we need to figure out
        // whether or not it's just a bunch of whitespace.
        $content = '';
        for ($i = ($stackPtr + 1); $i < $phpcsFile->numTokens; $i++) {
            $content .= $tokens[$i]['content'];
        }

        // Check if the remaining inline HTML is just whitespace.
        $content = trim($content);
        if (empty($content) === true) {
            $error = 'A closing tag is not permitted at the end of a PHP file';
            $phpcsFile->addError($error, $stackPtr, 'NotAllowed');
        }

    }//end process()

}//end class

?>


text:
#include "ion/base/allocator.h"

#include "ion/base/allocationmanager.h"
#include "ion/base/logchecker.h"
#include "ion/base/tests/testallocator.h"
#include "third_party/googletest/googletest/include/gtest/gtest.h"

namespace {

// A derived Allocator class used only for testing SetTracker()/GetTracker().
class DummyAllocator : public ion::base::Allocator {
 public:
  // Implementations don't matter - they will never be called.
  void* Allocate(size_t size) override { return nullptr; }
  void Deallocate(void* p) override {}
};

}  // anonymous namespace

TEST(Allocator, RefCount) {
  using ion::base::testing::TestAllocator;
  using ion::base::testing::TestAllocatorPtr;

  TestAllocator::ClearNumCreations();
  TestAllocator::ClearNumDeletions();

  {
    TestAllocatorPtr p;
  }
  EXPECT_EQ(0U, TestAllocator::GetNumCreations());
  EXPECT_EQ(0U, TestAllocator::GetNumDeletions());

  {
    TestAllocatorPtr p(new TestAllocator);
    EXPECT_EQ(1, p->GetRefCount());
    TestAllocatorPtr p2 = p;
    EXPECT_EQ(2, p->GetRefCount());
    EXPECT_EQ(1U, TestAllocator::GetNumCreations());
    EXPECT_EQ(0U, TestAllocator::GetNumDeletions());
  }
  EXPECT_EQ(1U, TestAllocator::GetNumCreations());
  EXPECT_EQ(1U, TestAllocator::GetNumDeletions());

  TestAllocator::ClearNumCreations();
  TestAllocator::ClearNumDeletions();
}

TEST(Allocator, GetAllocatorForLifetime) {
  using ion::base::AllocationManager;
  using ion::base::kShortTerm;
  using ion::base::kMediumTerm;
  using ion::base::kLongTerm;

  ion::base::testing::TestAllocatorPtr p(new ion::base::testing::TestAllocator);

  // The base Allocator class should return the same Allocators as the
  // AllocationManager.
  EXPECT_EQ(AllocationManager::GetDefaultAllocatorForLifetime(kShortTerm),
            p->GetAllocatorForLifetime(kShortTerm));
  EXPECT_EQ(AllocationManager::GetDefaultAllocatorForLifetime(kMediumTerm),
            p->GetAllocatorForLifetime(kMediumTerm));
  EXPECT_EQ(AllocationManager::GetDefaultAllocatorForLifetime(kLongTerm),
            p->GetAllocatorForLifetime(kLongTerm));

  // Override Allocators.
  p->SetAllocatorForLifetime(kMediumTerm, p);
  EXPECT_EQ(AllocationManager::GetDefaultAllocatorForLifetime(kShortTerm),
            p->GetAllocatorForLifetime(kShortTerm));
  EXPECT_EQ(p.Get(), p->GetAllocatorForLifetime(kMediumTerm).Get());
  EXPECT_EQ(AllocationManager::GetDefaultAllocatorForLifetime(kLongTerm),
            p->GetAllocatorForLifetime(kLongTerm));

  p->SetAllocatorForLifetime(kShortTerm, p);
  EXPECT_EQ(p.Get(), p->GetAllocatorForLifetime(kShortTerm).Get());
  EXPECT_EQ(p.Get(), p->GetAllocatorForLifetime(kMediumTerm).Get());
  EXPECT_EQ(AllocationManager::GetDefaultAllocatorForLifetime(kLongTerm),
            p->GetAllocatorForLifetime(kLongTerm));

  // p refs itself as a default allocator, so cleanup is necessary to avoid
  // a memory leak report.
  p->SetAllocatorForLifetime(kShortTerm, ion::base::AllocatorPtr());
  p->SetAllocatorForLifetime(kMediumTerm, ion::base::AllocatorPtr());
}

TEST(Allocator, Tracker) {
  ion::base::AllocatorPtr al(new DummyAllocator);
  EXPECT_FALSE(al->GetTracker());
  ion::base::AllocationTrackerPtr tr(new ion::base::FullAllocationTracker);
  al->SetTracker(tr);
  EXPECT_EQ(tr, al->GetTracker());
  al->SetTracker(ion::base::AllocationTrackerPtr());
  EXPECT_FALSE(al->GetTracker());
}


text:
"""
The MIT License (MIT)

Copyright (c) 2015-present Rapptz

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

from __future__ import annotations

from . import utils
from .user import BaseUser
from .asset import Asset
from .enums import TeamMembershipState, try_enum

from typing import TYPE_CHECKING, Optional, List

if TYPE_CHECKING:
    from .state import ConnectionState

    from .types.team import (
        Team as TeamPayload,
        TeamMember as TeamMemberPayload,
    )

__all__ = (
    'Team',
    'TeamMember',
)

class Team:
    """Represents an application team for a bot provided by Discord.

    Attributes
    -------------
    id: :class:`int`
        The team ID.
    name: :class:`str`
        The team name
    owner_id: :class:`int`
        The team's owner ID.
    members: List[:class:`TeamMember`]
        A list of the members in the team

        .. versionadded:: 1.3
    """

    __slots__ = ('_state', 'id', 'name', '_icon', 'owner_id', 'members')

    def __init__(self, state: ConnectionState, data: TeamPayload):
        self._state: ConnectionState = state

        self.id: int = int(data['id'])
        self.name: str = data['name']
        self._icon: Optional[str] = data['icon']
        self.owner_id: Optional[int] = utils._get_as_snowflake(data, 'owner_user_id')
        self.members: List[TeamMember] = [TeamMember(self, self._state, member) for member in data['members']]

    def __repr__(self) -> str:
        return f'<{self.__class__.__name__} id={self.id} name={self.name}>'

    @property
    def icon(self) -> Optional[Asset]:
        """Optional[:class:`.Asset`]: Retrieves the team's icon asset, if any."""
        if self._icon is None:
            return None
        return Asset._from_icon(self._state, self.id, self._icon, path='team')

    @property
    def owner(self) -> Optional[TeamMember]:
        """Optional[:class:`TeamMember`]: The team's owner."""
        return utils.get(self.members, id=self.owner_id)

class TeamMember(BaseUser):
    """Represents a team member in a team.

    .. container:: operations

        .. describe:: x == y

            Checks if two team members are equal.

        .. describe:: x != y

            Checks if two team members are not equal.

        .. describe:: hash(x)

            Return the team member's hash.

        .. describe:: str(x)

            Returns the team member's name with discriminator.

    .. versionadded:: 1.3

    Attributes
    -------------
    name: :class:`str`
        The team member's username.
    id: :class:`int`
        The team member's unique ID.
    discriminator: :class:`str`
        The team member's discriminator. This is given when the username has conflicts.
    bot: :class:`bool`
        Specifies if the user is a bot account.
    team: :class:`Team`
        The team that the member is from.
    membership_state: :class:`TeamMembershipState`
        The membership state of the member (e.g. invited or accepted)
    """

    __slots__ = ('team', 'membership_state', 'permissions')

    def __init__(self, team: Team, state: ConnectionState, data: TeamMemberPayload):
        self.team: Team = team
        self.membership_state: TeamMembershipState = try_enum(TeamMembershipState, data['membership_state'])
        self.permissions: List[str] = data['permissions']
        super().__init__(state=state, data=data['user'])

    def __repr__(self) -> str:
        return (
            f'<{self.__class__.__name__} id={self.id} name={self.name!r} '
            f'discriminator={self.discriminator!r} membership_state={self.membership_state!r}>'
        )


text:
from testagent.parser.parser import Parser
from testagent.parser.collector_parser import CollectorParser
from testagent.parser.testcase_parser import TestCaseParser
from testagent.parser.testinstance_parser import TestInstanceParser


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.activiti5.engine.impl.persistence.entity;

import org.activiti5.engine.impl.persistence.AbstractManager;

/**
 * @author Joram Barrez
 * @author Marcus Klimstra (CGI)
 */
public class ByteArrayEntityManager extends AbstractManager {

  public ByteArrayEntity findById(String byteArrayEntityId) {
    return getDbSqlSession().selectById(ByteArrayEntity.class, byteArrayEntityId);
  }

  /**
   * Deletes the {@link ByteArrayEntity} with the given id from the database.
   * Important: this operation will NOT do any optimistic locking, to avoid loading the
   * bytes in memory. So use this method only in conjunction with an entity that has
   * optimistic locking!.
   */
  public void deleteByteArrayById(String byteArrayEntityId) {
    getDbSqlSession().delete("deleteByteArrayNoRevisionCheck", byteArrayEntityId);
  }

  public void deleteByteArray(ByteArrayEntity byteArray) {
    getDbSqlSession().delete(byteArray);
  }

}


text:
require 'net/http'
require 'uri'

# Make the HTTP socket timeout 10 seconds
class BufferedIO   #:nodoc: internal use only
  def initialize(io)
    @io = io
    @read_timeout = 10 # overrides the default in the Ruby lib, which is 60 seconds.
    @debug_output = nil
    @rbuf = ''
  end
end

module Net
  class HTTP

    # Convenience method to do HTTP GET with custom headers
    def HTTP.get_with_headers(host, port, path, headers)
      start(host, port) do |http|
        return http.get(path, headers)
      end
    end
  end
end


text:
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;

public class CollectionSet
{
	private static final Logger LOGGER = LogManager.getLogger(CollectionSet.class);

	@SuppressWarnings("unchecked")
	public static void main(String[] args)
	{
		Dog ouou = new Dog("欧欧","雪纳瑞");
		Dog yaya = new Dog("亚亚","拉布拉多");
		Dog feifei = new Dog("菲菲","拉布拉多");
		Dog meimei = new Dog("美美","雪纳瑞");

		Set<Dog> dogs = new HashSet<>();
		dogs.add(ouou);
		dogs.add(yaya);
		dogs.add(meimei);
		dogs.add(feifei);

		//2.for each遍历循环和输出结果
		LOGGER.info ("使用for each迭代器遍历集合。");

		for(Object obj : dogs)
		{
			LOGGER.info (obj);
		}

		//迭代遍历循环和输出结果
		LOGGER.info ("使用iterator迭代器遍历集合。");

		Iterator iterator = dogs.iterator();
		while(iterator.hasNext())
		{
			Dog dog = (Dog)iterator.next();
			LOGGER.info(iterator.next());
		}
	}
}
class Dog
{
	private String name;
	private String varieties;
	public Dog(String name, String varieties)
	{
		this.name = name;
		this.varieties = varieties;
	}

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

	public String getName()
	{
		return this.name;
	}

	public void setVarieties(String varieties)
	{
		this.varieties = varieties;
	}

	public String getVarieties()
	{
		return this.varieties;
	}

	@Override
	public String toString()
	{
		return name + "\"" + varieties;

	}
}


text:
#include <aws/glue/model/StreamingDataPreviewOptions.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Glue
{
namespace Model
{

StreamingDataPreviewOptions::StreamingDataPreviewOptions() :
    m_pollingTime(0),
    m_pollingTimeHasBeenSet(false),
    m_recordPollingLimit(0),
    m_recordPollingLimitHasBeenSet(false)
{
}

StreamingDataPreviewOptions::StreamingDataPreviewOptions(JsonView jsonValue) :
    m_pollingTime(0),
    m_pollingTimeHasBeenSet(false),
    m_recordPollingLimit(0),
    m_recordPollingLimitHasBeenSet(false)
{
  *this = jsonValue;
}

StreamingDataPreviewOptions& StreamingDataPreviewOptions::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("PollingTime"))
  {
    m_pollingTime = jsonValue.GetInt64("PollingTime");

    m_pollingTimeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("RecordPollingLimit"))
  {
    m_recordPollingLimit = jsonValue.GetInt64("RecordPollingLimit");

    m_recordPollingLimitHasBeenSet = true;
  }

  return *this;
}

JsonValue StreamingDataPreviewOptions::Jsonize() const
{
  JsonValue payload;

  if(m_pollingTimeHasBeenSet)
  {
   payload.WithInt64("PollingTime", m_pollingTime);

  }

  if(m_recordPollingLimitHasBeenSet)
  {
   payload.WithInt64("RecordPollingLimit", m_recordPollingLimit);

  }

  return payload;
}

} // namespace Model
} // namespace Glue
} // namespace Aws


text:
package sqs

import (
	"runtime"
	"sync"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/service/sqs"
	"github.com/toomore/simpleaws/utils"
)

// SQS struct
type SQS struct {
	url *string
	sqs *sqs.SQS
}

// Send to send a queue message.
func (s SQS) Send(Body string) (*sqs.SendMessageOutput, error) {
	return s.sqs.SendMessage(&sqs.SendMessageInput{
		MessageBody: aws.String(string(utils.Base64Encode([]byte(Body)))),
		QueueURL:    s.url,
	})
}

// Receive to receive a queue message.
func (s SQS) Receive(Visibility int64) (*sqs.ReceiveMessageOutput, error) {
	return s.sqs.ReceiveMessage(&sqs.ReceiveMessageInput{
		MaxNumberOfMessages: aws.Long(10),
		QueueURL:            s.url,
		VisibilityTimeout:   aws.Long(Visibility),
	})
}

// Delete to delete a queue message.
func (s SQS) Delete(ReceiptHandle *string) (*sqs.DeleteMessageOutput, error) {
	return s.sqs.DeleteMessage(&sqs.DeleteMessageInput{
		QueueURL:      s.url,
		ReceiptHandle: ReceiptHandle,
	})
}

// sendBatch to send batch messages.
func (s SQS) sendBatch(Bodies []string) (*sqs.SendMessageBatchOutput, error) {
	var entries []*sqs.SendMessageBatchRequestEntry
	entries = make([]*sqs.SendMessageBatchRequestEntry, len(Bodies))

	for i, body := range Bodies {
		entries[i] = &sqs.SendMessageBatchRequestEntry{
			ID:          aws.String(string(97 + i)),
			MessageBody: aws.String(string(utils.Base64Encode([]byte(body)))),
		}
	}
	return s.sqs.SendMessageBatch(&sqs.SendMessageBatchInput{
		Entries:  entries,
		QueueURL: s.url,
	})
}

// BatchOutput struct
type BatchOutput struct {
	Output *sqs.SendMessageBatchOutput
	Error  error
}

// SendBatch to split Bodies into batch messages and send.
func (s SQS) SendBatch(Bodies []string) []*BatchOutput {
	var (
		BodiesLen   = len(Bodies)
		maxlen      = 10
		times       = BodiesLen / maxlen
		more        = BodiesLen % maxlen
		wg          sync.WaitGroup
		result      chan *BatchOutput
		do          func([]string)
		batchOutput []*BatchOutput
	)

	result = make(chan *BatchOutput)
	do = func(Bodies []string) {
		defer wg.Done()
		runtime.Gosched()
		var b = &BatchOutput{}
		b.Output, b.Error = s.sendBatch(Bodies)
		result <- b
	}

	wg.Add(times)

	if more > 0 {
		wg.Add(1)
		go do(Bodies[maxlen*times : maxlen*times+more])
	}
	for i := 0; i < times; i++ {
		go do(Bodies[maxlen*i : maxlen*(i+1)])
	}

	batchOutput = make([]*BatchOutput, 0)
	go func() {
		for {
			select {
			case v, ok := <-result:
				if ok {
					batchOutput = append(batchOutput, v)
				}
			}
		}
	}()
	wg.Wait()
	return batchOutput
}

// PurgeQueue to purge queue all messages.
func (s SQS) PurgeQueue() (*sqs.PurgeQueueOutput, error) {
	return s.sqs.PurgeQueue(&sqs.PurgeQueueInput{
		QueueURL: s.url,
	})
}

// New to new a sqs.
func New(AWSID, AWSKEY, Region, URL string) *SQS {
	var config = aws.DefaultConfig
	config.Region = Region
	config.Credentials = credentials.NewStaticCredentials(AWSID, AWSKEY, "")
	return &SQS{
		url: aws.String(URL),
		sqs: sqs.New(config),
	}
}

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
<<<<<<< HEAD
using Microsoft.CodeAnalysis.Editor.FindUsages;
=======
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
using Microsoft.CodeAnalysis.Editor.GoToDefinition;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.FindSymbols;
<<<<<<< HEAD
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.LanguageServices.Implementation;
=======
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices
{
    [Export(typeof(VisualStudioWorkspace))]
    [Export(typeof(VisualStudioWorkspaceImpl))]
    internal class RoslynVisualStudioWorkspace : VisualStudioWorkspaceImpl
    {
        private readonly IEnumerable<Lazy<IStreamingFindUsagesPresenter>> _streamingPresenters;
<<<<<<< HEAD
        private readonly IEnumerable<Lazy<IDefinitionsAndReferencesPresenter>> _referencedSymbolsPresenters;
=======
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00

        [ImportingConstructor]
        private RoslynVisualStudioWorkspace(
            ExportProvider exportProvider,
            [ImportMany] IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters,
<<<<<<< HEAD
            [ImportMany] IEnumerable<Lazy<IDefinitionsAndReferencesPresenter>> referencedSymbolsPresenters,
=======
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
            [ImportMany] IEnumerable<IDocumentOptionsProviderFactory> documentOptionsProviderFactories)
            : base(exportProvider.AsExportProvider())
        {
            _streamingPresenters = streamingPresenters;
<<<<<<< HEAD
            _referencedSymbolsPresenters = referencedSymbolsPresenters;
=======
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00

            foreach (var providerFactory in documentOptionsProviderFactories)
            {
                Services.GetRequiredService<IOptionService>().RegisterDocumentOptionsProvider(providerFactory.Create(this));
            }
        }

        public override EnvDTE.FileCodeModel GetFileCodeModel(DocumentId documentId)
        {
            if (documentId == null)
            {
                throw new ArgumentNullException(nameof(documentId));
            }

            if (DeferredState == null)
            {
                // We haven't gotten any projects added yet, so we don't know where this came from
                throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
            }

            var project = DeferredState.ProjectTracker.GetProject(documentId.ProjectId);
            if (project == null)
            {
                throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
            }

            var document = project.GetDocumentOrAdditionalDocument(documentId);
            if (document == null)
            {
                throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
            }

            var provider = project as IProjectCodeModelProvider;
            if (provider != null)
            {
                var projectCodeModel = provider.ProjectCodeModel;
                if (projectCodeModel.CanCreateFileCodeModelThroughProject(document.FilePath))
                {
                    return (EnvDTE.FileCodeModel)projectCodeModel.CreateFileCodeModelThroughProject(document.FilePath);
                }
            }

            return null;
        }

        internal override bool RenameFileCodeModelInstance(DocumentId documentId, string newFilePath)
        {
            if (documentId == null)
            {
                return false;
            }

            var project = DeferredState.ProjectTracker.GetProject(documentId.ProjectId);
            if (project == null)
            {
                return false;
            }

            var document = project.GetDocumentOrAdditionalDocument(documentId);
            if (document == null)
            {
                return false;
            }

            var codeModelProvider = project as IProjectCodeModelProvider;
            if (codeModelProvider == null)
            {
                return false;
            }

            var codeModelCache = codeModelProvider.ProjectCodeModel.GetCodeModelCache();
            if (codeModelCache == null)
            {
                return false;
            }

            codeModelCache.OnSourceFileRenaming(document.FilePath, newFilePath);

            return true;
        }

        internal override IInvisibleEditor OpenInvisibleEditor(DocumentId documentId)
        {
            var hostDocument = GetHostDocument(documentId);
            return OpenInvisibleEditor(hostDocument);
        }

        internal override IInvisibleEditor OpenInvisibleEditor(IVisualStudioHostDocument hostDocument)
        {
            var globalUndoService = this.Services.GetService<IGlobalUndoService>();
            var needsUndoDisabled = false;

            // Do not save the file if is open and there is not a global undo transaction.
            var needsSave = globalUndoService.IsGlobalTransactionOpen(this) || !hostDocument.IsOpen;
            if (needsSave)
            {
                if (this.CurrentSolution.ContainsDocument(hostDocument.Id))
                {
                    // Disable undo on generated documents
                    needsUndoDisabled = this.CurrentSolution.GetDocument(hostDocument.Id).IsGeneratedCode(CancellationToken.None);
                }
                else
                {
                    // Enable undo on "additional documents" or if no document can be found.
                    needsUndoDisabled = false;
                }
            }

            return new InvisibleEditor(DeferredState.ServiceProvider, hostDocument.FilePath, needsSave, needsUndoDisabled);
        }

        private static bool TryResolveSymbol(ISymbol symbol, Project project, CancellationToken cancellationToken, out ISymbol resolvedSymbol, out Project resolvedProject)
        {
            resolvedSymbol = null;
            resolvedProject = null;

            var currentProject = project.Solution.Workspace.CurrentSolution.GetProject(project.Id);
            if (currentProject == null)
            {
                return false;
            }

            var originalCompilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var symbolId = SymbolKey.Create(symbol, cancellationToken);
            var currentCompilation = currentProject.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var symbolInfo = symbolId.Resolve(currentCompilation, cancellationToken: cancellationToken);

            if (symbolInfo.Symbol == null)
            {
                return false;
            }

            resolvedSymbol = symbolInfo.Symbol;
            resolvedProject = currentProject;

            return true;
        }

        public override bool TryGoToDefinition(
            ISymbol symbol, Project project, CancellationToken cancellationToken)
        {
            if (!_streamingPresenters.Any())
            {
                return false;
            }

            if (!TryResolveSymbol(symbol, project, cancellationToken,
                    out var searchSymbol, out var searchProject))
            {
                return false;
            }

            return GoToDefinitionHelpers.TryGoToDefinition(
                searchSymbol, searchProject,
                _streamingPresenters, cancellationToken);
        }

        public override bool TryFindAllReferences(ISymbol symbol, Project project, CancellationToken cancellationToken)
        {
<<<<<<< HEAD
            if (!_referencedSymbolsPresenters.Any())
            {
                return false;
            }

            if (!TryResolveSymbol(symbol, project, cancellationToken, out var searchSymbol, out var searchProject))
            {
                return false;
            }

            var searchSolution = searchProject.Solution;

            var result = SymbolFinder
                .FindReferencesAsync(searchSymbol, searchSolution, cancellationToken)
                .WaitAndGetResult(cancellationToken).ToList();

            if (result != null)
            {
                DisplayReferencedSymbols(searchSolution, result);
                return true;
            }

=======
            // Legacy API.  Previously used by ObjectBrowser to support 'FindRefs' off of an
            // object browser item.  Now ObjectBrowser goes through the streaming-FindRefs system.
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
            return false;
        }

        public override void DisplayReferencedSymbols(
            Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols)
        {
<<<<<<< HEAD
            var service = this.Services.GetService<IDefinitionsAndReferencesFactory>();
            var definitionsAndReferences = service.CreateDefinitionsAndReferences(
                solution, referencedSymbols,
                includeHiddenLocations: false, cancellationToken: CancellationToken.None);

            foreach (var presenter in _referencedSymbolsPresenters)
            {
                presenter.Value.DisplayResult(definitionsAndReferences);
                return;
            }
=======
            // Legacy API.  Previously used by ObjectBrowser to support 'FindRefs' off of an
            // object browser item.  Now ObjectBrowser goes through the streaming-FindRefs system.
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
        }

        internal override object GetBrowseObject(SymbolListItem symbolListItem)
        {
            var compilation = symbolListItem.GetCompilation(this);
            if (compilation == null)
            {
                return null;
            }

            var symbol = symbolListItem.ResolveSymbol(compilation);
            var sourceLocation = symbol.Locations.Where(l => l.IsInSource).FirstOrDefault();

            if (sourceLocation == null)
            {
                return null;
            }

            var projectId = symbolListItem.ProjectId;
            if (projectId == null)
            {
                return null;
            }

            var project = this.CurrentSolution.GetProject(projectId);
            if (project == null)
            {
                return null;
            }

            var codeModelService = project.LanguageServices.GetService<ICodeModelService>();
            if (codeModelService == null)
            {
                return null;
            }

            var tree = sourceLocation.SourceTree;
            var document = project.GetDocument(tree);

            var vsFileCodeModel = this.GetFileCodeModel(document.Id);

            var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(vsFileCodeModel);
            if (fileCodeModel != null)
            {
                var syntaxNode = tree.GetRoot().FindNode(sourceLocation.SourceSpan);
                while (syntaxNode != null)
                {
                    if (!codeModelService.TryGetNodeKey(syntaxNode).IsEmpty)
                    {
                        break;
                    }

                    syntaxNode = syntaxNode.Parent;
                }

                if (syntaxNode != null)
                {
                    var codeElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(syntaxNode);
                    if (codeElement != null)
                    {
                        return codeElement;
                    }
                }
            }

            return null;
        }
    }
}


text:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class p04_Unicode_Characters {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String inputLine = reader.readLine();

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < inputLine.length(); i++) {
            result.append("\\u").append(Integer.toHexString(inputLine.charAt(i) | 0x10000).substring(1));
        }
        System.out.printf(result.toString());
    }
}


text:
'use strict';
var Browser = require('zombie');

setup(function(done) {
    this.browser = Browser.create();
    this.browser.visit('http://localhost:3000').then(done, done);
    this.browser.on("error", function(error) {
        console.error(error);
    });
});

test('browser should connect', function() {
    return this.browser.success.should.be.ok;
});

test('should redirect to /basket', function() {
    this.browser.location.pathname.should.eql("/basket");
});

test('we should have two products on the page', function() {
    this.product = this.browser.queryAll('.basket--product');
    this.product.length.should.eql(2);

});

test('clicking on remove item button should remove item', function(done) {
    var self = this;
    this.browser.pressButton('.remove-item', function() {
        self.product = self.browser.queryAll('.basket--product');
        self.product.length.should.eql(1);
        self.count = self.browser.text('.basket-count');
        self.price = self.browser.text('.price-total');
    }).then(done);
});

test('shopping bag should reflect the change in the basket', function() {
    // use cart count from previous
    // test setup
    this.count.should.eql(1);
});

test('total price should be smaller after removal of item', function() {
    var oldPrice = this.browser.text('.price-total');
    this.price.should.be.lessThan(oldPrice);
});

test('clicking checkout should go to /shipping', function(done) {
    var self = this;
    this.browser.clickLink('Checkout', function() {
        self.browser.location.pathname.should.eql("/shipping");
    }).then(done);
});


text:
Logged in as <?php echo $user_data['first_name']; ?>

Log out


text:
<?php

// Include the initialization file
require_once dirname(dirname(__FILE__)) . '/init.php';

// Enter parameters required by the code example.
$adGroupId = 'INSERT_AD_GROUP_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the id of the parent ad group
 */
function GetTextAdsExample(AdWordsUser $user, $adGroupId) {
  // Get the service, which loads the required classes.
  $adGroupAdService = $user->GetService('AdGroupAdService', ADWORDS_VERSION);

  // Create selector.
  $selector = new Selector();
  $selector->fields = array('Headline', 'Id');
  $selector->ordering[] = new OrderBy('Headline', 'ASCENDING');

  // Create predicates.
  $selector->predicates[] = new Predicate('AdGroupId', 'IN', array($adGroupId));
  $selector->predicates[] = new Predicate('AdType', 'IN', array('TEXT_AD'));
  // By default disabled ads aren't returned by the selector. To return them
  // include the DISABLED status in a predicate.
  $selector->predicates[] =
      new Predicate('Status', 'IN', array('ENABLED', 'PAUSED', 'DISABLED'));

  // Create paging controls.
  $selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);

  do {
    // Make the get request.
    $page = $adGroupAdService->get($selector);

    // Display results.
    if (isset($page->entries)) {
      foreach ($page->entries as $adGroupAd) {
        printf("Text ad with headline '%s' and ID '%s' was found.\n",
            $adGroupAd->ad->headline, $adGroupAd->ad->id);
      }
    } else {
      print "No text ads were found.\n";
    }

    // Advance the paging index.
    $selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
  } while ($page->totalNumEntries > $selector->paging->startIndex);
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Run the example.
  GetTextAdsExample($user, $adGroupId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}


text:
@interface BGLButton : BGLNode <Touchable> {
    CGRect frame;
    id target;
    SEL touchDownAction;
    SEL touchUpInsideAction;
    BOOL enabled;
    BOOL highlighted;
    BGLColor color;
    float vertexPositions[8];
}
@property (nonatomic) CGRect frame;
@property (nonatomic) BGLColor color;
@property (nonatomic, retain) id target;
@property (nonatomic) SEL touchDownAction;
@property (nonatomic) SEL touchUpInsideAction;
@property (nonatomic,readonly,getter=isHighlighted) BOOL highlighted;
@property (nonatomic,getter=isEnabled) BOOL enabled;
@end


text:
chorus_home = File.expand_path(File.dirname(__FILE__) + '/../')
require File.join(chorus_home, 'app', 'models', 'chorus_config')

chorus_config = ChorusConfig.new(chorus_home)

java_options = chorus_config["java_options"].gsub(/-Xms\S+/, '')

jruby_options = java_options.split(" ").map do |option|
  if ["-server", "-client"].include?(option)
    "-#{option}"
  else
    "-J#{option}"
  end
end

unless ENV['RAILS_ENV'] == 'production'
  jruby_options << '-J-Dapple.awt.UIElement=true'
end

print jruby_options.join(" ")


text:
template: layout.jade
title: Script Fields
menusection: search
menuitem: script-fields
---

# Script fields

	var queryResults = this._client.Search<ElasticSearchProject>(s=>s
		.From(0)
		.Size(10)
		.MatchAll()
		.Fields(f=>f.Name)
		.ScriptFields(sf=>sf
			.Add("locscriptfield", sff=>sff
				.Script("doc['loc'].value * multiplier")
				.Params(sp=>sp
					.Add("multiplier", 4)
				)
			)
		)
	);
	Assert.True(queryResults.IsValid);
	Assert.True(queryResults.Documents.Any());
	Assert.True(queryResults.Documents.All(d=>d.LocScriptField != 0));


text:
| Build Status                             | Latest Release                                      | Version                                            | Last Commit                                                    | Activity                                    |
| :--------------------------------------: | :--------------------------:                        | :----:                                             | :------:                                                       | :------:                                    |
| [![Travis][travis_shield]][travis]       | [![Github Release][release_shield]][github_release] | [![Github Version][version_shield]][github_version] | [![Github Last Commit][last_commit_shield]][github_last_commit] | [![Github commit activity][activity_shield]][github_activity] |

[travis_shield]: https://travis-ci.org/skulumani/business_card.svg?branch=master
[release_shield]: https://img.shields.io/github/release/skulumani/business_card.svg
[version_shield]: https://badge.fury.io/gh/skulumani%2Fbusiness_card.svg
[last_commit_shield]: https://img.shields.io/github/last-commit/skulumani/business_card.svg
[activity_shield]: https://img.shields.io/github/commit-activity/y/skulumani/business_card.svg

[travis]: https://travis-ci.org/skulumani/business_card
[github_release]: https://github.com/skulumani/business_card/releases/latest
[github_version]: https://github.com/skulumani/business_card/releases/latest
[github_last_commit]: https://github.com/skulumani/business_card/commits/master
[github_activity]: https://github.com/skulumani/business_card/graphs/commit-activity

# Business card in LaTeX

LaTeX source code for a business card.
It is a high quality pdf output suitable for printing from any reputable printing service:

* [vistaprint](http://www.vistaprint.com)
* [moo](http://www.moo.com)

It follows the standard US business card size of 3.5 x 2 inch but is easily modified.
I've complied this from some guides online using standard the standard LaTeX memoir class.

# QR code

[QR Codes](https://en.wikipedia.org/wiki/QR_code) are a useful and efficient way of encoding data into a two dimensional barcode.
The codes are machine readable and are popular in the manufacturing and shipping communities.
In addition, there is a significant built in error correction and simplicity (there's no need for a power source to transmit the data ).
This allows QR codes to be very robust to poor lighting or even damage.
With the rise of smartphones, QR codes have gained significant popularity in several countries (excluding the US).

I wanted to include a QR code on my business card to allow an easy way to bridge the gap from paper to digital.
Luckily, someone has already thought about this and created the [qrcode](https://www.ctan.org/tex-archive/macros/latex/contrib/qrcode?lang=en) package.

# License

The MIT License (MIT)

Copyright (c) 2015 Shankar Kulumani


text:
require 'rails/generators'

module Recommendable
  module Generators
    class InstallGenerator < Rails::Generators::Base
      argument     :redis_host,   :type => :string,  :default => "localhost",       :desc => "The hostname your redis server is running on."
      argument     :redis_port,   :type => :string,  :default => "6379",            :desc => "The port your redis server is running on."
      class_option :redis_socket, :type => :string,                                 :desc => "Indicates the UNIX socket your redis server is running on (if it is)."
      class_option :no_migrate,   :type => :boolean, :default => false,             :desc => "Skip migrations. The Like and Dislike tables will not be created."

      source_root File.expand_path("../templates", __FILE__)

      def add_recommendable_initializer
        path = "#{Rails.root}/config/initializers/recommendable.rb"
        if File.exists?(path)
          puts "Skipping config/initializers/recommendable.rb creation; file already exists!"
        else
          puts "Adding Recommendable initializer (config/initializers/recommendable.rb)"
          template "initializer.rb", path
        end
      end

      def install_migrations
        puts "Copying migrations..."
        Dir.chdir(Rails.root) { puts `rake recommendable:install:migrations` }
      end

      def run_migrations
        unless options[:no_migrate]
          puts "Running rake db:migrate"
          puts `rake db:migrate`
        end
      end

      def finished
        puts "Done! Recommendable has been successfully installed. Please configure it in config/intializers/recommendable.rb"
      end
    end
  end
end


text:
using System;

namespace System.Net.Tests
{
    internal class HttpTestServers
    {
        public const string Host = "corefx-net.cloudapp.net";
        public const string Http2Host = "http2.akamai.com";

        private const string HttpScheme = "http";
        private const string HttpsScheme = "https";

        private const string EchoHandler = "Echo.ashx";
        private const string EmptyContentHandler = "EmptyContent.ashx";
        private const string StatusCodeHandler = "StatusCode.ashx";
        private const string RedirectHandler = "Redirect.ashx";
        private const string VerifyUploadHandler = "VerifyUpload.ashx";
        private const string DeflateHandler = "Deflate.ashx";
        private const string GZipHandler = "GZip.ashx";

        public readonly static Uri RemoteEchoServer = new Uri("http://" + Host + "/" + EchoHandler);
        public readonly static Uri SecureRemoteEchoServer = new Uri("https://" + Host + "/" + EchoHandler);

        public readonly static Uri RemoteVerifyUploadServer = new Uri("http://" + Host + "/" + VerifyUploadHandler);
        public readonly static Uri SecureRemoteVerifyUploadServer = new Uri("https://" + Host + "/" + VerifyUploadHandler);

        public readonly static Uri RemoteEmptyContentServer = new Uri("http://" + Host + "/" + EmptyContentHandler);
        public readonly static Uri RemoteDeflateServer = new Uri("http://" + Host + "/" + DeflateHandler);
        public readonly static Uri RemoteGZipServer = new Uri("http://" + Host + "/" + GZipHandler);

        public readonly static object[][] EchoServers = { new object[] { RemoteEchoServer }, new object[] { SecureRemoteEchoServer } };
        public readonly static object[][] VerifyUploadServers = { new object[] { RemoteVerifyUploadServer }, new object[] { SecureRemoteVerifyUploadServer } };
        public readonly static object[][] CompressedServers = { new object[] { RemoteDeflateServer }, new object[] { RemoteGZipServer } };
        public readonly static object[][] Http2Servers = { new object[] { new Uri("https://" + Http2Host) } };

        public static Uri NegotiateAuthUriForDefaultCreds(bool secure)
        {
            return new Uri(
                string.Format(
                    "{0}://{1}/{2}?auth=negotiate",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    EchoHandler));
        }

        public static Uri BasicAuthUriForCreds(bool secure, string userName, string password)
        {
            return new Uri(
                string.Format(
                    "{0}://{1}/{2}?auth=basic&user={3}&password={4}",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    EchoHandler,
                    userName,
                    password));
        }

        public static Uri StatusCodeUri(bool secure, int statusCode)
        {
            return new Uri(
                string.Format(
                    "{0}://{1}/{2}?statuscode={3}",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    StatusCodeHandler,
                    statusCode));
        }

        public static Uri StatusCodeUri(bool secure, int statusCode, string statusDescription)
        {
            return new Uri(
                string.Format(
                    "{0}://{1}/{2}?statuscode={3}&statusDescription={4}",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    StatusCodeHandler,
                    statusCode,
                    statusDescription));
        }

        public static Uri RedirectUriForDestinationUri(bool secure, Uri destinationUri, int hops)
        {
            string uriString;
            string destination = Uri.EscapeDataString(destinationUri.AbsoluteUri);

            if (hops > 1)
            {
                uriString = string.Format("{0}://{1}/{2}?uri={3}&hops={4}",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    RedirectHandler,
                    destination,
                    hops);
            }
            else
            {
                uriString = string.Format("{0}://{1}/{2}?uri={3}",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    RedirectHandler,
                    destination);
            }

            return new Uri(uriString);
        }

        public static Uri RedirectUriForCreds(bool secure, string userName, string password)
        {
                Uri destinationUri = BasicAuthUriForCreds(secure, userName, password);
                string destination = Uri.EscapeDataString(destinationUri.AbsoluteUri);

                return new Uri(string.Format("{0}://{1}/{2}?uri={3}",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    RedirectHandler,
                    destination));
        }
    }
}


text:
EXIF Orientation-flag example images
====================================

Example images using each of the EXIF orientation flags (1-to-8), in both landscape and portrait orientations.

[See here](http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto/) for more information.

Generating your own images
--------------------------

If you would like to generate test images based on your own photos, you can use the `generate.rb` script included in the `generator` folder.

The instructions below assume you are running on OSX - if not, you will need to install the Ghostscript fonts (`brew install gs`) some other way.

To install the dependencies:

```
> brew install gs
> cd generator
> gem install bundler
> bundle install
```

To generate test images:

```
> cd generator
> ./generate path/to/image.jpg
```

This will create images `image_1.jpg` through to `image_8.jpg`.

Re-generating sample images
---------------------------

Simply run `make` to regenerate the included sample images. This will download random portrait and landscape orientation images from [unsplash.com](https://unsplash.com/) and generate sample images for each of them.

Generating these images depends on having the generator dependencies installed - see the *Generating your own images* section for instructions on installing dependencies.

Credits
-------

* The sample landscape image is by [Pierre Bouillot](https://unsplash.com/photos/v15iOM6pWgI).
* The sample portrait image is by [John Salvino](https://unsplash.com/photos/1PPpwrTNkJI).

Change history
--------------

* **Version 2.0.0 (2017-08-05)** : Add a script to generate example images from the command line.
* **Version 1.0.2 (2017-03-06)** : Remove Apple Copyrighted ICC profile from orientations 2-8 (thanks @mans0954!).
* **Version 1.0.1 (2013-03-10)** : Add MIT license and some contact details.
* **Version 1.0.0 (2012-07-28)** : 1.0 release.

Contributing
------------

Once you've made your commits:

1. [Fork](http://help.github.com/fork-a-repo/) exif-orientation-examples
2. Create a topic branch - `git checkout -b my_branch`
3. Push to your branch - `git push origin my_branch`
4. Create a [Pull Request](http://help.github.com/pull-requests/) from your branch
5. That's it!

Author
------

Dave Perrett :: hello@daveperrett.com :: [@daveperrett](http://twitter.com/daveperrett)

Copyright
---------

These images are licensed under the [MIT License](http://opensource.org/licenses/MIT).

Copyright (c) 2010 Dave Perrett. See [License](https://github.com/recurser/exif-orientation-examples/blob/master/LICENSE) for details.


text:
<?php
declare(strict_types=1);

namespace Teein\Html\Ast;

use Teein\Html\Ast\Element;
use Teein\Html\Beautifier\Beautifier;
use Teein\Html\VirtualDom\Element as ElementInterface;

/**
 * A NormalElement represents a html-element that must not have childNodes.
 * For instance, this is used to represent <br>- and <link>-elements.
 */
final class VoidElement extends Element implements ElementInterface
{

    /**
     * Construct a new VoidElement with localName set to $localName and
     * attributes set to $attributes
     *
     * @param string $localName The localName of the new VoidElement
     * @param array $attributes The attributes of the new VoidElement
     */
    public function __construct(string $localName, array $attributes)
    {
        $this->localName = $localName;
        $this->attributes = $attributes;
    }

    /**
     * Get a beautified VoidElement for debugging-purpose. This inserts a
     * new line after the opening tag "<$localName>".
     * The original VoidElement is left unmodified.
     *
     * This function should not be called directly on a VoidElement. It is
     * invoked automatically if the document-ancestor is about to be
     * beautified. However, it is a debugging-utility, so don't take the former
     * rule too serious, but make sure to remove the call to "beautify" for
     * production-code.
     *
     * @param int $level The current level of indentation
     */
    public function beautify(int $level = 0) : Beautifier
    {
        return $this;
    }

    /**
     * Get the html-representation of the this VoidElement.
     */
    public function toHtml() : string
    {
        $htmlLocalName = $this->localName;
        $htmlAttributes = $this->attributesToHtml();
        return "<{$htmlLocalName}{$htmlAttributes}>";
    }

    /**
     * Get a new VoidElement that is like this one but with its localName set
     * to $localName
     *
     * @param string $localName The localName of the new VoidElement
     */
    public function setLocalName(string $localName) : ElementInterface
    {
        return new VoidElement($localName, $this->attributes);
    }

    /**
     * Get a new VoidElement that is like this one but with its attributes set
     * to $attributes
     *
     * @param array $attributes The attributes of the new VoidElement
     */
    public function setAttributes(array $attributes) : ElementInterface
    {
        return new VoidElement($this->localName, $attributes);
    }
}


text:
require 'spec_helper'

describe FCReminder::Runner do
  let(:options) { { foo: "bar" } }

  describe "#initialize" do
    subject(:runner) { FCReminder::Runner.new(options) }

    it "sets #options" do
      expect(runner.options).to eq(options)
    end
    it "sets #reminder" do
      expect(runner.reminder).to be_kind_of(FCReminder::Reminder)
    end
  end

  describe "#start" do
    before do
      allow(Clockwork).to receive(:every) { |&block| block.call }
      allow(runner.reminder).to receive(:run)
      allow(runner).to receive(:run)
    end

    context "sets reminder" do
      subject(:runner) { FCReminder::Runner.new({ daemon: false }) }

      it "calls Clockwork.every" do
        expect(Clockwork)
          .to receive(:every)
          .with(1.day, FCReminder::Runner::JOB_NAME, { at: anything() })

        runner.start
      end
    end

    context "starts normal process" do
      subject(:runner) { FCReminder::Runner.new({ daemon: false }) }

      it "runs" do
        expect(runner).to receive(:run)
        runner.start
      end
    end

    context "starts daemon process" do
      subject(:runner) { FCReminder::Runner.new({ daemon: true }) }
      before { allow(Daemons).to receive(:run_proc) }

      it "calls Daemons.run_proc" do
        expect(Daemons)
          .to receive(:run_proc)
          .with(anything(), anything())

        runner.start
      end
    end
  end
end


text:
using Utilities.IoC.Interfaces;

namespace Utilities.DataTypes.CodeGen.Module
{
    /// <summary>
    /// Compiler module
    /// </summary>
    public class CompilerModule : IModule
    {
        /// <summary>
        /// Order to run it in
        /// </summary>
        public int Order
        {
            get { return 0; }
        }

        /// <summary>
        /// Loads the module
        /// </summary>
        /// <param name="Bootstrapper">Bootstrapper to register with</param>
        public void Load(IBootstrapper Bootstrapper)
        {
            Bootstrapper.Register(new Compiler());
        }
    }
}


text:
#include "assoc_preamble.h"
#include <map>

int main()
{
    // count number of times each word occurs in the input
    map<string, int> word_count;  // empty map from string to int
    string word;
    while (cin >> word)
      ++word_count[word];

    // get iterator positioned on the first element
    map<string, int>::const_iterator
                            map_it = word_count.begin();
    // for each element in the map
    while (map_it != word_count.end()) {
        // print the element key, value pairs
        cout << map_it->first << " occurs "
             << map_it->second << " times" << endl;
        ++map_it;  // increment iterator to denote the next element
    }
return 0;
}

// Alternative implementation using insert instead of subscript
void alt_word_count()
{
    // count number of times each word occurs in the input
    map<string, int> word_count;  // empty map from string to int
    string word;

    while (cin >> word) {
        // inserts element with key equal to word and value 1;
        // if word already in word_count, insert does nothing
        pair<map<string, int>::iterator, bool> ret =
                word_count.insert(make_pair(word, 1));
        if (!ret.second)         // word already in word_count
            ++ret.first->second; // increment counter
    }
}


text:
package internal

import (
	"unsafe"
)

// Pointer wraps an unsafe.Pointer to be 64bit to
// conform to the syscall specification.
type Pointer struct {
	ptr unsafe.Pointer
}


text:
package org.elasticsearch.index.mapper.core;

import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticSearchParseException;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.compress.CompressorFactory;
import org.elasticsearch.common.io.stream.CachedStreamOutput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.codec.postingsformat.PostingsFormatProvider;
import org.elasticsearch.index.mapper.*;

import java.io.IOException;
import java.util.Map;

import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeBooleanValue;
import static org.elasticsearch.index.mapper.MapperBuilders.binaryField;
import static org.elasticsearch.index.mapper.core.TypeParsers.parseField;

/**
 *
 */
public class BinaryFieldMapper extends AbstractFieldMapper<byte[]> {

    public static final String CONTENT_TYPE = "binary";

    public static class Defaults extends AbstractFieldMapper.Defaults {
        public static final long COMPRESS_THRESHOLD = -1;
        public static final FieldType BINARY_FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE);

        static {
            BINARY_FIELD_TYPE.setStored(false);
            BINARY_FIELD_TYPE.freeze();
        }
    }

    public static class Builder extends AbstractFieldMapper.Builder<Builder, BinaryFieldMapper> {

        private Boolean compress = null;

        private long compressThreshold = Defaults.COMPRESS_THRESHOLD;

        public Builder(String name) {
            super(name, new FieldType(Defaults.BINARY_FIELD_TYPE));
            builder = this;
        }

        public Builder compress(boolean compress) {
            this.compress = compress;
            return this;
        }

        public Builder compressThreshold(long compressThreshold) {
            this.compressThreshold = compressThreshold;
            return this;
        }

        @Override
        public Builder indexName(String indexName) {
            return super.indexName(indexName);
        }

        @Override
        public BinaryFieldMapper build(BuilderContext context) {
            return new BinaryFieldMapper(buildNames(context), fieldType, compress, compressThreshold, provider);
        }
    }

    public static class TypeParser implements Mapper.TypeParser {
        @Override
        public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
            BinaryFieldMapper.Builder builder = binaryField(name);
            parseField(builder, name, node, parserContext);
            for (Map.Entry<String, Object> entry : node.entrySet()) {
                String fieldName = Strings.toUnderscoreCase(entry.getKey());
                Object fieldNode = entry.getValue();
                if (fieldName.equals("compress") && fieldNode != null) {
                    builder.compress(nodeBooleanValue(fieldNode));
                } else if (fieldName.equals("compress_threshold") && fieldNode != null) {
                    if (fieldNode instanceof Number) {
                        builder.compressThreshold(((Number) fieldNode).longValue());
                        builder.compress(true);
                    } else {
                        builder.compressThreshold(ByteSizeValue.parseBytesSizeValue(fieldNode.toString()).bytes());
                        builder.compress(true);
                    }
                }
            }
            return builder;
        }
    }

    private Boolean compress;

    private long compressThreshold;

    protected BinaryFieldMapper(Names names, FieldType fieldType, Boolean compress, long compressThreshold, PostingsFormatProvider provider) {
        super(names, 1.0f, fieldType, null, null, provider, null);
        this.compress = compress;
        this.compressThreshold = compressThreshold;
    }

    @Override
    public Object valueForSearch(Field field) {
        return value(field);
    }

    @Override
    public byte[] value(Field field) {
        BytesRef value = field.binaryValue();
        if (value == null) {
            return null;
        }
        try {
            return CompressorFactory.uncompressIfNeeded(new BytesArray(value)).toBytes();
        } catch (IOException e) {
            throw new ElasticSearchParseException("failed to decompress source", e);
        }
    }

    @Override
    public byte[] valueFromString(String value) {
        // assume its base64 (json)
        try {
            return Base64.decode(value);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public String valueAsString(Field field) {
        return null;
    }

    @Override
    public String indexedValue(String value) {
        return value;
    }

    @Override
    protected Field parseCreateField(ParseContext context) throws IOException {
        if (!stored()) {
            return null;
        }
        byte[] value;
        if (context.parser().currentToken() == XContentParser.Token.VALUE_NULL) {
            return null;
        } else {
            value = context.parser().binaryValue();
            if (compress != null && compress && !CompressorFactory.isCompressed(value, 0, value.length)) {
                if (compressThreshold == -1 || value.length > compressThreshold) {
                    CachedStreamOutput.Entry cachedEntry = CachedStreamOutput.popEntry();
                    StreamOutput streamOutput = cachedEntry.bytes(CompressorFactory.defaultCompressor());
                    streamOutput.writeBytes(value, 0, value.length);
                    streamOutput.close();
                    // we copy over the byte array, since we need to push back the cached entry
                    // TODO, we we had a handle into when we are done with parsing, then we push back then and not copy over bytes
                    value = cachedEntry.bytes().bytes().copyBytesArray().toBytes();
                    CachedStreamOutput.pushEntry(cachedEntry);
                }
            }
        }
        if (value == null) {
            return null;
        }
        return new Field(names.indexName(), value, fieldType);
    }

    @Override
    protected String contentType() {
        return CONTENT_TYPE;
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(names.name());
        builder.field("type", contentType());
        if (!names.name().equals(names.indexNameClean())) {
            builder.field("index_name", names.indexNameClean());
        }
        if (compress != null) {
            builder.field("compress", compress);
        }
        if (compressThreshold != -1) {
            builder.field("compress_threshold", new ByteSizeValue(compressThreshold).toString());
        }
        builder.endObject();
        return builder;
    }

    @Override
    public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
        BinaryFieldMapper sourceMergeWith = (BinaryFieldMapper) mergeWith;
        if (!mergeContext.mergeFlags().simulate()) {
            if (sourceMergeWith.compress != null) {
                this.compress = sourceMergeWith.compress;
            }
            if (sourceMergeWith.compressThreshold != -1) {
                this.compressThreshold = sourceMergeWith.compressThreshold;
            }
        }
    }

}