text:
var LinkedDataFragmentsServer = require('../lib/LinkedDataFragmentsServer');

var request = require('supertest'),
    fs = require('fs'),
    http = require('http'),
    url = require('url');

describe('LinkedDataFragmentsServer', function () {
  describe('A LinkedDataFragmentsServer instance', function () {
    var server, client;
    before(function () {
      server = new LinkedDataFragmentsServer({
        log: function () {},
        writers: { '*/*': {
          writeNotFound: function (destination, settings) {
            destination.end(settings.url + ' not found');
          },
        }},
      });
      client = request.agent(server);
    });

    it('should send CORS headers', function (done) {
      client.head('/').expect(function (response) {
        response.headers.should.have.property('access-control-allow-origin', '*');
      }).end(done);
    });

    it('should not allow POST requests', function (done) {
      client.post('/').expect(function (response) {
        response.should.have.property('statusCode', 405);
        response.headers.should.have.property('content-type', 'text/plain;charset=utf-8');
        response.should.have.property('text', 'The HTTP method "POST" is not allowed; try "GET" instead.');
      }).end(done);
    });

    it('should not send a body with HEAD requests', function (done) {
      client.head('/').expect(function (response) {
        response.should.have.property('statusCode', 404);
        response.should.have.property('text', '');
      }).end(done);
    });

    it('should not send a body with OPTIONS requests', function (done) {
      client.options('/').expect(function (response) {
        response.should.have.property('statusCode', 404);
        response.should.have.property('text', '');
      }).end(done);
    });

    it('should send a 404 if a resource is not found', function (done) {
      client.get('/notfound').expect(function (response) {
        response.should.have.property('statusCode', 404);
        response.headers.should.have.property('content-type', 'text/plain;charset=utf-8');
        response.should.have.property('text', '/notfound not found');
      }).end(done);
    });

    it('should correctly serve SVG assets', function (done) {
      client.get('/assets/logo').expect(function (response) {
        var asset = fs.readFileSync(__dirname + '/../assets/logo.svg', 'utf8');
        response.should.have.property('statusCode', 200);
        response.headers.should.have.property('content-type', 'image/svg+xml');
        response.headers.should.have.property('cache-control', 'public,max-age=1209600');
        response.should.have.property('text', asset);
      }).end(done);
    });

    it('should correctly serve CSS assets', function (done) {
      client.get('/assets/style').expect(function (response) {
        var asset = fs.readFileSync(__dirname + '/../assets/style.css', 'utf8');
        response.should.have.property('statusCode', 200);
        response.headers.should.have.property('content-type', 'text/css;charset=utf-8');
        response.headers.should.have.property('cache-control', 'public,max-age=1209600');
        response.should.have.property('text', asset);
      }).end(done);
    });

    it('should correctly serve ICO assets', function (done) {
      client.get('/favicon.ico').expect(function (response) {
        var asset = fs.readFileSync(__dirname + '/../assets/favicon.ico', 'utf8');
        response.should.have.property('statusCode', 200);
        response.headers.should.have.property('content-type', 'image/x-icon');
        response.headers.should.have.property('cache-control', 'public,max-age=1209600');
        response.should.have.property('text', asset);
      }).end(done);
    });

    it('should send a 404 if an asset is not found', function (done) {
      client.get('/assets/unknown').expect(function (response) {
        response.should.have.property('statusCode', 404);
        response.headers.should.have.property('content-type', 'text/plain;charset=utf-8');
        response.should.have.property('text', '/assets/unknown not found');
      }).end(done);
    });

    describe('when an internal error occurs', function (done) {
      before(function () {
        server._oldSendAsset = server._sendAsset;
        delete server._sendAsset;
      });
      after(function () {
        server._sendAsset = server._oldSendAsset;
        delete server._oldSendAsset;
      });

      it('should send a 500 error message', function (done) {
        client.get('/assets/logo', function (response) {
          response.should.have.property('statusCode', 500);
          response.headers.should.have.property('content-type', 'text/plain;charset=utf-8');
          response.should.have.property('text', 'A server error occurred.');
        }).end(done);
      });
    });
  });

  describe('A LinkedDataFragmentsServer instance with 3 routers', function () {
    var server, client, routerA, routerB, routerC, datasource, datasources, writer, prefixes;
    before(function () {
      routerA = { extractQueryParams: sinon.stub() };
      routerB = { extractQueryParams: sinon.stub().throws(new Error('second router error')) };
      routerC = { extractQueryParams: sinon.spy(function (request, query) {
        query.features.datasource = true;
        query.features.other = true;
        query.datasource = 'my-datasource';
        query.other = 'other';
      })};
      datasource = {
        supportsQuery: sinon.stub().returns(true),
        select: sinon.stub().returns({ queryResult: true }),
      };
      datasources = { 'my-datasource': { title: 'My data', datasource: datasource } };
      writer = {
        writeFragment: sinon.spy(function (outputStream) { outputStream.end(); }),
        writeNotFound: sinon.spy(function (outputStream) { outputStream.end(); }),
      };
      prefixes = { a: 'a' };
      server = new LinkedDataFragmentsServer({
        routers: [ routerA, routerB, routerC ],
        datasources: datasources,
        writers: { '*/*': writer },
        prefixes: prefixes,
        baseURL: 'https://example.org/base/?bar=foo',
      });
      client = request.agent(server);
    });
    function resetAll() {
      routerA.extractQueryParams.reset();
      routerB.extractQueryParams.reset();
      routerC.extractQueryParams.reset();
      datasource.supportsQuery.reset();
      datasource.select.reset();
    }

    describe('receiving a request for a fragment', function () {
      var response;
      before(function (done) {
        resetAll();
        response = client.get('/my-datasource?a=b&c=d').end(done);
      });

      it('should call the first router with the request and an empty query', function () {
        routerA.extractQueryParams.should.have.been.calledOnce;

        var extractQueryParamsArgs = routerA.extractQueryParams.firstCall.args;
        extractQueryParamsArgs[0].should.have.property('url');
        extractQueryParamsArgs[0].url.should.have.property('path', '/my-datasource?a=b&c=d');
        extractQueryParamsArgs[0].url.should.have.property('pathname', '/my-datasource');
        extractQueryParamsArgs[0].url.should.have.property('query');
        extractQueryParamsArgs[0].url.query.should.deep.equal({ a: 'b', c: 'd' });

        extractQueryParamsArgs[1].should.be.an('object');
        extractQueryParamsArgs[1].should.have.property('features');
        extractQueryParamsArgs[1].features.should.be.an('array');
      });

      it('should call the second router with the same request and query', function () {
        routerB.extractQueryParams.should.have.been.calledOnce;

        routerB.extractQueryParams.firstCall.args[0].should.equal(
          routerA.extractQueryParams.firstCall.args[0]);
        routerB.extractQueryParams.firstCall.args[1].should.equal(
          routerA.extractQueryParams.firstCall.args[1]);
      });

      it('should call the third router with the same request and query', function () {
        routerC.extractQueryParams.should.have.been.calledOnce;

        routerC.extractQueryParams.firstCall.args[0].should.equal(
          routerA.extractQueryParams.firstCall.args[0]);
        routerC.extractQueryParams.firstCall.args[1].should.equal(
          routerA.extractQueryParams.firstCall.args[1]);
      });

      it('should verify whether the data source supports the query', function () {
        var query = routerC.extractQueryParams.firstCall.args[1];
        datasource.supportsQuery.should.have.been.calledOnce;
        datasource.supportsQuery.should.have.been.calledWith(query);
      });

      it('should send the query to the right data source', function () {
        var query = routerC.extractQueryParams.firstCall.args[1];
        datasource.select.should.have.been.calledOnce;
        datasource.select.should.have.been.calledWith(query);
      });

      it('should pass the query result to the output writer', function () {
        writer.writeFragment.should.have.been.calledOnce;
        var writeFragmentArgs = writer.writeFragment.firstCall.args;

        writeFragmentArgs[0].should.be.an.instanceof(http.ServerResponse); // where to write to
        writeFragmentArgs[1].should.deep.equal({ queryResult: true }); // what to write
        writeFragmentArgs[2].should.be.an('object'); // writing settings
      });

      it('should pass the correct settings to the output writer', function () {
        writer.writeFragment.should.have.been.calledOnce;
        var query = routerC.extractQueryParams.firstCall.args[1];
        var settings = writer.writeFragment.firstCall.args[2];

        settings.should.deep.equal({
          datasource: {
            title: 'My data',
            index: 'https://example.org/#dataset',
            url: 'https://example.org/my-datasource#dataset',
            templateUrl: 'https://example.org/my-datasource{?subject,predicate,object}',
          },
          fragment: {
            url:             'https://example.org/my-datasource?a=b&c=d',
            pageUrl:         'https://example.org/my-datasource?a=b&c=d',
            firstPageUrl:    'https://example.org/my-datasource?a=b&c=d&page=1',
            nextPageUrl:     'https://example.org/my-datasource?a=b&c=d&page=2',
            previousPageUrl: null
          },
          prefixes: prefixes,
          query: query,
          datasources: datasources,
        });
        query.should.have.property('patternString', '{ ?s ?p ?o }');
      });
    });

    describe('receiving a request for an unsupported fragment', function () {
      before(function (done) {
        resetAll();
        datasource.supportsQuery = sinon.stub().returns(false);
        client.get('/my-datasource?a=b&c=d').end(done);
      });

      it('should verify whether the data source supports the query', function () {
        var query = routerC.extractQueryParams.firstCall.args[1];
        datasource.supportsQuery.should.have.been.calledOnce;
        datasource.supportsQuery.should.have.been.calledWith(query);
      });

      it('should not send the query to the data source', function () {
        datasource.select.should.not.have.been.called;
      });
    });
  });

  describe('A LinkedDataFragmentsServer instance with 3 writers', function () {
    var server, client, writerHtml, writerJson, writerTurtle;
    before(function () {
      var datasource = {
        supportsQuery: sinon.stub().returns(true),
        select: sinon.stub(),
      };
      var router = { extractQueryParams: function (request, query) {
        query.features.datasource = true;
        query.datasource = 'my-datasource';
      }};
      writerHtml   = { writeFragment: sinon.spy(function (stream) { stream.end(); }) };
      writerJson   = { writeFragment: sinon.spy(function (stream) { stream.end(); }) };
      writerTurtle = { writeFragment: sinon.spy(function (stream) { stream.end(); }) };
      server = new LinkedDataFragmentsServer({
        routers: [ router ],
        datasources: { 'my-datasource': { datasource: datasource } },
        writers: {
          'application/json': writerJson,
          'text/turtle,text/n3': writerTurtle,
          'text/html,*/*': writerHtml,
        },
      });
      client = request.agent(server);
    });
    function resetAll() {
      writerHtml.writeFragment.reset();
      writerJson.writeFragment.reset();
      writerTurtle.writeFragment.reset();
    }

    describe('receiving a request without Accept header', function () {
      var response;
      before(function (done) {
        resetAll();
        client.get('/my-datasource')
              .end(function (error, res) { response = res; done(error); });
      });

      it('should call the default writer', function () {
        writerHtml.writeFragment.should.have.been.calledOnce;
      });

      it('should set the text/html content type', function () {
        response.headers.should.have.property('content-type', 'text/html;charset=utf-8');
      });

      it('should indicate Accept in the Vary header', function () {
        response.headers.should.have.property('vary', 'Accept');
      });
    });

    describe('receiving a request with an Accept header of */*', function () {
      var response;
      before(function (done) {
        resetAll();
        client.get('/my-datasource').set('Accept', '*/*')
              .end(function (error, res) { response = res; done(error); });
      });

      it('should call the */* writer', function () {
        writerHtml.writeFragment.should.have.been.calledOnce;
      });

      it('should set the text/html content type', function () {
        response.headers.should.have.property('content-type', 'text/html;charset=utf-8');
      });

      it('should indicate Accept in the Vary header', function () {
        response.headers.should.have.property('vary', 'Accept');
      });
    });

    describe('receiving a request with an Accept header of text/html', function () {
      var response;
      before(function (done) {
        resetAll();
        client.get('/my-datasource').set('Accept', 'text/html')
              .end(function (error, res) { response = res; done(error); });
      });

      it('should call the HTML writer', function () {
        writerHtml.writeFragment.should.have.been.calledOnce;
      });

      it('should set the text/html content type', function () {
        response.headers.should.have.property('content-type', 'text/html;charset=utf-8');
      });

      it('should indicate Accept in the Vary header', function () {
        response.headers.should.have.property('vary', 'Accept');
      });
    });

    describe('receiving a request with an Accept header of application/json', function () {
      var response;
      before(function (done) {
        resetAll();
        client.get('/my-datasource').set('Accept', 'application/json')
              .end(function (error, res) { response = res; done(error); });
      });

      it('should call the JSON writer', function () {
        writerJson.writeFragment.should.have.been.calledOnce;
      });

      it('should set the application/json content type', function () {
        response.headers.should.have.property('content-type', 'application/json;charset=utf-8');
      });

      it('should indicate Accept in the Vary header', function () {
        response.headers.should.have.property('vary', 'Accept');
      });
    });

    describe('receiving a request with an Accept header of text/turtle', function () {
      var response;
      before(function (done) {
        resetAll();
        client.get('/my-datasource').set('Accept', 'text/turtle')
              .end(function (error, res) { response = res; done(error); });
      });

      it('should call the Turtle writer', function () {
        writerTurtle.writeFragment.should.have.been.calledOnce;
      });

      it('should set the text/turtle content type', function () {
        response.headers.should.have.property('content-type', 'text/turtle;charset=utf-8');
      });

      it('should indicate Accept in the Vary header', function () {
        response.headers.should.have.property('vary', 'Accept');
      });
    });

    describe('receiving a request with an Accept header of text/n3', function () {
      var response;
      before(function (done) {
        resetAll();
        client.get('/my-datasource').set('Accept', 'text/n3')
              .end(function (error, res) { response = res; done(error); });
      });

      it('should call the Turtle writer', function () {
        writerTurtle.writeFragment.should.have.been.calledOnce;
      });

      it('should set the text/n3 content type', function () {
        response.headers.should.have.property('content-type', 'text/n3;charset=utf-8');
      });

      it('should indicate Accept in the Vary header', function () {
        response.headers.should.have.property('vary', 'Accept');
      });
    });
  });

  describe('A LinkedDataFragmentsServer instance without matching writer', function () {
    var server, client, writerHtml, writerJson, writerTurtle;
    before(function () {
      var datasource = {
        supportsQuery: sinon.stub().returns(true),
        select: sinon.stub(),
      };
      var router = { extractQueryParams: function (request, query) {
        query.features.dataset = true;
        query.datasource = 'my-datasource';
      }};
      server = new LinkedDataFragmentsServer({
        log: function () {},
        routers: [ router ],
        datasources: { 'my-datasource': { datasource: datasource } },
      });
      client = request.agent(server);
    });

    describe('receiving a request without Accept header', function () {
      var response;
      before(function (done) {
        client.get('/my-datasource')
              .end(function (error, res) { response = res; done(error); });
      });

      it('should return status code 406', function () {
        response.should.have.property('statusCode', 406);
      });

      it('should set the text/plain content type', function () {
        response.headers.should.have.property('content-type', 'text/plain;charset=utf-8');
      });

      it('should indicate Accept in the Vary header', function () {
        response.headers.should.have.property('vary', 'Accept');
      });
    });

    describe('receiving a request with an Accept header of text/html', function () {
      var response;
      before(function (done) {
        client.get('/my-datasource').set('Accept', 'text/html')
              .end(function (error, res) { response = res; done(error); });
      });

      it('should return status code 406', function () {
        response.should.have.property('statusCode', 406);
      });

      it('should set the text/plain content type', function () {
        response.headers.should.have.property('content-type', 'text/plain;charset=utf-8');
      });

      it('should indicate Accept in the Vary header', function () {
        response.headers.should.have.property('vary', 'Accept');
      });
    });
  });

  describe('A LinkedDataFragmentsServer instance with dereferencing', function () {
    var server, client, writerTurtle;
    before(function () {
      var datasource = {
        supportsQuery: sinon.stub().returns(true),
        select: sinon.stub(),
      };
      var router = { extractQueryParams: function (request, query) {
        query.features.datasource = true;
        query.datasource = request.url.pathname.substr(1);
      }};
      writerTurtle = { writeFragment: sinon.spy(function (stream) { stream.end(); }) };
      server = new LinkedDataFragmentsServer({
        datasources: { 'resource/datasource': { datasource: datasource } },
        dereference: { '/resource/': 'dbpedia' },
        writers: { 'text/turtle': writerTurtle },
        routers: [ router ],
      });
      client = request.agent(server);
    });

    describe('receiving a request for a dereferenced URL', function () {
      var response;
      before(function (done) {
        client.get('/resource/Mickey_Mouse')
              .end(function (error, res) { response = res; done(error); });
      });

      it('should return status code 303', function () {
        response.should.have.property('statusCode', 303);
      });

      it('should set the text/plain content type', function () {
        response.headers.should.have.property('content-type', 'text/plain;charset=utf-8');
      });

      it('should set the Location header correctly', function () {
        var hostname = response.req.getHeader('Host'),
            entityUrl = encodeURIComponent('http://' + hostname + '/resource/Mickey_Mouse'),
            expectedLocation = 'http://' + hostname + '/dbpedia?subject=' + entityUrl;

        response.headers.should.have.property('location', expectedLocation);
      });

      it('should mention the desired location in the body', function () {
        var hostname = response.req.getHeader('Host'),
            entityUrl = encodeURIComponent('http://' + hostname + '/resource/Mickey_Mouse'),
            expectedLocation = 'http://' + hostname + '/dbpedia?subject=' + entityUrl;

        response.text.should.contain(expectedLocation);
      });
    });

    describe('receiving a request for a data source URL', function () {
      var response;
      before(function (done) {
        client.get('/resource/datasource')
              .end(function (error, res) { response = res; done(error); });
      });

      it('should not dereference', function () {
        response.should.have.property('statusCode', 200);
      });

      it('should call the Turtle writer', function () {
        writerTurtle.writeFragment.should.have.been.calledOnce;
      });

      it('should set the text/turtle content type', function () {
        response.headers.should.have.property('content-type', 'text/turtle;charset=utf-8');
      });
    });
  });
});


text:
// $Id: BrowserLaunchingExecutionException.java,v 1.2 2006/03/23 20:30:50 jchapman0 Exp $
package edu.stanford.ejalbert.exception;

/**
 * Exception thrown if there is problem during the attempt to launch
 * a browser.
 *
 * @author Markus Gebhard
 */
public class BrowserLaunchingExecutionException
        extends Exception {

    public BrowserLaunchingExecutionException(Throwable cause) {
        super(cause);
    }

    public BrowserLaunchingExecutionException(String message) {
        super(message);
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'stall'
require 'offsite_payments'

module Stall
  module AuthorizeDotNet
    extend ActiveSupport::Autoload

    autoload :Version
    autoload :FakeGatewayPaymentNotification
  end
end

require 'stall/authorize_dot_net/gateway'
require 'stall/authorize_dot_net/engine'


text:
RSpec.describe Dota::API::Match do
  let(:match) do
    VCR.use_cassette("GetMatchDetails") do
      test_client.matches(sample_match_id)
    end
  end

  specify "#id" do
    expect(match.id).to eq sample_match_id
  end

  specify "#league_id" do
    expect(match.league_id).to eq 2129
  end

  specify "#type" do
    expect(match.type).to eq "Practice"
  end

  specify "#type_id" do
    expect(match.type_id).to eq 1
  end

  specify "#mode" do
    expect(match.mode).to eq "Captain's Mode"
  end

  specify "#mode_id" do
    expect(match.mode_id).to eq 2
  end

  describe "#drafts" do
    specify "match with drafts" do
      drafts = match.drafts
      expect(drafts.count).to eq 20
      expect(drafts.first).to be_a Dota::API::Match::Draft
    end

    specify "match without drafts" do
      expect(match.raw).to receive(:[]).with("picks_bans") { nil }
      expect(match.drafts).to eq []
    end
  end

  specify "#sequence" do
    expect(match.sequence).to eq 1283900397
  end

  specify "#starts_at" do
    expect(match.starts_at).to eq Time.at(1430252064)
  end

  specify "#duration" do
    expect(match.duration).to eq 3198
  end

  specify "#winner" do
    expect(match.winner).to eq :dire
  end

  specify "#first_blood" do
    expect(match.first_blood).to eq 448
  end

  specify "#positive_votes" do
    expect(match.positive_votes).to eq 71
  end

  specify "#negative_votes" do
    expect(match.negative_votes).to eq 18
  end

  specify "#season" do
    expect(match.season).to be_nil
  end

  specify "#players_count" do
    expect(match.players_count).to eq 10
  end

  specify "#cluster" do
    expect(match.cluster).to eq 135
  end
end


text:
{{ partial "header.html" . }}
{{ partial "posts.html" . }}
{{ partial "footer.html" . }}


text:
- Add `#description` to matchers.
- Update rspec dependency.

## [0.1.2](https://github.com/modocache/state_machine_rspec/compare/v0.1.1...v0.1.2)

- state_machine dependency updated from "~> 1.1.0" to ">= 1.1.0".
  Fixes https://github.com/modocache/state_machine_rspec/issues/5.

## [0.1.1](https://github.com/modocache/state_machine_rspec/compare/v0.1.0...v0.1.1)

- `StateMachineRspec::Matchers::Events` conform to `Matchers::States` API, and now
  take a `:on` parameter when specifying a non-default state_machine attribute. This
  used to be specified with a `:state` parameter.
- Add Travis-CI build status image to README.
- Update README with instructions on including module in during RSpec configuration.

## [0.1.0](https://github.com/modocache/state_machine_rspec/tree/v0.1.0)

- Initial release.


text:
from flask import render_template, redirect, request, url_for, flash, abort
from flask_login import login_user, logout_user, login_required, current_user
from werkzeug.utils import secure_filename
from time import gmtime, strftime
from . import main
from ..auth.forms import LoginForm, ChangePasswordForm, ChangeEmailForm, PaymentForm, \
    MemberRegistrationForm, MD5Form, UploadForm
from ..models import User, Member
from .. import db
from ..json_reader import GetFile
from ..email import send_email
from .. import storage

@main.route('/' , methods=['GET', 'POST'])
def index():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            return redirect(request.args.get('next') or url_for('main.dashboard'))
        flash('Invalid username or password.')
    return render_template('index.html', form=form)

@main.route('/dashboard', methods=['GET', 'POST'])
@login_required
def dashboard():
    user = User.query.filter_by(id=current_user.id).first()
    admin_settings = GetFile('admin_settings.json').Read()
    site_data = {
        "payed": user.fee_payed,
        "registered": user.team_registered,
        "download_questions_time": admin_settings['download_questions_time'],
        "zip_password_time":admin_settings['zip_password_time'],
        "code_submission_time":admin_settings['code_submission_time'],
        "solution_upload_time":admin_settings['solution_upload_time'],
        "check_solution_time":admin_settings['check_solution_time']
    }
    template_name='选手首页'
    return render_template('dashboard/home.html', template_name=template_name, site_data=site_data)

@main.route('/dashboard/pay', methods=['GET', 'POST'])
@login_required
def pay():
    template_name='网上缴费'
    form = PaymentForm()
    if request.method == "POST":
        if form.validate_on_submit():
            current_user.fee_payed = strftime("%Y-%m-%d %H:%M:%S", gmtime())
            db.session.add(current_user)
            db.session.commit()
            flash('缴费成功!')
        else:
            flash('缴费出错!!!')
    return render_template('dashboard/pay.html', template_name=template_name, form=form)

@main.route('/dashboard/team_info', methods=['GET', 'POST'])
@login_required
def team():
    template_name='编辑资料'
    # the registration form will dissapear when the whole team is registered
    visible = 'true'
    members_ammount = Member.query.count()
    members = Member.query.filter_by(group_id=current_user.id)
    if members_ammount >= 3:
        visible = 'none'
        if current_user.team_registered == False:
            current_user.team_registered = True
            db.session.add(current_user)
            db.session.commit()

    form = MemberRegistrationForm()
    if request.method == "POST":
        if form.validate_on_submit():
            member = Member(group_id=current_user.id,\
            phone=form.phone.data,\
            email=form.email.data,\
            name=form.name.data,\
            student_number=form.student_number.data,\
            sex = form.sex.data,\
            ethnic=form.ethnic.data,\
            student_type=form.student_type.data,\
            province=form.province.data,\
            school=form.school.data,\
            discipline=form.discipline.data,\
            specialty=form.specialty.data,\
            grade=form.grade.data,\
            faculty=form.faculty.data,\
            grad_time=form.grad_time.data,\
            teacher_assigned=form.teacher_assigned.data,\
            id_type=form.id_type.data,\
            id_number=form.id_number.data,\
            address=form.address.data,\
            zip_code=form.zip_code.data)

            db.session.add(member)
            db.session.commit()

            flash('队员报名成功!')
        else:
            flash('信息有错误!!!')
    return render_template('dashboard/team_info.html', visible=visible, template_name=template_name, form=form, members=members)

# Upload Solutions
@main.route('/dashboard/upload', methods=['GET', 'POST'])
@login_required
def upload():
    template_name='上传论文'
    form = UploadForm()
    if request.method == 'POST':
        if not form.validate_filename(form):
            flash('文件名不正确')
            redirect(url_for('main.upload'))
        if form.validate_on_submit() and form.validate_filename(form) :
            filename = secure_filename(form.file.data.filename)
            form.file.data.save('uploads/' + filename)
            flash('上传完成')
    return render_template('dashboard/upload.html', form=form, template_name=template_name)

# Download Questions
@main.route('/dashboard/download', methods=['GET', 'POST'])
@login_required
def download_questions():
    template_name='下载试题'
    admin_settings = GetFile('admin_settings.json').Read()
    site_data = {
        "doc_password": admin_settings['doc_password'],
        "zip_password_time":admin_settings['zip_password_time']
    }
    return render_template('dashboard/download.html', site_data=site_data,template_name=template_name)

# MD5 code submission
@main.route('/dashboard/md5', methods=['GET', 'POST'])
@login_required
def md5():
    template_name='提交识别码'
    form = MD5Form()
    md5_status = {
        "actual": current_user.md5_code,
        "code_submission_time": current_user.md5_code_date
    }
    if md5_status['actual'] != None:
        form.submit.label.text = '重新提交识别码'

    if request.method == "POST":
        if form.validate_on_submit():
            current_user.md5_code = form.md5_code.data
            current_user.md5_code_date = strftime("%Y-%m-%d %H:%M:%S", gmtime())
            db.session.add(current_user)
            flash('识别码提交成功!')
            form.reset()
            redirect(url_for('main.md5'))
    # form.submit.label.text = 'asd'
    return render_template('dashboard/md5.html', form=form, md5_status=md5_status,template_name=template_name)

# A download endpoint, to download the file
@main.route('/download/<path:object_name>')
@login_required
def download(object_name):
    my_object = storage.get(object_name)
    if my_object:
        download_url = my_object.download_url()
        return redirect(download_url)
    else:
        abort(404, "File doesn't exist")


text:
<?php
App::uses('CartAppModel', 'Cart.Model');

class OrderItem extends CartAppModel {

/**
 * belongsTo associations
 *
 * @var array
 */
	public $belongsTo = array(
		'Order' => array(
			'className' => 'Cart.Order',
			'counterCache' => true
		)
	);

/**
 * beforeSave callback
 *
 * @param  array $options, not used
 * @return boolean
 */
	public function beforeSave($options = array()) {
		$this->data = $this->_serializeFields(
			array(
				'additional_data',
			),
			$this->data
		);
		return true;
	}
}


text:
#region Namespaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Architecture;
using System.Globalization;
using System.Resources;
#endregion

namespace RoomFinishes
{
    /// <summary>
    /// Interaction logic for UserControl1.xaml
    /// </summary>
    public partial class FloorsFinishesControl : Window
    {
        private Document _doc;
        private UIDocument _UIDoc;

        public readonly FloorsFinishesSetup FloorsFinishesSetup;

        public FloorsFinishesControl(UIDocument UIDoc, FloorsFinishesSetup floorsFinishesSetup)
        {
            InitializeComponent();
            _doc = UIDoc.Document;
            _UIDoc = UIDoc;
            FloorsFinishesSetup = floorsFinishesSetup;

            //Fill out Text in form
            this.Title = Tools.LangResMan.GetString("floorFinishes_TaskDialogName", Tools.Cult);
            this.all_rooms_radio.Content = Tools.LangResMan.GetString("roomFinishes_all_rooms_radio", Tools.Cult);
            this.floor_height_radio.Content = Tools.LangResMan.GetString("floorFinishes_height_label", Tools.Cult);
            this.height_param_radio.Content = Tools.LangResMan.GetString("floorFinishes_height_param_label", Tools.Cult);
            this.groupboxName.Header = Tools.LangResMan.GetString("floorFinishes_groupboxName", Tools.Cult);
            this.select_floor_label.Content = Tools.LangResMan.GetString("floorFinishes_select_floor_label", Tools.Cult);
            this.selected_rooms_radio.Content = Tools.LangResMan.GetString("roomFinishes_selected_rooms_radio", Tools.Cult);
            this.Cancel_Button.Content = Tools.LangResMan.GetString("roomFinishes_Cancel_Button", Tools.Cult);
            this.Ok_Button.Content = Tools.LangResMan.GetString("roomFinishes_OK_Button", Tools.Cult);

            //Select the floor type in the document
            IEnumerable<FloorType> floorTypes = from elem in new FilteredElementCollector(_doc).OfClass(typeof(FloorType))
                                               let type = elem as FloorType
                                               where type.IsFoundationSlab == false
                                               select type;

            floorTypes = floorTypes.OrderBy(floorType => floorType.Name);

            // Bind ArrayList with the ListBox
            FloorTypeListBox.ItemsSource = floorTypes;
            FloorTypeListBox.SelectedItem = FloorTypeListBox.Items[0];

            //Find a room
            IList<Element> roomList = new FilteredElementCollector(_doc).OfCategory(BuiltInCategory.OST_Rooms).ToList();

            if (roomList.Count != 0)
            {
                //Get all double parameters
                Room room = roomList.First() as Room;

#if DEBUG || V2022
                List<Parameter> doubleParam = (from Parameter p in room.Parameters
                                               where p.Definition.GetDataType() == SpecTypeId.Length
                                               select p).ToList();
#else
                List<Parameter> doubleParam = (from Parameter p in room.Parameters
                                               where p.Definition.ParameterType == ParameterType.Length
                                               select p).ToList();
#endif

                paramSelector.ItemsSource = doubleParam;
                paramSelector.DisplayMemberPath = "Definition.Name";
                paramSelector.SelectedIndex = 0;
            }
            else
            {
                paramSelector.IsEnabled = false;
                height_param_radio.IsEnabled = false;
            }
        }

        private void Ok_Button_Click(object sender, RoutedEventArgs e)
        {
            if (floor_height_radio.IsChecked == true)
            {
                FloorsFinishesSetup.RoomParameter = null;
                if (Tools.GetValueFromString(Height_TextBox.Text, _doc.GetUnits()) != null)
                {
                    FloorsFinishesSetup.FloorHeight = (double)Tools.GetValueFromString(Height_TextBox.Text, _doc.GetUnits());

                    if (FloorTypeListBox.SelectedItem != null)
                    {
                        //Select wall type for skirting board
                        FloorsFinishesSetup.SelectedFloorType = FloorTypeListBox.SelectedItem as FloorType;

                        this.DialogResult = true;
                        this.Close();

                        //Select the rooms
                        FloorsFinishesSetup.SelectedRooms = SelectRooms().ToList();
                    }
                }
                else
                {
                    TaskDialog.Show(Tools.LangResMan.GetString("floorFinishes_TaskDialogName", Tools.Cult),
                        Tools.LangResMan.GetString("floorFinishes_heightValueError", Tools.Cult), TaskDialogCommonButtons.Close, TaskDialogResult.Close);
                    this.Activate();
                }
            }
            else
            {
                FloorsFinishesSetup.RoomParameter = paramSelector.SelectedItem as Parameter;

                if (FloorTypeListBox.SelectedItem != null)
                {
                    //Select floor type
                    FloorsFinishesSetup.SelectedFloorType = FloorTypeListBox.SelectedItem as FloorType;

                    this.DialogResult = true;
                    this.Close();

                    //Select the rooms
                    FloorsFinishesSetup.SelectedRooms = SelectRooms().ToList();
                }
            }
        }

        private void Cancel_Button_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

        private IEnumerable<Room> SelectRooms()
        {
            //Create a set of selected elements ids
            ICollection<ElementId> selectedObjectsIds = _UIDoc.Selection.GetElementIds();

            //Create a set of rooms
            IEnumerable<Room> ModelRooms = null;
            IList<Room> tempList = new List<Room>();

            if (all_rooms_radio.IsChecked.Value)
            {
                // Find all rooms in current view
                ModelRooms = from elem in new FilteredElementCollector(_doc, _doc.ActiveView.Id).OfClass(typeof(SpatialElement))
                             let room = elem as Room
                             select room;
            }
            else
            {
                if (selectedObjectsIds.Count != 0)
                {
                    // Find all rooms in selection
                    ModelRooms = from elem in new FilteredElementCollector(_doc, selectedObjectsIds).OfClass(typeof(SpatialElement))
                                 let room = elem as Room
                                 select room;
                    tempList = ModelRooms.ToList();
                }

                if (tempList.Count == 0)
                {
                    //Create a selection filter on rooms
                    ISelectionFilter filter = new RoomSelectionFilter();

                    IList<Reference> rs = _UIDoc.Selection.PickObjects(ObjectType.Element, filter,
                        Tools.LangResMan.GetString("roomFinishes_SelectRooms", Tools.Cult));

                    foreach (Reference r in rs)
                    {
                        tempList.Add(_doc.GetElement(r) as Room);
                    }

                    ModelRooms = tempList;
                }
            }

            return ModelRooms;
        }

        private void Height_TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if (Tools.GetValueFromString(Height_TextBox.Text, _doc.GetUnits()) != null)
            {
                FloorsFinishesSetup.FloorHeight = (double)Tools.GetValueFromString(Height_TextBox.Text, _doc.GetUnits());

#if DEBUG || V2022
                Height_TextBox.Text = UnitFormatUtils.Format(_doc.GetUnits(), SpecTypeId.Length, FloorsFinishesSetup.FloorHeight, true);
#else
                Height_TextBox.Text = UnitFormatUtils.Format(_doc.GetUnits(), UnitType.UT_Length, FloorsFinishesSetup.FloorHeight, true, true);
#endif

            }
            else
            {
                TaskDialog.Show(Tools.LangResMan.GetString("roomFinishes_TaskDialogName", Tools.Cult),
                    Tools.LangResMan.GetString("roomFinishes_heightValueError", Tools.Cult), TaskDialogCommonButtons.Close, TaskDialogResult.Close);
                this.Activate();
            }
        }

    }
}


text:
import matplotlib.pyplot as plt
import subprocess
import datetime
import sys
import argparse
import os.path

# Parse arguments
parser = argparse.ArgumentParser(
    description='Create pie chart of logins from campus versus otherwise \
                 using a specified wtmp file.')

parser.add_argument('-d', '--days', type=int, default=31,
                    help='The number of days in the past to collect data \
                    from (default: 31)')

parser.add_argument('-f', '--file', default='wtmp',
                    help='Location of wtmp file (default: ./wtmp)')

parser.add_argument('-l', '--last',
                    help='The last day for data to be collected in\
                          dd-mm-yyyy format (default: today)')

parser.add_argument('-c', '--config', default='userutil.conf',
                    help='Configuration file to use \
                          (default: ./userutil.conf)')

args = parser.parse_args()

history = args.days

# Check if the specified file exists, if not print an error and exit.
if os.path.isfile(args.file):
    wtmp_loc = args.file
else:
    print "File doesn't exist, use -h for help."
    sys.exit()

# Check if -l was given, if it wasn't, set last_day to today. If it was, use it
# to create a datetime object, throw an error if it doesn't work.
if args.last:
    try:
        last_day = datetime.datetime.strptime(args.last, '%d-%m-%Y')
    except:
        print "Day must be in dd-mm-yyyy format, use -h for help."
        sys.exit()
else:
    last_day = datetime.datetime.today()

# Parse the config file
if os.path.isfile(args.config):
    with open(args.config, 'r') as config:
        lines = config.readlines()
else:
    print "Config file doesn't exist, use -h for help."

for line in lines:
    line = line.strip()
    if not line.startswith('#'):  # if not a comment
         # find ignored users.
        if line.startswith('ignore'):
            # Delete all whitespace
            line = ''.join(line.split())
            # Get the list of users to ignore
            ignorenames = line[7:].split(",")

# Get the initial data.
# -i displays IP
# -f specifies file
# -F prints full login dates
searchresult = subprocess.Popen("last -i -F -f" + wtmp_loc,
                                stdout=subprocess.PIPE, shell=True)
searchresult = searchresult.communicate()[0]
m = searchresult.split('\n')

logins_from_campus = 0
logins_from_home = 0
total_logins = 0

for entry in m:
    username = entry.split(" ")[0]

    # Check if username exists and that it's not in ignorenames.
    if username and username not in ignorenames:
        entry = ' '.join(entry.split())

        ent_year = entry.split(' ')[7]
        ent_month = entry.split(' ')[4]
        ent_day = entry.split(' ')[5]
        ent_ip = entry.split(' ')[2]

        #print ent_year + " " + ent_month + " " + ent_day

        ent_date = datetime.datetime.strptime((ent_month
                                               + " " + ent_day
                                               + " " + ent_year),
                                              '%b %d %Y')

        days_since_login = (last_day - ent_date).days
        # Ignore local logins.
        if ((days_since_login < history) and ent_ip != "0.0.0.0"):
            # Logins coming from an IP with a first octet of 10 are considered
            # as coming from campus
            if ent_ip.startswith("10."):
                logins_from_campus += 1
            else:
                logins_from_home += 1
            total_logins += 1

print "Logins from Campus: " + str(logins_from_campus)
print "Logins from off Campus: " + str(logins_from_home)
print "Total Logins: " + str(total_logins)

#fig_size = plt.rcParams["figure.figsize"]

# Set figure width to 9 and height to 9
#fig_size[0] = 9
#fig_size[1] = 9

#plt.rcParams["figure.figsize"] = fig_size
plt.figure(figsize=(7,7))

# Generate the pi chart, with labels.
# Autopct can take a function as an argument and it passes the percent to it,
# and the percent needs to be turned back into the actual data
plt.pie([logins_from_campus, logins_from_home],
        labels=["Campus", "Other"],
        colors=["r", "#FF6600"],
        autopct=lambda(a): '{:g}'.format(a * total_logins / 100))
plt.title('Logins from on Campus vs Other', y=1.08)
plt.axis('equal')

plt.legend(loc=4)
plt.tight_layout()
plt.savefig('Source_of_logins.eps', format='eps', dpi=1000)
plt.show()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Acta R. Soc. Scient. upsal. 8(2): 269 (1932)

#### Original name
Pezizella aphanes Rehm

### Remarks
null


text:
package moontime.droid;

import java.util.Calendar;

import moontime.droid.InfiniteSlider.InfiniteAdapter;
import moontime.droid.util.Util;
import moontime.droid.util.YearMonthAdapterPositioning;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;

public abstract class CalendarSliders {

  final InfiniteSlider _yearSlider;
  final InfiniteSlider _monthSlider;
  final Context _context;
  final InfiniteMonthAdapter _monthAdapter;
  final InfiniteYearAdapter _yearAdapter;
  final Calendar _currentDate;

  public CalendarSliders(Context context, InfiniteSlider yearSlider, InfiniteSlider monthSlider, Calendar initDate) {
    _currentDate = initDate;
    int initialYear = _currentDate.get(Calendar.YEAR);
    int initialMonth = _currentDate.get(Calendar.MONTH);
    YearMonthAdapterPositioning positioning = new YearMonthAdapterPositioning(initialYear, initialMonth,
        InfiniteAdapter.MID_POSITION, InfiniteAdapter.MID_POSITION);

    _context = context;
    _yearSlider = yearSlider;
    _monthSlider = monthSlider;
    _yearAdapter = new InfiniteYearAdapter(this, positioning);
    _yearSlider.init(_yearAdapter);
    _yearSlider.setCallbackDuringFling(false);
    _yearSlider.setOnItemSelectedListener(_yearAdapter);
    _yearSlider.setSelection(positioning.getCurrentYearPosition());

    _monthAdapter = new InfiniteMonthAdapter(this, positioning);
    _monthSlider.init(_monthAdapter);
    _monthSlider.setCallbackDuringFling(false);
    _monthSlider.setOnItemSelectedListener(_monthAdapter);
    _monthSlider.setSelection(positioning.getCurrentMonthPosition());
  }

  public Context getContext() {
    return _context;
  }

  public void onDateChange(YearMonthAdapterPositioning adapterPositioning) {
    Log.d("calendsr", adapterPositioning.getCurrentYear() + ", " + adapterPositioning.getCurrentMonth());
    _yearSlider.setSelection(adapterPositioning.getCurrentYearPosition());
    _monthSlider.setSelection(adapterPositioning.getCurrentMonthPosition());
    _currentDate.set(Calendar.YEAR, adapterPositioning.getCurrentYear());
    _currentDate.set(Calendar.MONTH, adapterPositioning.getCurrentMonth());
    onDateChange(_currentDate);
  }

  protected abstract void onDateChange(Calendar date);

  static class InfiniteYearAdapter extends InfiniteAdapter implements OnItemSelectedListener {

    private final CalendarSliders _calendarSlider;
    private YearMonthAdapterPositioning _adapterPositioning;

    public InfiniteYearAdapter(CalendarSliders calendarSlider, YearMonthAdapterPositioning adapterPositioning) {
      super(calendarSlider.getContext());
      _calendarSlider = calendarSlider;
      _adapterPositioning = adapterPositioning;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
      _adapterPositioning.setCurrentYearPosition(position);
      _calendarSlider.onDateChange(_adapterPositioning);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
      // nothing todo
    }

    @Override
    public String getItem(int position) {
      return Integer.toString(_adapterPositioning.getYear(position));
    }

  }

  static class InfiniteMonthAdapter extends InfiniteAdapter implements OnItemSelectedListener {

    private final YearMonthAdapterPositioning _adapterPositioning;
    private final CalendarSliders _calendarSlider;

    public InfiniteMonthAdapter(CalendarSliders calendarSlider, YearMonthAdapterPositioning adapterPositioning) {
      super(calendarSlider.getContext());
      _calendarSlider = calendarSlider;
      _adapterPositioning = adapterPositioning;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
      _adapterPositioning.setCurrentMonthPosition(position);
      _calendarSlider.onDateChange(_adapterPositioning);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
      // nothing todo

    }

    @Override
    public String getItem(int position) {
      int index = _adapterPositioning.getMonth(position);
      return Util.MONTH_SHORT_NAMES.get(index);
    }

  }

}


text:
package mk.ukim.finki.mp.roommates.model;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import mk.ukim.finki.mp.roommates.util.CustomLocalDateSerializer;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

/**
* Class for the bookmarked listings with getters and setters for all properties
*/

@Entity
@Table(name = "listlook")
public class ListLook extends BaseEntity {

	@ManyToOne
	private Listing listing;

	@ManyToOne
	private Member member;

	@JsonSerialize(using = CustomLocalDateSerializer.class)
	private Date date;

	public Listing getListing() {
		return listing;
	}

	public void setListing(Listing listing) {
		this.listing = listing;
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}
}


text:
package com.hotf.client.view;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.user.client.ui.Focusable;
import com.google.gwt.user.client.ui.HasHTML;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.IsWidget;

/**
 * View interface. Extends IsWidget so a view impl can easily provide its
 * container widget.
 *
 * @author drfibonacci
 */
public interface PlaceEdit extends IsWidget {

	HasText getNameField();
	HasText getTypeField();
	Focusable getNameFocus();
	HasHTML getDescriptionField();
	void setPresenter(Presenter presenter);

	public interface Presenter extends Activity {
		void close();
		void save();
	}

}


text:
Tabs Demo

<ui-tabs>
  <template ui-pane title='Overview' active="true">
    You have {{details.length}} details.
  </template>
  <template *ngFor="#detail of details" ui-pane [title]="detail.title">
    {{detail.text}}

    <button class="btn" (click)="removeDetail(detail)">Remove</button>
  </template>
  <template ui-pane title='Summary'>
    Next last ID is {{id}}.
  </template>
</ui-tabs>

<button class="btn" (click)="addDetail()">Add Detail</button>


text:
package org.tros.torgo.viz;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.tros.logo.DynamicLogoController;
import static org.junit.Assert.*;
import org.tros.logo.swing.LogoMenuBar;
import org.tros.torgo.TorgoInfo;
import org.tros.torgo.TorgoToolkit;
import org.tros.torgo.interpreter.CodeBlock;
import org.tros.torgo.interpreter.InterpreterListener;
import org.tros.torgo.interpreter.Scope;
import org.tros.utils.logging.Logging;

/**
 *
 * @author matta
 */
public class TraceLoggerTest {

    private final static Logger LOGGER;

    static {
        Logging.initLogging(TorgoToolkit.getBuildInfo());
        LOGGER = Logger.getLogger(TraceLoggerTest.class.getName());
    }

    public TraceLoggerTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of create method, of class TraceLogger.
     */
    @Test
    public void traceLoggerTest() {
        LOGGER.info("traceLoggerTest");
        final java.util.prefs.Preferences prefs = java.util.prefs.Preferences.userNodeForPackage(LogoMenuBar.class);
        boolean checked = prefs.getBoolean("wait-for-repaint", true);
        prefs.putBoolean("wait-for-repaint", true);
        DynamicLogoController controller = (DynamicLogoController) TorgoToolkit.getController("dynamic-logo");
        controller.run();
        controller.newFile();
        assertEquals("dynamic-logo", controller.getLang());

        controller.enable("TraceLogger");

        String[] files = new String[]{
            "logo/examples/tortue/octagon.logo",
//            "logo/examples/tortue/pretty.logo",
//            "logo/examples/tortue/snowflake.logo",
//            "logo/examples/tortue/spokes.logo",
            "logo/examples/tortue/test.logo"
//            "logo/examples/tortue/tortue-text.logo"
        };

        for (String file : files) {
            LOGGER.log(Level.INFO, file);
            controller.openFile(ClassLoader.getSystemClassLoader().getResource(file));

            final AtomicBoolean started = new AtomicBoolean(false);
            final AtomicBoolean finished = new AtomicBoolean(false);
            controller.addInterpreterListener(new InterpreterListener() {
                @Override
                public void started() {
                    started.set(true);
                }

                @Override
                public void finished() {
                    finished.set(true);
                }

                @Override
                public void error(Exception e) {
                }

                @Override
                public void message(String msg) {
                }

                @Override
                public void currStatement(CodeBlock block, Scope scope) {
                }
            });

            controller.startInterpreter();

            try {
                while (!finished.get()) {
                    Thread.sleep(10);
                }
            } catch (InterruptedException ex) {
                LOGGER.log(Level.SEVERE, null, ex);
            }
            assertTrue(started.get());
            assertTrue(finished.get());
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                LOGGER.log(Level.SEVERE, null, ex);
            }
        }

        controller.close();
        prefs.putBoolean("wait-for-repaint", checked);
    }
}


text:
'use strict';

import { app } from 'electron';
import { assign } from 'vs/base/common/objects';
import * as platform from 'vs/base/common/platform';
import { parseMainProcessArgv } from 'vs/platform/environment/node/argv';
import { mkdirp } from 'vs/base/node/pfs';
import { validatePaths } from 'vs/code/electron-main/paths';
import { LifecycleService, ILifecycleService } from 'vs/code/electron-main/lifecycle';
import { Server, serve, connect } from 'vs/base/parts/ipc/node/ipc.net';
import { TPromise } from 'vs/base/common/winjs.base';
import { ILaunchChannel, LaunchChannelClient } from './launch';
import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { ILogService, MainLogService } from 'vs/code/electron-main/log';
import { IStorageService, StorageService } from 'vs/code/electron-main/storage';
import { IBackupMainService } from 'vs/platform/backup/common/backup';
import { BackupMainService } from 'vs/platform/backup/electron-main/backupMainService';
import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ConfigurationService } from 'vs/platform/configuration/node/configurationService';
import { IRequestService } from 'vs/platform/request/node/request';
import { RequestService } from 'vs/platform/request/electron-main/requestService';
import { IURLService } from 'vs/platform/url/common/url';
import { URLService } from 'vs/platform/url/electron-main/urlService';
import * as fs from 'original-fs';
import { VSCodeApplication } from "vs/code/electron-main/app";

function createServices(args: ParsedArgs): IInstantiationService {
	const services = new ServiceCollection();

	services.set(IEnvironmentService, new SyncDescriptor(EnvironmentService, args, process.execPath));
	services.set(ILogService, new SyncDescriptor(MainLogService));
	services.set(ILifecycleService, new SyncDescriptor(LifecycleService));
	services.set(IStorageService, new SyncDescriptor(StorageService));
	services.set(IConfigurationService, new SyncDescriptor(ConfigurationService));
	services.set(IRequestService, new SyncDescriptor(RequestService));
	services.set(IURLService, new SyncDescriptor(URLService, args['open-url']));
	services.set(IBackupMainService, new SyncDescriptor(BackupMainService));

	return new InstantiationService(services, true);
}

function createPaths(environmentService: IEnvironmentService): TPromise<any> {
	const paths = [
		environmentService.appSettingsHome,
		environmentService.extensionsPath,
		environmentService.nodeCachedDataDir
	];
	return TPromise.join(paths.map(p => p && mkdirp(p))) as TPromise<any>;
}

function setupIPC(accessor: ServicesAccessor): TPromise<Server> {
	const logService = accessor.get(ILogService);
	const environmentService = accessor.get(IEnvironmentService);

	function allowSetForegroundWindow(service: LaunchChannelClient): TPromise<void> {
		let promise = TPromise.as(null);
		if (platform.isWindows) {
			promise = service.getMainProcessId()
				.then(processId => {
					logService.log('Sending some foreground love to the running instance:', processId);

					try {
						const { allowSetForegroundWindow } = <any>require.__$__nodeRequire('windows-foreground-love');
						allowSetForegroundWindow(processId);
					} catch (e) {
						// noop
					}
				});
		}

		return promise;
	}

	function setup(retry: boolean): TPromise<Server> {
		return serve(environmentService.mainIPCHandle).then(server => {
			if (platform.isMacintosh) {
				app.dock.show(); // dock might be hidden at this case due to a retry
			}

			return server;
		}, err => {
			if (err.code !== 'EADDRINUSE') {
				return TPromise.wrapError(err);
			}

			// Since we are the second instance, we do not want to show the dock
			if (platform.isMacintosh) {
				app.dock.hide();
			}

			// there's a running instance, let's connect to it
			return connect(environmentService.mainIPCHandle, 'main').then(
				client => {

					// Tests from CLI require to be the only instance currently (TODO@Ben support multiple instances and output)
					if (environmentService.extensionTestsPath && !environmentService.debugExtensionHost.break) {
						const msg = 'Running extension tests from the command line is currently only supported if no other instance of Code is running.';
						console.error(msg);
						client.dispose();
						return TPromise.wrapError(msg);
					}

					logService.log('Sending env to running instance...');

					const channel = client.getChannel<ILaunchChannel>('launch');
					const service = new LaunchChannelClient(channel);

					return allowSetForegroundWindow(service)
						.then(() => service.start(environmentService.args, process.env))
						.then(() => client.dispose())
						.then(() => TPromise.wrapError('Sent env to running instance. Terminating...'));
				},
				err => {
					if (!retry || platform.isWindows || err.code !== 'ECONNREFUSED') {
						return TPromise.wrapError(err);
					}

					// it happens on Linux and OS X that the pipe is left behind
					// let's delete it, since we can't connect to it
					// and the retry the whole thing
					try {
						fs.unlinkSync(environmentService.mainIPCHandle);
					} catch (e) {
						logService.log('Fatal error deleting obsolete instance handle', e);
						return TPromise.wrapError(e);
					}

					return setup(false);
				}
			);
		});
	}

	return setup(true);
}

function quit(accessor: ServicesAccessor, errorOrMessage?: Error | string): void {
	const logService = accessor.get(ILogService);
	const lifecycleService = accessor.get(ILifecycleService);

	let exitCode = 0;
	if (typeof errorOrMessage === 'string') {
		logService.log(errorOrMessage);
	} else if (errorOrMessage) {
		exitCode = 1; // signal error to the outside
		if (errorOrMessage.stack) {
			console.error(errorOrMessage.stack);
		} else {
			console.error('Startup error: ' + errorOrMessage.toString());
		}
	}

	lifecycleService.kill(exitCode);
}

function main() {
	let args: ParsedArgs;

	try {
		args = parseMainProcessArgv(process.argv);
		args = validatePaths(args);
	} catch (err) {
		console.error(err.message);
		app.exit(1);

		return;
	}

	const instantiationService = createServices(args);

	return instantiationService.invokeFunction(accessor => {

		// Patch `process.env` with the instance's environment
		const environmentService = accessor.get(IEnvironmentService);
		const instanceEnv: typeof process.env = {
			VSCODE_PID: String(process.pid),
			VSCODE_IPC_HOOK: environmentService.mainIPCHandle,
			VSCODE_NLS_CONFIG: process.env['VSCODE_NLS_CONFIG']
		};
		assign(process.env, instanceEnv);

		// Startup
		return instantiationService.invokeFunction(a => createPaths(a.get(IEnvironmentService)))
			.then(() => instantiationService.invokeFunction(setupIPC))
			.then(mainIpcServer => {
				const app = instantiationService.createInstance(VSCodeApplication, mainIpcServer, instanceEnv);
				app.startup();
			});
	}).done(null, err => instantiationService.invokeFunction(quit, err));
}

main();


text:
package edu.washington.escience.myria.systemtest;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

import org.junit.Test;

import com.google.common.collect.ImmutableList;

import edu.washington.escience.myria.RelationKey;
import edu.washington.escience.myria.Schema;
import edu.washington.escience.myria.Type;
import edu.washington.escience.myria.column.Column;
import edu.washington.escience.myria.operator.DbQueryScan;
import edu.washington.escience.myria.operator.DupElim;
import edu.washington.escience.myria.operator.Operator;
import edu.washington.escience.myria.operator.RootOperator;
import edu.washington.escience.myria.operator.SinkRoot;
import edu.washington.escience.myria.operator.StreamingStateWrapper;
import edu.washington.escience.myria.operator.SymmetricHashJoin;
import edu.washington.escience.myria.operator.TBQueueExporter;
import edu.washington.escience.myria.operator.UnionAll;
import edu.washington.escience.myria.operator.network.CollectConsumer;
import edu.washington.escience.myria.operator.network.CollectProducer;
import edu.washington.escience.myria.operator.network.GenericShuffleConsumer;
import edu.washington.escience.myria.operator.network.GenericShuffleProducer;
import edu.washington.escience.myria.operator.network.partition.PartitionFunction;
import edu.washington.escience.myria.operator.network.partition.SingleFieldHashPartitionFunction;
import edu.washington.escience.myria.parallel.ExchangePairID;
import edu.washington.escience.myria.storage.TupleBatch;
import edu.washington.escience.myria.storage.TupleBatchBuffer;
import edu.washington.escience.myria.util.TestUtils;
import edu.washington.escience.myria.util.Tuple;

public class MultithreadScanTest extends SystemTestBase {
  // change configuration here
  private final int MaxID = 100;
  private final int numTbl1Worker1 = 50;

  public TupleBatchBuffer getResultInMemory(final TupleBatchBuffer table1, final Schema schema, final int numIteration) {
    // a brute force check

    final Iterator<List<? extends Column<?>>> tbs = table1.getAllAsRawColumn().iterator();
    final boolean graph[][] = new boolean[MaxID][MaxID];
    final boolean cntgraph[][] = new boolean[MaxID][MaxID];
    while (tbs.hasNext()) {
      final List<? extends Column<?>> output = tbs.next();
      final int numRow = output.get(0).size();
      for (int i = 0; i < numRow; i++) {
        final int fr = Integer.parseInt(output.get(0).getObject(i).toString());
        final int fe = Integer.parseInt(output.get(1).getObject(i).toString());
        graph[fr][fe] = cntgraph[fr][fe] = true;
      }
    }

    final boolean tmpgraph[][] = new boolean[MaxID][MaxID];
    int cnt = 0;
    while (true) {
      ++cnt;
      for (int i = 0; i < MaxID; ++i) {
        for (int j = 0; j < MaxID; ++j) {
          for (int k = 0; k < MaxID; ++k) {
            if (graph[j][i] && cntgraph[i][k]) {
              tmpgraph[j][k] = true;
            }
          }
        }
      }
      for (int i = 0; i < MaxID; ++i) {
        for (int j = 0; j < MaxID; ++j) {
          cntgraph[i][j] = tmpgraph[i][j];
          tmpgraph[i][j] = false;
        }
      }
      if (cnt == numIteration - 1) {
        break;
      }
    }

    final TupleBatchBuffer result = new TupleBatchBuffer(schema);
    for (int i = 0; i < MaxID; ++i) {
      for (int j = 0; j < MaxID; ++j) {
        if (cntgraph[i][j]) {
          result.putLong(0, i);
          result.putLong(1, j);
          LOGGER.debug(i + "\t" + j);
        }
      }
    }
    LOGGER.debug("" + result.numTuples());
    return result;
  }

  @Test
  public void OneThreadTwoConnectionsTest() throws Exception {

    // data generation
    final ImmutableList<Type> table1Types = ImmutableList.of(Type.LONG_TYPE, Type.LONG_TYPE);
    final ImmutableList<String> table1ColumnNames = ImmutableList.of("follower", "followee");
    final Schema tableSchema = new Schema(table1Types, table1ColumnNames);

    final long[] tbl1ID1Worker1 = TestUtils.randomLong(1, MaxID - 1, numTbl1Worker1);
    final long[] tbl1ID2Worker1 = TestUtils.randomLong(1, MaxID - 1, numTbl1Worker1);
    final TupleBatchBuffer tbl1Worker1 = new TupleBatchBuffer(tableSchema);
    for (int i = 0; i < numTbl1Worker1; i++) {
      tbl1Worker1.putLong(0, tbl1ID1Worker1[i]);
      tbl1Worker1.putLong(1, tbl1ID2Worker1[i]);
    }

    final TupleBatchBuffer expectedTBB = getResultInMemory(tbl1Worker1, tableSchema, 2);
    final TupleBatchBuffer expectedTBBCopy = new TupleBatchBuffer(tableSchema);
    expectedTBBCopy.unionAll(expectedTBB);
    final RelationKey testtableKey = RelationKey.of("test", "test", "testtable");

    createTable(workerIDs[0], testtableKey, "follower long, followee long");
    createTable(workerIDs[1], testtableKey, "follower long, followee long");
    // }
    TupleBatch tb = null;
    while ((tb = tbl1Worker1.popAny()) != null) {
      insert(workerIDs[0], testtableKey, tableSchema, tb);
      insert(workerIDs[1], testtableKey, tableSchema, tb);
    }

    final DbQueryScan scan1 = new DbQueryScan(testtableKey, tableSchema);
    final DbQueryScan scan2 = new DbQueryScan(testtableKey, tableSchema);
    final SymmetricHashJoin localjoin =
        new SymmetricHashJoin(scan1, scan2, new int[] { 1 }, new int[] { 0 }, new int[] { 0 }, new int[] { 1 });
    final StreamingStateWrapper de = new StreamingStateWrapper(localjoin, new DupElim());

    final ExchangePairID serverReceiveID = ExchangePairID.newID();
    final CollectProducer cp = new CollectProducer(de, serverReceiveID, MASTER_ID);

    final HashMap<Integer, RootOperator[]> workerPlans = new HashMap<Integer, RootOperator[]>();
    workerPlans.put(workerIDs[0], new RootOperator[] { cp });
    workerPlans.put(workerIDs[1], new RootOperator[] { cp });

    final CollectConsumer serverCollect =
        new CollectConsumer(tableSchema, serverReceiveID, new int[] { workerIDs[0], workerIDs[1] });
    final LinkedBlockingQueue<TupleBatch> receivedTupleBatches = new LinkedBlockingQueue<TupleBatch>();
    final TBQueueExporter queueStore = new TBQueueExporter(receivedTupleBatches, serverCollect);
    final SinkRoot serverPlan = new SinkRoot(queueStore);

    server.submitQueryPlan(serverPlan, workerPlans).get();
    TupleBatchBuffer actualResult = new TupleBatchBuffer(queueStore.getSchema());
    while (!receivedTupleBatches.isEmpty()) {
      tb = receivedTupleBatches.poll();
      if (tb != null) {
        tb.compactInto(actualResult);
      }
    }
    final HashMap<Tuple, Integer> resultBag = TestUtils.tupleBatchToTupleBag(actualResult);
    expectedTBB.unionAll(expectedTBBCopy);
    TestUtils.assertTupleBagEqual(TestUtils.tupleBatchToTupleBag(expectedTBB), resultBag);

  }

  @Test
  public void TwoThreadsTwoConnectionsSameDBFileTest() throws Exception {

    // data generation
    final ImmutableList<Type> table1Types = ImmutableList.of(Type.LONG_TYPE, Type.LONG_TYPE);
    final ImmutableList<String> table1ColumnNames = ImmutableList.of("follower", "followee");
    final Schema tableSchema = new Schema(table1Types, table1ColumnNames);

    final long[] tbl1ID1Worker1 = TestUtils.randomLong(1, MaxID - 1, numTbl1Worker1);
    final long[] tbl1ID2Worker1 = TestUtils.randomLong(1, MaxID - 1, numTbl1Worker1);
    final TupleBatchBuffer tbl1Worker1 = new TupleBatchBuffer(tableSchema);
    for (int i = 0; i < numTbl1Worker1; i++) {
      tbl1Worker1.putLong(0, tbl1ID1Worker1[i]);
      tbl1Worker1.putLong(1, tbl1ID2Worker1[i]);
    }
    final TupleBatchBuffer table1 = new TupleBatchBuffer(tableSchema);
    table1.unionAll(tbl1Worker1);

    final TupleBatchBuffer expectedTBB = getResultInMemory(table1, tableSchema, 2);
    final TupleBatchBuffer expectedTBBCopy = getResultInMemory(table1, tableSchema, 2);

    final RelationKey testtableKey = RelationKey.of("test", "test", "testtable");

    createTable(workerIDs[0], testtableKey, "follower long, followee long");
    createTable(workerIDs[1], testtableKey, "follower long, followee long");
    TupleBatch tb = null;
    while ((tb = tbl1Worker1.popAny()) != null) {
      insert(workerIDs[0], testtableKey, tableSchema, tb);
      insert(workerIDs[1], testtableKey, tableSchema, tb);
    }

    final DbQueryScan scan1 = new DbQueryScan(testtableKey, tableSchema);
    final DbQueryScan scan2 = new DbQueryScan(testtableKey, tableSchema);
    final SymmetricHashJoin localjoin1 =
        new SymmetricHashJoin(scan1, scan2, new int[] { 1 }, new int[] { 0 }, new int[] { 0 }, new int[] { 1 });
    final StreamingStateWrapper de1 = new StreamingStateWrapper(localjoin1, new DupElim());
    final DbQueryScan scan3 = new DbQueryScan(testtableKey, tableSchema);
    final DbQueryScan scan4 = new DbQueryScan(testtableKey, tableSchema);
    final SymmetricHashJoin localjoin2 =
        new SymmetricHashJoin(scan3, scan4, new int[] { 1 }, new int[] { 0 }, new int[] { 0 }, new int[] { 1 });
    final StreamingStateWrapper de2 = new StreamingStateWrapper(localjoin2, new DupElim());

    final int numPartition = 2;
    final PartitionFunction pf0 = new SingleFieldHashPartitionFunction(numPartition, 0); // 2 workers

    ExchangePairID arrayID1, arrayID2;
    arrayID1 = ExchangePairID.newID();
    arrayID2 = ExchangePairID.newID();

    final GenericShuffleProducer sp1 =
        new GenericShuffleProducer(de1, arrayID1, new int[] { workerIDs[0], workerIDs[1] }, pf0);
    final GenericShuffleProducer sp2 =
        new GenericShuffleProducer(de2, arrayID2, new int[] { workerIDs[0], workerIDs[1] }, pf0);
    final GenericShuffleConsumer sc1 =
        new GenericShuffleConsumer(sp1.getSchema(), arrayID1, new int[] { workerIDs[0], workerIDs[1] });
    final GenericShuffleConsumer sc2 =
        new GenericShuffleConsumer(sp2.getSchema(), arrayID2, new int[] { workerIDs[0], workerIDs[1] });
    final UnionAll unionAll = new UnionAll(new Operator[] { sc1, sc2 });

    final ExchangePairID serverReceiveID = ExchangePairID.newID();
    final CollectProducer cp = new CollectProducer(unionAll, serverReceiveID, MASTER_ID);
    final HashMap<Integer, RootOperator[]> workerPlans = new HashMap<Integer, RootOperator[]>();
    workerPlans.put(workerIDs[0], new RootOperator[] { cp, sp1, sp2 });
    workerPlans.put(workerIDs[1], new RootOperator[] { cp, sp1, sp2 });

    final CollectConsumer serverCollect =
        new CollectConsumer(tableSchema, serverReceiveID, new int[] { workerIDs[0], workerIDs[1] });
    final LinkedBlockingQueue<TupleBatch> receivedTupleBatches = new LinkedBlockingQueue<TupleBatch>();
    final TBQueueExporter queueStore = new TBQueueExporter(receivedTupleBatches, serverCollect);
    final SinkRoot serverPlan = new SinkRoot(queueStore);

    server.submitQueryPlan(serverPlan, workerPlans).get();
    TupleBatchBuffer actualResult = new TupleBatchBuffer(queueStore.getSchema());
    while (!receivedTupleBatches.isEmpty()) {
      tb = receivedTupleBatches.poll();
      if (tb != null) {
        tb.compactInto(actualResult);
      }
    }
    final HashMap<Tuple, Integer> resultBag = TestUtils.tupleBatchToTupleBag(actualResult);

    expectedTBB.unionAll(expectedTBBCopy);
    expectedTBB.unionAll(expectedTBBCopy);
    expectedTBB.unionAll(expectedTBBCopy);
    TestUtils.assertTupleBagEqual(TestUtils.tupleBatchToTupleBag(expectedTBB), resultBag);

  }
}


text:
/*
 * This code was generated by
 * ___ _ _ _ _ _    _ ____    ____ ____ _    ____ ____ _  _ ____ ____ ____ ___ __   __
 *  |  | | | | |    | |  | __ |  | |__| | __ | __ |___ |\ | |___ |__/ |__|  | |  | |__/
 *  |  |_|_| | |___ | |__|    |__| |  | |    |__] |___ | \| |___ |  \ |  |  | |__| |  \
 *
 * Twilio - Supersim
 * This is the public Twilio REST API.
 *
 * NOTE: This class is auto generated by OpenAPI Generator.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package openapi

import (
	"time"
)

// SupersimV1NetworkAccessProfile struct for SupersimV1NetworkAccessProfile
type SupersimV1NetworkAccessProfile struct {
	// The unique string that identifies the resource
	Sid *string `json:"sid,omitempty"`
	// An application-defined string that uniquely identifies the resource
	UniqueName *string `json:"unique_name,omitempty"`
	// The SID of the Account that the Network Access Profile belongs to
	AccountSid *string `json:"account_sid,omitempty"`
	// The ISO 8601 date and time in GMT when the resource was created
	DateCreated *time.Time `json:"date_created,omitempty"`
	// The ISO 8601 date and time in GMT when the resource was last updated
	DateUpdated *time.Time `json:"date_updated,omitempty"`
	// The absolute URL of the resource
	Url   *string                 `json:"url,omitempty"`
	Links *map[string]interface{} `json:"links,omitempty"`
}


text:
namespace jnc {

//..............................................................................

QString
highlightJancySource(
	const QString& source,
	const EditTheme* theme
) {
	QTextDocument document;
	document.setPlainText(source);

	JancyHighlighter highlighter(&document, theme);
	highlighter.rehighlight();

	QString html;

	QTextBlock block = document.firstBlock();
	for (; block.isValid(); block = block.next()) {
		QString blockText = block.text();

#if (QT_VERSION >= 0x050600)
		QVector<QTextLayout::FormatRange> formats = block.layout()->formats();
#else
		QList<QTextLayout::FormatRange> formats = block.layout()->additionalFormats();
#endif

		int pos = 0;
		int count = formats.count();
		for (int i = 0; i < count; i++) {
			QTextLayout::FormatRange range = formats[i];
			uint_t color = range.format.foreground().color().rgb();
			if (!color)
				continue;

			if (range.start > pos)
				html += blockText.mid(pos, range.start - pos);

			html += QString("").arg(color, 6, 16, QChar('0'));
			html += blockText.mid(range.start, range.length);
			html += "";

			pos = range.start + range.length;
		}

		int blockEnd = block.position() + block.length();

		if (blockEnd > pos)
			html += blockText.mid(pos);

		pos = blockEnd;
	}

	return html;
}

//..............................................................................

} // namespace jnc


text:
using namespace CppCommon;

TEST_CASE("Latch single thread", "[CppCommon][Threads]")
{
    Latch latch(3);

    // Test CountDown()/TryWait()/Wait() methods
    REQUIRE(!latch.TryWait());
    latch.CountDown();
    REQUIRE(!latch.TryWait());
    latch.CountDown();
    REQUIRE(!latch.TryWait());
    latch.CountDown();
    latch.Wait();
    REQUIRE(latch.TryWait());

    // Test Rest() method
    latch.Reset(1);

    REQUIRE(!latch.TryWait());
    latch.CountDown();
    latch.Wait();
    REQUIRE(latch.TryWait());
}

TEST_CASE("Latch one thread to wait for multiple threads", "[CppCommon][Threads]")
{
    int concurrency = 8;
    std::atomic<int> count(0);
    Latch latch(concurrency);

    // Start some threads
    std::vector<std::thread> threads;
    for (int thread = 0; thread < concurrency; ++thread)
    {
        threads.emplace_back([&latch, &count, thread]()
        {
            // Increment threads counter
            ++count;

            // Sleep for a while...
            Thread::Sleep(thread * 10);

            // Count down the latch
            latch.CountDown();
        });
    }

    // Wait until work is done
    latch.Wait();

    // Wait for all threads to complete
    for (auto& thread : threads)
        thread.join();

    // Check results
    REQUIRE(count == concurrency);
}

TEST_CASE("Latch multiple threads to wait for the one initialization thread", "[CppCommon][Threads]")
{
    int concurrency = 8;
    std::atomic<int> count(0);

    Latch latch(1);

    // Start some threads
    std::vector<std::thread> threads;
    for (int thread = 0; thread < concurrency; ++thread)
    {
        threads.emplace_back([&latch, &count, thread]()
        {
            // Wait for the latch
            latch.Wait();

            // Increment threads counter
            ++count;

            // Sleep for a while...
            Thread::Sleep(thread * 100);
        });
    }

    // Perform some initialization
    Thread::Sleep(100);

    // Threads can now start processing
    latch.CountDown();

    // Wait for all threads to complete
    for (auto& thread : threads)
        thread.join();

    // Check results
    REQUIRE(count == concurrency);
}


text:
var buffer = new Buffer('王海波');

function Base64Encode(buffer) {
    console.log(buffer);
    var tmp = [];
    buffer.forEach(function (buf) {
       tmp.push(parseInt(buf));
    });
    console.log(tmp);
    tmp.forEach(function (item, index) {
        tmp[index] = item.toString(2);
    });
    var tmp1 = tmp.join('');
    console.log(tmp1);
}

Base64Encode(buffer);


text:
#pragma once

#include "../codereview_api.h"

#include "VisualizationBase/src/overlays/Overlay.h"
#include "VisualizationBase/src/declarative/DeclarativeItem.h"

#include "../nodes/NodeReviews.h"

#include "CodeReviewCommentOverlayStyle.h"

namespace CodeReview
{

class CODEREVIEW_API CodeReviewCommentOverlay :
		public Super<Visualization::Overlay<Visualization::DeclarativeItem<CodeReviewCommentOverlay>>>
{
	ITEM_COMMON(CodeReviewCommentOverlay)

	public:
		CodeReviewCommentOverlay(Visualization::Item* associatedItem, NodeReviews* nodeReviews,
										 const StyleType* style = itemStyles().get());

		static void initializeForms();

		void updateOffsetItemLocal(QPointF scenePos);

	protected:
		virtual void updateGeometry(int availableWidth, int availableHeight) override;

	private:
		NodeReviews* nodeReviews_{};
		Visualization::Item* nodeReviewsItem_{};

		QPointF offsetItemLocal_;

};

}


text:
package org.olat.data.commons.vfs;

import org.olat.data.commons.vfs.callbacks.VFSSecurityCallback;

/**
 * Description:

 * TODO: Felix Jost Class Description for VFSItem
 *

 * Initial Date: 23.06.2005

 *
 * @author Felix Jost
 */
public interface VFSItem {

    /**
     * a relative path. the implementation will search all its children. e.g. bla/blu/bli.txt this vfsitem's name must thus be 'bla'
     *
     * @param path
     * @return
     */
    public VFSItem resolve(String path);

    /**
     * Get the parent of this vfsItem.
     *
     * @return
     */
    public VFSContainer getParentContainer();

    /**
     * Sets the parent container. -> DO NOT CALL THIS METHOD... USED ONLY INTERNALLY!
     *
     * @param parentContainer
     */
    public void setParentContainer(VFSContainer parentContainer);

    /**
     * @param newname
     *            e.g test.txt or myfolder (no path prepended)
     * @return status
     */
    public VFSStatus rename(String newname);

    /**
     * deletes the item. if the item is a container, all children will be deleted recursively
     *
     * @return status
     */
    public VFSStatus delete();

    /**
     * @return if can write
     */
    public VFSStatus canRename();

    /**
     * @return if can delete
     */
    public VFSStatus canDelete();

    /**
     * @return the name
     */
    public String getName();

    /**
     * Return the last modified date of this item or -1 if not available.
     *
     * @return
     */
    public long getLastModified();

    /**
     * @return true if this container (and all its children recursively) can be copied to some other place. this is normally true for containers with a physical
     *         implementation, but not for virtual/named containers
     */
    public VFSStatus canCopy();

    /**
     * @return true if a child can be added at all(only files and folder cab be copied to). the operation may still fail because e.g. of quota limitation.
     */
    public VFSStatus canWrite();

    /**
     * Get the local security callback for this item. NOTE: Usually you would not need to access local security callbacks directly. You'd rather want to get the inherited
     * security callback of this item via getInheritedSecurityCallback. This will get you the local security callback if set aswell but also any inherited security
     * callbacks from parent containers.
     *
     * @return SecurityCallback if any, or null if not set.
     */
    public VFSSecurityCallback getLocalSecurityCallback();

    /**
     * Set a custom security callback for this item.
     *
     * @param secCallback
     */
    public void setLocalSecurityCallback(VFSSecurityCallback secCallback);

    /**
     * Test if this is the same item as ourselves.
     *
     * @param vfsItem
     * @return
     */
    public boolean isSame(VFSItem vfsItem);

    /** checks if file joined with item exists on file system */
    public boolean exists();

    /**
     * @return the complete path of this VFSItem. Depends on the implementation of the VFS.
     */
    public String getPath();
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>B-Index</title>
<meta name="date" content="2017-03-07">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I K L M N O P R S T U V W

B

b - Variable in class test.subtester.Game30x30Tester

b - Variable in class test.subtester.Game5x5Tester

b - Variable in class test.subtester.Game9x9Tester

BLOCK_SIZE - Static variable in class com.view.gui.MainPage

board - Variable in class com.controller.OXGame

The game board.

board - Variable in class com.model.algorithm.WinStrategy

Board - Class in com.model.board

The board of the game that created by Shape class.

Board(Shape) - Constructor for class com.model.board.Board

Create the board with the Shape.

Board(Shape, int) - Constructor for class com.model.board.Board

Create the board with Shape and the win condition.

board - Variable in class com.model.board.Board

board - Variable in class com.model.history.BoardHistory.Triple

BoardHistory - Class in com.model.history

history of the game board, and this class is Singleton class.

BoardHistory() - Constructor for class com.model.history.BoardHistory

BoardHistory.Triple - Class in com.model.history

Use in Board history only

 This contains board information, player and location of current symbol placed.

A B C D E F G H I K L M N O P R S T U V W

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


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 io.prestosql.operator.scalar;

import io.prestosql.spi.PrestoException;
import io.prestosql.spi.function.ScalarFunction;
import io.prestosql.spi.function.SqlType;
import io.prestosql.spi.type.ArrayType;
import io.prestosql.spi.type.SqlDecimal;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static io.prestosql.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.spi.type.BooleanType.BOOLEAN;
import static io.prestosql.spi.type.DecimalType.createDecimalType;
import static io.prestosql.spi.type.DoubleType.DOUBLE;
import static io.prestosql.spi.type.IntegerType.INTEGER;
import static io.prestosql.spi.type.TimestampType.createTimestampType;
import static io.prestosql.spi.type.VarcharType.createVarcharType;
import static io.prestosql.type.JsonType.JSON;
import static io.prestosql.type.UnknownType.UNKNOWN;
import static java.util.Arrays.asList;

public class TestTryFunction
        extends AbstractTestFunctions
{
    @BeforeClass
    public void setUp()
    {
        registerScalar(getClass());
    }

    @ScalarFunction
    @SqlType("bigint")
    public static long throwError()
    {
        throw new PrestoException(GENERIC_INTERNAL_ERROR, "internal error, should not be suppressed by " + TryFunction.NAME);
    }

    @Test
    public void testBasic()
    {
        assertFunction(createTryExpression("42"), INTEGER, 42);
        assertFunction(createTryExpression("DOUBLE '4.5'"), DOUBLE, 4.5);
        assertFunction(createTryExpression("DECIMAL '4.5'"), createDecimalType(2, 1), SqlDecimal.of("4.5"));
        assertFunction(createTryExpression("TRUE"), BOOLEAN, true);
        assertFunction(createTryExpression("'hello'"), createVarcharType(5), "hello");
        assertFunction(createTryExpression("JSON '[true, false, 12, 12.7, \"12\", null]'"), JSON, "[true,false,12,12.7,\"12\",null]");
        assertFunction(createTryExpression("ARRAY [1, 2]"), new ArrayType(INTEGER), asList(1, 2));
        assertFunction(createTryExpression("TIMESTAMP '2020-05-10 12:34:56.123456789'"), createTimestampType(9), legacyTimestamp(9, "2020-05-10 12:34:56.123456789"));
        assertFunction(createTryExpression("NULL"), UNKNOWN, null);
    }

    @Test
    public void testExceptions()
    {
        // Exceptions that should be suppressed
        assertFunction(createTryExpression("1/0"), INTEGER, null);
        assertFunction(createTryExpression("JSON_PARSE('INVALID')"), JSON, null);
        assertFunction(createTryExpression("CAST(NULL AS INTEGER)"), INTEGER, null);
        assertFunction(createTryExpression("ABS(-9223372036854775807 - 1)"), BIGINT, null);

        // Exceptions that should not be suppressed
        assertInvalidFunction(createTryExpression("throw_error()"), GENERIC_INTERNAL_ERROR);
    }

    private static String createTryExpression(String expression)
    {
        return "\"" + TryFunction.NAME + "\"(() -> " + expression + ")";
    }
}


text:
/*!
 * Copyright (c) 2018 by Contributors
 * \file add_relu_split-inl.h
 * \brief fused backward pass of add_relu + copy/split (beginning of residual module)
 * \author Clement Fuji Tsang
*/
#ifndef MXNET_OPERATOR_ADD_RELU_SPLIT_INL_H_
#define MXNET_OPERATOR_ADD_RELU_SPLIT_INL_H_

#include <vector>
#include <algorithm>
#include "./tensor/elemwise_binary_op.h"
#include "./tensor/elemwise_binary_op-inl.h"
namespace mxnet {
namespace op {

struct AddReluSplitGradKernel {
  template<typename DType>
  MSHADOW_XINLINE static void Map(int i, DType* input_grad, const DType* lhs_out_grad,
                                  const DType* rhs_out_grad, const DType* out_data,
                                  const OpReqType req) {
    DType tmp = lhs_out_grad[i] + rhs_out_grad[i];
    KERNEL_ASSIGN(input_grad[i], req, out_data[i] == DType(0.) ? DType(0.) : tmp);
  }
};

#if MSHADOW_CUDA_HALF2
template<>
MSHADOW_XINLINE void AddReluSplitGradKernel::Map<mshadow::half::half2_t>(int i,
    mshadow::half::half2_t* input_grad, const mshadow::half::half2_t* lhs_out_grad,
    const mshadow::half::half2_t* rhs_out_grad, const mshadow::half::half2_t* out_data,
    const OpReqType req) {
  float low = __low2float(lhs_out_grad[i].half2_) + __low2float(rhs_out_grad[i].half2_);
  float high = __high2float(lhs_out_grad[i].half2_) + __high2float(rhs_out_grad[i].half2_);
  KERNEL_ASSIGN(input_grad[i], req,  mshadow::half::half2_t(__floats2half2_rn(
                __low2float(out_data[i].half2_) == 0.f ? 0.f : low,
                __high2float(out_data[i].half2_) == 0.f ? 0.f : high)));
}
#else
template<>
MSHADOW_XINLINE void AddReluSplitGradKernel::Map<mshadow::half::half2_t>(int i,
    mshadow::half::half2_t* input_grad, const mshadow::half::half2_t* lhs_out_grad,
    const mshadow::half::half2_t* rhs_out_grad, const mshadow::half::half2_t* out_data,
    const OpReqType req) {
  mshadow::half::half_t low = lhs_out_grad[i].half_t2[0] + rhs_out_grad[i].half_t2[0];
  mshadow::half::half_t high = lhs_out_grad[i].half_t2[1] + rhs_out_grad[i].half_t2[1];
  KERNEL_ASSIGN(input_grad[i], req, mshadow::half::half2_t(
                out_data[i].half_t2[0] == mshadow::half::half_t(0.) ?
                mshadow::half::half_t(0.) : low,
                out_data[i].half_t2[1] == mshadow::half::half_t(0.) ?
                mshadow::half::half_t(0.) : high));
}
#endif

template<typename xpu>
inline void AddReluSplitGradCpu(const nnvm::NodeAttrs& attrs,
                                const OpContext &ctx,
                                const std::vector<TBlob> &inputs,
                                const std::vector<OpReqType> &req,
                                const std::vector<TBlob> &outputs) {
  using namespace mxnet_op;
  Stream<xpu>* s = ctx.get_stream<xpu>();
  MSHADOW_REAL_TYPE_SWITCH(inputs[0].type_flag_, DType, {
    Kernel<AddReluSplitGradKernel, xpu>::Launch(s, inputs[0].Size(),
      outputs[0].dptr<DType>(), inputs[0].dptr<DType>(),
      inputs[1].dptr<DType>(), inputs[2].dptr<DType>(), req[0]);
  });
}

template<typename xpu>
inline void AddReluSplitGradGpu(const nnvm::NodeAttrs& attrs,
                                const OpContext &ctx,
                                const std::vector<TBlob> &inputs,
                                const std::vector<OpReqType> &req,
                                const std::vector<TBlob> &outputs) {
  using namespace mxnet_op;
  Stream<xpu>* s = ctx.get_stream<xpu>();
  switch (inputs[0].type_flag_) {
  case mshadow::kFloat32:
    {
      typedef float DType;
      Kernel<AddReluSplitGradKernel, xpu>::Launch(s, inputs[0].Size(), outputs[0].dptr<DType>(),
        inputs[0].dptr<DType>(), inputs[1].dptr<DType>(), inputs[2].dptr<DType>(), req[0]);
    }
    break;
  case mshadow::kFloat64:
    {
      typedef double DType;
      Kernel<AddReluSplitGradKernel, xpu>::Launch(s, inputs[0].Size(), outputs[0].dptr<DType>(),
        inputs[0].dptr<DType>(), inputs[1].dptr<DType>(), inputs[2].dptr<DType>(), req[0]);
    }
    break;
  case mshadow::kFloat16:
    {
      typedef mshadow::half::half2_t DType;
      Kernel<AddReluSplitGradKernel, xpu>::Launch(s, (inputs[0].Size() + 1) / 2,
        outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>(),
        inputs[2].dptr<DType>(), req[0]);
    }
    break;
  case mshadow::kUint8:
    LOG(FATAL) << "This operation only support "
                  "floating point types not uint8";
    break;
  case mshadow::kInt8:
    LOG(FATAL) << "This operation only support "
                  "floating point types not int8";
    break;
  case mshadow::kInt32:
    LOG(FATAL) << "This operation only support "
                  "floating point types, not int32";
    break;
  case mshadow::kInt64:
    LOG(FATAL) << "This operation only support "
                  "floating point types, not int64";
    break;
  default:
    LOG(FATAL) << "Unknown type enum " << inputs[0].type_flag_;
  }
}

}  // namespace op
}  // namespace mxnet

#endif  // MXNET_OPERATOR_ADD_RELU_SPLIT_INL_H_


text:
package uaa_client_test

import (
	"testing"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

func TestUaaClient(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "UaaClient Suite")
}


text:
<?php

namespace Google\AdsApi\AdWords\v201809\cm;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class Selector
{

    /**
     * @var string[] $fields
     */
    protected $fields = null;

    /**
     * @var \Google\AdsApi\AdWords\v201809\cm\Predicate[] $predicates
     */
    protected $predicates = null;

    /**
     * @var \Google\AdsApi\AdWords\v201809\cm\DateRange $dateRange
     */
    protected $dateRange = null;

    /**
     * @var \Google\AdsApi\AdWords\v201809\cm\OrderBy[] $ordering
     */
    protected $ordering = null;

    /**
     * @var \Google\AdsApi\AdWords\v201809\cm\Paging $paging
     */
    protected $paging = null;

    /**
     * @param string[] $fields
     * @param \Google\AdsApi\AdWords\v201809\cm\Predicate[] $predicates
     * @param \Google\AdsApi\AdWords\v201809\cm\DateRange $dateRange
     * @param \Google\AdsApi\AdWords\v201809\cm\OrderBy[] $ordering
     * @param \Google\AdsApi\AdWords\v201809\cm\Paging $paging
     */
    public function __construct(array $fields = null, array $predicates = null, $dateRange = null, array $ordering = null, $paging = null)
    {
      $this->fields = $fields;
      $this->predicates = $predicates;
      $this->dateRange = $dateRange;
      $this->ordering = $ordering;
      $this->paging = $paging;
    }

    /**
     * @return string[]
     */
    public function getFields()
    {
      return $this->fields;
    }

    /**
     * @param string[] $fields
     * @return \Google\AdsApi\AdWords\v201809\cm\Selector
     */
    public function setFields(array $fields)
    {
      $this->fields = $fields;
      return $this;
    }

    /**
     * @return \Google\AdsApi\AdWords\v201809\cm\Predicate[]
     */
    public function getPredicates()
    {
      return $this->predicates;
    }

    /**
     * @param \Google\AdsApi\AdWords\v201809\cm\Predicate[] $predicates
     * @return \Google\AdsApi\AdWords\v201809\cm\Selector
     */
    public function setPredicates(array $predicates)
    {
      $this->predicates = $predicates;
      return $this;
    }

    /**
     * @return \Google\AdsApi\AdWords\v201809\cm\DateRange
     */
    public function getDateRange()
    {
      return $this->dateRange;
    }

    /**
     * @param \Google\AdsApi\AdWords\v201809\cm\DateRange $dateRange
     * @return \Google\AdsApi\AdWords\v201809\cm\Selector
     */
    public function setDateRange($dateRange)
    {
      $this->dateRange = $dateRange;
      return $this;
    }

    /**
     * @return \Google\AdsApi\AdWords\v201809\cm\OrderBy[]
     */
    public function getOrdering()
    {
      return $this->ordering;
    }

    /**
     * @param \Google\AdsApi\AdWords\v201809\cm\OrderBy[] $ordering
     * @return \Google\AdsApi\AdWords\v201809\cm\Selector
     */
    public function setOrdering(array $ordering)
    {
      $this->ordering = $ordering;
      return $this;
    }

    /**
     * @return \Google\AdsApi\AdWords\v201809\cm\Paging
     */
    public function getPaging()
    {
      return $this->paging;
    }

    /**
     * @param \Google\AdsApi\AdWords\v201809\cm\Paging $paging
     * @return \Google\AdsApi\AdWords\v201809\cm\Selector
     */
    public function setPaging($paging)
    {
      $this->paging = $paging;
      return $this;
    }

}


text:
module HandlePolicyNotification

  # It is possible that we have a policy which needs to be transmitted to
  # the EDI systems using a different enrollment group ID.
  # For example:
  # - we are given a dependent add
  # - we actually need to treat the enrollment that came over as a continuation
  #   of the previous policy, even though we now have a new enrollment group ID
  # - transmissions to EDI for the enrollment in question need to go out to
  #   other systems with the enrollment group id of this existing policy,
  #   NOT with the new enrollment group ID
  # - Updates should be performed on this existing policy, a new policy should
  #   not be created
  class FindContinuationPolicy
    include Interactor

    # Context requires:
    # - interacting_policies (array of Policy)
    # Context outputs:
    # - continuation_policy (either a Policy or nil)
    # - may also alter interacting_policies to remove the policy which was
    #   chosen as the continuation
    def call
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Gen. Fungi Sporul. Cult. (Vaduz), Edn 3 174 (1981)

#### Original name
Griphosphaerella stevensonii Petr.

### Remarks
null