text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using RentahuntApp.Models;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
using System.Web.Security;
using System.Threading.Tasks;

namespace RentahuntApp.Controllers
{
    public class ListingController : Controller
    {
        private ApplicationSignInManager _signInManager;
        private ApplicationUserManager _userManager;

        private ApplicationDbContext db = new ApplicationDbContext();

        public ListingController()
        {
        }

        public ListingController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
        {
            UserManager = userManager;
            SignInManager = signInManager;
        }

        public ApplicationSignInManager SignInManager
        {
            get
            {
                return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
            }
            private set
            {
                _signInManager = value;
            }
        }

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        // GET: Listing
        public ActionResult Index()
        {
            return View(db.ListingModels.ToList());
        }

        // GET: Listing/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            ListingDetailsViewModel model = new ListingDetailsViewModel();
            ListingModels listing = db.ListingModels.Find(id);
            var bookings = db.BookingModel.Where(w => w.ListingId == listing.ListingId).Select(s => s).ToList();
            model.ListingModel = listing;
            model.ListingId = listing.ListingId;

            var weekDaysToBlock = String.Join(",",GetDaysToBlock(listing.WeekDayBlock));
            var monthsToBlock = GetMonthsToBlock(listing.MonthBlock);
            var bookedDaysToBlock = GetDaysToBlock(bookings);

            monthsToBlock.AddRange(bookedDaysToBlock);

            var daysToBlock = monthsToBlock.ToArray();

            ViewBag.WeekDays = weekDaysToBlock;
            ViewBag.Days = daysToBlock;

            if (model == null)
            {
                return HttpNotFound();
            }
            return View(model);
        }

        // GET: Listing/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Listing/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "Title,Location,County,Acreage,Description,ProhibitedActivities,HostPhone,HostEmail,HostPayPalEmail, ListingFee, BoundaryInfo,AccessInfo,MeetupReqired")] ListingModels model)
        {
            var userId = User.Identity.GetUserId();

            model.ApplicationUser = db.Users.Find(userId);
            model.UserId = userId;
            model.DateCreated = DateTime.Now;
            model.Active = true;
            model.ExpirationDate = null;
            var latLng = Helpers.GoogleAPIs.GeocodeAddress(model.Location);
            model.Lat = latLng[0];
            model.Lng = latLng[1];

            WeekDayBlockModels weekDayAvailability = new WeekDayBlockModels();
            MonthBlockModels monthAvailability = new MonthBlockModels();

            ModelState.Clear();
            ValidateModel(model);

            if (ModelState.IsValid)
            {
                db.ListingModels.Add(model);
                db.SaveChanges();

                //add new Weekday and Month Availability Table entry for listing
                weekDayAvailability.ListingId = model.ListingId;
                monthAvailability.ListingId = model.ListingId;
                db.WeekDayBlockModels.Add(weekDayAvailability);
                db.MonthBlockModels.Add(monthAvailability);
                db.SaveChanges();

                await EmailUser("New Listing Created", $"A new listing titled '{model.Title}' has been created", "Login to your account for details", "Click here to login", "Login", "Account", "Thank you", "Admin");

                var message = ManageController.ManageMessageId.AddedListingSuccess;
                return RedirectToAction("Index","Manage", new { Message = message });
            }

            return View(model);
        }

        // GET: Listing/Availability/5
        public ActionResult Availability(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var months = db.MonthBlockModels.Where(x => x.ListingId == id).Select(x => x).First();
            var days = db.WeekDayBlockModels.Where(x => x.ListingId == id).Select(x => x).First();
            var listing = db.ListingModels.Where(x => x.ListingId == id).Select(x => x).First();
            //var dateRanges = db.DateRangeBlockModels.Where(x => x.ListingId == id).Select(x => x.StartDate.ToString() + "-" + x.EndDate.ToString());

            ListingAvailabilityViewModel model = new ListingAvailabilityViewModel();

            model.ListingId = id;
            model.UserId = listing.UserId;

            model.WeekDays = new WeekDayBlockViewModel();
            model.WeekDays.WeekDayBlocks = days;
            model.WeekDays.DaysOfWeekList = new MultiSelectList(Helpers.SelectLists.GetDaysOfWeekList(), "Value", "Text");
            model.WeekDays.SelectedDays = GetCurrentAvailability(days);

            model.Months = new MonthBlockViewModel();
            model.Months.MonthBlocks = months;
            model.Months.MonthsList = new MultiSelectList(Helpers.SelectLists.GetMonthsOfYearList(), "Value", "Text");
            model.Months.SelectedMonths = GetCurrentAvailability(months);

            //availabilityModel.DateRanges = dateRanges.ToList();

            if (model == null || User.Identity.GetUserId() != model.UserId && !User.IsInRole("Admin"))
            {
                return HttpNotFound();
            }
            return View(model);
        }
        // POST: Listing/Availability/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Availability(ListingAvailabilityViewModel model)
        {
            WeekDayBlockModels days = db.WeekDayBlockModels.Where(x => x.ListingId == model.ListingId).Select(x => x).First();
            MonthBlockModels months = db.MonthBlockModels.Where(x => x.ListingId == model.ListingId).Select(x => x).First();

            if(model.WeekDays != null)
            {
                days = UpdateWeekDayAvailability(days, model.WeekDays.SelectedDays);
                days.Listings = db.ListingModels.Find(model.ListingId);
                db.Entry(days).State = EntityState.Modified;
            }
            if(model.Months != null)
            {
                months = UpdateMonthAvailability(months, model.Months.SelectedMonths);
                months.Listings = db.ListingModels.Find(model.ListingId);
                db.Entry(months).State = EntityState.Modified;
            }

            if (ModelState.IsValid)
            {
                try
                {
                    db.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
                {
                    Exception raise = dbEx;
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            //string message = string.Format("{0}:{1}",
                            //    validationErrors.Entry.Entity.ToString(),
                            //    validationError.ErrorMessage);
                            //// raise a new exception nesting
                            //// the current instance as InnerException
                            //raise = new InvalidOperationException(message, raise);
                        }
                    }
                    throw raise;
                }

                var message = ManageController.ManageMessageId.UpdatedListingAvailabilitySuccess;
                return RedirectToAction(User.IsInRole("Admin") ? "IndexAdmin" : "Index", "Manage", new { Message = message });
            }
            return RedirectToAction("Index", "Manage");
        }
        [Authorize]
        // GET: Listing/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ListingModels model = db.ListingModels.Find(id);
            if (model == null || User.Identity.GetUserId() != model.UserId && !User.IsInRole("Admin"))
            {
                return HttpNotFound();
            }
            return View(model);
        }

        // POST: Listing/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ListingId,UserId,DateCreated,Active,ExpirationDate,Title,Location,Lat,Lng,County,Acreage,Description,ProhibitedActivities,HostPhone,HostEmail,ListingFee,HostPayPalEmail,BoundaryInfo,AccessInfo,MeetupReqired")] ListingModels listingModels)
        {
            var user = db.Users.Find(listingModels.UserId);
            listingModels.ApplicationUser = db.Users.Find(listingModels.UserId);

            var latLng = Helpers.GoogleAPIs.GeocodeAddress(listingModels.Location);
            listingModels.Lat = latLng[0];
            listingModels.Lng = latLng[1];

            listingModels.DateCreated = DateTime.Now;

            ModelState.Clear();
            ValidateModel(listingModels);

            if (ModelState.IsValid)
            {
                db.Entry(listingModels).State = EntityState.Modified;
                try
                {
                    db.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
                {
                    Exception raise = dbEx;
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            //string message = string.Format("{0}:{1}",
                            //    validationErrors.Entry.Entity.ToString(),
                            //    validationError.ErrorMessage);
                            //// raise a new exception nesting
                            //// the current instance as InnerException
                            //raise = new InvalidOperationException(message, raise);
                        }
                    }
                    throw raise;
                }
                var message = ManageController.ManageMessageId.UpdatedListingSuccess;
                return RedirectToAction(User.IsInRole("Admin") ? "IndexAdmin" : "Index", "Manage", new { Message = message });
            }
            return RedirectToAction("Index", "Manage");
        }

        // GET: Listing/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ListingModels listingModels = db.ListingModels.Find(id);
            if (listingModels == null)
            {
                return HttpNotFound();
            }
            return View(listingModels);
        }

        // POST: Listing/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            ListingModels listingModels = db.ListingModels.Find(id);
            db.ListingModels.Remove(listingModels);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
        protected List<string> GetCurrentAvailability(WeekDayBlockModels days)
        {
            var dayNameList = Helpers.SelectLists.GetDaysOfWeekNamesList();
            List<string> selectedDays = new List<string>();

            foreach (var d in dayNameList)
            {
                if (days.Sunday == true && d == "Sunday") selectedDays.Add(d);
                if (days.Monday == true && d == "Monday") selectedDays.Add(d);
                if (days.Tuesday == true && d == "Tuesday") selectedDays.Add(d);
                if (days.Wednesday == true && d == "Wednesday") selectedDays.Add(d);
                if (days.Thursday == true && d == "Thursday") selectedDays.Add(d);
                if (days.Friday == true && d == "Friday") selectedDays.Add(d);
                if (days.Saturday == true && d == "Saturday") selectedDays.Add(d);
            }

            return selectedDays;
        }
        protected List<string> GetCurrentAvailability(MonthBlockModels months)
        {
            var monthNameList = Helpers.SelectLists.GetMonthsOfYearNamesList();
            List<string> selectedMonths = new List<string>();

            foreach (var m in monthNameList)
            {
                if (months.January == true && m == "January") selectedMonths.Add(m);
                if (months.February == true && m == "February") selectedMonths.Add(m);
                if (months.March == true && m == "March") selectedMonths.Add(m);
                if (months.April == true && m == "April") selectedMonths.Add(m);
                if (months.May == true && m == "May") selectedMonths.Add(m);
                if (months.June == true && m == "June") selectedMonths.Add(m);
                if (months.July == true && m == "July") selectedMonths.Add(m);
                if (months.August == true && m == "August") selectedMonths.Add(m);
                if (months.September == true && m == "September") selectedMonths.Add(m);
                if (months.October == true && m == "October") selectedMonths.Add(m);
                if (months.November == true && m == "November") selectedMonths.Add(m);
                if (months.December == true && m == "December") selectedMonths.Add(m);
            }

            return selectedMonths;
        }
        protected WeekDayBlockModels UpdateWeekDayAvailability(WeekDayBlockModels days, List<string> selectedDays)
        {
            days.Sunday = false;
            days.Monday = false;
            days.Tuesday = false;
            days.Wednesday = false;
            days.Thursday = false;
            days.Friday = false;
            days.Saturday = false;

            if (selectedDays.Count > 0)
            {
                foreach (string d in selectedDays)
                {
                    if (d == "Sunday") days.Sunday = true;
                    else if (d == "Monday") days.Monday = true;
                    else if (d == "Tuesday") days.Tuesday = true;
                    else if (d == "Wednesday") days.Wednesday = true;
                    else if (d == "Thursday") days.Thursday = true;
                    else if (d == "Friday") days.Friday = true;
                    else if (d == "Saturday") days.Saturday = true;
                }
            }

            return days;
        }
        protected MonthBlockModels UpdateMonthAvailability(MonthBlockModels months, List<string> selectedMonths)
        {
            months.January = false;
            months.February = false;
            months.March = false;
            months.April = false;
            months.May = false;
            months.June = false;
            months.July = false;
            months.August = false;
            months.September = false;
            months.October = false;
            months.November = false;
            months.December = false;

            if (selectedMonths.Count > 0)
            {
                foreach (string d in selectedMonths)
                {
                    if (d == "January") months.January = true;
                    else if (d == "February") months.February = true;
                    else if (d == "March") months.March = true;
                    else if (d == "April") months.April = true;
                    else if (d == "May") months.May = true;
                    else if (d == "June") months.June = true;
                    else if (d == "July") months.July = true;
                    else if (d == "August") months.August = true;
                    else if (d == "September") months.September = true;
                    else if (d == "October") months.October = true;
                    else if (d == "November") months.November = true;
                    else if (d == "December") months.December = true;
                }
            }

            return months;
        }

        private List<string> GetMonthsToBlock(MonthBlockModels model)
        {
            var currentMonth = DateTime.Now.Month;
            var currentYear = DateTime.Now.Year;

            List<string> monthsToAdd = new List<string>();

            if (model.January == true) monthsToAdd.AddRange(MonthDaysToList(1, 1 >= currentMonth ? currentYear : currentYear + 1));
            if (model.February == true) monthsToAdd.AddRange(MonthDaysToList(2, 2 >= currentMonth ? currentYear : currentYear + 1));
            if (model.March == true) monthsToAdd.AddRange(MonthDaysToList(3, 3 >= currentMonth ? currentYear : currentYear + 1));
            if (model.April == true) monthsToAdd.AddRange(MonthDaysToList(4, 4 >= currentMonth ? currentYear : currentYear + 1));
            if (model.May == true) monthsToAdd.AddRange(MonthDaysToList(5, 5 >= currentMonth ? currentYear : currentYear + 1));
            if (model.June == true) monthsToAdd.AddRange(MonthDaysToList(6, 6 >= currentMonth ? currentYear : currentYear + 1));
            if (model.July == true) monthsToAdd.AddRange(MonthDaysToList(7, 7 >= currentMonth ? currentYear : currentYear + 1));
            if (model.August == true) monthsToAdd.AddRange(MonthDaysToList(8, 8 >= currentMonth ? currentYear : currentYear + 1));
            if (model.September == true) monthsToAdd.AddRange(MonthDaysToList(9, 9 >= currentMonth ? currentYear : currentYear + 1));
            if (model.October == true) monthsToAdd.AddRange(MonthDaysToList(10, 10 >= currentMonth ? currentYear : currentYear + 1));
            if (model.November == true) monthsToAdd.AddRange(MonthDaysToList(11, 11 >= currentMonth ? currentYear : currentYear + 1));
            if (model.December == true) monthsToAdd.AddRange(MonthDaysToList(12, 12 >= currentMonth ? currentYear : currentYear + 1));

            return monthsToAdd;
        }
        private List<string> MonthDaysToList(int month, int year)
        {
            return Enumerable.Range(1, DateTime.DaysInMonth(year, month)).Select(day => new DateTime(year, month, day).ToString("MM/dd/yyyy")).ToList();
        }
        private List<string> GetDaysToBlock(WeekDayBlockModels model)
        {
            List<string> daysToAdd = new List<string>();

            if (model.Sunday == true) daysToAdd.Add("0");
            if (model.Monday == true) daysToAdd.Add("1");
            if (model.Tuesday == true) daysToAdd.Add("2");
            if (model.Wednesday == true) daysToAdd.Add("3");
            if (model.Thursday == true) daysToAdd.Add("4");
            if (model.Friday == true) daysToAdd.Add("5");
            if (model.Saturday == true) daysToAdd.Add("6");

            return daysToAdd;
        }
        private List<string> GetDaysToBlock(List<BookingModel> model)
        {
            var dates = new List<string>();
            foreach (BookingModel b in model)
            {
                for (var d = b.StartDate; d <= b.EndDate; d = d.AddDays(1))
                {
                    dates.Add(d.ToString("MM/dd/yyyy"));
                }
            }

            return dates;
        }
        private async Task EmailUser(string subject, string body, string callBackUrlActionText, string callBackUrlText, string action, string controller, string emailEnd, string userId)
        {
            var callbackUrl = Url.Action(action, controller, null, protocol: Request.Url.Scheme);
            string FirstName;
            if (userId == "Admin")
            {
                FirstName = "Admin";
                userId = Helpers.Admin.GetAdminIds();
            }
            else
            {
                var user = db.ContactInfoModels.Find(userId);
                FirstName = user.FirstName;
            }
            var appUser = db.Users.Find(userId);
            string emailBody = $"{FirstName},<br /><br />";
            emailBody += $"{body}.";
            emailBody += $"<br /><br />{callBackUrlActionText}:";
            emailBody += "<br /><a href = '" + callbackUrl + $"'>{callBackUrlText}</a>";
            emailBody += $"<br /><br />{emailEnd}.";

            IdentityMessage message = new IdentityMessage();
            message.Body = emailBody;
            message.Destination = appUser.Email;
            message.Subject = subject;

            EmailService newEmail = new EmailService();
            await newEmail.SendAsync(message);
        }
    }
}


text:
namespace FreeRiders.Web.Areas.Administration.ViewModels
{
    using FreeRiders.Models;
    using System.Web;

    public class InputLocationModel
    {
        public string Name { get; set; }

        public double Latitude { get; set; }

        public double Longitude { get; set; }

        public string Description { get; set; }

        public int CategoryID { get; set; }

        public HttpPostedFileBase Picture { get; set; }

        public Location GetLocationForDb()
        {
            var result = new Location
            {
                Name = this.Name,
                Latitude = this.Latitude,
                Longitude = this.Longitude,
                Description = this.Description,
                CategoryID = this.CategoryID,
            };

            return result;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
            <a href="<?php  echo $this->createUrl('/home/index'); ?>">首页

<?php echo $this->pageTitle ?>

        <form class="form-search">

                <input type="text" placeholder="Search ..." class="nav-search-input" id="nav-search-input" autocomplete="off" />

        </form>


text:
require File.expand_path(File.join(File.dirname(__FILE__),'..','..','util','mongodb_md5er'))

module Puppet::Parser::Functions
  newfunction(:mongodb_password, :type => :rvalue, :doc => <<-EOS
    Returns the mongodb password hash from the clear text password.
    EOS
  ) do |args|

    raise(Puppet::ParseError, 'mongodb_password(): Wrong number of arguments ' +
      "given (#{args.size} for 2)") if args.size != 2

    Puppet::Util::MongodbMd5er.md5(args[0],args[1])
  end
end


text:
package org.apache.activemq.artemis.jdbc.store.journal;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.activemq.artemis.core.io.SequentialFileFactory;
import org.apache.activemq.artemis.core.journal.EncodingSupport;
import org.apache.activemq.artemis.core.journal.IOCompletion;
import org.apache.activemq.artemis.core.journal.Journal;
import org.apache.activemq.artemis.core.journal.JournalLoadInformation;
import org.apache.activemq.artemis.core.journal.LoaderCallback;
import org.apache.activemq.artemis.core.journal.PreparedTransactionInfo;
import org.apache.activemq.artemis.core.journal.RecordInfo;
import org.apache.activemq.artemis.core.journal.TransactionFailureCallback;
import org.apache.activemq.artemis.core.journal.impl.JournalFile;
import org.apache.derby.jdbc.AutoloadedDriver;

public class JDBCJournalImpl implements Journal {

   // Sync Delay in ms
   public static final int SYNC_DELAY = 500;

   private static int USER_VERSION = 1;

   private final String tableName;

   private Connection connection;

   private List<JDBCJournalRecord> records;

   private PreparedStatement insertJournalRecords;

   private PreparedStatement selectJournalRecords;

   private PreparedStatement countJournalRecords;

   private PreparedStatement deleteJournalRecords;

   private PreparedStatement deleteTxJournalRecords;

   private boolean started;

   private String jdbcUrl;

   private Timer syncTimer;

   private Driver dbDriver;

   private final ReadWriteLock journalLock = new ReentrantReadWriteLock();

   private boolean isDerby = false;

   public JDBCJournalImpl(String jdbcUrl, String tableName) {
      this.tableName = tableName;
      this.jdbcUrl = jdbcUrl;

      records = new ArrayList<JDBCJournalRecord>();
   }

   @Override
   public void start() throws Exception {
      // Load Database driver, sets Derby Autoloaded Driver as lowest priority.
      List<Driver> drivers = Collections.list(DriverManager.getDrivers());
      if (drivers.size() <= 2 && drivers.size() > 0) {
         dbDriver = drivers.get(0);
         isDerby = dbDriver instanceof AutoloadedDriver;

         if (drivers.size() > 1 && isDerby) {
            dbDriver = drivers.get(1);
         }

         if (isDerby) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
               @Override
               public void run() {
                  try {
                     DriverManager.getConnection("jdbc:derby:;shutdown=true");
                  }
                  catch (Exception e) {
                  }
               }
            });
         }
      }
      else {
         String error = drivers.isEmpty() ? "No DB driver found on class path" : "Too many DB drivers on class path, not sure which to use";
         throw new RuntimeException(error);
      }

      connection = dbDriver.connect(jdbcUrl, new Properties());

      // If JOURNAL table doesn't exist then create it
      ResultSet rs = connection.getMetaData().getTables(null, null, tableName, null);
      if (!rs.next()) {
         Statement statement = connection.createStatement();
         statement.executeUpdate(JDBCJournalRecord.createTableSQL(tableName));
      }

      insertJournalRecords = connection.prepareStatement(JDBCJournalRecord.insertRecordsSQL(tableName));
      selectJournalRecords = connection.prepareStatement(JDBCJournalRecord.selectRecordsSQL(tableName));
      countJournalRecords = connection.prepareStatement("SELECT COUNT(*) FROM " + tableName);
      deleteJournalRecords = connection.prepareStatement(JDBCJournalRecord.deleteRecordsSQL(tableName));
      deleteTxJournalRecords = connection.prepareStatement(JDBCJournalRecord.deleteTxRecordsSQL(tableName));

      syncTimer = new Timer();
      syncTimer.scheduleAtFixedRate(new JDBCJournalSync(this), SYNC_DELAY * 2, SYNC_DELAY);

      started = true;
   }

   @Override
   public void stop() throws Exception {
      stop(true);
   }

   public synchronized void stop(boolean shutdownConnection) throws Exception {
      if (started) {
         syncTimer.cancel();
         sync();
         if (shutdownConnection) {
            connection.close();
         }
         started = false;
      }
   }

   public synchronized void destroy() throws Exception {
      connection.setAutoCommit(false);
      Statement statement = connection.createStatement();
      statement.executeUpdate("DROP TABLE " + tableName);
      connection.commit();
      stop();
   }

   public int sync() throws SQLException {
      List<JDBCJournalRecord> recordRef = records;
      records = new ArrayList<JDBCJournalRecord>();

      for (JDBCJournalRecord record : recordRef) {
         record.storeLineUp();

         switch (record.getRecordType()) {
            case JDBCJournalRecord.DELETE_RECORD:
               record.writeDeleteRecord(deleteJournalRecords);
               break;
            case JDBCJournalRecord.DELETE_RECORD_TX:
               record.writeDeleteTxRecord(deleteTxJournalRecords);
               break;
            default:
               record.writeRecord(insertJournalRecords);
               break;
         }
      }

      boolean success = false;
      try {
         connection.setAutoCommit(false);
         insertJournalRecords.executeBatch();
         deleteJournalRecords.executeBatch();
         deleteTxJournalRecords.executeBatch();
         connection.commit();
         success = true;
      }
      catch (SQLException e) {
         connection.rollback();
         e.printStackTrace();
      }
      executeCallbacks(recordRef, success);
      return recordRef.size();
   }

   // TODO Use an executor.
   private void executeCallbacks(final List<JDBCJournalRecord> records, final boolean result) {
      Runnable r = new Runnable() {
         @Override
         public void run() {
            for (JDBCJournalRecord record : records) {
               record.complete(result);
            }
         }
      };
      Thread t = new Thread(r);
      t.start();
   }

   private void appendRecord(JDBCJournalRecord record) throws SQLException {
      try {
         journalLock.writeLock().lock();
         records.add(record);
      }
      finally {
         journalLock.writeLock().unlock();
      }
   }

   @Override
   public void appendAddRecord(long id, byte recordType, byte[] record, boolean sync) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.ADD_RECORD);
      r.setUserRecordType(recordType);
      r.setRecord(record);
      r.setSync(sync);
      appendRecord(r);
   }

   @Override
   public void appendAddRecord(long id, byte recordType, EncodingSupport record, boolean sync) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.ADD_RECORD);
      r.setUserRecordType(recordType);
      r.setRecord(record);
      r.setSync(sync);
      appendRecord(r);
   }

   @Override
   public void appendAddRecord(long id,
                               byte recordType,
                               EncodingSupport record,
                               boolean sync,
                               IOCompletion completionCallback) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.ADD_RECORD);
      r.setUserRecordType(recordType);
      r.setRecord(record);
      r.setSync(sync);
      r.setIoCompletion(completionCallback);
      appendRecord(r);
   }

   @Override
   public void appendUpdateRecord(long id, byte recordType, byte[] record, boolean sync) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.UPDATE_RECORD);
      r.setUserRecordType(recordType);
      r.setRecord(record);
      r.setSync(sync);
      appendRecord(r);
   }

   @Override
   public void appendUpdateRecord(long id, byte recordType, EncodingSupport record, boolean sync) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.UPDATE_RECORD);
      r.setUserRecordType(recordType);
      r.setRecord(record);
      r.setSync(sync);
      appendRecord(r);
   }

   @Override
   public void appendUpdateRecord(long id,
                                  byte recordType,
                                  EncodingSupport record,
                                  boolean sync,
                                  IOCompletion completionCallback) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.ADD_RECORD);
      r.setUserRecordType(recordType);
      r.setRecord(record);
      r.setSync(sync);
      r.setIoCompletion(completionCallback);
      appendRecord(r);
   }

   @Override
   public void appendDeleteRecord(long id, boolean sync) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.DELETE_RECORD);
      r.setSync(sync);
      appendRecord(r);
   }

   @Override
   public void appendDeleteRecord(long id, boolean sync, IOCompletion completionCallback) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.DELETE_RECORD);
      r.setSync(sync);
      r.setIoCompletion(completionCallback);
      appendRecord(r);
   }

   @Override
   public void appendAddRecordTransactional(long txID, long id, byte recordType, byte[] record) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.ADD_RECORD_TX);
      r.setUserRecordType(recordType);
      r.setRecord(record);
      r.setTxId(txID);
      appendRecord(r);
   }

   @Override
   public void appendAddRecordTransactional(long txID,
                                            long id,
                                            byte recordType,
                                            EncodingSupport record) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.ADD_RECORD_TX);
      r.setUserRecordType(recordType);
      r.setRecord(record);
      r.setTxId(txID);
      appendRecord(r);
   }

   @Override
   public void appendUpdateRecordTransactional(long txID, long id, byte recordType, byte[] record) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.UPDATE_RECORD_TX);
      r.setUserRecordType(recordType);
      r.setRecord(record);
      r.setTxId(txID);
      appendRecord(r);
   }

   @Override
   public void appendUpdateRecordTransactional(long txID,
                                               long id,
                                               byte recordType,
                                               EncodingSupport record) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.UPDATE_RECORD_TX);
      r.setUserRecordType(recordType);
      r.setRecord(record);
      r.setTxId(txID);
      appendRecord(r);
   }

   @Override
   public void appendDeleteRecordTransactional(long txID, long id, byte[] record) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.DELETE_RECORD_TX);
      r.setRecord(record);
      r.setTxId(txID);
      appendRecord(r);
   }

   @Override
   public void appendDeleteRecordTransactional(long txID, long id, EncodingSupport record) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.DELETE_RECORD_TX);
      r.setRecord(record);
      r.setTxId(txID);
      appendRecord(r);
   }

   @Override
   public void appendDeleteRecordTransactional(long txID, long id) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(id, JDBCJournalRecord.DELETE_RECORD_TX);
      r.setTxId(txID);
      appendRecord(r);
   }

   @Override
   public void appendCommitRecord(long txID, boolean sync) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(0, JDBCJournalRecord.COMMIT_RECORD);
      r.setTxId(txID);
      appendRecord(r);
   }

   @Override
   public void appendCommitRecord(long txID, boolean sync, IOCompletion callback) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(0, JDBCJournalRecord.COMMIT_RECORD);
      r.setTxId(txID);
      r.setIoCompletion(callback);
      appendRecord(r);
   }

   @Override
   public void appendCommitRecord(long txID,
                                  boolean sync,
                                  IOCompletion callback,
                                  boolean lineUpContext) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(0, JDBCJournalRecord.COMMIT_RECORD);
      r.setTxId(txID);
      r.setStoreLineUp(lineUpContext);
      r.setIoCompletion(callback);
      appendRecord(r);
   }

   @Override
   public void appendPrepareRecord(long txID, EncodingSupport transactionData, boolean sync) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(0, JDBCJournalRecord.PREPARE_RECORD);
      r.setTxId(txID);
      r.setTxData(transactionData);
      r.setSync(sync);
      appendRecord(r);
   }

   @Override
   public void appendPrepareRecord(long txID,
                                   EncodingSupport transactionData,
                                   boolean sync,
                                   IOCompletion callback) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(0, JDBCJournalRecord.PREPARE_RECORD);
      r.setTxId(txID);
      r.setTxData(transactionData);
      r.setSync(sync);
      r.setIoCompletion(callback);
      appendRecord(r);
   }

   @Override
   public void appendPrepareRecord(long txID, byte[] transactionData, boolean sync) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(0, JDBCJournalRecord.PREPARE_RECORD);
      r.setTxId(txID);
      r.setTxData(transactionData);
      r.setSync(sync);
      appendRecord(r);
   }

   @Override
   public void appendRollbackRecord(long txID, boolean sync) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(0, JDBCJournalRecord.ROLLBACK_RECORD);
      r.setTxId(txID);
      r.setSync(sync);
      appendRecord(r);
   }

   @Override
   public void appendRollbackRecord(long txID, boolean sync, IOCompletion callback) throws Exception {
      JDBCJournalRecord r = new JDBCJournalRecord(0, JDBCJournalRecord.PREPARE_RECORD);
      r.setTxId(txID);
      r.setSync(sync);
      r.setIoCompletion(callback);
      appendRecord(r);
   }

   @Override
   public JournalLoadInformation load(LoaderCallback reloadManager) throws Exception {
      JournalLoadInformation jli = new JournalLoadInformation();
      JDBCJournalReaderCallback jrc = new JDBCJournalReaderCallback(reloadManager);
      JDBCJournalRecord r;

      try (ResultSet rs = selectJournalRecords.executeQuery()) {
         int noRecords = 0;
         while (rs.next()) {
            r = JDBCJournalRecord.readRecord(rs);
            switch (r.getRecordType()) {
               case JDBCJournalRecord.ADD_RECORD:
                  jrc.onReadAddRecord(r.toRecordInfo());
                  break;
               case JDBCJournalRecord.UPDATE_RECORD:
                  jrc.onReadUpdateRecord(r.toRecordInfo());
                  break;
               case JDBCJournalRecord.DELETE_RECORD:
                  jrc.onReadDeleteRecord(r.getId());
                  break;
               case JDBCJournalRecord.ADD_RECORD_TX:
                  jrc.onReadAddRecordTX(r.getTxId(), r.toRecordInfo());
                  break;
               case JDBCJournalRecord.UPDATE_RECORD_TX:
                  jrc.onReadUpdateRecordTX(r.getTxId(), r.toRecordInfo());
                  break;
               case JDBCJournalRecord.DELETE_RECORD_TX:
                  jrc.onReadDeleteRecordTX(r.getTxId(), r.toRecordInfo());
                  break;
               case JDBCJournalRecord.PREPARE_RECORD:
                  jrc.onReadPrepareRecord(r.getTxId(), r.getTxDataAsByteArray(), r.getTxCheckNoRecords());
                  break;
               case JDBCJournalRecord.COMMIT_RECORD:
                  jrc.onReadCommitRecord(r.getTxId(), r.getTxCheckNoRecords());
                  break;
               case JDBCJournalRecord.ROLLBACK_RECORD:
                  jrc.onReadRollbackRecord(r.getTxId());
                  break;
               default:
                  throw new Exception("Error Reading Journal, Unknown Record Type: " + r.getRecordType());
            }
            noRecords++;
         }
         jli.setMaxID(((JDBCJournalLoaderCallback) reloadManager).getMaxId());
         jli.setNumberOfRecords(noRecords);
      }
      return jli;
   }

   @Override
   public JournalLoadInformation loadInternalOnly() throws Exception {
      return null;
   }

   @Override
   public JournalLoadInformation loadSyncOnly(JournalState state) throws Exception {
      return null;
   }

   @Override
   public void lineUpContext(IOCompletion callback) {
      callback.storeLineUp();
   }

   @Override
   public JournalLoadInformation load(List<RecordInfo> committedRecords,
                                      List<PreparedTransactionInfo> preparedTransactions,
                                      TransactionFailureCallback transactionFailure) throws Exception {
      return load(committedRecords, preparedTransactions, transactionFailure, true);
   }

   public synchronized JournalLoadInformation load(final List<RecordInfo> committedRecords,
                                                   final List<PreparedTransactionInfo> preparedTransactions,
                                                   final TransactionFailureCallback failureCallback,
                                                   final boolean fixBadTX) throws Exception {
      JDBCJournalLoaderCallback lc = new JDBCJournalLoaderCallback(committedRecords, preparedTransactions, failureCallback, fixBadTX);
      return load(lc);
   }

   @Override
   public int getAlignment() throws Exception {
      return 0;
   }

   @Override
   public int getNumberOfRecords() {
      int count = 0;
      try (ResultSet rs = countJournalRecords.executeQuery()) {
         rs.next();
         count = rs.getInt(1);
      }
      catch (SQLException e) {
         return -1;
      }
      return count;
   }

   @Override
   public int getUserVersion() {
      return USER_VERSION;
   }

   @Override
   public void perfBlast(int pages) {
   }

   @Override
   public void runDirectJournalBlast() throws Exception {
   }

   @Override
   public Map<Long, JournalFile> createFilesForBackupSync(long[] fileIds) throws Exception {
      return null;
   }

   public final void synchronizationLock() {
      journalLock.writeLock().lock();
   }

   public final void synchronizationUnlock() {
      journalLock.writeLock().unlock();
   }

   @Override
   public void forceMoveNextFile() throws Exception {
   }

   @Override
   public JournalFile[] getDataFiles() {
      return new JournalFile[0];
   }

   @Override
   public SequentialFileFactory getFileFactory() {
      return null;
   }

   @Override
   public int getFileSize() {
      return 0;
   }

   @Override
   public void scheduleCompactAndBlock(int timeout) throws Exception {

   }

   @Override
   public void replicationSyncPreserveOldFiles() {

   }

   @Override
   public void replicationSyncFinished() {

   }

   @Override
   public boolean isStarted() {
      return started;
   }

}


text:
<!DOCTYPE HTML>

Test for crbug.com/277848.

This test passes if there is a green square below with no red.


text:
//
//  NIMKitIndependentModeExtraInfo.h
//  NIMKit
//
//  Created by chris on 2017/10/10.
//  Copyright © 2017年 NetEase. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NIMKitIndependentModeExtraInfo : NSObject

/**
 *  自己的聊天室昵称
 */
@property (nonatomic,copy)    NSString *myChatroomNickname;

/**
 *  自己的聊天室头像
 */
@property (nonatomic,copy)    NSString *myChatroomAvatar;

@end


text:
package org.apache.juddi.api_v3;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

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

/**
 *
Java class for save_subscriptionInfo type.  Specific to juddi.
 *
 * @author Kurt T Stam
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "delete_clientSubscriptionInfo", propOrder = {
    "authInfo",
    "subscriptionKey"
})
public class DeleteClientSubscriptionInfo implements Serializable{

	@XmlTransient
	private static final long serialVersionUID = 8973820996268358139L;
	protected String authInfo;
    @XmlElement(required = true)
    protected List<String> subscriptionKey;

	public String getAuthInfo() {
		return authInfo;
	}
	public void setAuthInfo(String authInfo) {
		this.authInfo = authInfo;
	}
	public List<String> getSubscriptionKey() {
		if (subscriptionKey==null) {
			subscriptionKey = new ArrayList<String>();
		}
		return subscriptionKey;
	}

}


text:
#include "poses-precomp.h"	// Precompiled headers
//
#include <mrpt/math/CMatrixFixed.h>	 // for CMatrixF...
#include <mrpt/math/CQuaternion.h>	// for CQuatern...
#include <mrpt/math/distributions.h>
#include <mrpt/poses/CPose3D.h>	 // for CPose3D
#include <mrpt/poses/CPose3DQuat.h>	 // for CPose3DQuat
#include <mrpt/poses/CPose3DQuatPDF.h>	// for CPose3DQ...
#include <mrpt/poses/CPose3DQuatPDFGaussianInf.h>
#include <mrpt/random/RandomGenerators.h>  // for CRandomG...
#include <mrpt/serialization/CSerializable.h>  // for CSeriali...
#include <mrpt/serialization/stl_serialization.h>
#include <mrpt/system/os.h>	 // for fopen

#include <Eigen/Dense>
#include <algorithm>  // for move, max
#include <cstdio>  // for size_t
#include <exception>  // for exception
#include <new>	// for operator...
#include <ostream>	// for operator<<
#include <string>  // for allocator
#include <vector>  // for vector

using namespace mrpt;
using namespace mrpt::system;
using namespace mrpt::poses;
using namespace mrpt::math;
using namespace mrpt::random;
using namespace std;

IMPLEMENTS_SERIALIZABLE(CPose3DQuatPDFGaussianInf, CPose3DQuatPDF, mrpt::poses)

/** Default constructor - set all values to zero. */
CPose3DQuatPDFGaussianInf::CPose3DQuatPDFGaussianInf() : mean(), cov_inv() {}
// Un-initialized constructor:
CPose3DQuatPDFGaussianInf::CPose3DQuatPDFGaussianInf(
	[[maybe_unused]] TConstructorFlags_Quaternions constructor_dummy_param)
	: mean(UNINITIALIZED_QUATERNION), cov_inv(UNINITIALIZED_MATRIX)
{
}

/** Constructor from a default mean value, covariance equals to zero. */
CPose3DQuatPDFGaussianInf::CPose3DQuatPDFGaussianInf(
	const CPose3DQuat& init_Mean)
	: mean(init_Mean), cov_inv()
{
}

/** Constructor with mean and covariance. */
CPose3DQuatPDFGaussianInf::CPose3DQuatPDFGaussianInf(
	const CPose3DQuat& init_Mean, const CMatrixDouble77& init_CovInv)
	: mean(init_Mean), cov_inv(init_CovInv)
{
}

uint8_t CPose3DQuatPDFGaussianInf::serializeGetVersion() const { return 0; }
void CPose3DQuatPDFGaussianInf::serializeTo(
	mrpt::serialization::CArchive& out) const
{
	out << mean;

	for (int r = 0; r < cov_inv.rows(); r++)
		out << cov_inv(r, r);
	for (int r = 0; r < cov_inv.rows(); r++)
		for (int c = r + 1; c < cov_inv.cols(); c++)
			out << cov_inv(r, c);
}
void CPose3DQuatPDFGaussianInf::serializeFrom(
	mrpt::serialization::CArchive& in, uint8_t version)
{
	switch (version)
	{
		case 0:
		{
			in >> mean;

			for (int r = 0; r < cov_inv.rows(); r++)
				in >> cov_inv(r, r);
			for (int r = 0; r < cov_inv.rows(); r++)
				for (int c = r + 1; c < cov_inv.cols(); c++)
				{
					double x;
					in >> x;
					cov_inv(r, c) = cov_inv(c, r) = x;
				}
		}
		break;
		default: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version);
	};
}

void CPose3DQuatPDFGaussianInf::copyFrom(const CPose3DQuatPDF& o)
{
	if (this == &o) return;	 // It may be used sometimes

	// Convert to gaussian pdf:
	CMatrixDouble77 C(UNINITIALIZED_MATRIX);
	o.getCovarianceAndMean(C, this->mean);
	this->cov_inv = C.inverse_LLt();
}

/*---------------------------------------------------------------
					saveToTextFile
  ---------------------------------------------------------------*/
bool CPose3DQuatPDFGaussianInf::saveToTextFile(const string& file) const
{
	FILE* f = os::fopen(file.c_str(), "wt");
	if (!f) return false;

	os::fprintf(
		f, "%e %e %e %e %e %e %e\n", mean.x(), mean.y(), mean.z(),
		mean.quat()[0], mean.quat()[1], mean.quat()[2], mean.quat()[3]);

	for (unsigned int i = 0; i < 7; i++)
		os::fprintf(
			f, "%e %e %e %e %e %e %e\n", cov_inv(i, 0), cov_inv(i, 1),
			cov_inv(i, 2), cov_inv(i, 3), cov_inv(i, 4), cov_inv(i, 5),
			cov_inv(i, 6));

	os::fclose(f);
	return true;
}

/*---------------------------------------------------------------
						changeCoordinatesReference
 ---------------------------------------------------------------*/
void CPose3DQuatPDFGaussianInf::changeCoordinatesReference(
	const CPose3D& newReferenceBase)
{
	MRPT_START
	changeCoordinatesReference(CPose3DQuat(newReferenceBase));
	MRPT_END
}

/*---------------------------------------------------------------
						changeCoordinatesReference
 ---------------------------------------------------------------*/
void CPose3DQuatPDFGaussianInf::changeCoordinatesReference(
	const CPose3DQuat& newReferenceBaseQuat)
{
	MRPT_START

	// COV:
	const CMatrixDouble77 OLD_COV = this->cov_inv.inverse_LLt();

	CMatrixDouble77 df_dx(UNINITIALIZED_MATRIX), df_du(UNINITIALIZED_MATRIX);

	CPose3DQuatPDF::jacobiansPoseComposition(
		newReferenceBaseQuat,  // x
		this->mean,	 // u
		df_dx, df_du,
		&this->mean	 // Output:  newReferenceBaseQuat + this->mean;
	);

	// this->cov = H1*this->cov*H1' + H2*Ap.cov*H2';
	// df_dx: not used, since its COV are all zeros...

	this->cov_inv = mrpt::math::multiply_HCHt(df_du, OLD_COV).inverse_LLt();

	MRPT_END
}

/*---------------------------------------------------------------
					drawSingleSample
 ---------------------------------------------------------------*/
void CPose3DQuatPDFGaussianInf::drawSingleSample(CPose3DQuat& outPart) const
{
	MRPT_START
	const CMatrixDouble77 COV = this->cov_inv.inverse_LLt();

	getRandomGenerator().drawGaussianMultivariate(outPart, COV, &mean);
	MRPT_END
}

/*---------------------------------------------------------------
					drawManySamples
 ---------------------------------------------------------------*/
void CPose3DQuatPDFGaussianInf::drawManySamples(
	size_t N, vector<CVectorDouble>& outSamples) const
{
	MRPT_START
	const CMatrixDouble77 COV = this->cov_inv.inverse_LLt();

	getRandomGenerator().drawGaussianMultivariateMany(outSamples, N, COV);

	for (auto& outSample : outSamples)
		for (unsigned int k = 0; k < 7; k++)
			outSample[k] += mean[k];

	MRPT_END
}

/*---------------------------------------------------------------
					inverse
 ---------------------------------------------------------------*/
void CPose3DQuatPDFGaussianInf::inverse(CPose3DQuatPDF& o) const
{
	ASSERT_(o.GetRuntimeClass() == CLASS_ID(CPose3DQuatPDFGaussianInf));
	auto& out = dynamic_cast<CPose3DQuatPDFGaussianInf&>(o);

	// COV:
	CMatrixFixed<double, 3, 7> df_dpose(UNINITIALIZED_MATRIX);
	double lx, ly, lz;
	mean.inverseComposePoint(0, 0, 0, lx, ly, lz, nullptr, &df_dpose);

	CMatrixFixed<double, 7, 7> jacob;
	jacob.insertMatrix(0, 0, df_dpose);
	jacob(3, 3) = 1;
	jacob(4, 4) = -1;
	jacob(5, 5) = -1;
	jacob(6, 6) = -1;

	// C(0:2,0:2): H C H^t
	const CMatrixDouble77 COV = this->cov_inv.inverse_LLt();
	out.cov_inv = mrpt::math::multiply_HCHt(jacob, COV).inverse_LLt();

	// Mean:
	out.mean.x(lx);
	out.mean.y(ly);
	out.mean.z(lz);
	this->mean.quat().conj(out.mean.quat());
}

/*---------------------------------------------------------------
							+=
 ---------------------------------------------------------------*/
void CPose3DQuatPDFGaussianInf::operator+=(const CPose3DQuat& Ap)
{
	// COV:
	const CMatrixDouble77 OLD_COV = this->cov_inv.inverse_LLt();

	CMatrixDouble77 df_dx(UNINITIALIZED_MATRIX), df_du(UNINITIALIZED_MATRIX);

	CPose3DQuatPDF::jacobiansPoseComposition(
		this->mean,	 // x
		Ap,	 // u
		df_dx, df_du,
		&this->mean	 // Output: this->mean + Ap;
	);

	// this->cov = H1*this->cov*H1' + H2*Ap.cov*H2';
	this->cov_inv = mrpt::math::multiply_HCHt(df_dx, OLD_COV).inverse_LLt();
	// df_du: Nothing to do, since COV(Ap) = zeros
}

/*---------------------------------------------------------------
							+=
 ---------------------------------------------------------------*/
void CPose3DQuatPDFGaussianInf::operator+=(const CPose3DQuatPDFGaussianInf& Ap)
{
	// COV:
	const CMatrixDouble77 OLD_COV = this->cov_inv.inverse_LLt();

	CMatrixDouble77 df_dx(UNINITIALIZED_MATRIX), df_du(UNINITIALIZED_MATRIX);

	CPose3DQuatPDF::jacobiansPoseComposition(
		this->mean,	 // x
		Ap.mean,  // u
		df_dx, df_du,
		&this->mean	 // Output:  this->mean + Ap.mean;
	);

	// this->cov = H1*this->cov*H1' + H2*Ap.cov*H2';
	const CMatrixDouble77 Ap_cov = Ap.cov_inv.inverse_LLt();
	CMatrixDouble77 NEW_COV = mrpt::math::multiply_HCHt(df_dx, OLD_COV) +
		mrpt::math::multiply_HCHt(df_du, Ap_cov);

	this->cov_inv = NEW_COV.inverse_LLt();
}

/*---------------------------------------------------------------
							-=
 ---------------------------------------------------------------*/
void CPose3DQuatPDFGaussianInf::operator-=(const CPose3DQuatPDFGaussianInf& Ap)
{
	// THIS = THIS (-) Ap             -->
	// THIS = inverse(Ap) (+) THIS
	CPose3DQuatPDFGaussianInf inv_Ap = -Ap;
	*this = inv_Ap + *this;
}

/*---------------------------------------------------------------
						evaluatePDF
 ---------------------------------------------------------------*/
double CPose3DQuatPDFGaussianInf::evaluatePDF(const CPose3DQuat& x) const
{
	return mrpt::math::normalPDFInf(
		CMatrixDouble71(x), CMatrixDouble71(this->mean), this->cov_inv);
}

/*---------------------------------------------------------------
						evaluateNormalizedPDF
 ---------------------------------------------------------------*/
double CPose3DQuatPDFGaussianInf::evaluateNormalizedPDF(
	const CPose3DQuat& x) const
{
	return mrpt::math::normalPDFInf(
		CMatrixDouble71(x), CMatrixDouble71(this->mean), this->cov_inv, true);
}

/*---------------------------------------------------------------
						operator <<
 ---------------------------------------------------------------*/
ostream& mrpt::poses::operator<<(
	ostream& out, const CPose3DQuatPDFGaussianInf& obj)
{
	out << "Mean: " << obj.mean << "\n";
	out << "Information:\n" << obj.cov_inv << "\n";
	return out;
}

bool mrpt::poses::operator==(
	const CPose3DQuatPDFGaussianInf& p1, const CPose3DQuatPDFGaussianInf& p2)
{
	return p1.mean == p2.mean && p1.cov_inv == p2.cov_inv;
}

/** Pose composition for two 3D pose Gaussians  \sa
 * CPose3DQuatPDFGaussianInf::operator += */
CPose3DQuatPDFGaussianInf mrpt::poses::operator+(
	const CPose3DQuatPDFGaussianInf& x, const CPose3DQuatPDFGaussianInf& u)
{
	CPose3DQuatPDFGaussianInf res(x);
	res += u;
	return res;
}

/** Inverse pose composition for two 3D pose Gaussians  \sa
 * CPose3DQuatPDFGaussianInf::operator -= */
CPose3DQuatPDFGaussianInf mrpt::poses::operator-(
	const CPose3DQuatPDFGaussianInf& x, const CPose3DQuatPDFGaussianInf& u)
{
	CPose3DQuatPDFGaussianInf res(x);
	res -= u;
	return res;
}


text:
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGPolygonElement
       (js_getPoints, getPoints, js_getAnimatedPoints, getAnimatedPoints,
        SVGPolygonElement, castToSVGPolygonElement, gTypeSVGPolygonElement)
       where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums

foreign import javascript unsafe "$1[\"points\"]" js_getPoints ::
        SVGPolygonElement -> IO (Nullable SVGPointList)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPolygonElement.points Mozilla SVGPolygonElement.points documentation>
getPoints ::
          (MonadIO m) => SVGPolygonElement -> m (Maybe SVGPointList)
getPoints self = liftIO (nullableToMaybe <$> (js_getPoints (self)))

foreign import javascript unsafe "$1[\"animatedPoints\"]"
        js_getAnimatedPoints ::
        SVGPolygonElement -> IO (Nullable SVGPointList)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPolygonElement.animatedPoints Mozilla SVGPolygonElement.animatedPoints documentation>
getAnimatedPoints ::
                  (MonadIO m) => SVGPolygonElement -> m (Maybe SVGPointList)
getAnimatedPoints self
  = liftIO (nullableToMaybe <$> (js_getAnimatedPoints (self)))


text:
CREATE VIEW [dbo].[AssetRegisterView2014] AS
SELECT
	[AssetRegisterIconFin2014].*,
	AssetRegisterIconMove.Asset_Barcode_Nr,
	AssetRegisterIconMove.Room_Barcode_Nr,
	AssetRegisterIconMove.Room_Number,
	AssetRegisterIconMove.Building_Name,
	AssetRegisterIconMove.Serial_Number,
	AssetRegisterIconMove.Fleet_Number,
	AssetRegisterIconMove.Fleet_Reg_Year,
	AssetRegisterIconMove.Treasury_Code,
	AssetRegisterIconMove.Cost_Centre,
	AssetRegisterIconMove.Acquisition_Date,
	AssetRegisterIconMove.Floor
FROM
	[AssetRegisterIconFin2014]
LEFT JOIN
	AssetRegisterIconMove ON [AssetRegisterIconFin2014].ComponentID = AssetRegisterIconMove.ComponentID;


text:
var async = require('async');
var gracenode = require('gracenode');
var logger = gracenode.log.create('socket-request-hook');
var hookMapper = require('./mapper');
var hookMapList = [];

module.exports.addHooks = function (hooks) {
	hookMapList.push(hookMapper.map(hooks));
	logger.verbose('request hook mapped and added to hook map list:', hookMapList);
};

module.exports.exec = function (req, request, response, methodFunc) {
	var hook = hookMapper.find(hookMapList, req);
	if (hook) {
		execHook(hook, req, request, response, methodFunc);
		return true;
	}
	return false;
};

function execHook(hookList, req, request, response, methodFunc) {
	var count = 0;
	var endPoint = req.endPoint;
	logger.verbose('request hook found for (endPoint:' + endPoint + ')');
	async.eachSeries(hookList, function (hook, next) {
		hook(request, function (error, status) {
			status = status || 400;
			count += 1;
			if (error) {
				logger.error('request hook #' + count + ' executed with an error (endPoint:' + endPoint + '):', '(connection-id:' + req.id + ')', '(status:' + status + ')');
				return response.error(error.message, error.message, status);
			}
			logger.verbose('request hook #' + count + ' successfully executed (endPoint:' + endPoint + ')', '(connection-id:' + req.id + ')');
			next();
		});
	},
	function () {
		methodFunc(request, response);
	});
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
<TITLE> FreeCMS - 公开源码、免费使用、代码通俗易懂、注释详细、面向二次开发友好,致力于打造更好的中国开源免费CMS!</TITLE>
<META content="text/html; charset=utf-8" http-equiv=Content-Type><LINK
title="Main stylesheet" rel=stylesheet type=text/css
href="/site/FreeCMS/resources/css/site.css"
media=all>

要点

动态

关于

许可证

常见问题解答

维基

讨论

功能演示

单位

工具类

评论

网上调查

系统配置

信件

依申请公开

用户

在线申报

留言

图片集

招聘

自定义标签

下载

下载

源代码

获得支持

服务支持

解决方案

参与

Bug报告

贡献源码

加入FreeTeam

其它

捐赠

发表留言

<form name="guestbookForm" method="post"
action="/guestbook_save.do?siteid=7a4d22d6-762b-46e5-895b-d62da52bf9cb&templetPath=guestbook/guestbookSave.html"
onsubmit="return validata(this);">
<input type="hidden" name="guestbook.siteid" value="7a4d22d6-762b-46e5-895b-d62da52bf9cb"/>

              姓名:

              <input id="name" name="guestbook.name" type="text" class="ysqgk_box2" />
                *

              性别:

              <input type="radio" name="guestbook.sex" value="1" checked>男
              <input type="radio" name="guestbook.sex" value="0">女
              *

              电子邮箱:

              <input name="guestbook.email" id="email" type="text" class="ysqgk_box2" />

              QQ:

              <input name="guestbook.qq" id="qq" type="text" class="ysqgk_box2" />

              联系电话:
              <input name="guestbook.tel" id="tel" type="text" class="ysqgk_box1" />
                *

              标题:

              <input name="guestbook.title" id="title" type="text" class="ysqgk_box2" />
                *

              留言内容:

              <textarea name="guestbook.content" id="content" cols="30" rows="5"></textarea>
                (500字以内)*

              验证码:

              <input type="text" id="validatecode" name="validatecode" class="jzxx_yzm" size=10 maxlength="4" >

              <input type="submit" name="Submit" value="提交留言" />
                <input type="reset" name="Submit2" value="重 置" />

          </form>

Copyright © 2013 FreeTeam


text:
<?php

namespace Magento\Catalog\Test\TestStep;

use Magento\Mtf\Client\BrowserInterface;
use Magento\Mtf\TestStep\TestStepInterface;

/**
 * Open products on frontend via url.
 */
class OpenProductsOnFrontendStep implements TestStepInterface
{
    /**
     * Products fixtures.
     *
     * @var array
     */
    protected $products = [];

    /**
     * Browser.
     *
     * @var BrowserInterface
     */
    protected $browser;

    /**
     * Preparing step properties.
     *
     * @constructor
     * @param array $products
     * @param BrowserInterface $browser
     */
    public function __construct(array $products, BrowserInterface $browser)
    {
        $this->products = $products;
        $this->browser = $browser;
    }

    /**
     * Open products on frontend via url.
     *
     * @return void
     */
    public function run()
    {
        foreach ($this->products as $product) {
            $this->browser->open($_ENV['app_frontend_url'] . $product->getUrlKey() . '.html');
        }
    }
}


text:
<!doctype html>
<html>
  <head>
	<meta charset="utf-8">
	<title>Add to Firebase tree</title>
	<script src="https://cdn.firebase.com/js/client/2.1.2/firebase.js"></script>
  </head>

  <body>
    Password: <input type="password" id="guestPassword"><br>
    <input type="button" value="Add to tree" id="action">
    <script src="tree.js"></script>

	<script>

document.getElementById("action").addEventListener('click', function(event) {
  var firebase = new Firebase("https://dazona.firebaseio.com");

  var authData = firebase.getAuth();

  if (authData) {
    console.log("Welcome back " + authData.password.email);
  }

  var password = document.getElementById("guestPassword").value;
  console.log(password);

  firebase.authWithPassword({
    email: "guest@dazona.com",
    password: password
  }, function(err, authData) {
    if (err) {
      console.log("Login failed", err);
    } else {
      console.log("Authenticated ", authData);
      var firebaseAccountList = firebase.child("eucalyptus/accountList");
      var accountList = null;
      firebaseAccountList.once("value", function(snapshot) {
        accountList = snapshot.val();
        console.log(JSON.stringify(accountList));

        var clientTree = new AccountTree("accounts");
        clientTree.accounts = accountList;

        console.log(clientTree.flatten());

        try {
          clientTree.addAccount("rest", "Restaurants", "expenses");
          firebaseAccountList.set(clientTree.accounts);
        } catch (e) {
          console.log("cannot add juros: " + e);
        }

        try {
          clientTree.addAccount("mtnwest", "Mountain West", "bank");
          firebaseAccountList.set(clientTree.accounts);
        } catch (e) {
          console.log("cannot add mtnwest: " + e);
        }

      }, function(err) {
        console.log("Read account list failed: " + err.code);
      });
    }
  });
});

	</script>
  </body>
</html>


text:
package com.qumasoft.qvcslib;

/**
 * Types of promotions that we can support.
 *
 * @author Jim Voris
 */
public enum PromotionType {

    /** Simple merge. */
    SIMPLE_PROMOTION_TYPE,                              // 000 -- no rename or move, create or delete.
    /** The files have different names. */
    FILE_NAME_CHANGE_PROMOTION_TYPE,                    // 001 -- files have different names.
    /** The files are in different locations. */
    FILE_LOCATION_CHANGE_PROMOTION_TYPE,                // 010 -- files have different locations.
    /** The files have different names, and are in different locations. */
    LOCATION_AND_NAME_DIFFER_PROMOTION_TYPE,            // 011 -- location and name differ.
    /** The file was created on the branch. */
    FILE_CREATED_PROMOTION_TYPE,                        // file created on branch.
    /** An existing file was deleted on the branch. */
    FILE_DELETED_PROMOTION_TYPE,                        // an existing file was deleted on branch.
    /** Unknown merge. */
    UNKNOWN_PROMOTION_TYPE
}


text:
namespace zen {

    export class ScriptComponentSystem extends System {

        update(deltaTime:number) {
            for(let key in this._components) {
                let script = this._components[key] as ScriptComponent;
                script.enabled && script.update(this._app, deltaTime);
            }
        }

    }

}


text:
> More info about max aggregation is in the [official elasticsearch docs][1]

A single-value metrics aggregation that keeps track and returns the
maximum value among the numeric values extracted from the aggregated documents.

## Simple example

```JSON
{
    "aggregations" : {
        "max_price" : { "max" : { "field" : "price" } }
    }
}
```

And now the query via DSL:

```php
$maxAggregation = new MaxAggregation('max_price', 'price');

$search = new Search();
$search->addAggregation($maxAggregation);

$queryArray = $search->toArray();
```

[1]: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-max-aggregation.html


text:
  <meta charset="utf-8"/>
  <title>About JapKatsuyou</title>
  <meta name="author" content="Karim" />
  <meta name="date" content="2016/05/27 17:30:49" />
  <meta name="email" content="kariminfo0@gmail.com"/>
  <meta name="copyright" content="http://creativecommons.org/licenses/by-sa/3.0/"/>
  <meta name="language" content="english"/>

JapKatsuyou

JapKatsuyou is a free open source application used for Japanese verb conjugation.

It is destined for Japanese language learners, in the hope that it will simplify conjugation task.

It can be used, also, to simplify making sentences for advanced learners, since it contains some complex forms.

JapKatsuyou features

The application can afford the following features:

Search for the existence of a verb, using its dictionary form. Eg. 食べる, 飲む, 行く, etc.

If the verb is found, shows its type. Eg. 食べる: ichidan verb.

The verbs' database contains nouns which are used with the auxiliary verb "する". Eg. 勉強する, 選択する, 連絡する, etc.

The user interface is translated into four languages: Arabic, English, French, and Japanese.

The conjugation tables can be exported to three formats: pdf, odt, and htm.

Version 2 features:

Showing examples for verbs.

More preferences: fonts and icons.

Presenting furigana and romaji for new learners.

JapKatsuyou License

Copyright 2013-2016 AnqaFalak group

Copyright 2013 Abdelkrime Aries
(kariminfo0@gmail.com)

Licensed under
GNU GPLv3
or later

    This program 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
    any later version.

    This program 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 this program.  If not, see
    http://www.gnu.org/licenses/.

Legal information

Code

The code of this software is licensed under

Apache version 2

Source

Third party

This software uses other materials:

Edict2

Used to verify the existence of verbs.

Copyright: Jim Breen
and the EDRDG group

Licensed under
CC-BY-SA-3.0

Source

Tatoeba examples

Used to afford examples in different languages.

Copyright: tatoeba.org

Licensed under
CC-BY-2.0

Source

KIcona

Used for application's icons.

Copyright: Abdelkrime Aries

Licensed under
CC-BY-SA-3.0

Source


text:
"""
Copyright (c) 2018, MpicoSys
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

__copyright__ = "Copyright (C) MpicoSys-Embedded Pico Systems"
__author__ = "Andrzej Majchrzak <andrzej.majchrzak@mpicosys.com>"
__version__ = "1.0"

from PIL import Image
import cStringIO
import sys, getopt
import os
import os.path

class TCM2133:
    """
    Class used to convert images TCM2
    """
    __tc__ = "TCM2-E133-320"
    filename_prefix = "E133_"
    filename_sufix = "_1bit"

    def __init__(self):
        self.imagedata = None

    def get_epd_header(self):
        # EPD file format
        return b'\x3E\x06\x40\x04\xB0\x01\x00'+('\x00'*9)

    def __convert(self, img):
        (img_width, img_height) = img.size
        assert img_width == 1600
        assert img_height == 1200

        img=img.convert('P')
        imgnew = img
        palette = []
        for i in range(256):
            p=0xFF
            if i>0:
                p=0x00
            palette.extend((p, p, p))
        assert len(palette) == 768
        imgnew.putpalette(palette)
        newstr=imgnew.convert('1').tobytes()

        return newstr

    def load_image_from_string(self, str):
        # save string as IO
        src = cStringIO.StringIO()
        src.write(str)
        src.seek(0)

        img = Image.open(src)
        self.imagedata = self.__convert(img)

    def load_image(self, src):
        # Open file
        img = Image.open(src)

        self.imagedata = self.__convert(img)

    def load_image_from_pil(self, obj):
        self.imagedata = self.__convert(obj)

"""
Convert image to EPD file.
Command line usage: TCM2-E133_1bit.py -i <inputfile>
"""
def main(argv):
    inputfile = ''
    outputfile = ''
    try:
        opts, args = getopt.getopt(argv,"hi:",["ifile="])
    except getopt.GetoptError:
        print 'TCM2-E133_1bit.py -i <inputfile>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'TCM2-E133_1bit.py -i <inputfile>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg

    if not inputfile:
        print 'usage: TCM2-E133_1bit.py -i <inputfile>'
        sys.exit(2)

    print 'Input file is ', inputfile

    if not os.path.isfile(inputfile):
        print "Input filename is not pointing to an existing location!"
        sys.exit(2)

    tcm = TCM2133()
    (head_fname, tail_fname) = os.path.split(inputfile)
    tail_fname = tail_fname.split('.')[0]
    outputfile = os.path.join(head_fname, tcm.filename_prefix
                              +tail_fname+tcm.filename_sufix+".epd")

    print 'Output file is ', outputfile, ' + .dlz'

    tcm.load_image(inputfile)

    fil = open(outputfile, 'w+b')
    fil.seek(0)
    fil.write(tcm.get_epd_header())
    fil.write(tcm.imagedata)
    fil.close()

    os.system("bcl_tcm.exe c lz "+outputfile+" "+outputfile[:-4]+".dlz")
    #now remove 12bytes long BCL header
    f = open(outputfile[:-4]+".dlz", 'rb')
    compressed = f.read()
    f.close()
    f = open(outputfile[:-4]+".dlz", 'wb')
    f.write(compressed[12:])
    f.close()

if __name__ == "__main__":
   main(sys.argv[1:])


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

#nullable enable

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Remote;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Remote
{
    internal class JsonRpcConnection : RemoteHostClient.Connection
    {
        private readonly Workspace _workspace;

        // communication channel related to service information
        private readonly RemoteEndPoint _serviceEndPoint;

        // communication channel related to snapshot information
        private readonly ReferenceCountedDisposable<RemotableDataJsonRpc> _remoteDataRpc;

        public JsonRpcConnection(
            Workspace workspace,
            TraceSource logger,
            object? callbackTarget,
            Stream serviceStream,
            ReferenceCountedDisposable<RemotableDataJsonRpc> dataRpc)
        {
            Contract.ThrowIfNull(dataRpc);

            _workspace = workspace;
            _remoteDataRpc = dataRpc;
            _serviceEndPoint = new RemoteEndPoint(serviceStream, logger, callbackTarget);
            _serviceEndPoint.UnexpectedExceptionThrown += UnexpectedExceptionThrown;
            _serviceEndPoint.StartListening();
        }

        private void UnexpectedExceptionThrown(Exception exception)
            => RemoteHostCrashInfoBar.ShowInfoBar(_workspace, exception);

        public override Task InvokeAsync(string targetName, IReadOnlyList<object?> arguments, CancellationToken cancellationToken)
            => _serviceEndPoint.InvokeAsync(targetName, arguments, cancellationToken);

        public override Task<T> InvokeAsync<T>(string targetName, IReadOnlyList<object?> arguments, CancellationToken cancellationToken)
            => _serviceEndPoint.InvokeAsync<T>(targetName, arguments, cancellationToken);

        public override Task<T> InvokeAsync<T>(string targetName, IReadOnlyList<object?> arguments, Func<Stream, CancellationToken, Task<T>> dataReader, CancellationToken cancellationToken)
            => _serviceEndPoint.InvokeAsync(targetName, arguments, dataReader, cancellationToken);

        protected override void DisposeImpl()
        {
            // dispose service and snapshot channels
            _serviceEndPoint.UnexpectedExceptionThrown -= UnexpectedExceptionThrown;
            _serviceEndPoint.Dispose();
            _remoteDataRpc.Dispose();

            base.DisposeImpl();
        }
    }
}


text:
namespace v8 {
namespace internal {

class StringHtmlBuiltinsFromDSLAssembler {
 public:
  explicit StringHtmlBuiltinsFromDSLAssembler(compiler::CodeAssemblerState* state) : state_(state), ca_(state) { USE(state_, ca_); }
 private:
  compiler::CodeAssemblerState* const state_;
  compiler::CodeAssembler ca_;
};

}  // namespace internal
}  // namespace v8

#endif  // V8_TORQUE_STRING_HTML_FROM_DSL_BASE_H__


text:
@implementation NSTimer (HQExtension)

-(void)hq_pauseTimer {

    if (![self isValid]) {
        return ;
    }
    [self setFireDate:[NSDate distantFuture]];
}

-(void)hq_resumeTimer {

    if (![self isValid]) {
        return ;
    }
    [self setFireDate:[NSDate date]];
}

- (void)hq_resumeTimerAfterTimeInterval:(NSTimeInterval)interval {

    if (![self isValid]) {
        return ;
    }
    [self setFireDate:[NSDate dateWithTimeIntervalSinceNow:interval]];
}

@end


text:
require 'rubygems'
gem 'test-unit'
require 'test/unit'
require 'mocha'
require 'active_support'
require 'active_record'
require 'active_support/test_case'
require 'shoulda'
require File.join(File.dirname(__FILE__), "..", 'lib', 'txter')

# default test configuration
Txter.configure do |config|
  config.client_id  = '1'
  config.client_key = 'ABCDEF'
  config.gateway    = 'test'
end

Txter.mode = :test
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
ActiveRecord::Base.establish_connection(config[ENV['DB'] || 'sqlite3'])

ActiveRecord::Schema.define(:version => 1) do
  create_table :users do |t|
    t.column :sms_phone_number,           :string
    t.column :sms_confirmed_phone_number, :string
    t.column :sms_blocked,                :boolean
    t.column :sms_confirmation_attempted, :datetime
    t.column :sms_confirmation_code,      :string

    t.column :type, :string
  end
end

class User < ActiveRecord::Base
  include Txter::Contactable
end

# kill all network access
module Txter
  class Request
    def start
      raise "You forgot to stub out your net requests!"
    end
  end
end


text:
package com.easyapp.ble.connect.listener;

import android.bluetooth.BluetoothGattCharacteristic;

/**
 * Created by dingjikerbo on 2016/8/25.
 */
public interface ReadCharacterListener extends GattResponseListener {
    void onCharacteristicRead(BluetoothGattCharacteristic characteristic, int status, byte[] value);
}


text:
/**
 * Parametricke vyhledavani pro administraci.
 *
 * @param {Object} $scope
 * @param {Object} config
 * @param {UrlFilter} filter
 * @param {$location} $location
 */

function FormFilter($scope, config, filter, $location) {
  this._$scope = $scope;
  this._$location = $location;
  this._filter = filter;
  this._limit = config.limit || 10;
  this._orderColumns  = config.orderColumns || [];
  this._filterColumns = config.filterColumns || [];
  this._querySearch  = Boolean(config.querySearch);
  this._init();
}

/**
 * Uvodni inicializace dat podle defaultniho nastaveni a
 * podle hodnot z URL (pokud jiz nejake filtrovani probehlo).
 *
 */

FormFilter.prototype._init = function() {
  this._offset = this.filter().getOffset();
  this._$scope.limit  = this._filter.getLimit();
  this._$scope.page   = this._filter.getPage();
  if (this._querySearch) {
    this._$scope.query  = this._filter.getParam('query');
  }
  for (var i = 0; i < this._filterColumns.length; ++i) {
    this._$scope[this._filterColumns[i]] = this._filter.getFilterParamAsString(this._filterColumns[i], '');
  }
};

/**
 * Projde formular filtrovani a prevede jejich hodnoty do retezece,
 * který se pak bude zasilat na API v parametru query.
 *
 * Napr. formular vypada takto:
 *   <form>
 *     <input ng-model="price">
 *     <input ng-model="vat">
 *   </form>
 *
 * Po zavolani metody serialize() bude vracen tento retezec
 * (pro price = 1000 a vat = 20): price:1000@vat:20
 *
 *
 * @return {String}
 */

FormFilter.prototype.serialize = function() {
  var values = [];
  for (var i = 0; i < this._filterColumns.length; ++i) {
    if (this._$scope[this._filterColumns[i]]) {
      values.push(this._filterColumns[i] + ':' + this._$scope[this._filterColumns[i]]);
    }
  }
  return values.join('@');
};

/**
 * Po zmene formulare pro filtrovani provede aktualizaci URL.
 */

FormFilter.prototype.updateUrl = function() {
  var query = this.getApiData();
  this._$location.search({
    offset: query.offset,
    limit: query.limit,
    filter: query.filter,
    query: query.query,
    order: query.order
  });
};

/**
 * Vrati vsechny data pro dotaz na API.
 *
 * @return {Object}
 */

FormFilter.prototype.getApiData = function() {
  var query = {};
  query.offset = this.getOffset();
  query.query  = this._$scope.query || '';
  query.limit  = this._$scope.limit;
  query.filter = this.serialize();
  query.order  = this.filter().getOrder();
  return query;
};

/**
 * @return {Number}
 */

FormFilter.prototype.getOffset = function() {
  return this._offset || 0;
};

/**
 * @param {Number} offset
 */

FormFilter.prototype.setOffset = function(offset) {
  this._offset = offset;
};

/**
 * @return {FormFilter}
 */

FormFilter.prototype.filter = function() {
  return this._filter;
};


text:
from typing import List
from urllib.parse import quote

from pandas_profiling.config import Settings
from pandas_profiling.model.alerts import AlertType
from pandas_profiling.report.formatters import (
    fmt,
    fmt_bytesize,
    fmt_number,
    fmt_numeric,
    fmt_percent,
    fmt_timespan,
)
from pandas_profiling.report.presentation.core import Alerts, Container, Table
from pandas_profiling.report.presentation.core.renderable import Renderable

def get_dataset_overview(config: Settings, summary: dict) -> Renderable:
    table_metrics = [
        {
            "name": "Number of variables",
            "value": fmt_number(summary["table"]["n_var"]),
        },
        {
            "name": "Number of observations",
            "value": fmt_number(summary["table"]["n"]),
        },
        {
            "name": "Missing cells",
            "value": fmt_number(summary["table"]["n_cells_missing"]),
        },
        {
            "name": "Missing cells (%)",
            "value": fmt_percent(summary["table"]["p_cells_missing"]),
        },
    ]
    if "n_duplicates" in summary["table"]:
        table_metrics.extend(
            [
                {
                    "name": "Duplicate rows",
                    "value": fmt_number(summary["table"]["n_duplicates"]),
                },
                {
                    "name": "Duplicate rows (%)",
                    "value": fmt_percent(summary["table"]["p_duplicates"]),
                },
            ]
        )

    table_metrics.extend(
        [
            {
                "name": "Total size in memory",
                "value": fmt_bytesize(summary["table"]["memory_size"]),
            },
            {
                "name": "Average record size in memory",
                "value": fmt_bytesize(summary["table"]["record_size"]),
            },
        ]
    )

    dataset_info = Table(
        table_metrics,
        name="Dataset statistics",
    )

    dataset_types = Table(
        [
            {
                "name": str(type_name),
                "value": fmt_numeric(count, precision=config.report.precision),
            }
            for type_name, count in summary["table"]["types"].items()
        ],
        name="Variable types",
    )

    return Container(
        [dataset_info, dataset_types],
        anchor_id="dataset_overview",
        name="Overview",
        sequence_type="grid",
    )

def get_dataset_schema(metadata: dict) -> Container:
    about_dataset = []
    for key in ["description", "creator", "author"]:
        if key in metadata and len(metadata[key]) > 0:
            about_dataset.append(
                {"name": key.capitalize(), "value": fmt(metadata[key])}
            )

    if "url" in metadata:
        about_dataset.append(
            {
                "name": "URL",
                "value": f'{metadata["url"]}',
            }
        )

    if "copyright_holder" in metadata and len(metadata["copyright_holder"]) > 0:
        if "copyright_year" not in metadata:
            about_dataset.append(
                {
                    "name": "Copyright",
                    "value": fmt(f"(c) {metadata['copyright_holder']}"),
                }
            )
        else:
            about_dataset.append(
                {
                    "name": "Copyright",
                    "value": fmt(
                        f"(c) {metadata['copyright_holder']} {metadata['copyright_year']}"
                    ),
                }
            )

    return Container(
        [Table(about_dataset, name="Dataset", anchor_id="metadata_dataset")],
        name="Dataset",
        anchor_id="dataset",
        sequence_type="grid",
    )

def get_dataset_reproduction(summary: dict) -> Renderable:
    version = summary["package"]["pandas_profiling_version"]
    config = quote(summary["package"]["pandas_profiling_config"])
    date_start = summary["analysis"]["date_start"]
    date_end = summary["analysis"]["date_end"]
    duration = summary["analysis"]["duration"]

    reproduction_table = Table(
        [
            {"name": "Analysis started", "value": fmt(date_start)},
            {"name": "Analysis finished", "value": fmt(date_end)},
            {"name": "Duration", "value": fmt_timespan(duration)},
            {
                "name": "Software version",
                "value": f'pandas-profiling v{version}',
            },
            {
                "name": "Download configuration",
                "value": f'config.json',
            },
        ],
        name="Reproduction",
        anchor_id="overview_reproduction",
    )

    return Container(
        [reproduction_table],
        name="Reproduction",
        anchor_id="reproduction",
        sequence_type="grid",
    )

def get_dataset_column_definitions(definitions: dict) -> Container:
    """Generate an overview section for the variable description

    Args:
        definitions: the variable descriptions.

    Returns:
        A container object
    """

    variable_descriptions = [
        Table(
            [
                {"name": column, "value": fmt(value)}
                for column, value in definitions.items()
            ],
            name="Variable descriptions",
            anchor_id="variable_definition_table",
        )
    ]

    return Container(
        variable_descriptions,
        name="Variables",
        anchor_id="variable_descriptions",
        sequence_type="grid",
    )

def get_dataset_alerts(alerts: list) -> Alerts:
    count = len([alert for alert in alerts if alert.alert_type != AlertType.REJECTED])
    return Alerts(alerts=alerts, name=f"Alerts ({count})", anchor_id="alerts")

def get_dataset_items(config: Settings, summary: dict, alerts: list) -> list:
    """Returns the dataset overview (at the top of the report)

    Args:
        summary: the calculated summary
        alerts: the alerts

    Returns:
        A list with components for the dataset overview (overview, reproduction, alerts)
    """

    items: List[Renderable] = [get_dataset_overview(config, summary)]

    metadata = {key: config.dataset.dict()[key] for key in config.dataset.dict().keys()}

    if len(metadata) > 0 and any(len(value) > 0 for value in metadata.values()):
        items.append(get_dataset_schema(metadata))

    column_details = {
        key: config.variables.descriptions[key]
        for key in config.variables.descriptions.keys()
    }

    if len(column_details) > 0:
        items.append(get_dataset_column_definitions(column_details))

    if alerts:
        items.append(get_dataset_alerts(alerts))

    items.append(get_dataset_reproduction(summary))

    return items


text:
"""autogenerated by genpy from outdoor_bot/mainTargets_serviceRequest.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct

class mainTargets_serviceRequest(genpy.Message):
  _md5sum = "90fff5866c31f9caf1d5f5e7d43f49c1"
  _type = "outdoor_bot/mainTargets_serviceRequest"
  _has_header = False #flag to mark the presence of a Header object
  _full_text = """string image_filename
float32 approxRange
bool firstTarget

"""
  __slots__ = ['image_filename','approxRange','firstTarget']
  _slot_types = ['string','float32','bool']

  def __init__(self, *args, **kwds):
    """
    Constructor. Any message fields that are implicitly/explicitly
    set to None will be assigned a default value. The recommend
    use is keyword arguments as this is more robust to future message
    changes.  You cannot mix in-order arguments and keyword arguments.

    The available fields are:
       image_filename,approxRange,firstTarget

    :param args: complete set of field values, in .msg order
    :param kwds: use keyword arguments corresponding to message field names
    to set specific fields.
    """
    if args or kwds:
      super(mainTargets_serviceRequest, self).__init__(*args, **kwds)
      #message fields cannot be None, assign default values for those that are
      if self.image_filename is None:
        self.image_filename = ''
      if self.approxRange is None:
        self.approxRange = 0.
      if self.firstTarget is None:
        self.firstTarget = False
    else:
      self.image_filename = ''
      self.approxRange = 0.
      self.firstTarget = False

  def _get_types(self):
    """
    internal API method
    """
    return self._slot_types

  def serialize(self, buff):
    """
    serialize message into buffer
    :param buff: buffer, ``StringIO``
    """
    try:
      _x = self.image_filename
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      if python3:
        buff.write(struct.pack('<I%sB'%length, length, *_x))
      else:
        buff.write(struct.pack('<I%ss'%length, length, _x))
      _x = self
      buff.write(_struct_fB.pack(_x.approxRange, _x.firstTarget))
    except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
    except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))

  def deserialize(self, str):
    """
    unpack serialized message in str into this message instance
    :param str: byte array of serialized message, ``str``
    """
    try:
      end = 0
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.image_filename = str[start:end].decode('utf-8')
      else:
        self.image_filename = str[start:end]
      _x = self
      start = end
      end += 5
      (_x.approxRange, _x.firstTarget,) = _struct_fB.unpack(str[start:end])
      self.firstTarget = bool(self.firstTarget)
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

  def serialize_numpy(self, buff, numpy):
    """
    serialize message with numpy array types into buffer
    :param buff: buffer, ``StringIO``
    :param numpy: numpy python module
    """
    try:
      _x = self.image_filename
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      if python3:
        buff.write(struct.pack('<I%sB'%length, length, *_x))
      else:
        buff.write(struct.pack('<I%ss'%length, length, _x))
      _x = self
      buff.write(_struct_fB.pack(_x.approxRange, _x.firstTarget))
    except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
    except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))

  def deserialize_numpy(self, str, numpy):
    """
    unpack serialized message in str into this message instance using numpy for array types
    :param str: byte array of serialized message, ``str``
    :param numpy: numpy python module
    """
    try:
      end = 0
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.image_filename = str[start:end].decode('utf-8')
      else:
        self.image_filename = str[start:end]
      _x = self
      start = end
      end += 5
      (_x.approxRange, _x.firstTarget,) = _struct_fB.unpack(str[start:end])
      self.firstTarget = bool(self.firstTarget)
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

_struct_I = genpy.struct_I
_struct_fB = struct.Struct("<fB")
"""autogenerated by genpy from outdoor_bot/mainTargets_serviceResponse.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct

class mainTargets_serviceResponse(genpy.Message):
  _md5sum = "30b2d42be8045e43ef370b1aad370871"
  _type = "outdoor_bot/mainTargets_serviceResponse"
  _has_header = False #flag to mark the presence of a Header object
  _full_text = """int32 centerX
int32 centerY
int32 totalX
float32 rangeSquared
bool newDigcamImageReceived
bool newWebcamImageReceived

"""
  __slots__ = ['centerX','centerY','totalX','rangeSquared','newDigcamImageReceived','newWebcamImageReceived']
  _slot_types = ['int32','int32','int32','float32','bool','bool']

  def __init__(self, *args, **kwds):
    """
    Constructor. Any message fields that are implicitly/explicitly
    set to None will be assigned a default value. The recommend
    use is keyword arguments as this is more robust to future message
    changes.  You cannot mix in-order arguments and keyword arguments.

    The available fields are:
       centerX,centerY,totalX,rangeSquared,newDigcamImageReceived,newWebcamImageReceived

    :param args: complete set of field values, in .msg order
    :param kwds: use keyword arguments corresponding to message field names
    to set specific fields.
    """
    if args or kwds:
      super(mainTargets_serviceResponse, self).__init__(*args, **kwds)
      #message fields cannot be None, assign default values for those that are
      if self.centerX is None:
        self.centerX = 0
      if self.centerY is None:
        self.centerY = 0
      if self.totalX is None:
        self.totalX = 0
      if self.rangeSquared is None:
        self.rangeSquared = 0.
      if self.newDigcamImageReceived is None:
        self.newDigcamImageReceived = False
      if self.newWebcamImageReceived is None:
        self.newWebcamImageReceived = False
    else:
      self.centerX = 0
      self.centerY = 0
      self.totalX = 0
      self.rangeSquared = 0.
      self.newDigcamImageReceived = False
      self.newWebcamImageReceived = False

  def _get_types(self):
    """
    internal API method
    """
    return self._slot_types

  def serialize(self, buff):
    """
    serialize message into buffer
    :param buff: buffer, ``StringIO``
    """
    try:
      _x = self
      buff.write(_struct_3if2B.pack(_x.centerX, _x.centerY, _x.totalX, _x.rangeSquared, _x.newDigcamImageReceived, _x.newWebcamImageReceived))
    except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
    except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))

  def deserialize(self, str):
    """
    unpack serialized message in str into this message instance
    :param str: byte array of serialized message, ``str``
    """
    try:
      end = 0
      _x = self
      start = end
      end += 18
      (_x.centerX, _x.centerY, _x.totalX, _x.rangeSquared, _x.newDigcamImageReceived, _x.newWebcamImageReceived,) = _struct_3if2B.unpack(str[start:end])
      self.newDigcamImageReceived = bool(self.newDigcamImageReceived)
      self.newWebcamImageReceived = bool(self.newWebcamImageReceived)
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

  def serialize_numpy(self, buff, numpy):
    """
    serialize message with numpy array types into buffer
    :param buff: buffer, ``StringIO``
    :param numpy: numpy python module
    """
    try:
      _x = self
      buff.write(_struct_3if2B.pack(_x.centerX, _x.centerY, _x.totalX, _x.rangeSquared, _x.newDigcamImageReceived, _x.newWebcamImageReceived))
    except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
    except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))

  def deserialize_numpy(self, str, numpy):
    """
    unpack serialized message in str into this message instance using numpy for array types
    :param str: byte array of serialized message, ``str``
    :param numpy: numpy python module
    """
    try:
      end = 0
      _x = self
      start = end
      end += 18
      (_x.centerX, _x.centerY, _x.totalX, _x.rangeSquared, _x.newDigcamImageReceived, _x.newWebcamImageReceived,) = _struct_3if2B.unpack(str[start:end])
      self.newDigcamImageReceived = bool(self.newDigcamImageReceived)
      self.newWebcamImageReceived = bool(self.newWebcamImageReceived)
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

_struct_I = genpy.struct_I
_struct_3if2B = struct.Struct("<3if2B")
class mainTargets_service(object):
  _type          = 'outdoor_bot/mainTargets_service'
  _md5sum = '98f192b83a39359c19fd1f5bbe2ac28f'
  _request_class  = mainTargets_serviceRequest
  _response_class = mainTargets_serviceResponse


text:
#include <linux/kernel.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>

#include <asm/octeon/octeon.h>

static struct map_info flash_map;
static struct mtd_info *mymtd;
static int nr_parts;
static struct mtd_partition *parts;
static const char *part_probe_types[] = {
	"cmdlinepart",
#ifdef CONFIG_MTD_REDBOOT_PARTS
	"RedBoot",
#endif
	NULL
};

/**
 * Module/ driver initialization.
 *
 * Returns Zero on success
 */
static int __init flash_init(void)
{
	/*
	 * Read the bootbus region 0 setup to determine the base
	 * address of the flash.
	 */
	union cvmx_mio_boot_reg_cfgx region_cfg;
	region_cfg.u64 = cvmx_read_csr(CVMX_MIO_BOOT_REG_CFGX(0));
	if (region_cfg.s.en) {
		/*
		 * The bootloader always takes the flash and sets its
		 * address so the entire flash fits below
		 * 0x1fc00000. This way the flash aliases to
		 * 0x1fc00000 for booting. Software can access the
		 * full flash at the true address, while core boot can
		 * access 4MB.
		 */
		/* Use this name so old part lines work */
		flash_map.name = "phys_mapped_flash";
		flash_map.phys = region_cfg.s.base << 16;
		flash_map.size = 0x1fc00000 - flash_map.phys;
		flash_map.bankwidth = 1;
		flash_map.virt = ioremap(flash_map.phys, flash_map.size);
		pr_notice("Bootbus flash: Setting flash for %luMB flash at "
			  "0x%08llx\n", flash_map.size >> 20, flash_map.phys);
		simple_map_init(&flash_map);
		mymtd = do_map_probe("cfi_probe", &flash_map);
		if (mymtd) {
			mymtd->owner = THIS_MODULE;

			nr_parts = parse_mtd_partitions(mymtd,
							part_probe_types,
							&parts, 0);
			mtd_device_register(mymtd, parts, nr_parts);
		} else {
			pr_err("Failed to register MTD device for flash\n");
		}
	}
	return 0;
}

late_initcall(flash_init);