text:
var express = require('express');
var router = express.Router();

var fs = require('fs');
var path = require('path');

// included functions
var generateSchedules = require('./lib/generateSchedules');
var generateSchedulesFirebase = require('./lib/generateScheduleFirebase');
var TROJAN = require('trojan-course-api');
var _ = require('lodash');

// firebase
var database = require('./lib/firebase');
var scheduleRef = database.ref('/20171');
var courseRef = database.ref('/courses');

var suffix = '@usc.edu';

// ROUTES OF API

// middleware
// router.use(function (req, res, next) {
//   // console.log('api call made');
//   next();
// });

router.route('/')
  .get(function (req, res) {
    res.json({
      messages: "here are some methods you can call",
      rest_api: ['schedule', 'trojan', 'refreshDatabase']
    });
  });

router.route('/refreshDatabase')
  .get(function (req, res) {

    // get full list of departments with courses
    TROJAN.deptsCN().then(function (dlist) {
      var arrayOfDepts = Object.keys(dlist);

      // we want to iterate through each dept and grab its data,
      // and return the final results once we process the last dept.
      var maxIndex = arrayOfDepts.length;
      var index = 0;

      // this is where the data will be stored.
      var masterCourses = {};

      // now, go through all departments
      TROJAN.deptBatch_cb(arrayOfDepts, null, function (deptData) {
        var courses = deptData.courses;

        // merge it with the master data collector
        masterCourses = _.merge(masterCourses, courses);
        console.log(courses);
        courseRef.update(courses);
        index += 1;

        // once we hit the last index, turn the desc into the key.
        if (maxIndex <= index) {
          res.json(masterCourses);
        }
      });
    });
  });

router.route('/schedule')
  .get(function (req, res) {
    // for testing purposes only
    var courses = req.query.courses;
    var anchors = req.query.anchors;
    var blocks = req.query.blocks;
    if (courses && courses.length > 0) {
      if (!_.isArray(courses)) courses = courses.split(',');
      // taking array of courses, generate schedule
      generateSchedulesFirebase(courses, anchors, blocks, function (data) {
        // sort results by score
        data.results.sort(function (a, b) {
          if (a.score < b.score) return -1;
          else if (a.score > b.score) return 1;
          else return 0;
        });

        // respond json
        res.json(data);
      });
    } else {
      res.json({
        error: 'no courses defined'
      });
    }
  });

router.route('/update_server').post(function (req, res) {
  var courses = req.query.courses || [];
  // due diligence
  var uniqCourses = _.uniq(courses.map(function (courseId) { return courseId.split('-')[0]; }));
  for (var id of uniqCourses) {
    TROJAN.courses(id).then(function (courseData) {
      if (courseData) {
        courseRef.update(courseData);
      }
    });
  }
  res.json({ message: 'success', courses });
});

router.route('/schedule/:user_email')
  .post(function (req, res) {

    var userEmail = req.params.user_email.toLowerCase();
    var userName = userEmail.split('@')[0].replace('.', '-');

    if (isEmailValid(userEmail)) {
      userEmail = userEmail.split('@')[0].replace('.', '-');
      scheduleRef.orderByKey().equalTo(userEmail)
        .once('value')
        .then(function(snap) {

          if (!snap.exists()) {
            scheduleRef.child(userEmail).set({
              ts: Date.now(),
              email: req.params.user_email.toLowerCase(),
              courses: [],
              anchors: {},
              blocks: []
            });
            res.json({
              message: 'new user created',
              user_email: req.params.user_email.toLowerCase(),
              courses: [],
              anchors: {},
              blocks: []
            });
          } else {
            var courses = snap.val()[userEmail].courses || [];
            var anchors = snap.val()[userEmail].anchors || {};
            var blocks = snap.val()[userEmail].blocks || [];
            res.json({
              message: 'user exists',
              user_email: req.params.user_email.toLowerCase(),
              courses: courses,
              anchors: anchors,
              blocks: blocks,
            });
          }
        }).catch(function (e) {
          return res.status(400).json({ error: e.message });
        });
    } else {
      res.json({
        error: 'not a valid email'
      });
    }
  })
  .put(function (req, res) {
		// updates the information in the database
		// sends back a 202 (data accepted) with the

    var userEmail = req.params.user_email.toLowerCase();
    var userName = userEmail.split('@')[0].replace('.', '-');

		var newCourses = req.body.courses;
		var newAnchors = req.body.anchors;
		var newBlocks = req.body.blocks;

    if (isEmailValid(userEmail)) {
      userEmail = userEmail.split('@')[0].replace('.', '-');
      scheduleRef
				.orderByKey()
				.equalTo(userEmail)
				.once('value')
        .then(function (snap) {
          if (!snap.exists()) {
						res.status(400).json(userDoesNotExist(res, userEmail))
					} else {
            var rawData = snap.val()[userName];
						var newData = resolveNewData(rawData, newCourses, newAnchors, newBlocks);
            updateScheduleFor(userName, newData)
            res.status(202).json(createUserDataReturnMessage(userName, userEmail, newData))
          }
        }).catch(function (e) {
          res.status(400).json(createErrorMessage(e.message));
        });
    } else res.status(400).json(emailNotValid(res, userEmail))

		function resolveNewData(rawData, newCourses, newAnchors, newBlocks) {
			var toRet = {};

			if (newCourses) {
				toRet['courses'] = resolveCourses(rawData['courses'], newCourses);
			}

			if (newAnchors) {
				toRet['anchors'] = resolveAnchors(rawData['anchors'], newAnchors);
			}

			if (newBlocks) {
				toRet['blocks'] = resolveBlocks(rawData['blocks'], newBlocks);
			}

			return toRet;
		}

		function resolveCourses(courses, newCourses) {
			return _.union(courses, newCourses)
		}

		function resolveAnchors(anchors, newAnchors) {
			return _.assignIn(anchors, newAnchors)
		}

		function resolveBlocks(blocks, newBlocks) {
			return _.union(blocks, newBlocks)
		}

		function updateScheduleFor(userName, newData) {
			return scheduleRef.child(userName).update(newData)
		}
  })
  .get(function (req, res) {
    var userEmail = req.params.user_email.toLowerCase();
    var userName = userEmail.split('@')[0].replace('.', '-');

    if (isEmailValid(userEmail)) {
      scheduleRef
				.orderByKey()
				.equalTo(userName)
				.once('value')
				.then(function (snap) {
					if (!snap.exists()) {
						res.status(400).json(userDoesNotExist(userEmail))
					} else {
						var rawData = snap.val()[userName];
						res.status(200).json(createUserDataReturnMessage(userName, userEmail, rawData))
					}
				}).catch(function (e) {
          res.status(400).json(createErrorMessage(e.message));
        });
    } else res.status(400)
			.json(emailNotValid(userEmail))
  });

function userDoesNotExist(userEmail) {
	return {
		error: 'cannot mutate, email does not exist',
		user_email: userEmail
	}
}

function emailNotValid(userEmail) {
	return {
		error: 'not a valid email',
		user_email: userEmail
	}
}

function createUserDataReturnMessage(userName, userEmail, rawData) {
	var courses = rawData['courses'] || [];
	var anchors = rawData['anchors'] || [];
	var blocks = rawData['blocks'] || [];

	return {
		user_name: userName
		user_email: userEmail,
		courses: courses,
		anchors: anchors,
		blocks: blocks
	}
}

function createErrorMessage(errorMessage) {
	return {
		error: errorMessage
	}
}

router.route('/verify/:course_id')
  .get(function (req, res) {
    courseRef.child(req.params.course_id).once('value', function(snap) {
      res.json({ exists: snap.exists() });
      TROJAN.courses(req.params.course_id.split('-')[0])
        .then(function (courseData) {
        if (courseData) {
          courseRef.update(courseData);
        }
      });
    });
  });

router.route('/autocomplete')
  .get(function(req, res) {
    res.json([]);
  });
router.route('/autocomplete/:text')
  .get(function (req, res) {
    var text = req.params.text;
    text = text.toUpperCase();
    courseRef
      .orderByKey()
      .startAt(text)
      .limitToFirst(8)
      // .startAt(text).endAt(text + '\uf8ff')
      // .limit(5)
      // res.json({hello:text})
      .once('value')
      .then(function (snap) {
        res.json(_.values(_.mapValues(snap.val(), function (coursedata, key) {
          return {
            courseId: key,
            title: coursedata.title
          }
        })));
      }).catch(function (e) {
        return res.status(400).json({ error: e.message });
      });
  });

router.route('/upload/:user_email')
  .post(function (req, res) {

    var userEmail = req.params.user_email.toLowerCase();

    if (isEmailValid(userEmail) && 'data' in req.body) {
      userEmail = userEmail.split('@')[0].replace('.', '-');

      var data = req.body.data.replace(/^data:image\/\w+;base64,/, "");
      var dest = '../../www/screenshots/';
      var buf = new Buffer(data, 'base64');

      scheduleRef.orderByKey().equalTo(userEmail).once('value', function(snap) {

        if (!snap.exists()) {
          res.json({ error: 'not a valid email' });
        } else {
          var destination = path.join(__dirname, 'screenshots/' + snap.key + '.jpg')
          fs.writeFile(destination, buf, (err) => {
            if (err) {
              res.json({
                error: 'unable to upload file',
                why: err
              });
            } else {
              res.json({
                message: 'file uploaded',
                user_email: req.params.user_email.toLowerCase(),
                url: 'screenshots/' + snap.key + '.jpg'
              });
            }
          });
        }
      });
    } else {
      res.json({ error: 'not a valid email or file' });
    }

  });

router.route('/trojan')
  .get(function (req, res) {
    res.json({
      trojan: ['terms', 'current_term', 'depts', 'dept', 'courses', 'dept_info', 'course', 'section', 'depts_flat', 'deptsY', 'deptsC', 'deptsN', 'deptsCN', 'deptBatch']
    });
  });

router.route('/trojan/:action')
  .get(function (req, res) {
    var action = req.params.action;
    var q = req.query;

    switch (action) {
      case 'terms':
        TROJAN.terms().then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      case 'current_term':
        TROJAN.current_term().then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      case 'depts':
        if (q.term) TROJAN.depts(q.term).then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        else res.json({ depts: ['term'] })
        break;
      case 'dept':
        TROJAN.dept(q.dept, q.term).then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      case 'courses':
        TROJAN.courses(q.dept, q.term).then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      case 'dept_info':
        TROJAN.dept_info(q.dept, q.term).then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      case 'course':
        TROJAN.course(q.dept, q.num, q.seq, q.term).then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      case 'section':
        TROJAN.section(q.dept, q.num, q.seq, q.sect, q.term).then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      case 'depts_flat':
        TROJAN.depts_flat(q.term).then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      case 'deptsY':
        TROJAN.deptsY(q.term).then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      case 'deptsC':
        TROJAN.deptsC(q.term).then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      case 'deptsN':
        TROJAN.deptsN(q.term).then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      case 'deptsCN':
        TROJAN.deptsCN(q.term).then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      case 'deptBatch':
        TROJAN.deptBatch(q.depts).then(res.json).catch(function (e) { return res.status(400).json({ error: e.message }) });
        break;
      default:
        res.json({ error: 'action not found' });
    }
  });

router.route('/usercount')
  .get(function (req, res) {
    scheduleRef.once("value", function(snapshot) {
      res.json({
        userCount: snapshot.numChildren()
      });
    });
  });

module.exports = router;

function isEmailValid(email) {
  var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email) && email.indexOf('@usc.edu') > 1;
}


text:
package gravatar

// Rating is a value suitable for the rating parameter
type Rating string

// See https://de.gravatar.com/site/implement/images/#rating
const (
	NoRating Rating = ""
	G        Rating = "g"
	Pg       Rating = "pg"
	R        Rating = "r"
	X        Rating = "x"
)

redpajama_set_name: RedPajamaGithub


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

defined('MOODLE_INTERNAL') || die();

global $CFG;
require_once($CFG->dirroot . '/question/type/shortanswer/questiontype.php');
require_once($CFG->dirroot . '/question/engine/tests/helpers.php');
require_once($CFG->dirroot . '/question/type/edit_question_form.php');
require_once($CFG->dirroot . '/question/type/shortanswer/edit_shortanswer_form.php');

/**
 * Unit tests for the shortanswer question type class.
 *
 * @copyright  2007 The Open University
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class qtype_shortanswer_test extends advanced_testcase {
    public static $includecoverage = array(
        'question/type/questiontypebase.php',
        'question/type/shortanswer/questiontype.php',
    );

    protected $qtype;

    protected function setUp() {
        $this->qtype = new qtype_shortanswer();
    }

    protected function tearDown() {
        $this->qtype = null;
    }

    protected function get_test_question_data() {
        return test_question_maker::get_question_data('shortanswer');
    }

    public function test_name() {
        $this->assertEquals($this->qtype->name(), 'shortanswer');
    }

    public function test_can_analyse_responses() {
        $this->assertTrue($this->qtype->can_analyse_responses());
    }

    public function test_get_random_guess_score() {
        $q = test_question_maker::get_question_data('shortanswer');
        $q->options->answers[15]->fraction = 0.1;
        $this->assertEquals(0.1, $this->qtype->get_random_guess_score($q));
    }

    public function test_get_possible_responses() {
        $q = test_question_maker::get_question_data('shortanswer');

        $this->assertEquals(array(
            $q->id => array(
                13 => new question_possible_response('frog', 1),
                14 => new question_possible_response('toad', 0.8),
                15 => new question_possible_response('*', 0),
                null => question_possible_response::no_response()
            ),
        ), $this->qtype->get_possible_responses($q));
    }

    public function test_get_possible_responses_no_star() {
        $q = test_question_maker::get_question_data('shortanswer', 'frogonly');

        $this->assertEquals(array(
            $q->id => array(
                13 => new question_possible_response('frog', 1),
                0 => new question_possible_response(get_string('didnotmatchanyanswer', 'question'), 0),
                null => question_possible_response::no_response()
            ),
        ), $this->qtype->get_possible_responses($q));
    }

    public function test_question_saving_frogtoad() {
        $this->resetAfterTest(true);
        $this->setAdminUser();

        $questiondata = test_question_maker::get_question_data('shortanswer');
        $formdata = test_question_maker::get_question_form_data('shortanswer');

        $generator = $this->getDataGenerator()->get_plugin_generator('core_question');
        $cat = $generator->create_question_category(array());

        $formdata->category = "{$cat->id},{$cat->contextid}";
        qtype_shortanswer_edit_form::mock_submit((array)$formdata);

        $form = qtype_shortanswer_test_helper::get_question_editing_form($cat, $questiondata);

        $this->assertTrue($form->is_validated());

        $fromform = $form->get_data();

        $returnedfromsave = $this->qtype->save_question($questiondata, $fromform);
        $actualquestionsdata = question_load_questions(array($returnedfromsave->id));
        $actualquestiondata = end($actualquestionsdata);

        foreach ($questiondata as $property => $value) {
            if (!in_array($property, array('id', 'version', 'timemodified', 'timecreated', 'options'))) {
                $this->assertAttributeEquals($value, $property, $actualquestiondata);
            }
        }

        foreach ($questiondata->options as $optionname => $value) {
            if ($optionname != 'answers') {
                $this->assertAttributeEquals($value, $optionname, $actualquestiondata->options);
            }
        }

        foreach ($questiondata->options->answers as $answer) {
            $actualanswer = array_shift($actualquestiondata->options->answers);
            foreach ($answer as $ansproperty => $ansvalue) {
                // This question does not use 'answerformat', will ignore it.
                if (!in_array($ansproperty, array('id', 'question', 'answerformat'))) {
                    $this->assertAttributeEquals($ansvalue, $ansproperty, $actualanswer);
                }
            }
        }
    }

    public function test_question_saving_trims_answers() {
        $this->resetAfterTest(true);
        $this->setAdminUser();

        $questiondata = test_question_maker::get_question_data('shortanswer');
        $formdata = test_question_maker::get_question_form_data('shortanswer');

        $generator = $this->getDataGenerator()->get_plugin_generator('core_question');
        $cat = $generator->create_question_category(array());

        $formdata->category = "{$cat->id},{$cat->contextid}";
        $formdata->answer[0] = '   frog   ';
        qtype_shortanswer_edit_form::mock_submit((array)$formdata);

        $form = qtype_shortanswer_test_helper::get_question_editing_form($cat, $questiondata);

        $this->assertTrue($form->is_validated());

        $fromform = $form->get_data();

        $returnedfromsave = $this->qtype->save_question($questiondata, $fromform);
        $actualquestionsdata = question_load_questions(array($returnedfromsave->id));
        $actualquestiondata = end($actualquestionsdata);

        $firstsavedanswer = reset($questiondata->options->answers);
        $this->assertEquals('frog', $firstsavedanswer->answer);
    }
}


text:
var cdb = require('cartodb.js');
var CreateContentView = require('../../../../../../javascripts/cartodb/common/dialogs/create/create_content');
var CreateModel = require('../../../../../../javascripts/cartodb/common/dialogs/create/create_map_model');
var _ = require('underscore');
var $ = require('jquery');

describe('dashboard/dialogs/create/create_content', function() {
  beforeEach(function() {

    this.user = new cdb.admin.User({
      base_url: 'http://paco.cartodb.com',
      username: 'paco'
    });

    this.model = new CreateModel({
      type: "map",
      option: "templates"
    }, {
      user: this.user
    });

    var $el = $('<div>').append(cdb.templates.getTemplate('common/views/create/dialog_template')());

    this.view = new CreateContentView({
      el: $el,
      user: this.user,
      model: this.model
    });

    this.view.render();
  });

  it('should render correctly', function() {
    expect(_.size(this.view._subviews)).toBe(5);
    expect(this.view.createPane).toBeDefined();
    expect(this.view.$('.CreateDialog-templates').length).toBe(1);
    expect(this.view.$('.CreateDialog-preview').length).toBe(1);
    expect(this.view.$('.CreateDialog-listing').length).toBe(1);
  });

  it('should not render templates and preview when type is dataset', function() {
    this.model.set({
      type: 'dataset',
      option: 'listing'
    });
    this.view.render();
    expect(this.view.$('.CreateDialog-templates').length).toBe(0);
    expect(this.view.$('.CreateDialog-preview').length).toBe(0);
    expect(this.view.$('.CreateDialog-listing').html()).not.toBe('');
  });

  it('should have no leaks', function() {
    expect(this.view).toHaveNoLeaks();
  });

  afterEach(function() {
    this.view.clean();
  });
});


text:
import plumber from 'gulp-plumber';
import sass from 'gulp-sass';
import sourcemaps from 'gulp-sourcemaps';
import chmod from 'gulp-chmod';
import _isUndefined from 'lodash/isUndefined';
import _merge from 'lodash/merge';
import _forEach from 'lodash/forEach';

class SassTask {
	setOptions(options) {
		this.options = options;

		if (_isUndefined(this.options.src)) {
			throw new Error('SassTask: src is missing from configuration!');
		}

		if (_isUndefined(this.options.dest)) {
			throw new Error('SassTask: dest is missing from configuration!');
		}

		if (this.options.notify) {
			this.options.plumberOptions = this.options.defaultErrorHandler;
		}

		this.options.plumberOptions = _merge({}, this.options.plumberOptions);

		return this;
	}

	defineTask(gulp) {
		let options = this.options;
		gulp.task(options.taskName, options.taskDeps, () => {
			let chain = gulp.src(options.src)
				.pipe(plumber(options.plumberOptions))
				.pipe(sourcemaps.init())
				.pipe(sass(options.config))
				.pipe(sourcemaps.write('.'));
			if (!_isUndefined(options.chmod)) {
				chain = chain.pipe(chmod(options.chmod));
			}
			chain = chain.pipe(gulp.dest(options.dest));

			_forEach(options.globalBrowserSyncs, (bs) => {
				chain = chain.pipe(bs.stream({match: '**/*.css'}));
			});

			return chain;
		});
	}
}

module.exports = SassTask;


text:
<!DOCTYPE html>

    <title>Nuremberg | Henry Wadsworth Longfellow: Selected Works | Henry Wadsworth Longfellow | Lit2Go ETC</title>
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/screenless.css" type="text/css" media="screen" title="no title" charset="utf-8">
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/printless.css" type="text/css" media="print" title="no title" charset="utf-8">

          Lit2Go

<form action="http://etc.usf.edu/lit2go/search/"><input type="text" name="q" placeholder="Search" value=""></form>

Authors

Books

Genres

Collections

Readability

      Henry Wadsworth Longfellow: Selected Works

      by Henry Wadsworth Longfellow

      Nuremberg

        Additional Information

            Year Published:
            1866

            Language:
            English

            Country of Origin:
            United States of America

            Source:
            Longfellow, H.W. (1866)  The Complete Works of Henry Wadsworth Longfellow  Boston, Massachusetts: Ticknor & Fields

            Readability:

                Flesch–Kincaid Level:
                9.0

            Word Count:
            590

            Genre:
            Poetry

            ✎ Cite This

  Share
  |

Downloads

          Audio

          Passage PDF

Student Activity

            APA

            MLA

            Chicago

            Longfellow, H. (1866). Nuremberg. Henry Wadsworth Longfellow: Selected Works (Lit2Go Edition). Retrieved February 15, 2016, from http://etc.usf.edu/lit2go/71/henry-wadsworth-longfellow-selected-works/5024/nuremberg/

            Longfellow, Henry Wadsworth. "Nuremberg." Henry Wadsworth Longfellow: Selected Works. Lit2Go Edition. 1866. Web. <http://etc.usf.edu/lit2go/71/henry-wadsworth-longfellow-selected-works/5024/nuremberg/>. February 15, 2016.

            Henry Wadsworth Longfellow, "Nuremberg," Henry Wadsworth Longfellow: Selected Works, Lit2Go Edition, (1866), accessed February 15, 2016, http://etc.usf.edu/lit2go/71/henry-wadsworth-longfellow-selected-works/5024/nuremberg/.

Back

Next

                  <audio controls style="width:99%;">
            <source src="http://etc.usf.edu/lit2go/audio/mp3/henry-wadsworth-longfellow-selected-works-030-nuremberg.5024.mp3" type="audio/mpeg" />
                          <source src="http://etc.usf.edu/lit2go/audio/ogg/henry-wadsworth-longfellow-selected-works-030-nuremberg.5024.ogg" type="audio/ogg" />
                        The embedded audio player requires a modern internet browser. You should visit Browse Happy and update your internet browser today!
          </audio>

	In the valley of the Pegnitz, where across broad meadow-lands

	Rise the blue Franconian mountains, Nuremberg, the ancient, stands.

	Quaint old town of toil and traffic, quaint old town of art and song,

	Memories haunt thy pointed gables, like the rooks that round them throng:

	Memories of the Middle Ages, when the emperors, rough and bold,

	Had their dwelling in thy castle, time-defying, centuries old;

	And thy brave and thrifty burghers boasted, in their uncouth rhyme,

	That their great imperial city stretched its hand through every clime.

	In the court-yard of the castle, bound with many an iron hand,

	Stands the mighty linden planted by Queen Cunigunde’s hand;

	On the square the oriel window, where in old heroic days

	Sat the poet Melchior singing Kaiser Maximilian’s praise.

	Everywhere I see around me rise the wondrous world of Art:

	Fountains wrought with richest sculpture standing in the common mart;

	And above cathedral doorways saints and bishops carved in stone,

	By a former age commissioned as apostles to our own.

	In the church of sainted Sebald sleeps enshrined his holy dust,

	And in bronze the Twelve Apostles guard from age to age their trust;

	In the church of sainted Lawrence stands a pix of sculpture rare,

	Like the foamy sheaf of fountains, rising through the painted air.

	Here, when Art was still religion, with a simple, reverent heart,

	Lived and labored Albrecht Durer, the Evangelist of Art;

	Hence in silence and in sorrow, toiling still with busy hand,

	Like an emigrant he wandered, seeking for the Better Land.

	Emigravit is the inscription on the tombstone where he lies;

	Dead he is not, but departed,—for the artist never dies.

	Fairer seems the ancient city, and the sunshine seems more fair,

	That he once has trod its pavement, that he once has breathed its air!

	Through these streets so broad and stately, these obscure and dismal lanes,

	Walked of yore the Mastersingers, chanting rude poetic strains.

	From remote and sunless suburbs came they to the friendly guild,

	Building nests in Fame’s great temple, as in spouts the swallows build.

	As the weaver plied the shuttle, wove he too the mystic rhyme,

	And the smith his iron measures hammered to the anvil’s chime;

	Thanking God, whose boundless wisdom makes the flowers of poesy bloom

	In the forge’s dust and cinders, in the tissues of the loom.

	Here Hans Sachs, the cobbler-poet, laureate of the gentle craft,

	Wisest of the Twelve Wise Masters, in huge folios sang and laughed.

	But his house is now an ale-house, with a nicely sanded floor,

	And a garland in the window, and his face above the door;

	Painted by some humble artist, as in Adam Puschman’s song,

	As the old man gray and dove-like, with his great beard white and long.

	And at night the swart mechanic comes to drown his cark and care,

	Quaffing ale from pewter tankard; in the master’s antique chair.

	Vanished is the ancient splendor, and before my dreamy eye

	Wave these mingled shapes and figures, like a faded tapestry.

	Not thy Councils, not thy Kaisers, win for thee the world’s regard;

	But thy painter, Albrecht Durer, and Hans Sachs thy cobbler-bard.

	Thus, O Nuremberg, a wanderer from a region far away,

	As he paced thy streets and court-yards, sang in thought his careless lay:

	Gathering from the pavement’s crevice, as a floweret of the soil,

	The nobility of labor,—the long pedigree of toil.

Back

Next

            This collection of children's literature is a part of the Educational Technology Clearinghouse and is funded by various grants.

            Copyright © 2006—2016 by the Florida Center for Instructional Technology, College of Education, University of South Florida.

License

Credits

FAQ

Giving

This document was downloaded from Lit2Go, a free online collection of stories and poems in Mp3 (audiobook) format published by the Florida Center for Instructional Technology. For more information, including classroom activities, readability data, and original sources, please visit http://etc.usf.edu/lit2go/71/henry-wadsworth-longfellow-selected-works/5024/nuremberg/.

Lit2Go: Henry Wadsworth Longfellow: Selected Works

Nuremberg


text:
package com.holdenkarau.spark.testing

class JavaDataFrameSuiteBase extends
    SharedJavaSparkContext with DataFrameSuiteBaseLike with JavaTestSuite {

  override def beforeAllTestCasesHook(): Unit = {
    sqlBeforeAllTestCases()
  }

}


text:
package com.thebuyback.eve.service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.thebuyback.eve.domain.stock.Fitting;
import com.thebuyback.eve.domain.stock.FittingItem;

import org.springframework.stereotype.Component;

@Component
public class FittingParser {

    private final TypeService typeService;

    public FittingParser(final TypeService typeService) {
        this.typeService = typeService;
    }

    public Fitting parse(String text) {
        final AtomicReference<String> fittingName = new AtomicReference<>();
        Map<String, Integer> quantities = new HashMap<>();
        Arrays.stream(text.split("\n")).filter(s -> !s.isEmpty()).forEach(s -> {
            String typeName;
            int quantity = 1;
            if (s.startsWith("[")) {
                if (s.contains("[empty") || s.contains("[Empty")) {
                    return;
                }
                final String[] split = s.split(",");
                typeName = split[0].substring(1).trim();
                final String trimmedName = split[1].trim();
                final String fittingNameString = trimmedName.substring(0, trimmedName.length() - 1);
                fittingName.set(fittingNameString);
            } else if (s.contains(" x")) {
                final String[] split = s.split(" x");
                typeName = split[0];
                quantity = Integer.parseInt(split[1]);
            } else {
                typeName = s;
            }

            if (!quantities.containsKey(typeName)) {
                quantities.put(typeName, 0);
            }
            quantities.put(typeName, quantities.get(typeName) + quantity);
        });

        final List<FittingItem> items = quantities.entrySet().stream().map(e -> {
            final long typeId = typeService.getTypeIdByName(e.getKey());
            return new FittingItem(typeId, e.getValue());
        }).collect(Collectors.toList());

        if (null == fittingName.get()) {
            throw new RuntimeException("Fitting name was null: " + text);
        }

        return new Fitting(fittingName.get(), fittingName.get(), items);
    }
}


text:
require "waiter/menu"
require "waiter/dsl"
require "waiter/menu/drawer"

module Waiter
  class Engine < ::Rails::Engine
    initializer :assets do |config|
      Rails.application.config.assets.precompile += %w{ waiter/menu.css }
      Rails.application.config.assets.paths << root.join("app", "assets", "stylesheets")
      Rails.application.config.assets.paths << root.join("app", "assets", "images")
    end
  end
end


text: Reactive Extensible Application Protocol


text:
_G.FBMAKE_VERSION_MAJOR = 0
_G.FBMAKE_VERSION_MINOR = 2
_G.FBMAKE_VERSION_PATCH = 0

_G.FBMAKE_VERSION = FBMAKE_VERSION_MAJOR .. '.' .. FBMAKE_VERSION_MINOR .. '.' .. FBMAKE_VERSION_PATCH

function _G.require_fbmake_version(maj, min, patch)
	patch = patch or 0
	if type(maj) == 'string' then
		local v = maj:split('.', true)
		maj = tonumber(v[1])
		min = tonumber(v[2])
		if (#v >= 3) then
			patch = tonumber(v[3])
		end
	end
	if (maj > FBMAKE_VERSION_MAJOR or
			(maj == FBMAKE_VERSION_MAJOR and min > FBMAKE_VERSION_MINOR) or
			(maj == FBMAKE_VERSION_MAJOR and min == FBMAKE_VERSION_MINOR and patch > FBMAKE_VERSION_PATCH)) then
		error("FBMake version " .. FBMAKE_VERSION ..
			' is lower than required version ' .. maj ..'.' .. min .. '.' .. patch
		)
	end
end


text:
import * as mat4 from '@2gis/gl-matrix/mat4';
import assert from 'assert';
import {slice} from '../utils';
import Object3D from '../../src/Object3D';

import Camera from '../../src/cameras/Camera';

describe('Camera', () => {
    let camera;

    beforeEach(() => {
        camera = new Camera();
    });

    describe('#constructor', () => {
        it('should inherited from Object3D', () => {
            assert.ok(camera instanceof Object3D);
        });

        it('should have default up vector', () => {
            assert.deepEqual(slice(camera.up), [0, 1, 0]);
        });

        it('should have default projectionMatrix', () => {
            const matrix = mat4.create();
            assert.deepEqual(slice(camera.projectionMatrix), slice(matrix));
        });

        it('should have default modelViewMatrix', () => {
            const matrix = mat4.create();
            assert.deepEqual(slice(camera.modelViewMatrix), slice(matrix));
        });

        it('should have default worldInverseMatrix', () => {
            const matrix = mat4.create();
            assert.deepEqual(slice(camera.worldInverseMatrix), slice(matrix));
        });
    });

    describe('#updateProjectionMatrix', () => {
        it('should never did', () => {
            camera.updateProjectionMatrix();
        });
    });

    describe('#updateWorldMatrix', () => {
        let oldMatrix;

        beforeEach(() => {
            oldMatrix = slice(camera.worldMatrix);
        });

        it('old world matrix should be equal new after update', () => {
            camera.updateWorldMatrix();
            assert.deepEqual(oldMatrix, slice(camera.worldMatrix));
        });

        it('shouldn\'t change matrix after change position and update', () => {
            camera.position[1] = 123;
            camera.updateWorldMatrix();
            assert.deepEqual(oldMatrix, slice(camera.worldMatrix));
        });

        it('should update if local matrix changed', () => {
            camera.position[1] = 123;
            camera.updateLocalMatrix();
            camera.updateWorldMatrix();
            assert.notDeepEqual(oldMatrix, slice(camera.worldMatrix));
        });

        it('should update modelViewMatrix matrix', () => {
            oldMatrix = slice(camera.modelViewMatrix);
            camera.position[1] = 123;
            camera.updateLocalMatrix();
            camera.updateWorldMatrix();
            assert.notDeepEqual(oldMatrix, slice(camera.modelViewMatrix));
        });
    });
});


text:
#include <CQChartsPlotPropertyEdit.h>
#include <CQChartsLineEditBase.h>
#include <CQChartsPlot.h>
#include <CQChartsVariant.h>

#include <CQPropertyView.h>
#include <CQPropertyViewEditor.h>
#include <CQUtil.h>

#include <QLineEdit>
#include <QComboBox>
#include <QLabel>
#include <QCheckBox>
#include <QHBoxLayout>

CQChartsPlotPropertyEditGroup::
CQChartsPlotPropertyEditGroup(CQChartsPlot *plot) :
 plot_(plot)
{
  setObjectName("editGroup");

  setAutoFillBackground(true);

  setFrameShape(QFrame::StyledPanel);

  layout_ = CQUtil::makeLayout<QVBoxLayout>(this, 2, 2);

  auto *widgetFrame = CQUtil::makeWidget<QFrame>("frame");

  widgetLayout_ = CQUtil::makeLayout<QVBoxLayout>(widgetFrame, 0, 0);

  widgetFrame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

  layout_->addWidget(widgetFrame);

  auto *spacer = CQUtil::makeWidget<QFrame>("spacer");

  spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

  layout_->addWidget(spacer);
}

void
CQChartsPlotPropertyEditGroup::
setPlot(CQChartsPlot *p)
{
  plot_ = p;

  for (auto &edit : edits_)
    edit->setPlot(p);
}

void
CQChartsPlotPropertyEditGroup::
addSlot(const QString &s)
{
  auto strs = s.split(" ", Qt::SkipEmptyParts);

  if (strs.size() == 0)
    return;

  QString label;

  if (strs.size() > 1)
    label = strs[1];

  auto propertyName = strs[0];

  auto *edit = new CQChartsPlotPropertyEdit;

  edit->setObjectName(QString("edit%1").arg(edits_.size() + 1));

  if (label == "")
    label = propertyName;

  edit->setLabel(label);

  edit->setPropertyName(propertyName);

  addEdit(edit);
}

void
CQChartsPlotPropertyEditGroup::
addEdit(CQChartsPlotPropertyEdit *edit)
{
  edit->setPlot(plot_);

  widgetLayout_->addWidget(edit);

  edits_.push_back(edit);
}

QSize
CQChartsPlotPropertyEditGroup::
sizeHint() const
{
  int w = 0, h = 0;

  for (auto &edit : edits_) {
    auto s = edit->sizeHint();

    w  = std::max(w, s.width());
    h += s.height() + 2;
  }

  return QSize(w + 4, h + 2);
}

//------

CQChartsPlotPropertyEdit::
CQChartsPlotPropertyEdit(CQChartsPlot *plot, const QString &propertyName) :
 plot_(plot), propertyName_(propertyName)
{
  setObjectName("edit");

  layout_ = CQUtil::makeLayout<QHBoxLayout>(this, 2, 2);

  init();
}

void
CQChartsPlotPropertyEdit::
setPlot(CQChartsPlot *p)
{
  if (p != plot_) {
    plot_ = p;

    init(/*rebuild*/true);
  }
}

void
CQChartsPlotPropertyEdit::
setPropertyName(const QString &s)
{
  if (s != propertyName_) {
    propertyName_ = s;

    init(/*rebuild*/true);
  }
}

void
CQChartsPlotPropertyEdit::
setLabel(const QString &s)
{
  if (s != label_) {
    label_ = s;

    init();
  }
}

void
CQChartsPlotPropertyEdit::
init(bool rebuild)
{
  if (rebuild) {
    if (widget_) {
      delete widget_;

      widget_ = nullptr;
    }
  }

  if (! plot_ || propertyName_ == "")
    return;

  if (! labelWidget_) {
    labelWidget_ = CQUtil::makeWidget<QLabel>("label");

    layout_->addWidget(labelWidget_);

    widgetLayout_ = CQUtil::makeLayout<QHBoxLayout>(0, 0);

    layout_->addLayout(widgetLayout_);

    layout_->addStretch(1);
  }

  labelWidget_->setText(label_);

  if (rebuild) {
    widget_ = createEditor();

    if (widget_)
      widgetLayout_->addWidget(widget_);
  }
}

QWidget *
CQChartsPlotPropertyEdit::
createEditor()
{
  if (! plot_)
    return nullptr;

  CQUtil::PropInfo propInfo;
  QString          typeName;

  if (CQUtil::getPropInfo(plot_, propertyName_, &propInfo))
    typeName = propInfo.typeName();

  QVariant var;

  if (! CQUtil::getProperty(plot_, propertyName_, var))
    var = QVariant();

  if (propInfo.isEnumType()) {
    bool ok;
    long value = CQChartsVariant::toInt(var, ok);

    QString str;

    if (CQUtil::getPropInfoEnumValueName(propInfo, int(value), str))
      var = str;
  }

  QWidget *widget = nullptr;

  auto *factory = CQPropertyViewMgrInst->getEditor(typeName);

  if (factory) {
    widget = factory->createEdit(this);
    if (! widget) return nullptr;

    setWidgetPlot(widget);

    factory->setValue(widget, var);

    factory->connect(widget, this, SLOT(updateValue()));
  }
  else if (propInfo.isEnumType()) {
    auto valueStr = var.toString();

    const auto &names = propInfo.enumNames();

    auto *combo = CQUtil::makeWidget<QComboBox>(this, "combo");

    combo->addItems(names);
    combo->setCurrentIndex(combo->findText(valueStr));

    connect(combo, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(updateValue()));

    widget = combo;
  }
  // bool - create toggle
  // TODO: use button press (no need to edit) see CQCheckTree.cpp
  else if (typeName == "bool") {
    auto *check = CQUtil::makeWidget<QCheckBox>(this, "check");

    bool ok;
    check->setChecked(CQChartsVariant::toBool(var, ok));

    check->setText(CQChartsUtil::boolToString(check->isChecked()));

    check->setAutoFillBackground(true);
  //check->setLayoutDirection(Qt::RightToLeft);

    connect(check, SIGNAL(stateChanged(int)), this, SLOT(updateValue()));

    widget = check;
  }
  else if (CQChartsVariant::isUserType(var)) {
    QString valueStr;

    if (! CQUtil::userVariantToString(var, valueStr)) {
      //std::cerr << "Failed to convert to string" << std::endl;
    }

    auto edit = CQUtil::makeWidget<QLineEdit>(this, "edit");

    edit->setText(valueStr);

    widget = edit;
  }
  else {
    QString valueStr;

    if (! CQUtil::variantToString(var, valueStr)) {
      //std::cerr << "Failed to convert to string" << std::endl;
    }

    auto edit = CQUtil::makeWidget<QLineEdit>(this, "edit");

    edit->setText(valueStr);

    widget = edit;
  }

  return widget;
}

void
CQChartsPlotPropertyEdit::
setWidgetPlot(QWidget *widget)
{
  auto *lineEdit = qobject_cast<CQChartsLineEditBase *>(widget);

  if (lineEdit)
    lineEdit->setPlot(plot_);
}

void
CQChartsPlotPropertyEdit::
updateValue()
{
  if (! plot_)
    return;

  CQUtil::PropInfo propInfo;
  QString          typeName;

  if (CQUtil::getPropInfo(plot_, propertyName_, &propInfo))
    typeName = propInfo.typeName();

  auto *factory = CQPropertyViewMgrInst->getEditor(typeName);

  QVariant var;

  if      (factory) {
    var = factory->getValue(widget_);
  }
  else if (propInfo.isEnumType()) {
    auto *combo = qobject_cast<QComboBox *>(widget_);
    assert(combo);

    var = combo->currentText();
  }
  else if (typeName == "bool") {
    auto *check = qobject_cast<QCheckBox *>(widget_);
    assert(check);

    check->setText(CQChartsUtil::boolToString(check->isChecked()));

    var = (check->isChecked() ? "1" : "0");
  }
  else if (propInfo.type() == QVariant::UserType) {
    auto *edit = qobject_cast<QLineEdit *>(widget_);
    assert(edit);

    auto text = edit->text();

    var = text;

    if (! CQUtil::userVariantFromString(var, text))
      return;
  }
  else {
    auto *edit = qobject_cast<QLineEdit *>(widget_);
    assert(edit);

    var = edit->text();
  }

  CQUtil::setProperty(plot_, propertyName_, var);
}

QSize
CQChartsPlotPropertyEdit::
sizeHint() const
{
  auto ls = (labelWidget_ ? labelWidget_->sizeHint() : QSize());
  auto ws = (widget_      ? widget_     ->sizeHint() : QSize());

  return QSize(ls.width() + ws.width() + 6, std::max(ls.height(), ws.height()) + 4);
}


text:
package rationals.transformations;

import junit.framework.TestCase;
import rationals.Automaton;
import rationals.converters.ConverterException;
import rationals.converters.Expression;
import rationals.converters.ToRExpression;

/**
 * @author nono
 * @version $Id: ComplementTest.java 2 2006-08-24 14:41:48Z oqube $
 */
public class ComplementTest extends TestCase {

    /**
     * @param arg0
     */
    public ComplementTest(String arg0) {
        super(arg0);
    }

    public void testComp() throws ConverterException {
        Automaton a = new Pruner().transform(new Expression()
                .fromString("a(bb)*e"));
        Automaton c= new ToDFA().transform(new Complement().transform(a));
        System.out.println(c);
        String re;
        System.out.println(re =new ToRExpression().toString(c));
    }

}


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

import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;

import org.apache.aurora.common.stats.Stats;

import org.apache.aurora.gen.JobConfiguration;
import org.apache.aurora.gen.JobKey;
import org.apache.aurora.gen.ScheduledTask;
import org.apache.aurora.gen.TaskConfig;
import org.apache.aurora.scheduler.base.JobKeys;
import org.apache.aurora.scheduler.base.Query;
import org.apache.aurora.scheduler.configuration.ConfigurationManager;
import org.apache.aurora.scheduler.storage.Storage.MutableStoreProvider;
import org.apache.aurora.scheduler.storage.TaskStore.Mutable.TaskMutation;
import org.apache.aurora.scheduler.storage.entities.IJobConfiguration;
import org.apache.aurora.scheduler.storage.entities.IJobKey;
import org.apache.aurora.scheduler.storage.entities.IScheduledTask;
/**
 * Utility class to contain and perform storage backfill operations.
 */
public final class StorageBackfill {

  private static final Logger LOG = Logger.getLogger(StorageBackfill.class.getName());

  private static final AtomicLong BACKFILLED_TASK_CONFIG_KEYS =
      Stats.exportLong("task_config_keys_backfilled");

  private static final AtomicLong BACKFILLED_JOB_CONFIG_KEYS =
      Stats.exportLong("job_store_task_config_keys_backfilled");

  private StorageBackfill() {
    // Utility class.
  }

  private static void backfillJobDefaults(CronJobStore.Mutable jobStore) {
    for (JobConfiguration job : IJobConfiguration.toBuildersList(jobStore.fetchJobs())) {
      populateJobKey(job.getTaskConfig(), BACKFILLED_JOB_CONFIG_KEYS);
      ConfigurationManager.applyDefaultsIfUnset(job);
      jobStore.saveAcceptedJob(IJobConfiguration.build(job));
    }
  }

  private static void populateJobKey(TaskConfig config, AtomicLong counter) {
    if (!config.isSetJob() || !JobKeys.isValid(IJobKey.build(config.getJob()))) {
      config.setJob(new JobKey()
          .setRole(config.getOwner().getRole())
          .setEnvironment(config.getEnvironment())
          .setName(config.getJobName()));

      counter.incrementAndGet();
    }
  }

  /**
   * Backfills the storage to make it match any assumptions that may have changed since
   * the structs were first written.
   *
   * @param storeProvider Storage provider.
   */
  public static void backfill(final MutableStoreProvider storeProvider) {
    backfillJobDefaults(storeProvider.getCronJobStore());

    // Backfilling job keys has to be done in a separate transaction to ensure follow up scoped
    // Query calls work against upgraded MemTaskStore, which does not support deprecated fields.
    LOG.info("Backfilling task config job keys.");
    storeProvider.getUnsafeTaskStore().mutateTasks(Query.unscoped(), new TaskMutation() {
      @Override
      public IScheduledTask apply(final IScheduledTask task) {
        ScheduledTask builder = task.newBuilder();
        populateJobKey(builder.getAssignedTask().getTask(), BACKFILLED_TASK_CONFIG_KEYS);
        return IScheduledTask.build(builder);
      }
    });

    LOG.info("Performing shard uniqueness sanity check.");
    storeProvider.getUnsafeTaskStore().mutateTasks(Query.unscoped(), new TaskMutation() {
      @Override
      public IScheduledTask apply(final IScheduledTask task) {
        ScheduledTask builder = task.newBuilder();
        ConfigurationManager.applyDefaultsIfUnset(builder.getAssignedTask().getTask());
        return IScheduledTask.build(builder);
      }
    });
  }
}


text:
/**
@module ember
@submodule ember-htmlbars
*/

import Ember from 'ember-metal/core';
import { isGlobal } from 'ember-metal/path_cache';
import ProxyStream from 'ember-metal/streams/proxy-stream';

export default function getRoot(scope, key) {
  if (key === 'this') {
    return [scope.self];
  } else if (key === 'hasBlock') {
    return [!!scope.blocks.default];
  } else if (key === 'hasBlockParams') {
    return [!!(scope.blocks.default && scope.blocks.default.arity)];
  } else if (isGlobal(key) && Ember.lookup[key]) {
    return [getGlobal(key)];
  } else if (key in scope.locals) {
    return [scope.locals[key]];
  } else {
    return [getKey(scope, key)];
  }
}

function getKey(scope, key) {
  if (key === 'attrs' && scope.attrs) {
    return scope.attrs;
  }

  var self = scope.self || scope.locals.view;

  if (scope.attrs && key in scope.attrs) {
    // TODO: attrs
    // Ember.deprecate("You accessed the `" + key + "` attribute directly. Please use `attrs." + key + "` instead.");
    return scope.attrs[key];
  } else if (self) {
    return self.getKey(key);
  }
}

function getGlobal(name) {
  Ember.deprecate('Global lookup of ' + name + ' from a Handlebars template is deprecated.');

  // This stream should be memoized, but this path is deprecated and
  // will be removed soon so it's not worth the trouble.
  return new ProxyStream(Ember.lookup[name], name);
}


text:
<title>MicroBlaze - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Embedded-Processors.html#Embedded-Processors" title="Embedded Processors">
<link rel="prev" href="M68K.html#M68K" title="M68K">
<link rel="next" href="MIPS-Embedded.html#MIPS-Embedded" title="MIPS Embedded">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: MIPS Embedded,
Previous: M68K,
Up: Embedded Processors

21.3.4 MicroBlaze

The MicroBlaze is a soft-core processor supported on various Xilinx
FPGAs, such as Spartan or Virtex series.  Boards with these processors
usually have JTAG ports which connect to a host system running the Xilinx
Embedded Development Kit (EDK) or Software Development Kit (SDK).
This host system is used to download the configuration bitstream to
the target FPGA.  The Xilinx Microprocessor Debugger (XMD) program
communicates with the target board using the JTAG interface and
presents a gdbserver interface to the board.  By default
xmd uses port 1234.  (While it is possible to change
this default port, it requires the use of undocumented xmd
commands.  Contact Xilinx support if you need to do this.)

Use these GDB commands to connect to the MicroBlaze target processor.

target remote :1234
Use this command to connect to the target if you are running gdb
on the same system as xmd.

target remote <var>xmd-host</var>:1234
Use this command to connect to the target if it is connected to xmd
running on a different system named <var>xmd-host</var>.

load
Use this command to download a program to the MicroBlaze target.

set debug microblaze <var>n</var>
Enable MicroBlaze-specific debugging messages if non-zero.

show debug microblaze <var>n</var>
Show MicroBlaze-specific debugging level.


text:
using Signum.Engine.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Maps;
using Signum.Engine.Operations;
using Signum.Entities;
using Signum.Entities.DynamicQuery;
using Signum.Entities.Word;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Signum.Engine.Templating;
using Signum.Entities.Templating;
using Signum.Entities.Basics;

namespace Signum.Engine.Word
{
    public class WordTemplateParameters : TemplateParameters
    {
        public WordTemplateParameters(IEntity? entity, CultureInfo culture, Dictionary<QueryToken, ResultColumn> columns,
            IEnumerable<ResultRow> rows, WordTemplateEntity template, IWordModel? wordModel) :
              base(entity, culture, columns, rows)
        {
            this.Template = template;
            this.Model = wordModel;

        }

        public IWordModel? Model;

        public WordTemplateEntity Template;

        public override object GetModel()
        {
            if (Model == null)
                throw new ArgumentException("There is no Model set");

            return Model;
        }
    }

    public interface IWordModel
    {
        ModifiableEntity UntypedEntity { get; }

        Entity? ApplicableTo { get; }

        List<Filter> GetFilters(QueryDescription qd);
        Pagination GetPagination();
        List<Order> GetOrders(QueryDescription queryDescription);
    }

    public abstract class WordModel<T> : IWordModel
       where T : ModifiableEntity
    {
        public WordModel(T entity)
        {
            this.Entity = entity;
        }

        public T Entity { get; set; }

        public virtual Entity? ApplicableTo => this.Entity as Entity;

        ModifiableEntity IWordModel.UntypedEntity
        {
            get { return Entity; }
        }

        public virtual List<Filter> GetFilters(QueryDescription qd)
        {
            var imp = qd.Columns.SingleEx(a => a.IsEntity).Implementations!.Value;

            if (imp.IsByAll && typeof(Entity).IsAssignableFrom(typeof(T)) || imp.Types.Contains(typeof(T)))
                return new List<Filter>
                {
                    new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.EqualTo, ((Entity)(ModifiableEntity)Entity).ToLite())
                };

            throw new InvalidOperationException($"Since {typeof(T).Name} is not in {imp}, it's necessary to override ${nameof(GetFilters)} in ${this.GetType().Name}");
        }

        public virtual List<Order> GetOrders(QueryDescription queryDescription)
        {
            return new List<Order>();
        }

        public virtual Pagination GetPagination()
        {
            return new Pagination.All();
        }
    }

    public class MultiEntityWord : WordModel<MultiEntityModel>
    {
        public MultiEntityWord(MultiEntityModel entity) : base(entity)
        {
        }

        public override List<Filter> GetFilters(QueryDescription qd)
        {
            return new List<Filter>
            {
                new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.IsIn, this.Entity.Entities.ToList())
            };
        }
    }

    public class QueryWord : WordModel<QueryModel>
    {
        public QueryWord(QueryModel entity) : base(entity)
        {
        }

        public override List<Filter> GetFilters(QueryDescription qd)
        {
            return this.Entity.Filters;
        }

        public override Pagination GetPagination()
        {
            return this.Entity.Pagination;
        }

        public override List<Order> GetOrders(QueryDescription queryDescription)
        {
            return this.Entity.Orders;
        }
    }

    public static class WordModelLogic
    {
        class WordModelInfo
        {
            public object QueryName;
            public Func<WordTemplateEntity>? DefaultTemplateConstructor;

            public WordModelInfo(object queryName)
            {
                QueryName = queryName;
            }
        }

        static ResetLazy<Dictionary<Lite<WordModelEntity>, List<Lite<WordTemplateEntity>>>> WordModelToTemplates = null!;
        static Dictionary<Type, WordModelInfo> registeredWordModels = new Dictionary<Type, WordModelInfo>();
        public static ResetLazy<Dictionary<Type, WordModelEntity>> WordModelTypeToEntity = null!;
        public static ResetLazy<Dictionary<WordModelEntity, Type>> WordModelEntityToType = null!;

        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Schema.Generating += Schema_Generating;
                sb.Schema.Synchronizing += Schema_Synchronizing;
                sb.Include<WordModelEntity>()
                    .WithQuery(() => se => new
                    {
                        Entity = se,
                        se.Id,
                        se.FullClassName,
                    });

                RegisterWordModel<MultiEntityWord>(null);
                RegisterWordModel<QueryWord>(null);

                new Graph<WordTemplateEntity>.ConstructFrom<WordModelEntity>(WordTemplateOperation.CreateWordTemplateFromWordModel)
                {
                    CanConstruct = se => HasDefaultTemplateConstructor(se) ? null : WordTemplateMessage.NoDefaultTemplateDefined.NiceToString(),
                    Construct = (se, _) => CreateDefaultTemplate(se)!.Save()
                }.Register();

                WordModelToTemplates = sb.GlobalLazy(() => (
                    from et in Database.Query<WordTemplateEntity>()
                    where et.Model != null
                    select new { swe = et.Model, et = et.ToLite() })
                    .GroupToDictionary(pair => pair.swe!.ToLite(), pair => pair.et!),
                    new InvalidateWith(typeof(WordModelEntity), typeof(WordTemplateEntity)));

                WordModelTypeToEntity = sb.GlobalLazy(() =>
                {
                    var dbWordModels = Database.RetrieveAll<WordModelEntity>();
                    return EnumerableExtensions.JoinRelaxed(
                        dbWordModels,
                        registeredWordModels.Keys,
                        swr => swr.FullClassName,
                        type => type.FullName!,
                        (swr, type) => KeyValuePair.Create(type, swr),
                        "caching " + nameof(WordModelEntity)).ToDictionary();
                }, new InvalidateWith(typeof(WordModelEntity)));

                sb.Schema.Initializing += () => WordModelTypeToEntity.Load();

                WordModelEntityToType = sb.GlobalLazy(() => WordModelTypeToEntity.Value.Inverse(),
                    new InvalidateWith(typeof(WordModelEntity)));
            }
        }

        internal static bool HasDefaultTemplateConstructor(WordModelEntity wordModel)
        {
            WordModelInfo info = registeredWordModels.GetOrThrow(wordModel.ToType());

            return info.DefaultTemplateConstructor != null;
        }

        internal static WordTemplateEntity? CreateDefaultTemplate(WordModelEntity wordModel)
        {
            WordModelInfo info = registeredWordModels.GetOrThrow(wordModel.ToType());

            if (info.DefaultTemplateConstructor == null)
                return null;

            WordTemplateEntity template = info.DefaultTemplateConstructor();

            if (template.Name == null)
                template.Name = wordModel.FullClassName;

            template.Model = wordModel;
            template.Query = QueryLogic.GetQueryEntity(info.QueryName);
            template.ParseData(QueryLogic.Queries.QueryDescription(info.QueryName));

            return template;
        }

        public static byte[] CreateReport(this IWordModel model, bool avoidConversion = false)
        {
            return model.CreateReport(out WordTemplateEntity rubish, avoidConversion);
        }

        public static byte[] CreateReport(this IWordModel model, out WordTemplateEntity template, bool avoidConversion = false, WordTemplateLogic.FileNameBox? fileNameBox = null)
        {
            WordModelEntity wordModel = GetWordModelEntity(model.GetType());

            template = GetDefaultTemplate(wordModel, model.UntypedEntity as Entity);

            return template.ToLite().CreateReport(null, model, avoidConversion, fileNameBox);
        }

        public static FileContent CreateReportFileContent(this IWordModel model, bool avoidConversion = false)
        {
            var box = new WordTemplateLogic.FileNameBox();
            var bytes = model.CreateReport(out WordTemplateEntity rubish, avoidConversion, box);
            return new FileContent(box.FileName!, bytes);
        }

        public static WordModelEntity GetWordModelEntity(Type type)
        {
            return WordModelTypeToEntity.Value.GetOrThrow(type);
        }

        public static WordTemplateEntity GetDefaultTemplate(WordModelEntity model, Entity? entity)
        {
            var templates = WordModelToTemplates.Value.TryGetC(model.ToLite()).EmptyIfNull().Select(a => WordTemplateLogic.WordTemplatesLazy.Value.GetOrThrow(a));
            if (templates.IsNullOrEmpty() && HasDefaultTemplateConstructor(model))
            {
                using (ExecutionMode.Global())
                using (OperationLogic.AllowSave<WordTemplateEntity>())
                using (Transaction tr = Transaction.ForceNew())
                {
                    var template = CreateDefaultTemplate(model)!;

                    template.Save();

                    return tr.Commit(template);
                }
            }

            var ci = WordTemplateLogic.GetCultureInfo?.Invoke(entity) ?? CultureInfo.CurrentCulture;

            var isAllowed = Schema.Current.GetInMemoryFilter<WordTemplateEntity>(userInterface: false);
            var candidates = templates.Where(isAllowed).Where(t => t.IsApplicable(entity));
            return GetTemplate(candidates, model, ci) ??
                GetTemplate(candidates, model, CultureInfo.CurrentCulture.Parent) ??
                candidates.SingleEx(
                    () => $"No active WordTemplate for {registeredWordModels} in {CultureInfo.CurrentCulture} or {CultureInfo.CurrentCulture.Parent}",
                    () => $"More than one active WordTemplate for {registeredWordModels} in {CultureInfo.CurrentCulture} or {CultureInfo.CurrentCulture.Parent}");
        }

        private static WordTemplateEntity? GetTemplate(IEnumerable<WordTemplateEntity> candidates, WordModelEntity model, CultureInfo culture)
        {
            return candidates
                .Where(a => a.Culture.Name == culture.Name)
                .SingleOrDefaultEx(() => $"More than one active WordTemplate for WordModel {model} in {culture.Name} found");
        }

        static SqlPreCommand? Schema_Generating()
        {
            Table table = Schema.Current.Table<WordModelEntity>();

            return (from ei in GenerateTemplates()
                    select table.InsertSqlSync(ei)).Combine(Spacing.Simple);
        }

        internal static List<WordModelEntity> GenerateTemplates()
        {
            var list = (from type in registeredWordModels.Keys
                        select new WordModelEntity { FullClassName = type.FullName! }).ToList();
            return list;
        }

        static readonly string wordModelReplacementKey = "WordModel";

        static SqlPreCommand? Schema_Synchronizing(Replacements replacements)
        {
            Table table = Schema.Current.Table<WordModelEntity>();

            Dictionary<string, WordModelEntity> should = GenerateTemplates().ToDictionary(s => s.FullClassName);
            Dictionary<string, WordModelEntity> old = Administrator.TryRetrieveAll<WordModelEntity>(replacements).ToDictionary(c =>
                c.FullClassName);

            replacements.AskForReplacements(
                old.Keys.ToHashSet(),
                should.Keys.ToHashSet(), wordModelReplacementKey);

            Dictionary<string, WordModelEntity> current = replacements.ApplyReplacementsToOld(old, wordModelReplacementKey);

            using (replacements.WithReplacedDatabaseName())
                return Synchronizer.SynchronizeScript(Spacing.Double, should, current,
                    createNew: (tn, s) => table.InsertSqlSync(s),
                    removeOld: (tn, c) => table.DeleteSqlSync(c, swt => swt.FullClassName == c.FullClassName),
                    mergeBoth: (tn, s, c) =>
                    {
                        var oldClassName = c.FullClassName;
                        c.FullClassName = s.FullClassName;
                        return table.UpdateSqlSync(c, swt => swt.FullClassName == oldClassName);
                    });
        }

        public static void RegisterWordModel<T>(Func<WordTemplateEntity>? defaultTemplateConstructor, object? queryName = null)
         where T : IWordModel
        {
            RegisterWordModel(typeof(T), defaultTemplateConstructor, queryName);
        }

        public static void RegisterWordModel(Type wordModelType, Func<WordTemplateEntity>? defaultTemplateConstructor = null, object? queryName = null)
        {
            registeredWordModels[wordModelType] = new WordModelInfo(queryName ?? GetEntityType(wordModelType))
            {
                DefaultTemplateConstructor = defaultTemplateConstructor,
            };
        }

        public static Type GetEntityType(Type wordModelType)
        {
            var baseType = wordModelType.Follow(a => a.BaseType).FirstOrDefault(b => b.IsInstantiationOf(typeof(WordModel<>)));

            if (baseType != null)
            {
                return baseType.GetGenericArguments()[0];
            }

            throw new InvalidOperationException("Unknown queryName from {0}, set the argument queryName in RegisterWordModel".FormatWith(wordModelType.TypeName()));
        }

        public static Type ToType(this WordModelEntity modelEntity)
        {
            return WordModelEntityToType.Value.GetOrThrow(modelEntity);
        }

        public static bool RequiresExtraParameters(WordModelEntity modelEntity)
        {
            return GetEntityConstructor(modelEntity.ToType()) == null;
        }

        public static ConstructorInfo? GetEntityConstructor(Type wordModelType)
        {
            var entityType = GetEntityType(wordModelType);

            return (from ci in wordModelType.GetConstructors()
                    let pi = ci.GetParameters().Only()
                    where pi != null && pi.ParameterType == entityType
                    select ci).SingleOrDefaultEx();
        }

        public static IWordModel CreateDefaultWordModel(WordModelEntity wordModel, ModifiableEntity? entity)
        {
            return (IWordModel)WordModelLogic.GetEntityConstructor(wordModel.ToType())!.Invoke(new[] { entity });
        }
    }
}


text:
class SectionsController < ApplicationController

  # GET /sections
  # GET /sections.xml
  # GET /sections.json
  def index
    @space = Space.where(:name => params[:orbit_id])[0]
    @documents = @space.documents.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @documents }
      format.json { render :json => @documents.to_json }
    end
  end

  # GET /orbits/orbit_name/sections/section_name
  def show
  	@space = Space.where(:name => params[:orbit_id])[0]
    @document = Document.find(params[:id])

    respond_to do |format|
        format.html {redirect_to("/spaces/"+@space.wiki_name+"/documents/"+@document.id.to_s)}
        format.xml  { render :xml => @document }
        format.json  { render :jsom => @document.to_json }
    end
  end
end


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */
package com.facebook;

public final class R {
	public static final class attr {
		public static final int com_facebook_auxiliary_view_position = 0x7f01016f;
		public static final int com_facebook_confirm_logout = 0x7f010171;
		public static final int com_facebook_foreground_color = 0x7f01016b;
		public static final int com_facebook_horizontal_alignment = 0x7f010170;
		public static final int com_facebook_is_cropped = 0x7f010176;
		public static final int com_facebook_login_text = 0x7f010172;
		public static final int com_facebook_logout_text = 0x7f010173;
		public static final int com_facebook_object_id = 0x7f01016c;
		public static final int com_facebook_object_type = 0x7f01016d;
		public static final int com_facebook_preset_size = 0x7f010175;
		public static final int com_facebook_style = 0x7f01016e;
		public static final int com_facebook_tooltip_mode = 0x7f010174;
	}
	public static final class color {
		public static final int com_facebook_blue = 0x7f0c0016;
		public static final int com_facebook_button_background_color = 0x7f0c0017;
		public static final int com_facebook_button_background_color_disabled = 0x7f0c0018;
		public static final int com_facebook_button_background_color_pressed = 0x7f0c0019;
		public static final int com_facebook_button_like_background_color_selected = 0x7f0c001a;
		public static final int com_facebook_button_login_silver_background_color = 0x7f0c001b;
		public static final int com_facebook_button_login_silver_background_color_pressed = 0x7f0c001c;
		public static final int com_facebook_button_send_background_color = 0x7f0c001d;
		public static final int com_facebook_button_send_background_color_pressed = 0x7f0c001e;
		public static final int com_facebook_likeboxcountview_border_color = 0x7f0c001f;
		public static final int com_facebook_likeboxcountview_text_color = 0x7f0c0020;
		public static final int com_facebook_likeview_text_color = 0x7f0c0021;
		public static final int com_facebook_share_button_text_color = 0x7f0c0022;
	}
	public static final class dimen {
		public static final int com_facebook_likeboxcountview_border_radius = 0x7f090056;
		public static final int com_facebook_likeboxcountview_border_width = 0x7f090057;
		public static final int com_facebook_likeboxcountview_caret_height = 0x7f090058;
		public static final int com_facebook_likeboxcountview_caret_width = 0x7f090059;
		public static final int com_facebook_likeboxcountview_text_padding = 0x7f09005a;
		public static final int com_facebook_likeboxcountview_text_size = 0x7f09005b;
		public static final int com_facebook_likeview_edge_padding = 0x7f09005c;
		public static final int com_facebook_likeview_internal_padding = 0x7f09005d;
		public static final int com_facebook_likeview_text_size = 0x7f09005e;
		public static final int com_facebook_profilepictureview_preset_size_large = 0x7f09005f;
		public static final int com_facebook_profilepictureview_preset_size_normal = 0x7f090060;
		public static final int com_facebook_profilepictureview_preset_size_small = 0x7f090061;
		public static final int com_facebook_share_button_compound_drawable_padding = 0x7f090062;
		public static final int com_facebook_share_button_padding_bottom = 0x7f090063;
		public static final int com_facebook_share_button_padding_left = 0x7f090064;
		public static final int com_facebook_share_button_padding_right = 0x7f090065;
		public static final int com_facebook_share_button_padding_top = 0x7f090066;
		public static final int com_facebook_share_button_text_size = 0x7f090067;
		public static final int com_facebook_tooltip_horizontal_padding = 0x7f090068;
	}
	public static final class drawable {
		public static final int com_facebook_button_background = 0x7f02004e;
		public static final int com_facebook_button_icon = 0x7f02004f;
		public static final int com_facebook_button_like_background = 0x7f020050;
		public static final int com_facebook_button_like_icon_selected = 0x7f020051;
		public static final int com_facebook_button_login_silver_background = 0x7f020052;
		public static final int com_facebook_button_send_background = 0x7f020053;
		public static final int com_facebook_button_send_icon = 0x7f020054;
		public static final int com_facebook_close = 0x7f020055;
		public static final int com_facebook_profile_picture_blank_portrait = 0x7f020056;
		public static final int com_facebook_profile_picture_blank_square = 0x7f020057;
		public static final int com_facebook_tooltip_black_background = 0x7f020058;
		public static final int com_facebook_tooltip_black_bottomnub = 0x7f020059;
		public static final int com_facebook_tooltip_black_topnub = 0x7f02005a;
		public static final int com_facebook_tooltip_black_xout = 0x7f02005b;
		public static final int com_facebook_tooltip_blue_background = 0x7f02005c;
		public static final int com_facebook_tooltip_blue_bottomnub = 0x7f02005d;
		public static final int com_facebook_tooltip_blue_topnub = 0x7f02005e;
		public static final int com_facebook_tooltip_blue_xout = 0x7f02005f;
		public static final int messenger_bubble_large_blue = 0x7f0200ae;
		public static final int messenger_bubble_large_white = 0x7f0200af;
		public static final int messenger_bubble_small_blue = 0x7f0200b0;
		public static final int messenger_bubble_small_white = 0x7f0200b1;
		public static final int messenger_button_blue_bg_round = 0x7f0200b2;
		public static final int messenger_button_blue_bg_selector = 0x7f0200b3;
		public static final int messenger_button_send_round_shadow = 0x7f0200b4;
		public static final int messenger_button_white_bg_round = 0x7f0200b5;
		public static final int messenger_button_white_bg_selector = 0x7f0200b6;
	}
	public static final class id {
		public static final int automatic = 0x7f0d007f;
		public static final int bottom = 0x7f0d003e;
		public static final int box_count = 0x7f0d007b;
		public static final int button = 0x7f0d007c;
		public static final int center = 0x7f0d003f;
		public static final int com_facebook_body_frame = 0x7f0d00e9;
		public static final int com_facebook_button_xout = 0x7f0d00eb;
		public static final int com_facebook_fragment_container = 0x7f0d00e7;
		public static final int com_facebook_login_activity_progress_bar = 0x7f0d00e8;
		public static final int com_facebook_tooltip_bubble_view_bottom_pointer = 0x7f0d00ed;
		public static final int com_facebook_tooltip_bubble_view_text_body = 0x7f0d00ec;
		public static final int com_facebook_tooltip_bubble_view_top_pointer = 0x7f0d00ea;
		public static final int display_always = 0x7f0d0080;
		public static final int inline = 0x7f0d007e;
		public static final int large = 0x7f0d0082;
		public static final int left = 0x7f0d0044;
		public static final int messenger_send_button = 0x7f0d011e;
		public static final int never_display = 0x7f0d0081;
		public static final int normal = 0x7f0d002f;
		public static final int open_graph = 0x7f0d0078;
		public static final int page = 0x7f0d0079;
		public static final int right = 0x7f0d0045;
		public static final int small = 0x7f0d0083;
		public static final int standard = 0x7f0d007d;
		public static final int top = 0x7f0d0047;
		public static final int unknown = 0x7f0d007a;
	}
	public static final class layout {
		public static final int com_facebook_activity_layout = 0x7f040025;
		public static final int com_facebook_login_fragment = 0x7f040026;
		public static final int com_facebook_tooltip_bubble = 0x7f040027;
		public static final int messenger_button_send_blue_large = 0x7f04004a;
		public static final int messenger_button_send_blue_round = 0x7f04004b;
		public static final int messenger_button_send_blue_small = 0x7f04004c;
		public static final int messenger_button_send_white_large = 0x7f04004d;
		public static final int messenger_button_send_white_round = 0x7f04004e;
		public static final int messenger_button_send_white_small = 0x7f04004f;
	}
	public static final class string {
		public static final int com_facebook_image_download_unknown_error = 0x7f070013;
		public static final int com_facebook_internet_permission_error_message = 0x7f070014;
		public static final int com_facebook_internet_permission_error_title = 0x7f070015;
		public static final int com_facebook_like_button_liked = 0x7f070016;
		public static final int com_facebook_like_button_not_liked = 0x7f070017;
		public static final int com_facebook_loading = 0x7f070018;
		public static final int com_facebook_loginview_cancel_action = 0x7f070019;
		public static final int com_facebook_loginview_log_in_button = 0x7f07001a;
		public static final int com_facebook_loginview_log_in_button_long = 0x7f07001b;
		public static final int com_facebook_loginview_log_out_action = 0x7f07001c;
		public static final int com_facebook_loginview_log_out_button = 0x7f07001d;
		public static final int com_facebook_loginview_logged_in_as = 0x7f07001e;
		public static final int com_facebook_loginview_logged_in_using_facebook = 0x7f07001f;
		public static final int com_facebook_send_button_text = 0x7f070020;
		public static final int com_facebook_share_button_text = 0x7f070021;
		public static final int com_facebook_tooltip_default = 0x7f070022;
		public static final int messenger_send_button_text = 0x7f070041;
	}
	public static final class style {
		public static final int MessengerButton = 0x7f0a00c5;
		public static final int MessengerButtonText = 0x7f0a00cc;
		public static final int MessengerButtonText_Blue = 0x7f0a00cd;
		public static final int MessengerButtonText_Blue_Large = 0x7f0a00ce;
		public static final int MessengerButtonText_Blue_Small = 0x7f0a00cf;
		public static final int MessengerButtonText_White = 0x7f0a00d0;
		public static final int MessengerButtonText_White_Large = 0x7f0a00d1;
		public static final int MessengerButtonText_White_Small = 0x7f0a00d2;
		public static final int MessengerButton_Blue = 0x7f0a00c6;
		public static final int MessengerButton_Blue_Large = 0x7f0a00c7;
		public static final int MessengerButton_Blue_Small = 0x7f0a00c8;
		public static final int MessengerButton_White = 0x7f0a00c9;
		public static final int MessengerButton_White_Large = 0x7f0a00ca;
		public static final int MessengerButton_White_Small = 0x7f0a00cb;
		public static final int com_facebook_button = 0x7f0a016f;
		public static final int com_facebook_button_like = 0x7f0a0170;
		public static final int com_facebook_button_send = 0x7f0a0171;
		public static final int com_facebook_button_share = 0x7f0a0172;
		public static final int com_facebook_loginview_default_style = 0x7f0a0173;
		public static final int com_facebook_loginview_silver_style = 0x7f0a0174;
		public static final int tooltip_bubble_text = 0x7f0a0175;
	}
	public static final class styleable {
		public static final int[] com_facebook_like_view = { 0x7f01016b, 0x7f01016c, 0x7f01016d, 0x7f01016e, 0x7f01016f, 0x7f010170 };
		public static final int com_facebook_like_view_com_facebook_auxiliary_view_position = 4;
		public static final int com_facebook_like_view_com_facebook_foreground_color = 0;
		public static final int com_facebook_like_view_com_facebook_horizontal_alignment = 5;
		public static final int com_facebook_like_view_com_facebook_object_id = 1;
		public static final int com_facebook_like_view_com_facebook_object_type = 2;
		public static final int com_facebook_like_view_com_facebook_style = 3;
		public static final int[] com_facebook_login_view = { 0x7f010171, 0x7f010172, 0x7f010173, 0x7f010174 };
		public static final int com_facebook_login_view_com_facebook_confirm_logout = 0;
		public static final int com_facebook_login_view_com_facebook_login_text = 1;
		public static final int com_facebook_login_view_com_facebook_logout_text = 2;
		public static final int com_facebook_login_view_com_facebook_tooltip_mode = 3;
		public static final int[] com_facebook_profile_picture_view = { 0x7f010175, 0x7f010176 };
		public static final int com_facebook_profile_picture_view_com_facebook_is_cropped = 1;
		public static final int com_facebook_profile_picture_view_com_facebook_preset_size = 0;
	}
}


text:
@interface DDMultiFormatter () {
    dispatch_queue_t _queue;
    NSMutableArray *_formatters;
}

- (DDLogMessage *)logMessageForLine:(NSString *)line originalMessage:(DDLogMessage *)message;

@end

@implementation DDMultiFormatter

- (instancetype)init {
    self = [super init];

    if (self) {
#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
        _queue = dispatch_queue_create("cocoa.lumberjack.multiformatter", DISPATCH_QUEUE_CONCURRENT);
#else
        _queue = dispatch_queue_create("cocoa.lumberjack.multiformatter", NULL);
#endif
        _formatters = [NSMutableArray new];
    }

    return self;
}

#if NEEDS_DISPATCH_RETAIN_RELEASE
- (void)dealloc {
    dispatch_release(_queue);
}

#endif

#pragma mark Processing

- (NSString *)formatLogMessage:(DDLogMessage *)logMessage {
    __block NSString *line = logMessage->_message;

    dispatch_sync(_queue, ^{
        for (id<DDLogFormatter> formatter in _formatters) {
            DDLogMessage *message = [self logMessageForLine:line originalMessage:logMessage];
            line = [formatter formatLogMessage:message];

            if (!line) {
                break;
            }
        }
    });

    return line;
}

- (DDLogMessage *)logMessageForLine:(NSString *)line originalMessage:(DDLogMessage *)message {
    DDLogMessage *newMessage = [message copy];

    newMessage->_message = line;
    return newMessage;
}

#pragma mark Formatters

- (NSArray *)formatters {
    __block NSArray *formatters;

    dispatch_sync(_queue, ^{
        formatters = [_formatters copy];
    });

    return formatters;
}

- (void)addFormatter:(id<DDLogFormatter>)formatter {
    dispatch_barrier_async(_queue, ^{
        [_formatters addObject:formatter];
    });
}

- (void)removeFormatter:(id<DDLogFormatter>)formatter {
    dispatch_barrier_async(_queue, ^{
        [_formatters removeObject:formatter];
    });
}

- (void)removeAllFormatters {
    dispatch_barrier_async(_queue, ^{
        [_formatters removeAllObjects];
    });
}

- (BOOL)isFormattingWithFormatter:(id<DDLogFormatter>)formatter {
    __block BOOL hasFormatter;

    dispatch_sync(_queue, ^{
        hasFormatter = [_formatters containsObject:formatter];
    });

    return hasFormatter;
}

@end


text:
const $ = require('jquery')
const {remote, desktopCapturer} = require('electron')
const {Tray, Menu, MenuItem} = remote
const path = require('path')

const menu = new Menu()

menu.append(new MenuItem({
  label: 'MenuItem1',
  click() {
    console.log('click item 1')
  }
}))

menu.append(new MenuItem({type: 'separator'}))
menu.append(new MenuItem({label: 'MenuItem2', type: 'checkbox', checked: true}))
menu.append(new MenuItem({label: 'MenuItem3',
  click() {
    console.log('click item 3')
  }
}))

// prevent default action of right click on chromium
// replace with our menu
window.addEventListener('contextmenu', (e) => {
  e.preventDefault()
  menu.popup(remote.getCurrentWindow())
}, false)

// system tray
const iconPath = 'assets/images/dribbble.png'
// cant be ico format

console.log(path.join(__dirname, iconPath))
// let trayIcon = new Tray('/Users/liuxiangyu/Workspace/Dororis/packages/electron/quickstart/1-Part/assets/images/favicon.ico')
let trayIcon = new Tray(path.join(__dirname, iconPath))

const trayMenuTemplate = [
  {label: 'Empty App', enable: false },
  {label: 'Settings', click: () => { console.log('click on settings') }},
  {label: 'Help', click: () => { console.log('click on help') }},
]

let trayMenu = Menu.buildFromTemplate(trayMenuTemplate)

trayIcon.setContextMenu(trayMenu)

// notification
const notifier = require('node-notifier')
$('#notify').on('click', (e) => {
  notifier.notify({
    title: 'a title',
    message: 'ELECTRON APP MESSAGE',
    icon: path.join(__dirname, iconPath),
    sound: true, //
    wait: true, // wait callback
  }, (err, res) => {
    console.log(res)
  })
  notifier.on('click', (notifierObj, options) => {
    console.log('You click on the notification')
  })
  notifier.on('timeout', (notifierObj, options) => {
    console.log('Notification timed out.')
  })
})

// webview
const webview = $('#webview-example')
const indicator = $('.indicator')

const webLoadStart = () => {
  indicator.text('loading...')
}

const webLoadStop = () => {
  indicator.text('')
}

webview.on('did-start-loading', webLoadStart)
webview.on('did-stop-loading', webLoadStop)

// desktop capture
desktopCapturer.getSources({types: ['window', 'screen']}, (err, src) => {
  if (err) throw err
  for (let i = 0; i < src.length; ++i) {
    if (src[i].name === 'Electron') {
      navigator.webkitGetUserMedia({
        audio: false,
        video: {
          mandatory: {
            chromeMediaSource: 'desktop',
            chromeMediaSourceId: src[i].id,
            minWidth: 1200,
            maxWidth: 1280,
            minHeight: 720,
            maxHeight: 720,
          }
        }
      }, handleStream, handleError)
      return
    }
  }
})

const handleStream = (stream) => {
  $('video').src(URL.createObjectURL(stream))
}

const handleError = (e) => {
  console.log(e)
}


text:
package com.msiops.demo.swf;

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

import com.amazonaws.services.simpleworkflow.flow.annotations.Asynchronous;
import com.amazonaws.services.simpleworkflow.flow.annotations.Wait;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;

public final class PromiseUtil {

	/**
	 * Convert a list of promised values into a promised list of values. Use
	 * this to synchronize multiple independent promises.
	 *
	 * @param async
	 *            independent promises to synchronize. Notice the {@link Wait}
	 *            annotation. It tells FF that we want to wait for every promise
	 *            in the collection to be fulfilled.
	 *
	 * @param waitFor
	 *            anonymous dependencies.
	 *
	 * @return promise to fulfill all.
	 */
	@Asynchronous
	public static <T> Promise<List<T>> join(@Wait final List<Promise<T>> async,
			final Promise<?>... waitFor) {

		final List<T> result = new ArrayList<>(async.size());
		for (final Promise<T> pt : async) {
			result.add(pt.get());
		}

		return Promise.asPromise(result);

	}

	/**
	 * Convenient form of {@link #join(List, Promise...)} for a promised list of
	 * promises.
	 *
	 */
	@Asynchronous
	public static <T> Promise<List<T>> join(
			final Promise<List<Promise<T>>> async, final Promise<?>... waitFor) {
		return join(async.get());
	}

	/**
	 * Promise a value based on fulfillment of arbitrary values.
	 *
	 * @param sVal
	 *            substitution.
	 *
	 * @param waitFor
	 *            dependencies.
	 *
	 * @return promise to produce sVal.
	 */
	@Asynchronous
	public static <T> Promise<T> subst(final T sVal,
			final Promise<?>... waitFor) {

		return Promise.asPromise(sVal);

	}

	/**
	 * Synchronize on arbitrary dependencies.
	 *
	 * @param val
	 *            promise to return.
	 *
	 * @param waitFor
	 *            additional dependencies.
	 *
	 * @return promise to produce sVal.
	 */
	@Asynchronous
	public static <T> Promise<T> sync(final Promise<T> val,
			final Promise<?>... waitFor) {

		return val;

	}

	/**
	 * No instances.
	 */
	private PromiseUtil() {
		/*
		 * no instances
		 */
	}

}


text:
package org.spongepowered.api.entity.living.monster;

import org.spongepowered.api.entity.ArmorEquipable;
import org.spongepowered.api.entity.living.Ageable;

/**
 * Represents a Zombie.
 */
public interface Zombie extends Monster, ArmorEquipable, Ageable {

}


text:
package org.apache.geode.internal.protocol.protobuf.v1.operations;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.ExpectedException;

import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionDestroyedException;
import org.apache.geode.internal.protocol.TestExecutionContext;
import org.apache.geode.internal.protocol.protobuf.v1.BasicTypes;
import org.apache.geode.internal.protocol.protobuf.v1.RegionAPI;
import org.apache.geode.internal.protocol.protobuf.v1.Result;
import org.apache.geode.internal.protocol.protobuf.v1.serialization.exception.DecodingException;
import org.apache.geode.internal.protocol.protobuf.v1.serialization.exception.EncodingException;
import org.apache.geode.internal.protocol.protobuf.v1.utilities.ProtobufUtilities;
import org.apache.geode.test.junit.categories.ClientServerTest;

@Category({ClientServerTest.class})
@SuppressWarnings("unchecked") // Region lacks generics when we look it up
public class PutIfAbsentRequestOperationHandlerJUnitTest extends OperationHandlerJUnitTest {
  private final String TEST_KEY = "my key";
  private final String TEST_VALUE = "99";
  private final String TEST_REGION = "test region";
  private Region regionMock;
  private PutIfAbsentRequestOperationHandler operationHandler;

  @Rule
  public final ExpectedException expectedException = ExpectedException.none();

  @Before
  public void setUp() throws Exception {
    regionMock = mock(Region.class);
    operationHandler = new PutIfAbsentRequestOperationHandler();
    when(cacheStub.getRegion(TEST_REGION)).thenReturn(regionMock);
  }

  @Test
  public void newEntrySucceeds() throws Exception {
    when(regionMock.putIfAbsent(TEST_KEY, TEST_VALUE)).thenReturn(null);

    Result<RegionAPI.PutIfAbsentResponse> result1 = operationHandler.process(serializationService,
        generateTestRequest(), TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));

    assertNull(serializationService.decode(result1.getMessage().getOldValue()));

    verify(regionMock).putIfAbsent(TEST_KEY, TEST_VALUE);
    verify(regionMock, times(1)).putIfAbsent(any(), any());
  }

  @Test
  public void existingEntryFails() throws Exception {
    when(regionMock.putIfAbsent(TEST_KEY, TEST_VALUE)).thenReturn(1);

    Result<RegionAPI.PutIfAbsentResponse> result1 = operationHandler.process(serializationService,
        generateTestRequest(), TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));

    assertNotNull(serializationService.decode(result1.getMessage().getOldValue()));

    verify(regionMock).putIfAbsent(TEST_KEY, TEST_VALUE);
    verify(regionMock, times(1)).putIfAbsent(any(), any());
  }

  @Test
  public void nullValuePassedThrough() throws Exception {
    final RegionAPI.PutIfAbsentRequest request =
        RegionAPI.PutIfAbsentRequest.newBuilder().setRegionName(TEST_REGION)
            .setEntry(ProtobufUtilities.createEntry(serializationService, TEST_KEY, null)).build();

    Result<RegionAPI.PutIfAbsentResponse> response = operationHandler.process(serializationService,
        request, TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));

    assertNull(serializationService.decode(response.getMessage().getOldValue()));

    verify(regionMock).putIfAbsent(TEST_KEY, null);
  }

  @Test
  public void nullKeyPassedThrough() throws Exception {
    final RegionAPI.PutIfAbsentRequest request = RegionAPI.PutIfAbsentRequest.newBuilder()
        .setRegionName(TEST_REGION)
        .setEntry(ProtobufUtilities.createEntry(serializationService, null, TEST_VALUE)).build();

    Result<RegionAPI.PutIfAbsentResponse> response = operationHandler.process(serializationService,
        request, TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));

    assertNull(serializationService.decode(response.getMessage().getOldValue()));

    verify(regionMock).putIfAbsent(null, TEST_VALUE);
  }

  @Test(expected = DecodingException.class)
  public void unsetEntrythrowsDecodingException() throws Exception {
    Result<RegionAPI.PutIfAbsentResponse> result1 =
        operationHandler.process(serializationService, generateTestRequest(true, false),
            TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));

    assertEquals(BasicTypes.ErrorCode.INVALID_REQUEST,
        result1.getErrorMessage().getError().getErrorCode());
  }

  @Test
  public void unsetRegionGetsServerError() throws Exception {
    expectedException.expect(RegionDestroyedException.class);
    Result<RegionAPI.PutIfAbsentResponse> result1 =
        operationHandler.process(serializationService, generateTestRequest(false, true),
            TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));
  }

  @Test
  public void nonexistingRegionReturnsServerError() throws Exception {
    when(cacheStub.getRegion(TEST_REGION)).thenReturn(null);

    expectedException.expect(RegionDestroyedException.class);
    Result<RegionAPI.PutIfAbsentResponse> result1 = operationHandler.process(serializationService,
        generateTestRequest(), TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));
  }

  /**
   * Some regions (DataPolicy.NORMAL, for example) don't support concurrent ops such as putIfAbsent.
   */
  @Test(expected = UnsupportedOperationException.class)
  public void unsupportedOperation() throws Exception {
    when(regionMock.putIfAbsent(any(), any())).thenThrow(new UnsupportedOperationException());

    Result<RegionAPI.PutIfAbsentResponse> result1 = operationHandler.process(serializationService,
        generateTestRequest(), TestExecutionContext.getNoAuthCacheExecutionContext(cacheStub));
    assertEquals(BasicTypes.ErrorCode.INVALID_REQUEST,
        result1.getErrorMessage().getError().getErrorCode());
  }

  private RegionAPI.PutIfAbsentRequest generateTestRequest(boolean includeRegion,
      boolean includeEntry) throws EncodingException {
    RegionAPI.PutIfAbsentRequest.Builder builder = RegionAPI.PutIfAbsentRequest.newBuilder();

    if (includeRegion) {
      builder.setRegionName(TEST_REGION);
    }

    if (includeEntry) {
      BasicTypes.EncodedValue testKey = serializationService.encode(TEST_KEY);
      BasicTypes.EncodedValue testValue = serializationService.encode(TEST_VALUE);
      BasicTypes.Entry testEntry = ProtobufUtilities.createEntry(testKey, testValue);
      builder.setEntry(testEntry);
    }

    return builder.build();
  }

  private RegionAPI.PutIfAbsentRequest generateTestRequest() throws EncodingException {
    return generateTestRequest(true, true);
  }
}


text:
	width
	height
	border
	border-top
	padding
	background


text:
<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2017-06-16
 * Time: 16:38
 */

namespace app\app\controller;

use app\app\helper\AppMenuHelper;
use app\app\helper\SensitiveDataHelper;
use app\src\admin\helper\AdminConfigHelper;
use app\src\admin\helper\AdminSessionHelper;
use app\src\admin\helper\MenuHelper;
use app\src\base\helper\ConfigHelper;
use app\src\base\helper\ValidateHelper;
use app\src\session\action\LoginSessionCheckAction;
use app\src\session\logic\LoginSessionLogic;
use app\src\user\facade\DefaultUserFacade;

class Index extends App
{
    public function user_data(){

        if($this->uid <= 0){
            $this->failNeedLogin('请重新登录');
        }

        $result = (new DefaultUserFacade())->getInfo($this->uid,$this->sessionId);
        if(!ValidateHelper::legalArrayResult($result)){
            $this->failNeedLogin('请重新登录');
        }

        $user_info = $result['info'];
        $menuList = AppMenuHelper::getMenu($this->uid);

        $UCENTER_PLATFORM = ConfigHelper::getValue('UCENTER_PLATFORM');
        $user_info = [
            'id' => $user_info['id'],
            'username' => $user_info['username'],
            'nickname' => $user_info['nickname'],
            'head' => $user_info['head'],
            'mobile'=> SensitiveDataHelper::hiddenMobile($user_info['mobile'])
        ];
        $data = [
            'menuList' => $menuList,
            'userInfo' => $user_info,
            'platformInfo' => $UCENTER_PLATFORM
        ];
        $this->success($data,'获取成功');
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/church-events/book-of-mormon/alma/amlici-conspires-to-be-king" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-events/book-of-mormon/alma/amlici-conspires-to-be-king</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Amlici Conspires to Be King</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-events/book-of-mormon/alma/amlici-conspires-to-be-king</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-events/book-of-mormon/alma/amlici-conspires-to-be-king</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Event</sem:object>
  </sem:triple>
</sem:triples>


text:
/* Move down content because we have a fixed navbar that is 50px tall */

/**
 * Generic Question
 */
.eli-question {

}
  /* Question prompt */
  .eli-question-prompt {

  }
  .eli-question-option {

  }