text:
require 'spec_helper'

describe 'service for sysv init style' do
  include_context 'service setup'

  let :start_command_string do
    'service kafka start'
  end

  let :stop_command_string do
    'service kafka stop'
  end

  let :status_command_string do
    'service kafka status'
  end

  let :pidfile do
    file '/var/run/kafka.pid'
  end

  describe service('kafka'), pending: centos? && systemd? do
    it { should be_enabled }
  end

  describe 'service kafka start' do
    context 'when Kafka isn\'t already running' do
      before do
        start_command
      end

      it 'prints a message about starting Kafka' do
        expect(start_command.stdout).to match(/starting.+kafka/i)
        expect(start_command.stderr).to be_empty
      end

      it 'exists with status 0' do
        expect(start_command.exit_status).to be_zero
      end

      it 'starts Kafka' do
        expect(kafka_service).to be_running
      end

      it 'creates a pid file' do
        pid_file = file('/var/run/kafka.pid')
        expect(pid_file).to be_a_file
        expect(pid_file.content).to_not be_empty
      end

      it 'sets configured `ulimit` value' do
        pid = file('/var/run/kafka.pid').content.strip
        limits = file("/proc/#{pid}/limits").content
        expect(limits).to match(/Max open files\s+128000\s+128000\s+files/)
      end

      it 'runs as the configured user' do
        pid = file('/var/run/kafka.pid').content.strip
        user = shell_out!(format('ps -p %s -o user --no-header', pid)).stdout.strip
        expect(user).to eq('kafka')
      end

      it 'runs as the configured group' do
        pid = file('/var/run/kafka.pid').content.strip
        group = shell_out!(format('ps -p %s -o group --no-header', pid)).stdout.strip
        expect(group).to eq('kafka')
      end

      include_examples 'a Kafka start command'
    end

    context 'when Kafka is already running' do
      before do
        start_kafka(true)
      end

      it 'is actually running' do
        expect(kafka_service).to be_running
      end

      it 'prints a message about starting Kafka' do
        expect(start_command.stdout).to match(/starting.+kafka/i)
        expect(start_command.stderr).to be_empty
      end

      it 'exits with status 0' do
        expect(start_command.exit_status).to be_zero
      end

      it 'does not start a new process' do
        first_pid = file('/var/run/kafka.pid').content.strip
        start_kafka
        new_pid = file('/var/run/kafka.pid').content.strip
        expect(first_pid).to eq(new_pid)
      end
    end
  end

  describe 'service kafka stop' do
    context 'when Kafka is running' do
      before do
        start_command
        stop_command
      end

      it 'prints a message about stopping Kafka' do
        expect(stop_command.stdout).to match(/stopping.+kafka/i)
        expect(stop_command.stderr).to be_empty
      end

      it 'exits with status 0' do
        expect(stop_command.exit_status).to be_zero
      end

      it 'stops Kafka' do
        expect(kafka_service).to_not be_running
      end

      it 'removes the pid file' do
        expect(pidfile).to_not be_a_file
      end

      include_examples 'a Kafka stop command'
    end

    context 'when Kafka is not running' do
      before do
        stop_kafka
      end

      it 'prints a message about stopping kafka' do
        command = stop_kafka
        expect(command.stdout).to match(/stopping.+kafka/i)
        expect(command.stderr).to be_empty
      end

      it 'exits with status 0' do
        expect(stop_kafka.exit_status).to be_zero
      end
    end
  end

  describe 'service kafka status' do
    let :message do
      status_command.stdout
    end

    context 'when Kafka is running' do
      before do
        start_command
      end

      it 'exits with status 0' do
        expect(status_command.exit_status).to be_zero
      end

      it 'prints a message that Kafka is running' do
        if fedora?
          expect(message).to match(/Active: active \(running\)/)
          expect(message).to match(/Started SYSV: kafka daemon/)
        else
          expect(message).to match(/kafka.+running/i)
        end
        expect(status_command.stderr).to be_empty
      end
    end

    context 'when Kafka isn\'t running' do
      before do
        stop_kafka
      end

      it 'exits with status 3' do
        expect(status_command.exit_status).to eq 3
      end

      it 'prints a message that Kafka is not running / stopped' do
        if debian? || ubuntu?
          expect(message).to match(/kafka is not running/i)
        elsif fedora?
          expect(message).to match(/Active: failed/i)
          expect(message).to match(/Stopped SYSV: kafka daemon/i)
        else
          expect(message).to match(/kafka is stopped/i)
        end
        expect(status_command.stderr).to be_empty
      end
    end
  end
end


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

<title>T-Index</title>
<meta name="date" content="2015-01-21">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L M N O P R S T U V X Y Z

T

Target2D - Class in physics.entity

Represents a target to shoot at

Target2D(Vector2D, Vector2D) - Constructor for class physics.entity.Target2D

Constructs a target

tasks - package tasks

TEXTURE_SIZE - Static variable in class game.GamePanel

tick() - Method in class game.GamePanel

Causes the physics engine to do a tick, and repaints

titleImage - Static variable in class game.GamePanel

toggle() - Method in class game.graphics.menu.ToggleMenuItem

Toggles the toggle color with this item's actual color

ToggleMenuItem - Class in game.graphics.menu

A MenuItem which can be toggled

ToggleMenuItem(String, Font, Color, Color, Color, Rectangle, MenuItemAction, int) - Constructor for class game.graphics.menu.ToggleMenuItem

Creates a toggleable MenuItem

toString() - Method in class physics.entity.Entity2D

toString() - Method in class physics.util.Vector2D

translate(double, double) - Method in class physics.entity.AABB2D

translate(double, double) - Method in class physics.entity.Circle2D

translate(double, double) - Method in class physics.entity.Entity2D

Moves the entity over by x and y

translate(double, double) - Method in class physics.entity.Rectangle2D

TrebuchetDemolition - Class in game

A game which involves physics and calculations

TrebuchetDemolition() - Constructor for class game.TrebuchetDemolition

trebuchetImage - Static variable in class game.GamePanel

A B C D E F G H I L M N O P R S T U V X Y Z

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout>
    <Button android:id="@+id/button1"
            android:layout_toLeftOf="@button2" />
</LinearLayout>


text:
let express = require("express");
let router = express.Router();
let bodyParser = require("body-parser");
let cookieParser = require("cookie-parser");
let mongoose = require("mongoose");
mongoose.Promise = global.Promise;
let jwt = require("jsonwebtoken");
let passport = require("passport");
let bcrypt = require("bcryptjs");
let Strategy = require("passport-http-bearer").Strategy;
let BoxSDK = require("box-node-sdk");
let fs = require("fs");
let formidable = require("formidable");
let util = require("util");
let path = require("path");
let PDFDocument = require("pdfkit");

let prettyjson = require("prettyjson");

let Course = require("./models/Course");
let Enrollable = require("./models/Enrollable");
let UserElearn = require("./models/UserElearn");
let Quiz = require("./models/Quiz").Quiz;
let SubmittedItem = require("./models/SubmittedItem");

require("dotenv").config({ silent: true });
let ADMIN_EMAIL = process.env.ADMIN_EMAIL;
let TOKENSECRET = process.env.SECRET;
let KID = process.env.KID;
let CLIENT_ID = process.env.BOX_CLIENT_ID;
let CLIENT_SECRET = process.env.BOX_CLIENT_SECRET;
let PUBLIC_KEY_ID = process.env.BOX_PUBLIC_KEY_ID;
// var PRIVATE_KEY = process.env.BOX_PRIVATE_KEY;
let PRIVATE_KEY_PASSPHRASE = process.env.BOX_PRIVATE_KEY_PASSPHRASE;
let APP_ID = process.env.BOX_APP_ID;
let ENTERPRISE_ID = process.env.ENTERPRISE_ID;

let PRIVATE_KEY = fs.readFileSync("private_key.pem", "utf-8");
let sdk = new BoxSDK({
  clientID: CLIENT_ID,
  clientSecret: CLIENT_SECRET,
  appAuth: {
    keyID: PUBLIC_KEY_ID,
    privateKey: PRIVATE_KEY,
    passphrase: PRIVATE_KEY_PASSPHRASE
  }
});

//initialize BOX sdk to access course lessons
let box = sdk.getAppAuthClient("enterprise", ENTERPRISE_ID);
box.users.get(box.CURRENT_USER_ID, null, function(err, currentUser) {
  if (err) console.log("error: ", err);
});

let jsonParser = bodyParser.json();

//create passport strategy to check for valid json web tokens.
passport.use(
  new Strategy(function(token, done) {
    if (token) {
      jwt.verify(token, TOKENSECRET, function(err, decoded) {
        if (err) {
          return done(err);
        }
        return done(null, decoded, { scope: "all" });
      });
    } else {
      return done(null, false);
    }
  })
);
router.use(passport.initialize());

//serve files form build folder
router.use(express.static("dist"));

//parse cookies
router.use(cookieParser());

//register new user
//requires name, email and password in request body
//returns status 201 with mongo id, name, courses (enrolled in) and json web token valide for 24 hours
//returns status 400 for email already in use, status 500 for server or database error
router.post("/users", jsonParser, function(req, res) {
  let name = req.body.name;
  let email = req.body.email;
  let password = req.body.password;
  let enrolledCoursesUser = [],
    enrolledCoursesAdmin = [];
  UserElearn.findOne({ email: email })
    .exec()
    .then(function(user) {
      if (user != null) {
        throw "emailInUse";
      }
      return Enrollable.find({ email: req.body.email }).exec();
    })
    .then(function(enroll) {
      if (enroll) {
        enroll.forEach(function(entry) {
          enrolledCoursesUser.push(entry.course_id);
          if (entry.admin) enrolledCoursesAdmin.push(entry.course_id);
        });
      }
      return bcrypt.genSalt(10, function(err, salt) {
        if (err) {
          throw err;
        }
        return bcrypt.hash(password, salt, function(err, hash) {
          if (err) {
            throw err;
          }
          let user = new UserElearn();
          user.name = name;
          user.email = email;
          user.password = hash;
          if (enrolledCoursesUser) user.courses = enrolledCoursesUser;
          console.log("new user: ", user);
          user
            .save()
            .then(function(user) {
              console.log("user saved: ", user);
              console.log(
                "enrolledCoursesAdmin: ",
                enrolledCoursesAdmin,
                enrolledCoursesAdmin == null,
                enrolledCoursesAdmin == []
              );
              if (enrolledCoursesAdmin.length) {
                return Promise.all(
                  enrolledCoursesAdmin.map(function(course_id) {
                    return Course.findOneAndUpdate(
                      { _id: course_id },
                      { $push: { admin: user._id } }
                    ).exec();
                  })
                ).then(function(courses) {
                  console.log("courses admin updated: ", courses);
                  return user;
                });
              } else {
                return user;
              }
            })
            .then(function(user) {
              return UserElearn.findOne({ _id: user._id })
                .populate({
                  path: "courses",
                  populate: {
                    path: "quizzes",
                    select: "_id, title"
                  }
                })
                .lean()
                .exec();
            })
            .then(function(user) {
              let courses = user.courses.map(course => {
                course.admin = course.admin.toString().indexOf(user._id) > -1;
                return course;
              });
              let token = jwt.sign(
                {
                  _id: user._id,
                  name: user.name,
                  email: user.email,
                  courses: user.courses
                },
                TOKENSECRET,
                {
                  expiresIn: "24h"
                }
              );
              return res.status(201).json({
                _id: user._id,
                name: user.name,
                courses: courses,
                token: token
              });
            });
        });
      });
    })
    .catch(function(err) {
      console.log("error: ", err);
      if (err === "emailInUse") {
        return res
          .status(400)
          .json({ message: "email already associated with an account" });
      }
      return res.status(500).json({ message: "Internal server error" });
    });
});

router.put(
  "/users/auth",
  jsonParser,
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    let oldPassword = req.body.oldPassword;
    let newPassword = req.body.newPassword;

    UserElearn.findOne({ _id: req.body.userId })
      .then(function(user) {
        if (!user) return res.status(400).json({ message: "User not found" });
        user.validatePassword(oldPassword, function(err, isValid) {
          if (err || !isValid) {
            return res.status(400).json({ message: "Invalid password" });
          }
          return bcrypt.genSalt(10, function(err, salt) {
            if (err) {
              throw err;
            }
            return bcrypt.hash(newPassword, salt, function(err, hash) {
              if (err) {
                throw err;
              }
              user.password = hash;
              return user.save().then(function() {
                return res.status(201).json({ message: "Password updated" });
              });
            });
          });
        });
      })
      .catch(function(err) {
        return res.status(500).json({ message: "Internal server error" });
      });
  }
);

//unenroll user from a course
//must be course admin to submit request
//requires user email and course id in request body
//returns status 200 with remaining enrolled courses for user
//returns status 500 for server or database error
router.put(
  "/users",
  jsonParser,
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    let course_id = req.body.course_id;
    let courseInToken = req.user.courses.find(function(courseInToken) {
      if (courseInToken._id === course_id) return true;
    });
    if (!courseInToken.admin)
      return res
        .status(401)
        .json({ message: "only course admin can delete users from course" });
    if (req.body.email === ADMIN_EMAIL)
      return res
        .status(401)
        .json({ message: "Unable to delete site admin from course" });
    UserElearn.findOneAndUpdate(
      { email: req.body.email },
      {
        $pull: {
          courses: { $in: [course_id] }
        }
      }
    )
      .exec()
      .then(function() {
        return UserElearn.find({ courses: course_id }).exec();
      })
      .then(function(enrolled) {
        return res.status(200).json({
          enrolled: enrolled
        });
      })
      .catch(function(err) {
        console.log("Mongo error", err);
        return res.status(500).json("Internal Server Error");
      });
  }
);

//render certificate of completion pdf, send to client
//requires course id and json web token to be included in request url
//returns status 200 with rendered pdf
//returns status 401 for invalid token
router.get("/users/certificate/:course/:token", function(req, res) {
  if (req.params.token) {
    jwt.verify(req.params.token, TOKENSECRET, function(err, decoded) {
      if (err) {
        console.log("err: ", err);
        res.status(401).json({ message: "unauthorized" });
      } else {
        let token = decoded;
        let doc = new PDFDocument({ layout: "landscape" });
        res.writeHead(200, {
          "Content-Type": "application/pdf",
          "Access-Control-Allow-Origin": "*",
          "Content-Disposition": "inline; filename=Untitled.pdf"
        });
        doc.pipe(res);
        doc.image("utilities/Certificate.jpg", (doc.page.width - 720) / 2);
        doc.font("Times-Roman");
        doc.fontSize(30);
        doc.text(token.name, { align: "center" }, 250);
        doc.fontSize(20);
        doc.text(req.params.course, { align: "center" }, 450);
        doc.end();
      }
    });
  } else {
    res.status(401).json({ message: "unauthorized" });
  }
});

//logs in user, generates json web token valid for 24 hours
//requires user email and password in request body
//returns status 200 with user mongo id, name, email, enrolled courses, ids of passed quizzes and json web token
//returns status 400 for invalide password or token
router.post("/login", jsonParser, function(req, res) {
  let password = req.body.password;
  UserElearn.findOne({ email: req.body.email })
    .populate({
      path: "courses",
      populate: {
        path: "quizzes",
        select: "_id, title"
      }
    })
    .populate("passed", "of")
    .exec()
    .then(function(user) {
      if (!user) return res.status(400);
      user.validatePassword(password, function(err, isValid) {
        if (err || !isValid) {
          return res.status(400).json({ message: "Invalid password" });
        }
        let token = jwt.sign(
          {
            _id: user._id,
            name: user.name,
            email: user.email,
            courses: user.courses
          },
          TOKENSECRET,
          {
            expiresIn: "24h"
          }
        );
        user = user.toObject();
        let courses = user.courses.map(course => {
          course.admin = course.admin.toString().indexOf(user._id) > -1;
          return course;
        });
        return res.status(200).cookie({ credential: token }).json({
          _id: user._id,
          name: user.name,
          courses: courses,
          passed: user.passed,
          token: token
        });
      });
    })
    .catch(function(err) {
      console.log("error: ", err);
      return res.status(500).json({ message: "Internal server error" });
    });
});

//querys a course for enrolled and enrollable users
//requires course id in request url
//must be course admin to make request
//returns status 200 with list of enrolled users and enrollable unregistered user emails
//returns status 401 if request is not made by course admin
//returns status 500 for server or database error
router.get(
  "/course/enrollable/:course_id",
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    console.log("cookies in request: ", req.cookies);
    let course_id = req.params.course_id;
    let courseInToken = req.user.courses.find(function(courseInToken) {
      if (courseInToken._id === course_id) return true;
    });
    if (!courseInToken.admin)
      return res
        .status(401)
        .json({ message: "only course admin can see enrolled users" });
    Enrollable.find({ course_id: course_id })
      .exec()
      .then(function(enrollable) {
        return UserElearn.find({ courses: course_id })
          .select("_id name email")
          .exec()
          .then(function(enrolled) {
            return [enrollable, enrolled];
          });
      })
      .then(function(enrollArray) {
        return res.status(200).json({
          enrollable: enrollArray[0],
          enrolled: enrollArray[1]
        });
      })
      .catch(function(err) {
        console.log("Mongo error ", err);
        return res.status(500).json("Internal Server Error");
      });
  }
);

//adds unregistered user email to list of emails enrollable in a course
//must be course admin to make request
//requires course id, unregistered user email and admin boolean, indicating if user should be listed as a course admin, in request body
//returns status 201 with updated list of enrollable users for course
//returns status 401 if request is not made by course admin
//returns status 500 for server or database error
router.post(
  "/course/enrollable",
  jsonParser,
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    let course_id = req.body.course_id;
    let courseInToken = req.user.courses.find(function(courseInToken) {
      if (courseInToken._id === course_id) return true;
    });
    if (!courseInToken.admin)
      return res.status(401).json({ message: "only admin can alter course" });
    let enrolled = new Enrollable();
    enrolled.email = req.body.email;
    enrolled.course_id = course_id;
    enrolled.admin = req.body.admin;
    enrolled
      .save()
      .then(function(enrolled) {
        return Enrollable.find({ course_id: course_id }).exec();
      })
      .then(function(enrollable) {
        return res.status(201).json({ enrollable: enrollable });
      })
      .catch(function(err) {
        console.log("Mongo error ", err);
        return res.status(500).json("Internal Server Error");
      });
  }
);

//removes unregistered user email from list of emails enrollable in course
//must be course admin to make request
//requires course id, and unregistered user email in request body
//returns status 200 with updated list of enrollable users for course
//returns status 401 if request is not made by course admin
//returns status 500 for server or database error
router.delete(
  "/course/enrollable",
  jsonParser,
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    let course_id = req.body.course_id;
    let courseInToken = req.user.courses.find(function(courseInToken) {
      if (courseInToken._id === course_id) return true;
    });
    if (!courseInToken.admin)
      return res.status(401).json({ message: "only admin can alter course" });
    Enrollable.findOne({ email: req.body.email, course_id: course_id })
      .remove()
      .exec()
      .then(function(removedUser) {
        return Enrollable.find({ course_id: course_id }).exec();
      })
      .then(function(enrollable) {
        return res.status(200).json({ enrollable: enrollable });
      })
      .catch(function(err) {
        console.log("Mongo error ", err);
        return res.status(500).json("Internal Server Error");
      });
  }
);

//updates course name
//must be course admin to make request
//requires course id and updated course name in request body
//returns status 200 with updated course data (course quizzes populated with quiz id and title)
//returns status 401 if request is not made by course admin
//returns status 500 for server or database error
router.put(
  "/course",
  jsonParser,
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    let course = req.body.course;
    let courseInToken = req.user.courses.find(function(courseInToken) {
      if (courseInToken._id === course._id) return true;
    });
    if (!courseInToken.admin)
      return res.status(401).json({ message: "only admin can alter course" });
    return Course.findOneAndUpdate(
      { _id: course._id },
      { $set: { name: course.name } },
      { new: true }
    )
      .populate({
        path: "quizzes",
        select: "_id, title"
      })
      .exec()
      .then(function(updatedCourse) {
        return res.status(200).json({ course: updatedCourse });
      })
      .catch(function(err) {
        console.log("Mongo error ", err);
        return res.status(500).json("Internal Server Error");
      });
  }
);

//fetches quiz and any submissions of quiz by user
//requires quiz id and user id in request url
//returns status 200 with quiz and prior submissions of quiz by user
//returns status 500 for server or database error
router.get(
  "/quiz/:quizId/:userId",
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    Quiz.find({ _id: req.params.quizId })
      .exec()
      .then(function(quiz) {
        return SubmittedItem.find({
          user: req.params.userId,
          of: req.params.quizId
        })
          .exec()
          .then(function(submitted) {
            return [quiz, submitted];
          });
      })
      .then(function(results) {
        console.log("Quiz sent");
        return res.status(200).json(results);
      })
      .catch(function(err) {
        console.log("Mongo ERROR: ", err);
        return res.status(500).json("Internal Server Error");
      });
  }
);

//creates or updates quiz; new quiz is listed to course
//must be course admin to make request
//requires course id, quiz id, title, courses, items, and minimumScore in request body
//returns status 201 with created quiz and updated course when quiz created
//returns status 200 with updated quiz and course when quiz updated
//returns status 401 if request is not made by course admin
//returns status 500 for server or database error
router.put(
  "/quiz",
  jsonParser,
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    console.log("save quiz request received");
    let course = req.user.courses.find(function(course) {
      if (course._id === req.body.courseID) return true;
    });
    if (!course.admin)
      return res.status(401).json({ message: "only admin can alter course" });

    let quiz = req.body.quiz;
    if (quiz.courses[0] === "undefined")
      quiz.courses[0] = { id: req.body.courseID };
    if (!quiz._id || quiz._id == null) {
      let newQuiz = new Quiz();
      newQuiz.title = quiz.title;
      newQuiz.courses = quiz.courses;
      newQuiz.items = quiz.items;
      newQuiz.minimumScore = quiz.minimumScore;
      newQuiz.live = quiz.live;
      newQuiz
        .save()
        .then(function(quiz) {
          return Course.findOne({ _id: course._id })
            .populate({
              path: "quizzes",
              select: "_id, title"
            })
            .exec()
            .then(function(courseToUpdate) {
              courseToUpdate.quizzes.push({ _id: quiz._id, title: quiz.title });
              return courseToUpdate.save();
            })
            .then(function(course) {
              course.admin = true;
              return [quiz, course];
            });
        })
        .then(function(state) {
          console.log("quiz created, sending response...");
          return res.status(201).json(state);
        })
        .catch(function(err) {
          console.log("error: ", err);
          return res.status(500).json("Internal server error");
        });
    } else {
      Quiz.findOneAndUpdate(
        { _id: quiz._id },
        {
          title: quiz.title,
          courses: quiz.courses,
          items: quiz.items,
          minimumScore: quiz.minimumScore,
          live: quiz.live
        },
        { new: true, upsert: true },
        function(err, quiz) {
          if (err) {
            console.log("Mongo error ", err);
            return res.status(500).json("Internal Server Error");
          }
          console.log("quiz updated, sending response...");
          Course.findOne({ _id: course._id })
            .populate({
              path: "quizzes",
              select: "_id, title"
            })
            .exec()
            .then(function(course) {
              course.admin = true;
              return res.status(200).json([quiz, course]);
            })
            .catch(function(err) {
              if (err) console.log("Mongo error: ", err);
              return res.status(500).json("Internal Server Error");
            });
        }
      );
    }
  }
);

//deletes quiz, and removes quiz listing from course
//must be course admin to make request
//requires quiz id and course id in request url
//returns status 200 with updated course listings for user
//returns status 401 if request is not made by course admin
//returns status 500 for server or database error
router.delete(
  "/quiz/:quizId/:courseId",
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    let courseInToken = req.user.courses.find(function(course) {
      if (course._id === req.params.courseId) return true;
    });
    if (!courseInToken.admin)
      return res.status(401).json({ message: "only admin can alter course" });
    let course = Course.findOneAndUpdate(
      { _id: req.params.courseId },
      {
        $pull: {
          quizzes: { $in: [req.params.quizId] }
        }
      }
    ).exec();
    course
      .then(function(course) {
        return Quiz.remove({ _id: req.params.quizId }).exec();
      })
      .then(function(quiz) {
        return Quiz.findOne({ _id: req.params.quizId }).exec();
      })
      .then(function(quiz) {
        if (quiz) {
          throw new err();
        }
      })
      .then(function() {
        return UserElearn.findOne({ email: req.user.email })
          .populate({
            path: "courses",
            populate: {
              path: "quizzes",
              select: "_id, title"
            }
          })
          .exec();
      })
      .then(function(user) {
        res.status(200).json({ courses: user.courses });
      })
      .catch(function(err) {
        if (err) {
          console.log("error: ", err);
          res.status(500).json("Internal server error");
        }
      });
  }
);

//records quiz submission by user
//requires quizData (quiz submision), quiz id, user id in request body
//calculates and saves submission score and date into entry
//returns status 200 with quiz score, submission and passed (boolean, depreciated client side)
//returns status 500 for server or database error
router.post(
  "/quiz/submit",
  passport.authenticate("bearer", { session: false }),
  jsonParser,
  function(req, res) {
    // score
    let quizData = req.body.quizData;
    let score = quizData.map(question => {
      return question.correct ? 1 : 0;
    });
    score = score.reduce((a, b) => {
      return a + b;
    }, 0);

    let submission = new SubmittedItem();
    submission.user = req.body.user_Id;
    submission.submitted = new Date();
    submission.score = score;
    submission.item = quizData;
    submission.of = req.body.quiz_Id;
    submission
      .save()
      .then(function(submission) {
        return Quiz.findOne({ _id: submission.of }).exec().then(function(quiz) {
          console.log("sub and quiz: ", submission.score, quiz.minimumScore);
          if (submission.score >= quiz.minimumScore) {
            return [submission, true];
          } else {
            return [submission, false];
          }
        });
      })
      .then(function(state) {
        if (state[1]) {
          return UserElearn.findOne({ _id: req.body.user_Id })
            .exec()
            .then(function(user) {
              user.passed.push(state[0]._id);
              return user.save().then(function(user) {
                return state;
              });
            });
        } else {
          return state;
        }
      })
      .then(function(state) {
        return res.status(200).json({
          message: "quiz submitted",
          score: state[0].score,
          attempt: state[0],
          passed: state[1]
        });
      })
      .catch(function(err) {
        console.log("Mongo ERROR: ", err);
        res.status(500).json("Internal Server Error");
      });
  }
);

//queries list of lessons in BOX folder
//currently hardcoded folder, will need to implement course id or folder id in request url
//returns status 200 with entries found by BOX (contains lesson name, id, modified time, size, url and sync state)
//returns status 500 for server or BOX sdk error
router.get(
  "/lessons",
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    //box folder id is first arg
    console.log("loading BOX lessons");
    box.folders.getItems(
      "18155048374",
      {
        fields: "name,modified_at,size,url,sync_state",
        offset: 0,
        limit: 25
      },
      function(err, data) {
        if (err) {
          console.log("error: ", err);
          res.status(500).json("Internal Server Error");
        } else {
          res.status(200).json(data);
        }
      }
    );
  }
);

//fetchs BOX preview and download url of lesson pdf
//requires BOX lesson id in request url
//returns status 200 with selectedPdf preview (url), download (url), name and id
//returns status 500 for server or BOX sdk error
router.get(
  "/lessons/:id",
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    box.files.update(
      req.params.id,
      {
        shared_link: box.accessLevels.DEFAULT
      },
      function(err, link) {
        if (err) {
          console.log("error: ", err);
          res.status(500).json("Internal Server Error");
        }
        res.status(200).json({
          selectedPdf: {
            preview: link.shared_link.url,
            download: link.shared_link.download_url,
            name: link.name,
            id: link.id
          }
        });
      }
    );
  }
);

//serves client side assests, html, css and js
//enables react-router to navigate in client-side app
router.get("*", function(req, res) {
  res.sendFile(path.join(__dirname, "build", "index.html"));
});

//for file upload
router.post(
  "/lessons",
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    let form = new formidable.IncomingForm();
    form.multiples = true;
    form.uploadDir = path.join(__dirname);
    form.parse(req, function(err, fields, files) {
      console.log("parsed files: ", files);
      console.log("parsed files: ", files.file.path);
      let stream = fs.createReadStream(files.file.path);
      box.files.uploadFile("18155048374", files.file.name, stream, function() {
        if (err) {
          console.log("box error: ", err);
          return res.status(500).json("Internal Server Error");
        }
        res.status(200).json(files);
        fs.unlink(files.file.path, function(err) {
          if (err) console.log("file delete error: ", err);
        });
      });
    });
  }
);

router.delete(
  "/lessons/:courseID/:lessonID",
  passport.authenticate("bearer", { session: false }),
  function(req, res) {
    let courseInToken = req.user.courses.find(function(course) {
      if (course._id === req.params.courseID) return true;
    });
    if (!courseInToken.admin)
      return res.status(401).json({ message: "only admin can alter course" });
    box.files.delete(req.params.lessonID, function(err) {
      if (err) {
        console.log("box error: ", err);
        return res.status(500).json("Internal Server Error");
      }
      res.status(200).json("Lesson " + req.params.lessonID + " deleted");
    });
  }
);

module.exports = router;


text:
require "rails_helper"

RSpec.describe Atoms::Value::Text, type: :model  do
  describe "when executing" do
    xit "return its text content" do
      raise TODO
    end
  end
end


text:
import React, { Component } from 'react';
import { EditorState } from 'draft-js';
import Editor from 'draft-js-plugins-editor'; // eslint-disable-line import/no-unresolved
import createVideoPlugin from 'draft-js-video-plugin'; // eslint-disable-line import/no-unresolved
import VideoAdd from './VideoAdd';
import editorStyles from './editorStyles.css';

const videoPlugin = createVideoPlugin();

const plugins = [videoPlugin];

export default class CustomVideoEditor extends Component {

  state = {
    editorState: EditorState.createEmpty(),
  };

  onChange = (editorState) => {
    this.setState({
      editorState,
    });
  };

  focus = () => {
    this.editor.focus();
  };

  render() {
    return (

          <Editor
            editorState={this.state.editorState}
            onChange={this.onChange}
            plugins={plugins}
            ref={(element) => {
              this.editor = element;
            }}
          />

        <VideoAdd
          editorState={this.state.editorState}
          onChange={this.onChange}
          modifier={videoPlugin.addVideo}
        />

    );
  }
}


text:
django-list-wrestler
=======================

Make django admin lists easier to sort and collapse.

This plugin turns an ordinary order field into a high-powered sorting and collapsing tool including:

Add sorting functionality to both change list views and inline list views, including:

![Screenshot of changelist with drag controls](/../master/docs/screenshots/changelist_drag.png?raw=true "Screenshot of changelist with drag controls")

* Drag-and-Drop re-ordering
* Jump to Top and Jump to Bottom buttons
* Jump one up and Jump one bottom
* Send directly to a position in the list
* Sort by a custom field

For inline lists:
* Adjust table headers so they line up with the actual columns
* Make table headers sortable, so you can sort by a particular field (supports sorting by text inputs, text areas, check boxes, image uploads, and fks)
* Positioning order buttons anywhere in the table

For change lists:
* Add collapsing functionality to a changelist view to mimic the functionality of a tree folder structure.

![Screenshot of changelist with tree widget enabled and open](/../master/docs/screenshots/path_collapse_open.png?raw=true "Screenshot of changelist with tree widget enabled and open")

Requirements
=====
Requires Django

Usage
=====
1. pip install django-list-wrestler
2. Add 'django_list_wrestler' to your INSTALLED_APPS list in your project's settings.py
3. Customize your admin definition following the examples below:

### Inline Sorting Example

Inline list, with all the sorting options turned on:

![Screenshot of Django inline items](/../master/docs/screenshots/screenshot.png?raw=true "Screenshot of Tabular Inline Items")

Inline list, with only simplified control:

![Screenshot of Django inline items](/../master/docs/screenshots/simplified.png?raw=true "Screenshot of simplified Inline Items")

```python
from django_list_wrestler.admin import TabularInlineOrderable, StackedInlineOrderable

from .models import *

class ItemInline(TabularInlineOrderable):
	"""
	To bring drag-and-drop functionality to an inline:
	"""
	model = Item
	fields = ('order', 'name', 'txtid', 'description')
	prepopulated_fields = {'txtid': ('name',)}

class SubItemInline(TabularInlineOrderable):
	"""
	To bring drag-and-drop functionality to an inline, sorting on a custom field:
	"""
	model = SubItem
	fields = ('position', 'name', 'txtid')
	prepopulated_fields = {'txtid': ('name',)}

	# To override which field is used for ordering, add a class starting with order-by-[fieldname]. Make sure to also include 'django-list-wrestler' in the list:
	classes = ['django-list-wrestler', 'order-by-position']

	# Add any of the following css classes to this list to disable any of the buttons:
	#'inline-wrestler-drag-disabled', 'inline-wrestler-move-disabled',
	#'inline-wrestler-move-bottom-disabled', 'inline-wrestler-move-top-disabled',
	#'inline-wrestler-move-up-disabled', 'inline-wrestler-move-down-disabled',
	#'inline-wrestler-jump-disabled'

```

### Change List Sorting Example

Allow sorting within the change list, turning a basic integer field into a drag and drop or push-button sortable widget.

The raw ordering field:

![Screenshot of changelist without sorting](/../master/docs/screenshots/changelist_raw.png?raw=true "Screenshot of changelist without sorting")

With Dragging and Jumping:

![Screenshot of changelist with dragging and jumping](/../master/docs/screenshots/changelist_drag.png?raw=true "Screenshot of changelist with dragging and jumping")

With the whole kitchen sink of controls:

![Screenshot of changelist with all controls](/../master/docs/screenshots/changelist_full.png?raw=true "Screenshot of changelist with all controls")

```python
from django_list_wrestler.admin import AdminListOrderable

from .models import *

class ObjectAdmin(AdminListOrderable):
	"""
	To bring drag-and-drop functionality to a changelist view:
	"""
	model = Object
	fields = ('priority', 'title')
	list_editable = ('priority',)

	# REQUIRED: Set which field is used for ordering:
	custom_list_order_by = 'priority'

	# OPTIONAL: To disable any of the sorting functions:
    custom_list_settings = ['inline-wrestler-drag-disabled']
    #'inline-wrestler-drag-disabled', 'inline-wrestler-move-disabled',
	#'inline-wrestler-move-bottom-disabled', 'inline-wrestler-move-top-disabled',
	#'inline-wrestler-move-up-disabled', 'inline-wrestler-move-down-disabled',
	#'inline-wrestler-jump-disabled'

	inlines = [ItemInline, SubItemInline]

```

### Collapsing Tree Change List Example

Allow folder-style tree collapsling within the change list, turning a basic uri path (/path/to/item/) into a collapsing tree widget.

The raw hierarchical path field in the changelist:
![Screenshot of a raw path field](/../master/docs/screenshots/path_raw.png?raw=true "Screenshot of a raw path field")

With tree widget enabled:
![Screenshot of changelist with tree widget enabled and open](/../master/docs/screenshots/path_collapse_open.png?raw=true "Screenshot of changelist with tree widget enabled and open")

![Screenshot of changelist with tree widget enabled and closed](/../master/docs/screenshots/path_collapse_closed.png?raw=true "Screenshot of changelist with tree widget enabled and closed")

```python
import sys

from django_list_wrestler.admin import AdminListCollapsible

from .models import *

class ObjectAdmin(AdminListCollapsible):
	"""
	To bring collapsing tree functionality to a changelist view:

	where path is something like a tree path:
	- /root/
	- /root/child/
	- /root/child/grandchild/

	"""
	model = Object

	# Specify which field should be used to determine the hierarchy
	# in this case we're using "path"
	custom_list_order_by = 'path'
	list_display = ('path', 'title')

	# Also make sure to include this item in the display links list
	list_display_links = ('path', 'title')

	# It's also helpful to display all or more of the items,
	# since we are now nesting them:
	list_per_page = sys.maxsize
```

### Grapelli Support

To use a version that is skinned to match grappelli, use the following classes:

* AdminListOrderable -> GRPAdminListOrderable
* TabularInlineOrderable -> GRPTabularInlineOrderable
* StackedInlineOrderable -> GRPStackedInlineOrderable
* AdminListCollapsible -> GRPAdminListCollapsible


text:
package com.github.kmbulebu.dsc.it100.commands.util;

import java.util.Date;

public class DataStringBuilder {

	private StringBuilder data = new StringBuilder();

	public String build() {
		final String result = data.toString();
		data.setLength(0);
		return result;
	}

	private String intToString(int value, int stringLength) {
		String intString = Integer.toString(value);
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < (stringLength-intString.length()); i++) {
			builder.append('0');

		}
		builder.append(intString);
		return builder.toString();
	}

	public DataStringBuilder appendIntData(int value, int length) {
		this.data.append(intToString(value, length));
		return this;
	}

	public DataStringBuilder appendStringData(String data) {
		this.data.append(data);
		return this;
	}

	public DataStringBuilder appendBoolean(boolean on) {
		if (on) {
			this.data.append('1');
		} else {
			this.data.append('0');
		}
		return this;
	}

	public DataStringBuilder appendDate(Date date) {
		CommandTimeDateFormat format = new CommandTimeDateFormat();
		this.data.append(format.format(date));
		return this;
	}

	public DataStringBuilder appendPinCode(String code) {
		StringBuilder builder = new StringBuilder();
		builder.append(code);

		for (int i = 0; i < (6-code.length()); i++) {
			builder.append('0');
		}
		this.data.append(builder);
		return this;
	}

	@Override
	public String toString() {
		return data.toString();
	}

}


text:
#ifndef _PCB_H_
#define _PCB_H_

#include <atomic>

namespace pasl {
namespace data {
/**
 * \defgroup pcb Producer-consumer buffer
 * \brief Concurrent single producer, single consumer buffer
 * @ingroup data_structures
 * @{
 *
 */
namespace pcb {

/***********************************************************************/

/*---------------------------------------------------------------------*/
/**
 * \class signature
 * \ingroup pcb
 * \brief PCB interface
 */
template <typename Item>
class signature {
public:
  virtual bool empty() = 0;
  //! Pushes item `m` on the PCB
  virtual void push(Item m) = 0;
  /*! \brief Pops an item from the PCB.
   *  \param m place to write the popped item
   */
  virtual void pop(Item& m) = 0;
  /*! \brief Tries to pop from the PCB.
   *  \param m place to write the popped item
   *  \return true if an item is popped and false otherwise.
   */
  virtual bool try_pop(Item& m) = 0;
};

/*---------------------------------------------------------------------*/
/**
 * \class linked
 * \ingroup pcb
 * \brief PCB implemented with a singly-linked list
 */
template <typename Item>
class linked : public pcb::signature<Item> {

private:
  struct item_s {
    std::atomic<Item> msg;
    std::atomic<struct item_s*> next;
  };

  typedef struct item_s item_t;
  typedef item_t* item_p;

  item_p head;
  item_p tail;

  item_p item_create() {
    item_p item = new item_t;
    item->next.store(NULL);
    return item;
  }

public:

  void init() {
    item_p tail_item = item_create();
    head = tail_item;
    tail = tail_item;
  }

  void destroy() {
    // pop any remaining items off the PC
    Item m;
    while(try_pop(m));
    delete head;
    head = NULL;
  }

  linked() { }

  linked(const linked& src) {
    init();
  }

  bool empty() {
    return head->next == NULL;
  }

  void push(Item m) {
    assert(false);
    /*
    item_p item = item_create();
    tail->msg.store(m);
    // need store-store barrier
    tail->next.store(item);
    tail = item;
    */
  }

  void pop(Item& m) {
    /*
   assert(! empty());
    m = head->msg.load();
    item_p tmp = head;
    head = head->next.load();
    delete tmp;
    */
  }

  bool try_pop(Item& m) {
    if (empty()) {
      return false;
    } else {
      pop(m);
      return true;
    }
  }
};

/***********************************************************************/

} // end namespace
/*! @} */
} // end namespace
} // end namespace

#endif /*! _PCB_H_ */


text:
#include "ElemUse.hpp"

#include <cassert>

#include <xercesc/sax/AttributeList.hpp>

#include <xalanc/PlatformSupport/StringTokenizer.hpp>

#include "Constants.hpp"
#include "ElemAttributeSet.hpp"
#include "StylesheetRoot.hpp"
#include "StylesheetConstructionContext.hpp"

XALAN_CPP_NAMESPACE_BEGIN

/**
 * This acts as a superclass for ElemCopy, ElemAttributeSet,
 * ElemElement, and ElemLiteralResult, on order to implement
 * shared behavior the use-attribute-sets attribute.
 */
ElemUse::ElemUse(
			StylesheetConstructionContext&	constructionContext,
			Stylesheet&						stylesheetTree,
			int								lineNumber,
			int								columnNumber,
			int								xslToken) :
	ElemTemplateElement(constructionContext,
						stylesheetTree,
						lineNumber,
						columnNumber,
						xslToken),
	m_attributeSetsNames(0),
	m_attributeSetsNamesCount(0)
{
}

ElemUse::~ElemUse()
{
}

const XalanDOMString&
ElemUse::getElementName() const
{
	return s_emptyString;
}

void
ElemUse::postConstruction(
			StylesheetConstructionContext&	constructionContext,
			const NamespacesHandler&		theParentHandler)
{
	if (m_attributeSetsNamesCount > 0)
	{
		canGenerateAttributes(true);
	}

	// OK, now we can chain-up...
	ElemTemplateElement::postConstruction(constructionContext, theParentHandler);
}

#if !defined(XALAN_RECURSIVE_STYLESHEET_EXECUTION)
const ElemTemplateElement*
ElemUse::startElement(StylesheetExecutionContext&	executionContext) const
{

	if (m_attributeSetsNamesCount > 0)
	{
		assert(canGenerateAttributes() == true);

		executionContext.pushInvoker(this);

		executionContext.createUseAttributeSetIndexesOnStack();

		return getNextAttributeSet(executionContext);
	}

	return 0;

}

void
ElemUse::endElement(StylesheetExecutionContext&	executionContext) const
{
	if (m_attributeSetsNamesCount > 0)
	{
		executionContext.popInvoker();

		executionContext.popUseAttributeSetIndexesFromStack();
	}
}

const ElemTemplateElement*
ElemUse::getNextChildElemToExecute(
			StylesheetExecutionContext& executionContext,
			const ElemTemplateElement* currentElem) const
{
	const ElemTemplateElement* nextElement = 0;

	if (m_attributeSetsNamesCount > 0)
	{
		nextElement = getNextAttributeSet(executionContext);
	}

	// no more attribute sets,  check for next child element
	if (0 == nextElement)
	{
		nextElement = ElemTemplateElement::getNextChildElemToExecute(executionContext, currentElem);
	}

	// if next element to execute is the first child after executing attribute set(s),
	// evalute the element's AVTs first
	if (0 == nextElement && currentElem->getXSLToken() == StylesheetConstructionContext::ELEMNAME_ATTRIBUTE_SET)
	{
		evaluateAVTs(executionContext);
		nextElement = ElemTemplateElement::getFirstChildElemToExecute(executionContext);
	}

	return nextElement;
}

const ElemTemplateElement*
ElemUse::getFirstChildElemToExecute(
			StylesheetExecutionContext& executionContext) const
{
	const ElemTemplateElement* nextElement = 0;

	if (m_attributeSetsNamesCount > 0)
	{
		// reset
		executionContext.getUseAttributeSetIndexes().attributeSetNameIndex = 0;
		executionContext.getUseAttributeSetIndexes().matchingAttributeSetIndex = 0;

		nextElement = getNextAttributeSet(executionContext);
	}
	else
	{
		evaluateAVTs(executionContext);
	}

	if (0 == nextElement)
	{
		nextElement = ElemTemplateElement::getFirstChildElemToExecute(executionContext);
	}

	return nextElement;
}

const ElemTemplateElement*
ElemUse::getNextAttributeSet(
			StylesheetExecutionContext& executionContext) const
{
	const StylesheetRoot& theStylesheetRoot = getStylesheet().getStylesheetRoot();

	StylesheetExecutionContext::UseAttributeSetIndexes& useAttributeSetIndexes = executionContext.getUseAttributeSetIndexes();

	const ElemTemplateElement* attributeSet = 0;

	while (0 == attributeSet &&
		   useAttributeSetIndexes.attributeSetNameIndex < m_attributeSetsNamesCount)
	{
		attributeSet = theStylesheetRoot.getAttributeSet(
				executionContext,
				*m_attributeSetsNames[useAttributeSetIndexes.attributeSetNameIndex],
				 useAttributeSetIndexes.matchingAttributeSetIndex++,
				getLocator());

		if (0 == attributeSet)
		{

			useAttributeSetIndexes.attributeSetNameIndex++;
			useAttributeSetIndexes.matchingAttributeSetIndex = 0;
		}
	}

	return attributeSet;

}

void
ElemUse::evaluateAVTs(
		StylesheetExecutionContext&			/*executionContext*/) const
{
}
#endif

#if defined(XALAN_RECURSIVE_STYLESHEET_EXECUTION)
void
ElemUse::execute(StylesheetExecutionContext&	executionContext) const
{
	doExecute(executionContext, true);
}

void
ElemUse::doExecute(
			StylesheetExecutionContext&		executionContext,
			bool							applyAttributeSets) const
{
	assert(m_attributeSetsNamesCount == 0 || m_attributeSetsNames != 0);

	ElemTemplateElement::execute(executionContext);

	if(applyAttributeSets == true && m_attributeSetsNamesCount > 0)
	{
		assert(canGenerateAttributes() == true);

		const StylesheetRoot&		theStylesheetRoot = getStylesheet().getStylesheetRoot();
		const LocatorType* const	theLocator = getLocator();

		for(size_type i = 0; i < m_attributeSetsNamesCount; ++i)
		{
			theStylesheetRoot.executeAttributeSet(executionContext, *m_attributeSetsNames[i], theLocator);
		}
	}
}
#endif

bool
ElemUse::processUseAttributeSets(
			StylesheetConstructionContext&	constructionContext,
			const XalanDOMChar*				attrName,
			const AttributeListType&		atts,
			int								which)
{
	bool isUAS = false;

	if(StylesheetConstructionContext::ELEMNAME_LITERAL_RESULT == getXSLToken())
	{
		isUAS = constructionContext.isXSLUseAttributeSetsAttribute(
			attrName,
			getStylesheet(),
			getLocator());
	}
	else
	{
		isUAS = equals(attrName, Constants::ATTRNAME_USEATTRIBUTESETS);
	}

	if(isUAS == true)
	{
		m_attributeSetsNames =
			constructionContext.tokenizeQNames(
				m_attributeSetsNamesCount,
				atts.getValue(which),
				getStylesheet().getNamespaces(),
				getLocator());
		assert(m_attributeSetsNamesCount == 0 || m_attributeSetsNames != 0);
	}

	return isUAS;
}

XALAN_CPP_NAMESPACE_END


text:
package com.al.algorithms.sort;

import static org.junit.Assert.*;

import org.junit.Test;

public class TestsInsertionSort {

	@Test
	public void testSortAscending() {

		Integer [] array = new Integer[] {12, 4, 2, 10, 9};
		String expected = "2 4 9 10 12 ";
		String actual= "";

		InsertionSort.sortAscending(array);

		for (int i = 0; i < array.length; i++) {
			actual+= array[i] +  " ";
		}

		assertEquals(expected, actual);
	}

	@Test
	public void testSortDescending() {

		Integer [] array = new Integer[] {12, 4, 2, 10, 9};
		String expected = "12 10 9 4 2 ";
		String actual= "";

		InsertionSort.sortDescending(array);

		for (int i = 0; i < array.length; i++) {
			actual+= array[i] +  " ";
		}

		assertEquals(expected, actual);
	}

}


text:
package com.cooloongwu.emoji.utils;

import android.content.Context;
import android.util.TypedValue;

/**
 * 单位的转换
 * Created by CooLoongWu on 2017-1-5 17:24.
 */

public class DensityUtils {

    /**
     * dp转px
     *
     * @param context 上下文
     * @param dpVal   dp参数
     * @return 转换结果
     */
    public static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }

    /**
     * px转dp
     *
     * @param context 上下文
     * @param pxVal   px参数
     * @return 转换结果
     */
    public static float px2dp(Context context, float pxVal) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxVal / scale);
    }

    /**
     * sp转px
     *
     * @param context 上下文
     * @param spVal   sp参数
     * @return 转换结果
     */
    public static int sp2px(Context context, float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spVal, context.getResources().getDisplayMetrics());
    }

    /**
     * px转sp
     *
     * @param context 上下文
     * @param pxVal   px参数
     * @return 转换结果
     */
    public static float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }
}


text:
from .._internal_utils import arg_handler

from . import _VertaDataType

class Table(_VertaDataType):
    """
    Representation of a table.

    Parameters
    ----------
    data : list of list
        Tabular data.
    columns : list of str
        Column names.

    Examples
    --------
    .. code-block:: python

        from verta.data_types import Table
        data = Table(
            data=[[1, 24, "blue"], [2, 36, "red"]],
            columns=["id", "height", "color"],
        )
        run.log_attribute("measurements", data)

    """

    _TYPE_NAME = "table"
    _VERSION = "v1"

    @arg_handler.args_to_builtin(ignore_self=True)
    def __init__(self, data, columns):
        if len(set(len(row) for row in data)) != 1:
            raise ValueError("each row in `data` must have same length")
        if len(columns) != len(data[0]):
            raise ValueError("length of `columns` must equal length of rows in `data`")

        self._data = data
        self._columns = columns

    @classmethod
    def from_pandas(cls, df):
        """
        Alternate constructor that takes a pandas DataFrame.

        Parameters
        ----------
        df : :class:`pandas.DataFrame`
            DataFrame.

        Returns
        -------
        :class:`verta.data_types.Table`

        """
        return cls(df.values.tolist(), df.columns.tolist())

    def _as_dict(self):
        return self._as_dict_inner(
            {
                "rows": self._data,
                "header": self._columns,
            }
        )

    @classmethod
    def _from_dict_inner(cls, d):
        data = d[cls._TYPE_NAME]
        return cls(
            data=data["rows"],
            columns=data["header"],
        )

    def diff(self, other):
        if not isinstance(other, type(self)):
            raise TypeError(
                "`other` must be type {}, not {}".format(type(self), type(other))
            )

        raise NotImplementedError  # TODO


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaeria subconcava Schwein.

### Remarks
null


text:
// vim: ts=4:sw=4:nu:fdc=4:nospell
/*global Ext */
/**
 * @class Ext.ux.form.LovCombo
 * @extends Ext.form.ComboBox
 *
 * Simple list of values Combo
 *
 * @author    Ing. Jozef Sakáloš
 * @copyright (c) 2008, by Ing. Jozef Sakáloš
 * @version   1.3
 * @date

 *
16. April 2008

 *
2. February 2009

 *

 * @revision  $Id: Ext.ux.form.LovCombo.js 733 2009-06-26 07:29:07Z jozo $
 *
 * @license Ext.ux.form.LovCombo.js is licensed under the terms of the Open Source
 * LGPL 3.0 license. Commercial use is permitted to the extent that the
 * code/component(s) do NOT become part of another Open Source or Commercially
 * licensed development library or toolkit without explicit permission.
 *
 *
License details: http://www.gnu.org/licenses/lgpl.html

 *
 * @forum     32692
 * @demo      http://lovcombo.extjs.eu
 * @download
 *

 *
lovcombo.tar.bz2

 *
lovcombo.tar.gz

 *
lovcombo.zip

 *

 *
 * @donate
 * <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
 * <input type="hidden" name="cmd" value="_s-xclick">
 * <input type="hidden" name="hosted_button_id" value="3430419">
 * <input type="image" src="https://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif"
 * border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
 *
 * </form>
 */

// Check RegExp.escape dependency
if('function' !== typeof RegExp.escape) {
	throw('RegExp.escape function is missing. Include Ext.ux.util.js file.');
}

// create namespace
Ext.ns('Ext.ux.form');

/**
 * Creates new LovCombo
 * @constructor
 * @param {Object} config A config object
 */
Ext.ux.form.LovCombo = Ext.extend(Ext.form.ComboBox, {

	// {{{
    // configuration options
	/**
	 * @cfg {String} checkField Name of field used to store checked state.
	 * It is automatically added to existing fields.
	 * (defaults to "checked" - change it only if it collides with your normal field)
	 */
	 checkField:'checked'

	/**
	 * @cfg {String} separator Separator to use between values and texts (defaults to "," (comma))
	 */
    ,separator:','

	/**
	 * @cfg {String/Array} tpl Template for items.
	 * Change it only if you know what you are doing.
	 */
	// }}}
	// {{{
	,constructor:function(config) {
		config = config || {};
		config.listeners = config.listeners || {};
		Ext.applyIf(config.listeners, {
			 scope:this
			,beforequery:this.onBeforeQuery
			,blur:this.onRealBlur
		});
		Ext.ux.form.LovCombo.superclass.constructor.call(this, config);
	} // eo function constructor
	// }}}
    // {{{
    ,initComponent:function() {

		// template with checkbox
		if(!this.tpl) {
			this.tpl =
				 '<tpl for=".">'
				+'
'
				+''
				+'
{' + (this.displayField || 'text' )+ ':htmlEncode}
'
				+'
'
				+'</tpl>'
			;
		}

        // call parent
        Ext.ux.form.LovCombo.superclass.initComponent.apply(this, arguments);

		// remove selection from input field
		this.onLoad = this.onLoad.createSequence(function() {
			if(this.el) {
				var v = this.el.dom.value;
				this.el.dom.value = '';
				this.el.dom.value = v;
			}
		});

    } // eo function initComponent
    // }}}
	// {{{
	/**
	 * Disables default tab key bahavior
	 * @private
	 */
	,initEvents:function() {
		Ext.ux.form.LovCombo.superclass.initEvents.apply(this, arguments);

		// disable default tab handling - does no good
		this.keyNav.tab = false;

	} // eo function initEvents
	// }}}
	// {{{
	/**
	 * Clears value
	 */
	,clearValue:function() {
		this.value = '';
		this.setRawValue(this.value);
		this.store.clearFilter();
		this.store.each(function(r) {
			r.set(this.checkField, false);
		}, this);
		if(this.hiddenField) {
			this.hiddenField.value = '';
		}
		this.applyEmptyText();
	} // eo function clearValue
	// }}}
	// {{{
	/**
	 * @return {String} separator (plus space) separated list of selected displayFields
	 * @private
	 */
	,getCheckedDisplay:function() {
		var re = new RegExp(this.separator, "g");
		return this.getCheckedValue(this.displayField).replace(re, this.separator + ' ');
	} // eo function getCheckedDisplay
	// }}}
	// {{{
	/**
	 * @return {String} separator separated list of selected valueFields
	 * @private
	 */
	,getCheckedValue:function(field) {
		field = field || this.valueField;
		var c = [];

		// store may be filtered so get all records
		var snapshot = this.store.snapshot || this.store.data;

		snapshot.each(function(r) {
			if(r.get(this.checkField)) {
				c.push(r.get(field));
			}
		}, this);

		return c.join(this.separator);
	} // eo function getCheckedValue
	// }}}
	// {{{
	/**
	 * beforequery event handler - handles multiple selections
	 * @param {Object} qe query event
	 * @private
	 */
	,onBeforeQuery:function(qe) {
		qe.query = qe.query.replace(new RegExp(RegExp.escape(this.getCheckedDisplay()) + '[ ' + this.separator + ']*'), '');
	} // eo function onBeforeQuery
	// }}}
	// {{{
	/**
	 * blur event handler - runs only when real blur event is fired
	 * @private
	 */
	,onRealBlur:function() {
		this.list.hide();
		var rv = this.getRawValue();
		var rva = rv.split(new RegExp(RegExp.escape(this.separator) + ' *'));
		var va = [];
		var snapshot = this.store.snapshot || this.store.data;

		// iterate through raw values and records and check/uncheck items
		Ext.each(rva, function(v) {
			snapshot.each(function(r) {
				if(v === r.get(this.displayField)) {
					va.push(r.get(this.valueField));
				}
			}, this);
		}, this);
		this.setValue(va.join(this.separator));
		this.store.clearFilter();
	} // eo function onRealBlur
	// }}}
	// {{{
	/**
	 * Combo's onSelect override
	 * @private
	 * @param {Ext.data.Record} record record that has been selected in the list
	 * @param {Number} index index of selected (clicked) record
	 */
	,onSelect:function(record, index) {
        if(this.fireEvent('beforeselect', this, record, index) !== false){

			// toggle checked field
			record.set(this.checkField, !record.get(this.checkField));

			// display full list
			if(this.store.isFiltered()) {
				this.doQuery(this.allQuery);
			}

			// set (update) value and fire event
			this.setValue(this.getCheckedValue());
            this.fireEvent('select', this, record, index);
        }
	} // eo function onSelect
	// }}}
	// {{{
	/**
	 * Sets the value of the LovCombo. The passed value can by a falsie (null, false, empty string), in
	 * which case the combo value is cleared or separator separated string of values, e.g. '3,5,6'.
	 * @param {Mixed} v value
	 */
	,setValue:function(v) {
		if(v) {
			v = '' + v;
			if(this.valueField) {
				this.store.clearFilter();
				this.store.each(function(r) {
					var checked = !(!v.match(
						 '(^|' + this.separator + ')' + RegExp.escape(r.get(this.valueField))
						+'(' + this.separator + '|$)'))
					;

					r.set(this.checkField, checked);
				}, this);
				this.value = this.getCheckedValue();
				this.setRawValue(this.getCheckedDisplay());
				if(this.hiddenField) {
					this.hiddenField.value = this.value;
				}
			}
			else {
				this.value = v;
				this.setRawValue(v);
				if(this.hiddenField) {
					this.hiddenField.value = v;
				}
			}
			if(this.el) {
				this.el.removeClass(this.emptyClass);
			}
		}
		else {
			this.clearValue();
		}
	} // eo function setValue
	// }}}
	// {{{
	/**
	 * Selects all items
	 */
	,selectAll:function() {
        this.store.each(function(record){
            // toggle checked field
            record.set(this.checkField, true);
        }, this);

        //display full list
        this.doQuery(this.allQuery);
        this.setValue(this.getCheckedValue());
    } // eo full selectAll
	// }}}
	// {{{
	/**
	 * Deselects all items. Synonym for clearValue
	 */
    ,deselectAll:function() {
		this.clearValue();
    } // eo full deselectAll
	// }}}

}); // eo extend

// register xtype
Ext.reg('lovcombo', Ext.ux.form.LovCombo);

// eof


text:
int main() {
  // error: missing terminating quote
  "hello
}


text:
var mongoose = require('mongoose'),
  async = require('async'),
  elasticsearch = require('elasticsearch'),
  config = require('./config'),
  Schema = mongoose.Schema,
  mongoosastic = require('../lib/mongoosastic');

var DummySchema = new Schema({
  text: String
});

var Dummy = mongoose.model('Dummy1', DummySchema, 'dummys');

function tryDummySearch(model, cb) {
  setTimeout(function() {
    model.search({
      simple_query_string: {
        query: 'Text1'
      }
    }, {
      index: '_all'
    }, function(err, results) {
      if (err) {
        return cb(err);
      }

      results.hits.total.should.eql(0);
      model.esClient.close();
      cb(err);
    });
  }, config.INDEXING_TIMEOUT);

}

describe('Elasticsearch Connection', function() {

  before(function(done) {

    mongoose.connect(config.mongoUrl, function() {
      Dummy.remove(function() {
        config.deleteIndexIfExists(['dummys'], function() {
          var dummies = [
            new Dummy({
              text: 'Text1'
            }),
            new Dummy({
              text: 'Text2'
            })
          ];
          async.forEach(dummies, function(item, cb) {
            item.save(cb);
          }, function() {
            setTimeout(done, config.INDEXING_TIMEOUT);
          });
        });
      });
    });
  });

  after(function(done) {
    Dummy.remove();
    mongoose.disconnect();
    done();
  });

  it('should be able to connect with default options', function(done) {
    var Dummy2;

    DummySchema.plugin(mongoosastic);
    Dummy2 = mongoose.model('Dummy2', DummySchema, 'dummys');

    tryDummySearch(Dummy2, done);

  });

  it('should be able to connect with explicit options', function(done) {
    var Dummy3;

    DummySchema.plugin(mongoosastic, {
      host: 'localhost',
      port: 9200
    });

    Dummy3 = mongoose.model('Dummy3', DummySchema, 'dummys');

    tryDummySearch(Dummy3, done);

  });

  it('should be able to connect with an array of hosts', function(done) {
    var Dummy4;

    DummySchema.plugin(mongoosastic, {
      hosts: [
        'localhost:9200',
        'localhost:9200'
      ]
    });

    Dummy4 = mongoose.model('Dummy4', DummySchema, 'dummys');

    tryDummySearch(Dummy4, done);

  });

  it('should be able to connect with an existing elasticsearch client', function(done) {

    var esClient = new elasticsearch.Client({
      host: 'localhost:9200'
    });

    esClient.ping({
      requestTimeout: 1000
    }, function(err) {
      var Dummy5;

      if (err) {
        return done(err);
      }

      DummySchema.plugin(mongoosastic, {
        esClient: esClient
      });

      Dummy5 = mongoose.model('Dummy5', DummySchema, 'dummys');

      tryDummySearch(Dummy5, done);
    });

  });

});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Br. mycol. Soc. 31: 104 (1947)

#### Original name
Chytridium coconeidis Canter

### Remarks
null


text:
from ..helpers import indirectStarter
from ..scraper import ParserScraper
from ..util import getQueryParams

class CloneManga(ParserScraper):
    baseUrl = 'http://manga.clone-army.org'
    imageSearch = '//div[d:class("subsectionContainer")]//img'
    prevSearch = '//a[span[text()="<<"]]'
    latestSearch = '//a[span[text()=">|"]]'
    starter = indirectStarter
    help = 'Index format: n'

    def __init__(self, name, shortName, endOfLife=False):
        super().__init__('CloneManga/' + name)
        self.stripUrl = '%s/viewer.php?page=%%s&lang=&series=%s&HUDoff=' % (
            self.baseUrl, shortName)
        self.url = self.stripUrl % '1'
        self.endOfLife = endOfLife

    def namer(self, image_url, page_url):
        origname = image_url.rsplit('/', 1)[1]
        params = getQueryParams(page_url)
        if 'page' in params:
            return '{:03}_{}'.format(int(params['page'][0]), origname)
        else:
            return origname

    @classmethod
    def getmodules(cls):
        return (
            cls('ACaptainsWorries', 'captains_worries'),
            cls('AHimehornsDailyLife', 'himehorn'),
            cls('AprilAndMay', 'anm', endOfLife=True),
            cls('DollAndMaker', 'maria_doll', endOfLife=True),
            cls('Kanami', 'kanami', endOfLife=True),
            cls('MomokaCorner', 'momoka', endOfLife=True),
            cls('MyShutInVampirePrincess', 'snax'),
            cls('NanasEverydayLife', 'nana', endOfLife=True),
            cls('NNN', 'nnn', endOfLife=True),
            cls('PaperEleven', 'pxi', endOfLife=True),
            cls('PennyTribute', 'penny', endOfLife=True),
            cls('Tomoyo42sRoom', 't42r'),
        )


text:
Adds support for the `string_decoder` module to browserify.

# License

[MIT](http://jryans.mit-license.org/)


text:
'use strict';

module('ImageTexture', function()
{
   test('should return a valid instance of ImageTexture', function(assert)
   {
      var context = new Four.Context({ selector: '#test' });
      var gl = context.gl;
      var imageTexture = new Four.ImageTexture({ path: '/resources/textures/floor.jpg' });
      var done = assert.async();

      imageTexture.promise.then(
         function()
         {
            assert.strictEqual(Four.ImageTexture.prototype.constructor.name, 'ImageTexture', 'Passed: ImageTexture class is available.');
            assert.ok(imageTexture instanceof Four.Entity, 'Passed: ImageTexture inherits from Entity.');
            assert.ok(imageTexture instanceof Four.ImageTexture, 'Passed: ImageTexture is an instance of ImageTexture.');
            assert.ok(imageTexture.isType('Entity'), 'Passed: ImageTexture is of type Entity.');
            assert.ok(imageTexture.isType('ImageTexture'), 'Passed: ImageTexture is of type ImageTexture.');
            assert.ok(gl.isTexture(imageTexture.buffer), 'Passed: WebGLTexture successfully created.');
            assert.ok(imageTexture.image instanceof Image, 'Passed: ImageTexture texture is a valid image.');

            done();
         },
         function(response)
         {
            assert.ok(false, 'Failed: ImageTexture failed to fetch image');

            done();
         }
      );
   });
});


text:
package servicefakes

import (
	"context"
	"net/http"
	"sync"

	"github.com/dpb587/ssoca/client/service"
	servicea "github.com/dpb587/ssoca/service"
)

type FakeAuthService struct {
	AuthLoginStub        func(context.Context) error
	authLoginMutex       sync.RWMutex
	authLoginArgsForCall []struct {
		arg1 context.Context
	}
	authLoginReturns struct {
		result1 error
	}
	authLoginReturnsOnCall map[int]struct {
		result1 error
	}
	AuthLogoutStub        func(context.Context) error
	authLogoutMutex       sync.RWMutex
	authLogoutArgsForCall []struct {
		arg1 context.Context
	}
	authLogoutReturns struct {
		result1 error
	}
	authLogoutReturnsOnCall map[int]struct {
		result1 error
	}
	AuthRequestStub        func(*http.Request) error
	authRequestMutex       sync.RWMutex
	authRequestArgsForCall []struct {
		arg1 *http.Request
	}
	authRequestReturns struct {
		result1 error
	}
	authRequestReturnsOnCall map[int]struct {
		result1 error
	}
	NameStub        func() string
	nameMutex       sync.RWMutex
	nameArgsForCall []struct {
	}
	nameReturns struct {
		result1 string
	}
	nameReturnsOnCall map[int]struct {
		result1 string
	}
	TypeStub        func() servicea.Type
	typeMutex       sync.RWMutex
	typeArgsForCall []struct {
	}
	typeReturns struct {
		result1 servicea.Type
	}
	typeReturnsOnCall map[int]struct {
		result1 servicea.Type
	}
	VersionStub        func() string
	versionMutex       sync.RWMutex
	versionArgsForCall []struct {
	}
	versionReturns struct {
		result1 string
	}
	versionReturnsOnCall map[int]struct {
		result1 string
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakeAuthService) AuthLogin(arg1 context.Context) error {
	fake.authLoginMutex.Lock()
	ret, specificReturn := fake.authLoginReturnsOnCall[len(fake.authLoginArgsForCall)]
	fake.authLoginArgsForCall = append(fake.authLoginArgsForCall, struct {
		arg1 context.Context
	}{arg1})
	fake.recordInvocation("AuthLogin", []interface{}{arg1})
	fake.authLoginMutex.Unlock()
	if fake.AuthLoginStub != nil {
		return fake.AuthLoginStub(arg1)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.authLoginReturns
	return fakeReturns.result1
}

func (fake *FakeAuthService) AuthLoginCallCount() int {
	fake.authLoginMutex.RLock()
	defer fake.authLoginMutex.RUnlock()
	return len(fake.authLoginArgsForCall)
}

func (fake *FakeAuthService) AuthLoginCalls(stub func(context.Context) error) {
	fake.authLoginMutex.Lock()
	defer fake.authLoginMutex.Unlock()
	fake.AuthLoginStub = stub
}

func (fake *FakeAuthService) AuthLoginArgsForCall(i int) context.Context {
	fake.authLoginMutex.RLock()
	defer fake.authLoginMutex.RUnlock()
	argsForCall := fake.authLoginArgsForCall[i]
	return argsForCall.arg1
}

func (fake *FakeAuthService) AuthLoginReturns(result1 error) {
	fake.authLoginMutex.Lock()
	defer fake.authLoginMutex.Unlock()
	fake.AuthLoginStub = nil
	fake.authLoginReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeAuthService) AuthLoginReturnsOnCall(i int, result1 error) {
	fake.authLoginMutex.Lock()
	defer fake.authLoginMutex.Unlock()
	fake.AuthLoginStub = nil
	if fake.authLoginReturnsOnCall == nil {
		fake.authLoginReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.authLoginReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeAuthService) AuthLogout(arg1 context.Context) error {
	fake.authLogoutMutex.Lock()
	ret, specificReturn := fake.authLogoutReturnsOnCall[len(fake.authLogoutArgsForCall)]
	fake.authLogoutArgsForCall = append(fake.authLogoutArgsForCall, struct {
		arg1 context.Context
	}{arg1})
	fake.recordInvocation("AuthLogout", []interface{}{arg1})
	fake.authLogoutMutex.Unlock()
	if fake.AuthLogoutStub != nil {
		return fake.AuthLogoutStub(arg1)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.authLogoutReturns
	return fakeReturns.result1
}

func (fake *FakeAuthService) AuthLogoutCallCount() int {
	fake.authLogoutMutex.RLock()
	defer fake.authLogoutMutex.RUnlock()
	return len(fake.authLogoutArgsForCall)
}

func (fake *FakeAuthService) AuthLogoutCalls(stub func(context.Context) error) {
	fake.authLogoutMutex.Lock()
	defer fake.authLogoutMutex.Unlock()
	fake.AuthLogoutStub = stub
}

func (fake *FakeAuthService) AuthLogoutArgsForCall(i int) context.Context {
	fake.authLogoutMutex.RLock()
	defer fake.authLogoutMutex.RUnlock()
	argsForCall := fake.authLogoutArgsForCall[i]
	return argsForCall.arg1
}

func (fake *FakeAuthService) AuthLogoutReturns(result1 error) {
	fake.authLogoutMutex.Lock()
	defer fake.authLogoutMutex.Unlock()
	fake.AuthLogoutStub = nil
	fake.authLogoutReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeAuthService) AuthLogoutReturnsOnCall(i int, result1 error) {
	fake.authLogoutMutex.Lock()
	defer fake.authLogoutMutex.Unlock()
	fake.AuthLogoutStub = nil
	if fake.authLogoutReturnsOnCall == nil {
		fake.authLogoutReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.authLogoutReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeAuthService) AuthRequest(arg1 *http.Request) error {
	fake.authRequestMutex.Lock()
	ret, specificReturn := fake.authRequestReturnsOnCall[len(fake.authRequestArgsForCall)]
	fake.authRequestArgsForCall = append(fake.authRequestArgsForCall, struct {
		arg1 *http.Request
	}{arg1})
	fake.recordInvocation("AuthRequest", []interface{}{arg1})
	fake.authRequestMutex.Unlock()
	if fake.AuthRequestStub != nil {
		return fake.AuthRequestStub(arg1)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.authRequestReturns
	return fakeReturns.result1
}

func (fake *FakeAuthService) AuthRequestCallCount() int {
	fake.authRequestMutex.RLock()
	defer fake.authRequestMutex.RUnlock()
	return len(fake.authRequestArgsForCall)
}

func (fake *FakeAuthService) AuthRequestCalls(stub func(*http.Request) error) {
	fake.authRequestMutex.Lock()
	defer fake.authRequestMutex.Unlock()
	fake.AuthRequestStub = stub
}

func (fake *FakeAuthService) AuthRequestArgsForCall(i int) *http.Request {
	fake.authRequestMutex.RLock()
	defer fake.authRequestMutex.RUnlock()
	argsForCall := fake.authRequestArgsForCall[i]
	return argsForCall.arg1
}

func (fake *FakeAuthService) AuthRequestReturns(result1 error) {
	fake.authRequestMutex.Lock()
	defer fake.authRequestMutex.Unlock()
	fake.AuthRequestStub = nil
	fake.authRequestReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeAuthService) AuthRequestReturnsOnCall(i int, result1 error) {
	fake.authRequestMutex.Lock()
	defer fake.authRequestMutex.Unlock()
	fake.AuthRequestStub = nil
	if fake.authRequestReturnsOnCall == nil {
		fake.authRequestReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.authRequestReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeAuthService) Name() string {
	fake.nameMutex.Lock()
	ret, specificReturn := fake.nameReturnsOnCall[len(fake.nameArgsForCall)]
	fake.nameArgsForCall = append(fake.nameArgsForCall, struct {
	}{})
	fake.recordInvocation("Name", []interface{}{})
	fake.nameMutex.Unlock()
	if fake.NameStub != nil {
		return fake.NameStub()
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.nameReturns
	return fakeReturns.result1
}

func (fake *FakeAuthService) NameCallCount() int {
	fake.nameMutex.RLock()
	defer fake.nameMutex.RUnlock()
	return len(fake.nameArgsForCall)
}

func (fake *FakeAuthService) NameCalls(stub func() string) {
	fake.nameMutex.Lock()
	defer fake.nameMutex.Unlock()
	fake.NameStub = stub
}

func (fake *FakeAuthService) NameReturns(result1 string) {
	fake.nameMutex.Lock()
	defer fake.nameMutex.Unlock()
	fake.NameStub = nil
	fake.nameReturns = struct {
		result1 string
	}{result1}
}

func (fake *FakeAuthService) NameReturnsOnCall(i int, result1 string) {
	fake.nameMutex.Lock()
	defer fake.nameMutex.Unlock()
	fake.NameStub = nil
	if fake.nameReturnsOnCall == nil {
		fake.nameReturnsOnCall = make(map[int]struct {
			result1 string
		})
	}
	fake.nameReturnsOnCall[i] = struct {
		result1 string
	}{result1}
}

func (fake *FakeAuthService) Type() servicea.Type {
	fake.typeMutex.Lock()
	ret, specificReturn := fake.typeReturnsOnCall[len(fake.typeArgsForCall)]
	fake.typeArgsForCall = append(fake.typeArgsForCall, struct {
	}{})
	fake.recordInvocation("Type", []interface{}{})
	fake.typeMutex.Unlock()
	if fake.TypeStub != nil {
		return fake.TypeStub()
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.typeReturns
	return fakeReturns.result1
}

func (fake *FakeAuthService) TypeCallCount() int {
	fake.typeMutex.RLock()
	defer fake.typeMutex.RUnlock()
	return len(fake.typeArgsForCall)
}

func (fake *FakeAuthService) TypeCalls(stub func() servicea.Type) {
	fake.typeMutex.Lock()
	defer fake.typeMutex.Unlock()
	fake.TypeStub = stub
}

func (fake *FakeAuthService) TypeReturns(result1 servicea.Type) {
	fake.typeMutex.Lock()
	defer fake.typeMutex.Unlock()
	fake.TypeStub = nil
	fake.typeReturns = struct {
		result1 servicea.Type
	}{result1}
}

func (fake *FakeAuthService) TypeReturnsOnCall(i int, result1 servicea.Type) {
	fake.typeMutex.Lock()
	defer fake.typeMutex.Unlock()
	fake.TypeStub = nil
	if fake.typeReturnsOnCall == nil {
		fake.typeReturnsOnCall = make(map[int]struct {
			result1 servicea.Type
		})
	}
	fake.typeReturnsOnCall[i] = struct {
		result1 servicea.Type
	}{result1}
}

func (fake *FakeAuthService) Version() string {
	fake.versionMutex.Lock()
	ret, specificReturn := fake.versionReturnsOnCall[len(fake.versionArgsForCall)]
	fake.versionArgsForCall = append(fake.versionArgsForCall, struct {
	}{})
	fake.recordInvocation("Version", []interface{}{})
	fake.versionMutex.Unlock()
	if fake.VersionStub != nil {
		return fake.VersionStub()
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.versionReturns
	return fakeReturns.result1
}

func (fake *FakeAuthService) VersionCallCount() int {
	fake.versionMutex.RLock()
	defer fake.versionMutex.RUnlock()
	return len(fake.versionArgsForCall)
}

func (fake *FakeAuthService) VersionCalls(stub func() string) {
	fake.versionMutex.Lock()
	defer fake.versionMutex.Unlock()
	fake.VersionStub = stub
}

func (fake *FakeAuthService) VersionReturns(result1 string) {
	fake.versionMutex.Lock()
	defer fake.versionMutex.Unlock()
	fake.VersionStub = nil
	fake.versionReturns = struct {
		result1 string
	}{result1}
}

func (fake *FakeAuthService) VersionReturnsOnCall(i int, result1 string) {
	fake.versionMutex.Lock()
	defer fake.versionMutex.Unlock()
	fake.VersionStub = nil
	if fake.versionReturnsOnCall == nil {
		fake.versionReturnsOnCall = make(map[int]struct {
			result1 string
		})
	}
	fake.versionReturnsOnCall[i] = struct {
		result1 string
	}{result1}
}

func (fake *FakeAuthService) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.authLoginMutex.RLock()
	defer fake.authLoginMutex.RUnlock()
	fake.authLogoutMutex.RLock()
	defer fake.authLogoutMutex.RUnlock()
	fake.authRequestMutex.RLock()
	defer fake.authRequestMutex.RUnlock()
	fake.nameMutex.RLock()
	defer fake.nameMutex.RUnlock()
	fake.typeMutex.RLock()
	defer fake.typeMutex.RUnlock()
	fake.versionMutex.RLock()
	defer fake.versionMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

func (fake *FakeAuthService) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ service.AuthService = new(FakeAuthService)


text:
package jriot.objects;

public class TeamMemberInfo {

    private long inviteDate;
    private long joinDate;
    private long playerId;
    private String status;

    public long getInviteDate() {
        return inviteDate;
    }

    public void setInviteDate(long inviteDate) {
        this.inviteDate = inviteDate;
    }

    public long getJoinDate() {
        return joinDate;
    }

    public void setJoinDate(long joinDate) {
        this.joinDate = joinDate;
    }

    public long getPlayerId() {
        return playerId;
    }

    public void setPlayerId(long playerId) {
        this.playerId = playerId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "TeamMemberInfo [inviteDate=" + inviteDate + ", joinDate="
                + joinDate + ", playerId=" + playerId + ", status=" + status
                + "]";
    }

}