text:
package org.elasticsearch.search.aggregations.bucket.terms;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.util.SetBackedScalingCuckooFilter;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;

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

/**
 * Result of the RareTerms aggregation when the field is some kind of whole number like a integer, long, or a date.
 */
public class LongRareTerms extends InternalMappedRareTerms<LongRareTerms, LongRareTerms.Bucket> {
    public static final String NAME = "lrareterms";

    public static class Bucket extends InternalRareTerms.Bucket<Bucket> {
        long term;

        public Bucket(long term, long docCount, InternalAggregations aggregations, DocValueFormat format) {
            super(docCount, aggregations, format);
            this.term = term;
        }

        /**
         * Read from a stream.
         */
        public Bucket(StreamInput in, DocValueFormat format) throws IOException {
            super(in, format);
            term = in.readLong();
        }

        @Override
        protected void writeTermTo(StreamOutput out) throws IOException {
            out.writeLong(term);
        }

        @Override
        public String getKeyAsString() {
            return format.format(term).toString();
        }

        @Override
        public Object getKey() {
            return term;
        }

        @Override
        public Number getKeyAsNumber() {
            return term;
        }

        @Override
        public int compareKey(Bucket other) {
            return Long.compare(term, other.term);
        }

        @Override
        protected final XContentBuilder keyToXContent(XContentBuilder builder) throws IOException {
            builder.field(CommonFields.KEY.getPreferredName(), term);
            if (format != DocValueFormat.RAW) {
                builder.field(CommonFields.KEY_AS_STRING.getPreferredName(), format.format(term).toString());
            }
            return builder;
        }

        @Override
        public boolean equals(Object obj) {
            return super.equals(obj) && Objects.equals(term, ((Bucket) obj).term);
        }

        @Override
        public int hashCode() {
            return Objects.hash(super.hashCode(), term);
        }
    }

    LongRareTerms(String name, BucketOrder order, List<PipelineAggregator> pipelineAggregators,
                  Map<String, Object> metaData, DocValueFormat format,
                  List<LongRareTerms.Bucket> buckets, long maxDocCount, SetBackedScalingCuckooFilter filter) {
        super(name, order, pipelineAggregators, metaData, format, buckets, maxDocCount, filter);
    }

    /**
     * Read from a stream.
     */
    public LongRareTerms(StreamInput in) throws IOException {
        super(in, LongRareTerms.Bucket::new);
    }

    @Override
    public String getWriteableName() {
        return NAME;
    }

    @Override
    public LongRareTerms create(List<LongRareTerms.Bucket> buckets) {
        return new LongRareTerms(name, order, pipelineAggregators(), metaData, format, buckets, maxDocCount, filter);
    }

    @Override
    public LongRareTerms.Bucket createBucket(InternalAggregations aggregations, LongRareTerms.Bucket prototype) {
        return new LongRareTerms.Bucket(prototype.term, prototype.getDocCount(), aggregations, prototype.format);
    }

    @Override
    protected LongRareTerms createWithFilter(String name, List<LongRareTerms.Bucket> buckets, SetBackedScalingCuckooFilter filter) {
        return new LongRareTerms(name, order, pipelineAggregators(), getMetaData(), format,
            buckets, maxDocCount, filter);
    }

    @Override
    protected LongRareTerms.Bucket[] createBucketsArray(int size) {
        return new LongRareTerms.Bucket[size];
    }

    @Override
    public boolean containsTerm(SetBackedScalingCuckooFilter filter, LongRareTerms.Bucket bucket) {
        return filter.mightContain((long) bucket.getKey());
    }

    @Override
    public void addToFilter(SetBackedScalingCuckooFilter filter, LongRareTerms.Bucket bucket) {
        filter.add((long) bucket.getKey());
    }

    @Override
    Bucket createBucket(long docCount, InternalAggregations aggs, LongRareTerms.Bucket prototype) {
        return new Bucket(prototype.term, docCount, aggs, format);
    }
}


text:
/*
 * volleyball-dataset-mgr.cpp
 *
 *  Created on: Nov 28, 2015
 *      Author: msibrahi
 */

#include "volleyball-dataset-mgr.h"

#include <boost/filesystem.hpp>
namespace bst_fs = boost::filesystem;

#include "utilities.h"
#include "images-utilities.h"

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>

namespace MostCV {

map<string, int> global_video_id_frame_id_to_activityId;
map<string, vector<VolleyballPerson> > global_video_id_frame_id_to_persons;

map<string, int> persons_actions_ids_map;
map<string, int> scene_activities_ids_map;

// statistics
map<string, int> scene_activities_freq_map;
map<string, int> players_activities_freq_map;

VolleyballVideoData::VolleyballVideoData(string video_id, string video_dir) {
  MostCV::fixDir(video_dir);

  video_id_ = video_id;
  video_dir_ = video_dir;

  string annot_file = video_dir + "annotations.txt";
  vector<vector<string> > data2dVec = MostCV::read2dFileItems(annot_file, string(""), false);

  // For every frame, read the players in it
  for (auto frame_data : data2dVec) {
    VolleyballPerson person;

    string frame_id = frame_data[0];

    GetFramePath(frame_id); // verify on hard disk

    frame_data.erase(frame_data.begin());

   // if (frame_data[0].find("win") == string::npos)
   //   continue;

    scene_activities_freq_map[ frame_data[0] ]++;

    int frame_activity_id = MostCV::UpdateStringIdMap(scene_activities_ids_map, frame_data[0]);
    annot_frame_id_to_activity_id_map_[frame_id] = frame_activity_id;
    frame_data.erase(frame_data.begin());

    pair<int, int> min_max_persons_y = { 10000, 0 };

    for (int k = 0; k < (int) frame_data.size(); k += 5) {
      int x = MostCV::toType(frame_data[k + 0], 0);
      int y = MostCV::toType(frame_data[k + 1], 0);
      int w = MostCV::toType(frame_data[k + 2], 0);
      int h = MostCV::toType(frame_data[k + 3], 0);
      string activity_str = frame_data[k + 4];

      players_activities_freq_map[activity_str]++;

      min_max_persons_y.first = std::min(min_max_persons_y.first, y);
      min_max_persons_y.second = std::max(min_max_persons_y.second, y + h);

      person.bbox_ = RectHelper(Rect(x, y, w, h));
      person.action_id_ = MostCV::UpdateStringIdMap(persons_actions_ids_map, activity_str);

      annot_frame_id_persons_map_[frame_id].push_back(person);
    }

    if (min_max_persons_y.first < 0)
      min_max_persons_y.first = 0;

    annot_frame_id_to_min_max_persons_y_map_[frame_id] = min_max_persons_y;
    annot_frame_id_vec_.push_back(frame_id);

    string video_id_frame_id = video_id + "#"+frame_id;

    global_video_id_frame_id_to_activityId[video_id_frame_id] = frame_activity_id;
    global_video_id_frame_id_to_persons[video_id_frame_id] = annot_frame_id_persons_map_[frame_id];

    if (annot_frame_id_persons_map_[frame_id].size() < 7)
    {
    	cerr<<"video "<<video_id_frame_id<<" frame id "<<frame_id
    	    <<" has "<<annot_frame_id_persons_map_[frame_id].size()<<" persons\n";
    }

    if (annot_frame_id_persons_map_[frame_id].size() > 12)
        {
          cerr<<"video "<<video_id_frame_id<<" frame id "<<frame_id
              <<" has "<<annot_frame_id_persons_map_[frame_id].size()<<" persons!!\n";
        }
  }

  SortPersonsPerFrames();

  cerr << video_id_ << " is processed\n";
}

void VolleyballVideoData::SortPersonsPerFrames() {
  // Sorting the persons based on top left point: x first, if tie, y first. Kind of left-to-right sweeping
  for (auto &frame_persons_kv : annot_frame_id_persons_map_) {
    vector<VolleyballPerson> &persons = frame_persons_kv.second;

    sort(persons.begin(), persons.end(), [](const VolleyballPerson &a, const VolleyballPerson &b)
    {
      if(a.bbox_.r.x != b.bbox_.r.x)
      return a.bbox_.r.x < b.bbox_.r.x;
      return a.bbox_.r.y < b.bbox_.r.y;
    });
  }
}

void VolleyballVideoData::ResetPersons(string img_name, vector<RectHelper> rects) {
  annot_frame_id_persons_map_[img_name].clear();

  for (auto rect : rects) {
    VolleyballPerson person;

    person.bbox_ = rect;
    person.action_id_ = 0;

    annot_frame_id_persons_map_[img_name].push_back(person);
  }
}

vector<RectHelper> VolleyballVideoData::GetPersonsRect(string frame_id) {
  vector<RectHelper> rects;

  for (auto person : annot_frame_id_persons_map_[frame_id])
    rects.push_back(person.bbox_);

  return rects;
}

// Short Util
string VolleyballVideoData::GetFramePath(string frame_id, int shift) {
  string frame_id_no_ext = frame_id.substr(0, frame_id.find_first_of('.'));
  string ext = frame_id.substr(frame_id.find_first_of('.'));
  string target_frame_id = MostCV::toIntStr(frame_id_no_ext, shift, false);
  string frame_new_path = video_dir_ + frame_id_no_ext + MostCV::PATH_SEP + target_frame_id + ext;

  assert(boost::filesystem::exists(frame_new_path));

  return frame_new_path;
}

pair<vector<string>, vector<string> > VolleyballVideoData::GetTemporalWindowPaths(string frame_id, int temporal_window, int step, bool is_use_expend_factor) {
  vector<string> window_frames_after;
  vector<string> window_frames_before;

  if (is_use_expend_factor)
    temporal_window = 2 * temporal_window + 1;

  LP(w, 1+temporal_window/2)
  {
    string path = GetFramePath(frame_id, -w * step);
    window_frames_before.push_back(path);
  }

  LP(w, (temporal_window+1)/2)
  {
    string path = GetFramePath(frame_id, w * step);
    window_frames_after.push_back(path);
  }

  return {window_frames_before, window_frames_after};
}

vector<string> VolleyballVideoData::GetTemporalWindowPathsMerged(string frame_id, int temporal_window, int step) {
  vector<string> paths;

  int start = -temporal_window/2;

  LP(w, temporal_window)
  {
    string path = GetFramePath(frame_id, start * step);
    paths.push_back(path);
    ++start;
  }
  return paths;
}

void VolleyballVideoData::visualize()
{
  for (auto frame_id : annot_frame_id_vec_)
  {
    string path = GetFramePath(frame_id);
    Mat img = cv::imread(path);

    cerr<<video_id_<<" "<<frame_id<<" "<<path<<"\n";
    RectHelper::DrawRects(img, GetPersonsRect(frame_id));
  }
}

//---------------------------------------------------------------

VolleyballDatasetPart::VolleyballDatasetPart(string dataset_name, string config_file, string videos_root_dir) {

  cerr << "Preparing Dataset: " << dataset_name << "\n\tfrom config file: " << config_file << "\n";

  assert(MostCV::IsPathExist(config_file));

  MostCV::fixDir(videos_root_dir);
  ids_ = MostCV::readFileItems(config_file, string(""), false);
  dataset_name_ = dataset_name;

  for (auto video_seq : ids_)
	  videos_vec_.push_back(VolleyballVideoData(video_seq, videos_root_dir + video_seq));

  cerr << "\n\n************************\n\n";
}

void VolleyballDatasetPart::ReorderVideos(vector<string> video_ids) {
  for (int i = 0; i < (int) video_ids.size(); ++i) {
    for (int j = 0; j < (int) ids_.size(); ++j) {
      if (video_ids[i] != ids_[j])
        continue;
      std::swap(ids_[i], ids_[j]);
      std::swap(videos_vec_[i], videos_vec_[j]);
    }
  }
}

vector<pair<VolleyballVideoData, int> > VolleyballDatasetPart::GetVideoFrameList(bool is_shuffled, int subset_percent) {
  vector<pair<VolleyballVideoData, int> > database_shuffled;

  return database_shuffled;

  boost::mt19937 generator(100);
  boost::uniform_int<> uni_dist;
  boost::variate_generator<boost::mt19937&, boost::uniform_int<> > rand_generator(generator, uni_dist);

  vector<int> labels;

  for (auto video : videos_vec_) {
    int frame_pos = -1;

    for (auto frame_id : video.annot_frame_id_vec_) {
      ++frame_pos;

      database_shuffled.push_back(std::make_pair(video, frame_pos));
    }
  }

  if (is_shuffled) {
    cerr << "Before: Total Shuffled Elements: " << database_shuffled.size() << " with 1st video" << database_shuffled.begin()->first.video_id_ << "\n";

    std::random_shuffle(database_shuffled.begin(), database_shuffled.end(), rand_generator);

    cerr << "After: Total Shuffled Elements: " << database_shuffled.size() << " with 1st video" << database_shuffled.begin()->first.video_id_ << "\n";
  }

  int max_size = subset_percent * database_shuffled.size();
  database_shuffled.resize(max_size);

  return database_shuffled;
}

void VolleyballDatasetPart::visualize()
{
  for (auto video : videos_vec_)
    video.visualize();
}

//---------------------------------------------------------------

VolleyballDatasetMgr::VolleyballDatasetMgr(string config_dir_path, string videos_root_dir) {
  MostCV::fixDir(config_dir_path);

  dataset_division_.push_back(VolleyballDatasetPart("train", config_dir_path + "train.txt", videos_root_dir));
  dataset_division_.push_back(VolleyballDatasetPart("val", config_dir_path + "val.txt", videos_root_dir));
  dataset_division_.push_back(VolleyballDatasetPart("test", config_dir_path + "test.txt", videos_root_dir));
  dataset_division_.push_back(VolleyballDatasetPart("trainval", config_dir_path + "trainval.txt", videos_root_dir));

  total_videos_ = 0;
  total_frames_ = 0;

  // Remove empty datasets
  for (int i = 0; i < (int) dataset_division_.size(); ++i) {
    if (dataset_division_[i].videos_vec_.size() == 0) {
      cerr << dataset_division_[i].dataset_name_ << " dataset is EMPTY\n";

      dataset_division_.erase(dataset_division_.begin() + i);
      --i;
    }
  }

  assert(dataset_division_.size() > 0);

  for (auto dataset : dataset_division_) {
    int current_fames = 0;

    for (auto video : dataset.videos_vec_) {
      total_frames_ += video.annot_frame_id_vec_.size();
      current_fames += video.annot_frame_id_vec_.size();
    }
    cerr << "Total frames for dataset " << dataset.dataset_name_ << " = " << current_fames << "\n";

    total_videos_ += dataset.videos_vec_.size();
  }

  total_scene_labels = scene_activities_ids_map.size();
  total_persons_labels = persons_actions_ids_map.size();

  cerr << "\nTotal videos = " << total_videos_ << " - total frames = " << total_frames_ << "\n";

  cerr << "\nScenes Labels:\n";
  for (auto scene_kv : scene_activities_ids_map)
    cerr << "\t" << scene_kv.first << " " << scene_kv.second << "\n";

  cerr << "\nPersons Labels:\n";
  for (auto persons_kv : persons_actions_ids_map)
    cerr << "\t" << persons_kv.first << " " << persons_kv.second << "\n";

  cerr << "\nScenes Labels frequency:\n";
  for (auto entry : scene_activities_freq_map)
    cerr << "\t" << entry.first << " " << entry.second << "\n";

  cerr << "\nPlayers Labels frequency:\n";
  for (auto entry : players_activities_freq_map)
    cerr << "\t" << entry.first << " " << entry.second << "\n";
}

int VolleyballDatasetMgr::GetActivityId(string video_id, string frame_id)
{
  string video_id_frame_id = video_id + "#"+frame_id;

 if (global_video_id_frame_id_to_activityId.count(video_id_frame_id) == 0)
 {
   cerr<<"problem with "<<video_id_frame_id<<"\n\n";
   return -1;
 }

  assert( global_video_id_frame_id_to_activityId.count(video_id_frame_id) );

  return global_video_id_frame_id_to_activityId[video_id_frame_id];
}

vector<VolleyballPerson> VolleyballDatasetMgr::GetPersons(string video_id, string frame_id)
{
  string video_id_frame_id = video_id + "#"+frame_id;

  assert( global_video_id_frame_id_to_persons.count(video_id_frame_id) );

  return global_video_id_frame_id_to_persons[video_id_frame_id];

}

// verify 2*w+1 elements..e.g. centered around every frame
void VolleyballDatasetMgr::VerifyDataAvailbility(int temporal_window)
{
  for (auto dataset : dataset_division_) {
    cerr<<"Verifying dataset: "<<dataset.dataset_db_name_<<"\n";
    for (auto video : dataset.videos_vec_) {
      for (auto frame_id : video.annot_frame_id_vec_) {
        video.GetTemporalWindowPaths(frame_id, temporal_window, 1, true);
      }
    }
  }
}

}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

//Articles service used for articles REST endpoint
angular.module('mean.admin').factory('EventTickets', ['$resource',
    function($resource) {
        return $resource('event-tickets/:eventTicketId', {
            eventTicketId: '@_id'
        }, {
            update: {
                method: 'PUT'
            }
        });
    }
]);


text:
Simple Tic Tac Toe

![Video Walkthrough](demo.gif)

## To test

	rake install
	irb
	require "tictactoe"
	Tictactoe.start

- Tape "help" during the game to show you the different possible movements
- You can let the computer play with himself

## TODO

- Improve test coverage
- Try to replace the element of the board with the user object or empty string (" ")
- Move the Board#start method into a new class to simplify the code

## Installation

Add this line to your application's Gemfile:

    gem 'tictactoe'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install tictactoe

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package com.spotify.helios.cli;

import static ch.qos.logback.classic.Level.ALL;
import static ch.qos.logback.classic.Level.DEBUG;
import static ch.qos.logback.classic.Level.INFO;
import static ch.qos.logback.classic.Level.WARN;
import static com.google.common.collect.Iterables.get;
import static java.util.Arrays.asList;
import static org.slf4j.Logger.ROOT_LOGGER_NAME;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.spotify.helios.common.LoggingConfig;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import org.slf4j.LoggerFactory;

/**
 * Instantiates and runs helios CLI.
 */
public class CliMain {

  private final CliParser parser;
  private final PrintStream out;
  private final PrintStream err;

  @SuppressWarnings("UseOfSystemOutOrSystemErr")
  public static void main(final String... args) {
    try {
      final int exitCode = new CliMain(System.out, System.err, args).run();
      System.exit(exitCode);
    } catch (Throwable e) {
      // don't print error message for arg parser exception, because parser will do that
      if (!(e instanceof ArgumentParserException)) {
        System.err.println(e.toString());
      }
      System.exit(1);
    }
  }

  public CliMain(final PrintStream out, final PrintStream err, final String... args)
      throws Exception {
    this.parser = new CliParser(args);
    this.out = out;
    this.err = err;
    setupLogging();
  }

  public int run() {
    try {
      final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
      return parser.getCommand().run(parser.getNamespace(), parser.getTargets(), out, err,
                                     parser.getUsername(), parser.getJson(), stdin);
    } catch (Exception e) {
      // print entire stack trace in verbose mode, otherwise just the exception message
      if (parser.getNamespace().getInt("verbose") > 0) {
        e.printStackTrace(err);
      } else {
        err.println(e.getMessage());
      }
      return 1;
    }
  }

  private void setupLogging() {
    final LoggingConfig config = parser.getLoggingConfig();
    if (config.getNoLogSetup()) {
      return;
    }
    final int verbose = config.getVerbosity();
    final Level level = get(asList(WARN, INFO, DEBUG, ALL), verbose, ALL);
    final Logger rootLogger = (Logger) LoggerFactory.getLogger(ROOT_LOGGER_NAME);
    rootLogger.setLevel(level);
  }
}


text:
package gov.hhs.fha.nhinc.docsubmission._20.nhin.deferred.request;

import gov.hhs.fha.nhinc.aspect.InboundMessageEvent;
import gov.hhs.fha.nhinc.docsubmission.aspect.DocSubmissionBaseEventDescriptionBuilder;
import gov.hhs.fha.nhinc.docsubmission.inbound.deferred.request.InboundDocSubmissionDeferredRequest;
import ihe.iti.xdr._2007.XDRDeferredRequest20PortType;
import ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;

import javax.annotation.Resource;
import javax.xml.ws.BindingType;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.soap.Addressing;

import oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;

/**
 *
 * @author JHOPPESC
 */
@BindingType(value = javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
@Addressing(enabled = true)
public class NhinXDRRequest20 implements XDRDeferredRequest20PortType {

    private WebServiceContext context;

    private InboundDocSubmissionDeferredRequest inboundDocSubmissionRequest;

    @InboundMessageEvent(serviceType = "Document Submission Deferred Request", version = "2.0",
            beforeBuilder = DocSubmissionBaseEventDescriptionBuilder.class,
            afterReturningBuilder = DocSubmissionBaseEventDescriptionBuilder.class)
    public RegistryResponseType provideAndRegisterDocumentSetBDeferredRequest(
            ProvideAndRegisterDocumentSetRequestType body) {
        return new NhinDocSubmissionDeferredRequestImpl20(inboundDocSubmissionRequest)
                .provideAndRegisterDocumentSetBRequest(body, context);
    }

    public void setInboundDocSubmissionRequest(InboundDocSubmissionDeferredRequest inboundDocSubmissionRequest) {
        this.inboundDocSubmissionRequest = inboundDocSubmissionRequest;
    }

    @Resource
    public void setContext(WebServiceContext context) {
        this.context = context;
    }

    /**
     * @return
     */
    public InboundDocSubmissionDeferredRequest getInboundDocSubmission() {
        return this.inboundDocSubmissionRequest;
    }
}


text:
`AXAttributedLabel` is a lightweight attributed text tool based on __TextKit__ using `UITextView` as structures. With `AXAttributedLabel`, you can show text content with phone/address/date as attributed text on a interacting view. You can add custom link to the _label_ and capture the actions of touch on the links. On iOS9.0 (IPhone 6s) and higher platforms, you can interact with links using __Peek__ and __Pop__ to preview the content of links.

[![sample2](http://ww1.sinaimg.cn/large/d2297bd2gw1f6hhddhg0mg20ac0iju0x.gif)](http://ww1.sinaimg.cn/large/d2297bd2gw1f6hhddhg0mg20ac0iju0x.gif)

## Features
> Data detection supported.
>
> __Peek__&__Pop__ to preview the links.
>
> Insert any images into text content.
>
> Long press to show menu and customize the edit menu.
>
> Added customizable links.

## Requirements

`AXAttributedLabel` used on iOS 7.0 and higher version system of IPhone. It needs:

>* Foundation.framework
>* UIKit.framework

You best use the __newest__ version of xcode when you use the label to your projects.

## Adding AXAttributedLabel to your projet
### CocoaPods
[CocoaPods](http://cocoapods.org) is the recommended way to add AXAttributedLabel to your project.

1. Add a pod entry for AXAttributedLabel to your Podfile `pod 'AXAttributedLabel', '~> 0.2.9'`
2. Install the pod(s) by running `pod install`.
3. Include AXPopoverView wherever you need it with `#import "AXAttributedLabel.h"`.

### Source files

Alternatively you can directly add the `AXAttributedLabel.h` and `AXAttributedLabel.m`  source files to your project.

1. Download the [latest code version](https://github.com/devedbox/AXAttributedLabel/archive/master.zip) or add the repository as a git submodule to your git-tracked project.
2. Open your project in Xcode, then drag and drop `AXAttributedLabel.h` and `AXAttributedLabel.m` onto your project (use the "Product Navigator view"). Make sure to select Copy items when asked if you extracted the code archive outside of your project.
3. Include AXAttributedLabel wherever you need it with `#import "AXAttributedLabel.h"`.

## License

This code is distributed under the terms and conditions of the [MIT license](LICENSE).

## Usage

`AXAttributedLabel` is simple to use just like `UILabel` or `UITextView`. Before you use it, make sure you initialize correctly like:
```objective-c
_label = [AXAttributedLabel attributedLabel];
_label.translatesAutoresizingMaskIntoConstraints = NO;
_label.attribute = self;
_label.text = @"Multiple availability att[sss]ributes can be placed on a declaration, which may correspond to different platforms. Only the availability attr[sss]ibute with the platform[sss] correcorre 明天 sponding to the target pla[sss]tform will be used. https://www.baidu.com the availability 15680002585 any others wil[sss]l be ignored. If no 成都市成华区二仙桥东三路1号 availability attribute specifies availability for the cu[sss]rrent target platform, the a[sss]vailability attributes are ignored.";
```
And make sure `_label.attributedEnabled = NO;` is setted. `attributedEnabled` controls the detection of data. Default is `YES` to detect data and not to if it's `NO`.
### Set data detector
Like this:
```objective-c
_label.detectorTypes |= AXAttributedLabelDetectorTypeImage|AXAttributedLabelDetectorTypeLink|AXAttributedLabelDetectorTypeTransitInformation|AXAttributedLabelDetectorTypeAddress;
```
### Interact with links
If you want to interact with links. Add these codes after your initializer of `AXAttributedLabel`:
```objective-c
_label.shouldInteractWithURLs = YES;
_label.shouldInteractWithExclusionViews = YES;
```
### Preview links using __3D Touch__
Make sure you set interact enabled and add these codes:
```objective-c
_label.allowsPreviewURLs = YES;
```
This will work.
### Add images to content
Example:
```objective-c
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame)*.5-45, 45, 90, 90)];
imageView.image = [UIImage imageNamed:@"avatar.jpg"];
_label.exclusionViews = @[imageView];
```
### Add custom edit menu options
Example:
```objective-c
_label.showsMenuItems = YES;
AXMenuItem *item = [AXMenuItem itemWithTitle:@"aaa" handler:^(AXAttributedLabel * _Nonnull label, AXMenuItem * _Nonnull item) {
        NSLog(@"aaa");
    }];
AXMenuItem *item1 = [AXMenuItem itemWithTitle:@"bbb" handler:^(AXAttributedLabel * _Nonnull label, AXMenuItem * _Nonnull item) {
        NSLog(@"bbb");
    }];
AXMenuItem *item2 = [AXMenuItem itemWithTitle:@"ccc" handler:^(AXAttributedLabel * _Nonnull label, AXMenuItem * _Nonnull item) {
        NSLog(@"ccc");
    }];
AXMenuItem *item3 = [AXMenuItem itemWithTitle:@"ddd" handler:^(AXAttributedLabel * _Nonnull label, AXMenuItem * _Nonnull item) {
        NSLog(@"ddd");
    }];
AXMenuItem *item4 = [AXMenuItem itemWithTitle:@"eee" handler:^(AXAttributedLabel * _Nonnull label, AXMenuItem * _Nonnull item) {
        NSLog(@"eee");
    }];
AXMenuItem *item5 = [AXMenuItem itemWithTitle:@"fff" handler:^(AXAttributedLabel * _Nonnull label, AXMenuItem * _Nonnull item) {
        NSLog(@"fff");
    }];
AXMenuItem *item6 = [AXMenuItem itemWithTitle:@"hhh" handler:^(AXAttributedLabel * _Nonnull label, AXMenuItem * _Nonnull item) {
        NSLog(@"hhh");
    }];
[_label setMenuItems:@[item, item1, item2, item3, item4, item5, item6]];
```
Just make sure `showsMenuItems` set to `YES` first.
### Using delegate
Example:

```objective-c
#pragma mark - AXAttributedLabelDelegate
- (UIImage *)imageAttachmentForAttributedLabel:(AXAttributedLabel *)attl result:(NSTextCheckingResult *)result {
    return [UIImage imageNamed:@"avatar.jpg"];
}
- (void)attributedLabel:(AXAttributedLabel *)attributedLabel didSelectURL:(NSURL *)url {
    [AXPickerView showInView:self.view.window animated:YES style:0 items:@[url.absoluteString] title:@"打开链接?" tips:[NSString stringWithFormat:@"点击打开链接:%@", url.absoluteString] configuration:NULL completion:^(AXPickerView *pickerView) {
        pickerView.tipsLabel.textAlignment = NSTextAlignmentCenter;
    } revoking:NULL executing:^(NSString *selectedTitle, NSInteger index, AXPickerView *inPickerView) {
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }];
}
- (void)attributedLabel:(AXAttributedLabel *)attributedLabel didSelectAddress:(NSDictionary *)addressComponents {
    [AXPickerView showInView:self.view.window animated:YES style:0 items:[addressComponents allValues] title:@"地址" tips:@"显示所有地址" configuration:NULL completion:^(AXPickerView *pickerView) {
        pickerView.tipsLabel.textAlignment = NSTextAlignmentCenter;
    } revoking:NULL executing:NULL];
}
- (void)attributedLabel:(AXAttributedLabel *)attributedLabel didSelectPhoneNumber:(NSString *)phoneNumber {
    [AXPickerView showInView:self.view.window animated:YES style:0 items:@[phoneNumber] title:@"拨打电话?" tips:[NSString stringWithFormat:@"点击拨打电话:%@", phoneNumber] configuration:NULL completion:^(AXPickerView *pickerView) {
        pickerView.tipsLabel.textAlignment = NSTextAlignmentCenter;
    } revoking:NULL executing:^(NSString *selectedTitle, NSInteger index, AXPickerView *inPickerView) {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", phoneNumber]]]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", phoneNumber]]];
        }
    }];
}
- (void)attributedLabel:(AXAttributedLabel *)attributedLabel didSelectDate:(NSDate *)date {
    NSLog(@"date:%@",date);
}
- (void)attributedLabel:(AXAttributedLabel *)attributedLabel didSelectDate:(NSDate *)date timeZone:(NSTimeZone *)timeZone duration:(NSTimeInterval)duration {
    NSLog(@"date:%@",date);
}
- (void)attributedLabel:(AXAttributedLabel *)attributedLabel didSelectTransitInformation:(NSDictionary *)components {

}
- (void)attributedLabel:(AXAttributedLabel *)attributedLabel didSelectAttachment:(NSTextAttachment *)attachment {
    NSLog(@"attachment:%@",attachment);
}
- (void)attributedLabel:(AXAttributedLabel *)attributedLabel didSelectTextCheckingResult:(NSTextCheckingResult *)result {

}
- (void)attributedLabel:(AXAttributedLabel *)attributedLabel didSelectExclusionViewAtIndex:(NSUInteger)index {
    NSLog(@"selected exclusion view at index: %@", @(index));
}
```

## Contact me
If you find any bugs or require new features, please let me know:

`Wechat&Phone:15680002585`

`Weibo: @devedbox`

`GitHub: https://github.com/devedbox`

`LinkedIn:艾星`

`Email:devedbox@gmail.com`


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Tetris {
    /// It contains all of the procedures and the properties that represent the pieces of Tetris
    class Piece {
        /// It indicates the number of interface columns
        public const int nColumn = 13;

        /// It indicates the number of interface rows
        public const int nRows = 17;

        /// Class constructor
        /// <param name="interfaccia">The interface of squares on which the game is played</param>
        public Piece(Square[,] interf) {

            for (short i = 0; i < 4; i++)
                for (short j = 0; j < 4; j++) {
                    Shape[i, j] = new Square();
                    nextPiece[i, j] = new Square();
                }
            for (int i = 0; i <= nRows; i++)
                for (int j = 0; j <= nColumn; j++) {
                    gameInterface[i, j] = new Square();
                    gameInterface[i, j] = interf[i, j];
                }
            this.GetCasualPiece();//Generate the first piece
        }

        /// Indicates the number of rotation of the workpiece current
        public int CurrentRotation { get; set; }

        private Square[,] gameInterface = new Square[nRows + 1, nColumn + 1];
        /// Contains space expressed in PictureBox matrix
        public Square[,] GameInterface {
            get { return gameInterface; }
        }

        public Label X = new Label();
        /// Contains the X coordinate of the part of the game interface
        int posX {
            get { return Convert.ToInt32(X.Text); }
            set { X.Text = Convert.ToString(value); }
        }

        public Label Y = new Label();
        /// Contains the Y coordinate of the part of the game interface
        int posY {
            get { return Convert.ToInt32(Y.Text); }
            set { Y.Text = Convert.ToString(value); }
        }

        public Square[,] shape = new Square[4, 4];
        /// Contains the piece space expressed in PictureBox matrix
        public Square[,] Shape {
            get { return shape; }
            set { gameInterface = value; }
        }

        int[,] PieceCoordinate = new int[4, 2];
        /// Returns the coordinates of the squares of the piece
        public int[,] CoordinatePiece {
            get { return PieceCoordinate; }
        }

        private PieceType pieceType;
        /// It returns a value that indicates the type of piece generated
        public PieceType PieceType {
            get { return pieceType; }
        }

        /// It returns a Boolean value that indicates whether the part can rotate
        /// <param name="x">The vertical position of the workpiece in the interface</param>
        /// <param name="y">The horizontal position of the workpiece in the interface</param>
        private bool CanRotate(int x, int y) {
            Square[,] temp = new Square[4, 4];

            for (int i = 0; i < 4; i++)
                for (int j = 0; j < 4; j++) {
                    temp[j, 3 - i] = new Square();
                    temp[j, 3 - i].IsOccuped = Shape[i, j].IsOccuped;
                }

            for (int i = 0; i < 4; i++)
                for (int j = 0; j < 4; j++) {
                    try {
                        /*Check if rotating the piece overlaps the wall: if it happens it returns false*/
                        if ((temp[i, j].IsOccuped == Occuped.Yes ||
                            temp[i, j].IsOccuped == Occuped.No) &&
                            Shape[i, j].IsOccuped == Occuped.No &&
                            GameInterface[x + i, y + j].IsOccuped == Occuped.Yes) {
                            return false;
                        }
                    } catch {
                        /*If it returns an exception (index out of the matrix) means that turning the piece comes from the interface,
                         * then it returns false, indicating that the component can not run*/
                        return false;
                    }
                }
            return true;
        }

        /// Rotates the part to the right in a clockwise direction
        public void CanRotate() {
            if (posX >= 0 && CanRotate(posX, posY) == true) {
                this.CurrentRotation++;
                if (this.CurrentRotation == 4) this.CurrentRotation = 0;
                if (CurrentRotation == 3 && this.PieceType == PieceType.T) {
                    for (int i = StartX; i <= EndX; i++)
                        for (int j = CoordinatePiece[i, 0]; j <= CoordinatePiece[i, 1]; j++) {
                            GameInterface[posX + i, posY + j].IsOccuped = Occuped.No;
                            Shape[i, j].IsOccuped = Occuped.No;
                        }

                    GameInterface[posX + 0, posY + 0].IsOccuped = Occuped.Yes;
                    GameInterface[posX + 0, posY + 1].IsOccuped = Occuped.Yes;
                    GameInterface[posX + 0, posY + 2].IsOccuped = Occuped.Yes;
                    GameInterface[posX + 1, posY + 1].IsOccuped = Occuped.Yes;
                    this.iniX = 0;
                    this.finX = 1;
                    this.iniY = 0;
                    this.finY = 2;
                    CoordinatePiece[0, 0] = 0;
                    CoordinatePiece[0, 1] = 2;
                    CoordinatePiece[1, 0] = 1;
                    CoordinatePiece[1, 1] = 1;

                    Shape[0, 0].IsOccuped = Occuped.Yes;
                    Shape[0, 1].IsOccuped = Occuped.Yes;
                    Shape[0, 2].IsOccuped = Occuped.Yes;
                    Shape[1, 1].IsOccuped = Occuped.Yes;

                } else if (this.PieceType == PieceType.S && (CurrentRotation == 1 || CurrentRotation == 3)) {

                    for (int i = StartX; i <= EndX; i++)
                        for (int j = CoordinatePiece[i, 0]; j <= CoordinatePiece[i, 1]; j++) {
                            GameInterface[posX + i, posY + j].IsOccuped = Occuped.No;
                            Shape[i, j].IsOccuped = Occuped.No;
                        }

                    GameInterface[posX + 0, posY + 2].IsOccuped = Occuped.Yes;
                    GameInterface[posX + 0, posY + 3].IsOccuped = Occuped.Yes;
                    GameInterface[posX + 1, posY + 1].IsOccuped = Occuped.Yes;
                    GameInterface[posX + 1, posY + 2].IsOccuped = Occuped.Yes;
                    this.iniX = 0;
                    this.finX = 1;
                    this.iniY = 1;
                    this.finY = 3;
                    CoordinatePiece[0, 0] = 2;
                    CoordinatePiece[0, 1] = 3;
                    CoordinatePiece[1, 0] = 1;
                    CoordinatePiece[1, 1] = 2;

                    Shape[0, 2].IsOccuped = Occuped.Yes;
                    Shape[0, 3].IsOccuped = Occuped.Yes;
                    Shape[1, 1].IsOccuped = Occuped.Yes;
                    Shape[1, 2].IsOccuped = Occuped.Yes;

                } else if (this.PieceType != PieceType.O) {
                    Square[,] temp = new Square[4, 4];

                    //Remove the piece from the old location
                    for (int i = this.StartX; i <= this.EndX; i++)
                        for (int j = this.StartY; j <= this.EndY; j++)
                            GameInterface[posX + i, posY + j].IsOccuped = Occuped.No;

                    //Create a copy of the array form in the matrix temp
                    for (int i = 0; i <= 3; i++) {
                        for (int j = 0; j <= 3; j++) {
                            temp[i, j] = new Square();
                            temp[i, j].IsOccuped = Shape[i, j].IsOccuped;
                        }
                    }

                    for (int i = 0; i <= 3; i++)
                        for (int j = 0; j <= 3; j++) {
                            Shape[j, 3 - i].IsOccuped = temp[i, j].IsOccuped;
                            if (Shape[j, 3 - i].IsOccuped == Occuped.Yes)
                                GameInterface[posX + j, posY + 3 - i].IsOccuped = Occuped.Yes;

                        }
                    CalculateNewPieceLimits(Shape, ref iniX, ref finX, ref iniY, ref finY);
                    CalculateCurrentPieceCoordinates();
                }
            }
        }

        /// Calculate the new piece limits
        /// <param name="Forma">The space which contains the piece</param>
        /// <param name="inix">The variable that must contain the start of the X</param>
        /// <param name="finx">The variable that will contain the end of the X</param>
        /// <param name="iniy">The variable that must contain the start of Y</param>
        /// <param name="finy">The variable that will contain the end of the X/param>
        public void CalculateNewPieceLimits(Square[,] Forma, ref int inix, ref int finx, ref int iniy, ref int finy) {
            bool finded = false;
            for (int i = 0; i <= 3; i++)
                for (int j = 0; j <= 3; j++) {
                    if (this.Shape[i, j].IsOccuped == Occuped.Yes) {
                        if (finded == false) {
                            this.iniX = i;
                            this.finX = i;
                            this.iniY = j;
                            this.finY = j;
                            finded = true;
                        } else {
                            if (i < iniX) iniX = i;
                            if (i > finX) finX = i;
                            if (j < iniY) iniY = j;
                            if (j > iniY) finY = j;
                        }
                    }
                }
        }

        int iniX;
        public int StartX {
            get { return iniX; }
        }
        int finX;
        public int EndX {
            get { return finX; }
        }

        int iniY;
        public int StartY {
            get { return iniY; }
        }
        int finY;
        public int EndY {
            get { return finY; }
        }

        /// Calculates the coordinates of the square of the current price and puts them in the structure CoordinatePiece
        private void CalculateCurrentPieceCoordinates() {
            for (int i = 0; i <= 3; i++) {
                bool calculated = false;
                for (int j = 0; j <= 3; j++) {
                    if (Shape[i, j].IsOccuped == Occuped.Yes) {
                        if (calculated == false) {
                            this.PieceCoordinate[i, 0] = j;
                            this.PieceCoordinate[i, 1] = j;
                            calculated = true;
                        } else {
                            this.PieceCoordinate[i, 1] = j;
                        }
                    }
                }
                if (calculated == false) {
                    this.PieceCoordinate[i, 0] = 0;
                    this.PieceCoordinate[i, 1] = -1;
                }
            }
        }

        PieceType nextPieceType;
        //It contains the type of the next piece
        private PieceType NextPieceType {
            get { return nextPieceType; }
            set { nextPieceType = value; }
        }

        private Square[,] nextPiece = new Square[4, 4];
        /// Contains space expressed in matrix PictureBox next piece
        public Square[,] NextPiece {
            get { return nextPiece; }
            set { nextPiece = value; }
        }

        /// Set as part of the class in the matrix form casual one among the four types
        public void GetCasualPiece() {
            for (short i = 0; i < 4; i++) {
                for (short j = 0; j < 4; j++) {
                    this.Shape[i, j].IsOccuped = NextPiece[i, j].IsOccuped;
                    this.NextPiece[i, j].IsOccuped = Occuped.No;

                }
            }
            pieceType = NextPieceType;

            switch (PieceType) {
                case PieceType.I:
                    this.iniX = 0;
                    this.finX = 3;
                    this.iniY = 2;
                    this.finY = 2;
                    break;
                case PieceType.L:
                    this.iniX = 1;
                    this.finX = 3;
                    this.iniY = 2;
                    this.finY = 3;
                    break;
                case PieceType.J:
                    this.iniX = 1;
                    this.finX = 3;
                    this.iniY = 2;
                    this.finY = 3;
                    break;
                case PieceType.Z:
                    this.iniX = 1;
                    this.finX = 3;
                    this.iniY = 1;
                    this.finY = 2;
                    break;
                case PieceType.S:
                    this.iniX = 0;
                    this.finX = 2;
                    this.iniY = 0;
                    this.finY = 1;
                    break;
                case PieceType.O:
                    this.iniX = 1;
                    this.finX = 2;
                    this.iniY = 2;
                    this.finY = 3;
                    break;
                case PieceType.T:
                    this.iniX = 0;
                    this.finX = 2;
                    this.iniY = 1;
                    this.finY = 2;
                    break;

            }

            Random caso = new Random();

            switch (caso.Next(0, 7)) {
                case 0:
                    //Set as piece:
                    //[*][*][*][*]
                    this.NextPiece[0, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[1, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[2, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[3, 2].IsOccuped = Occuped.Yes;
                    this.NextPieceType = PieceType.I;
                    break;
                case 1:
                    //Set as piece:
                    //   [*]
                    //[*][*]
                    //   [*]
                    this.NextPiece[0, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[1, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[2, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[1, 1].IsOccuped = Occuped.Yes;
                    this.NextPieceType = PieceType.T;
                    break;
                case 2:
                    //Set as piece:
                    //[*][*]
                    //   [*]
                    //   [*]
                    this.NextPiece[1, 3].IsOccuped = Occuped.Yes;
                    this.NextPiece[2, 3].IsOccuped = Occuped.Yes;
                    this.NextPiece[3, 3].IsOccuped = Occuped.Yes;
                    this.NextPiece[1, 2].IsOccuped = Occuped.Yes;
                    this.NextPieceType = PieceType.L;
                    break;
                case 3:
                    //Set as piece:
                    //[*][*]
                    //[*][*]
                    this.NextPiece[1, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[2, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[1, 3].IsOccuped = Occuped.Yes;
                    this.NextPiece[2, 3].IsOccuped = Occuped.Yes;
                    this.NextPieceType = PieceType.O;
                    break;
                case 4:
                    //Set as piece:
                    //   [*]
                    //[*][*]
                    //[*]
                    this.NextPiece[1, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[2, 1].IsOccuped = Occuped.Yes;
                    this.NextPiece[2, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[3, 1].IsOccuped = Occuped.Yes;
                    this.NextPieceType = PieceType.Z;
                    break;
                case 5:
                    //Imposta come pezzo:
                    //[*][*]
                    //[*]
                    //[*]
                    this.NextPiece[1, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[2, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[3, 2].IsOccuped = Occuped.Yes;
                    this.NextPiece[1, 3].IsOccuped = Occuped.Yes;
                    this.NextPieceType = PieceType.J;
                    break;
                case 6:
                    //Set as piece:
                    //[*]
                    //[*][*]
                    //   [*]
                    this.NextPiece[0, 0].IsOccuped = Occuped.Yes;
                    this.NextPiece[1, 0].IsOccuped = Occuped.Yes;
                    this.NextPiece[1, 1].IsOccuped = Occuped.Yes;
                    this.NextPiece[2, 1].IsOccuped = Occuped.Yes;
                    this.NextPieceType = PieceType.S;
                    break;
            }
            CalculateCurrentPieceCoordinates();
            this.CurrentRotation = 0;
        }
    }
}


text:
This repository contains the source code for the paper MobileNeRF: Exploiting the Polygon Rasterization Pipeline for Efficient Neural Field Rendering on Mobile Architectures.

This code is created by [Zhiqin Chen](https://czq142857.github.io/) when he was a student researcher at Google.

*Please note that this is not an officially supported Google product.*

## Installation

You will need 8 v100 GPUs to successfully train the model.

We recommend using [Anaconda](https://www.anaconda.com/products/individual) to set up the environment. Clone the repo, go to the mobilenerf folder, and run the following commands:

```
conda create --name mobilenerf python=3.6.13; conda activate mobilenerf
conda install pip; pip install --upgrade pip
pip install -r requirements.txt
```

Please make sure that your jax supports GPU. You might need to re-install jax by following the [jax installation guide](https://github.com/google/jax#installation).

## Data

Please download the datasets from the [NeRF official Google Drive](https://drive.google.com/drive/folders/128yBriW1IG_3NJ5Rp7APSTZsJqdJdfc1).
Please download and unzip `nerf_synthetic.zip` and `nerf_llff_data.zip`.

**(TODO: how to download unbounded scenes from Mip-NeRF 360?)**

## Training

The training code is in three .py files, corresponding to the three training stages: 1. continuous opacity, 2. binarization and supersampling, 3. extracting meshes and textures.

First, modify the parameters in all .py files:
```
scene_type = "synthetic"
object_name = "chair"
scene_dir = "datasets/nerf_synthetic/"+object_name
```
*scene_type* can be synthetic, forwardfacing, or real360. *object_name* is the name of the scene to be trained; the available names are listed in the code. *scene_dir* is the folder holding the training data.

Afterwards, run the three .py files consecutively
```
python stage1.py
python stage2.py
python stage3.py
```
The intermediate weights will be saved in folder *weights* and the intermediate outputs (sample testing images, loss curves) will be written to folder *samples*. The output meshes+textures will be saved in folder *obj_phone*.

Note: the stage-1 training could occasionally fail for unknown reasons (especially on the bicycle scene); switch to a different set of GPUs could solve this.

Note: For unbounded 360 degree scenes, ```stage3.py``` will only extract meshes of the center unit cube. To extract the entire scene, use ```python stage3_with_box.py```.

It takes 8 hours to train the first stage, 12-16 hours to train the second, and 1-3 hours to run the third.

## Running the viewer

The viewer code is provided in this repo, as three .html files for three types of scenes.

You can set up a local server on your machine, e.g.,
```
cd folder_containing_the_html
python -m http.server
```
Then open
```
localhost:8000/view_synthetic.html?obj=chair
```
Note that you should put the meshes+textures of the chair model in a folder *chair_phone*. The folder should be in the same directory as the html file.

Please allow some time for the scenes to load. Use left mouse button to rotate, right mouse button to pan (especially for forward-facing scenes), and scroll wheel to zoom. On phones, Use you fingers to rotate or pan or zoom. Resize the window (or landscape<->portrait your phone) to show the resolution.


text:
package sim.app.guidedps.agents;

import sim.app.guidedps.gridworld.State;

public class Demonstration {
	State s;
	int a;

	public Demonstration(State s, int a) {
		this.s = s;
		this.a = a;
	}

	@Override
	public boolean equals(Object obj) {
		Demonstration that = (Demonstration)obj;
		if(that.s.equals(this.s)&&that.a==this.a)
			return true;
		return false;
	}

	@Override
	public int hashCode() {
		return 100*s.hashCode() + a;
	}
}


text:
from django.db import models
from googaccount.models import AppCreds
import main.models
import json

class YoutubeSubUpdate(main.models.Updater):
    credentials = models.ForeignKey(AppCreds)

class YoutubeSubEvent(main.models.UpdaterEvent):
    details = models.TextField()
    updater = models.ForeignKey(YoutubeSubUpdate)
    def as_dict(self):
        data = json.loads(self.details)
        info = {
            'name': data['subscriberSnippet']['title'],
        }
        return info

class YoutubeSubAlertConfig(main.models.AlertConfig):
    blacklist = models.TextField(blank=True, null=True)


text:
<?php

namespace Star\AnnoncesBundle\Controller;

use Sonata\AdminBundle\Controller\CRUDController as Controller;

class AnnonceAdminController extends Controller
{

    public function myCustomAction()
    {
        die('test de test ');
    }
}


text:
spnp::TimedTransition::TimedTransition():ImmediateTransition()
{
    this->value = "0.25";
    this->distribution = Distribution::Exponential;
    this->distValue = "";
    this->policy = Policy::PreemptiveRepeatDifferent;
    this->affected = Affected::PRS;
    this->label = new Label();
}

spnp::TimedTransition::TimedTransition(std::string name, std::string priority, std::string guard,
                                       ProbabilityType probType, std::string value,
                                       Label *label,
                                       Distribution distribution, std::string distValue,
                                       Policy policy, Affected affected, int x, int y)
    :ImmediateTransition(name, priority, guard, probType, value, label, x, y)
{
    this->distribution = distribution;
    this->distValue = distValue;
    this->policy = policy;
    this->affected = affected;
}

spnp::TimedTransition::~TimedTransition()
{

}

XMLNode *spnp::TimedTransition::toXML()
{
    XMLNode* node = ImmediateTransition::toXML();
    node->setAttribute("dist_value", this->distValue);
    node->setAttribute("dist", static_cast<int>(this->distribution));
    node->setAttribute("policy", static_cast<int>(this->policy));
    node->setAttribute("affected", static_cast<int>(this->affected));

    return node;
}

void spnp::TimedTransition::fromXML(XMLNode *xml)
{
    ImmediateTransition::fromXML(xml);
    this->distValue= xml->getAttributeS("dist_value");
    this->distribution = static_cast<Distribution>(xml->getAttributeI("dist"));
    this->policy = static_cast<Policy>(xml->getAttributeI("policy"));
    this->affected = static_cast<Affected>(xml->getAttributeI("affected"));
}

void spnp::TimedTransition::setDistribution(spnp::TimedTransition::Distribution d)
{
    this->distribution = d;
}

void spnp::TimedTransition::setDistributionValue(std::string dv)
{
    this->distValue = dv;
}

void spnp::TimedTransition::setPolicy(spnp::TimedTransition::Policy p)
{
    this->policy = p;
}

void spnp::TimedTransition::setAffected(spnp::TimedTransition::Affected a)
{
    this->affected = a;
}

spnp::TimedTransition::Distribution spnp::TimedTransition::getDistribution()
{
    return this->distribution;
}

std::string spnp::TimedTransition::getDistributionValue()
{
    return this->distValue;
}

spnp::TimedTransition::Policy spnp::TimedTransition::getPolicy()
{
    return this->policy;
}

spnp::TimedTransition::Affected spnp::TimedTransition::getAffected()
{
    return this->affected;
}

std::string spnp::TimedTransition::c_str(IData *data) const
{
    (void)data;
    std::stringstream ss;

    ss << "rateval(\"" << getName() << "\","<< this->getValue() << ");\n";

    if(this->guard.compare("")!=0)
    {
        ss << "guard(\"" << getName() << "\", " << this->getGuard() << ");\n";
    }

    return ss.str();
}

std::string spnp::TimedTransition::getClassNodeName()
{
    return "timed_transition";
}


text:
cygwin=false;
darwin=false;
case "`uname`" in
  CYGWIN*) cygwin=true ;;
  Darwin*) darwin=true
           if [ -z "$JAVA_HOME" ] ; then
             JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Home
           fi
           ;;
esac

REALANTHOME=$ANT_HOME
if [ -z "$PWD" ]; then
    ANT_HOME=./bootstrap
else
    ANT_HOME="$PWD"/bootstrap
fi
export ANT_HOME

if test ! -f bootstrap/lib/ant.jar -o  ! -x bootstrap/bin/ant -o ! -x bootstrap/bin/antRun ; then
  /bin/sh ./bootstrap.sh
fi

if test ! -f bootstrap/lib/ant.jar -o  ! -x bootstrap/bin/ant -o ! -x bootstrap/bin/antRun ; then
  echo Bootstrap FAILED
  exit 1
fi

if [ "$REALANTHOME" != "" ] ; then
  if $cygwin; then
     REALANTHOME=`cygpath --windows "$REALANTHOME"`
  fi
  ANT_INSTALL="-Dant.install=$REALANTHOME"
else
  ANT_INSTALL="-emacs"
fi

bootstrap/bin/ant -nouserlib -lib lib/optional "$ANT_INSTALL" $*


text:
package main

import "github.com/Kyperion/baldr/cmd"

func main() {
	cmd.Execute()
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace zuoraTools.DataEnumerators
{
    /*
     * This class takes data streams, parses them into lines of text and makes them consumable in foreach loops
     * See interface for info on what public methods do.
     *
     * This class is some complicated spaghetti, sorry about that.
     */
    class LineEnum : IDataEnumerator
    {
        //Todo: Close file handles when end of file is reached.
        public int LoopIterations { get; private set; }

        private int _bufferSize;
        private Stream _inputStream;
        private List<string> _lineBuffer = new List<string>();

        private string _textBuffer = "";
        private int _count = 1; //Non zero value for first iteration of loop.

        public List<string> Keys
        {
            get { throw new NotImplementedException("This is a simple record generator, it does not parse records and as a consequence does not have Keys."); }
            set { throw new NotImplementedException("This is a simple record generator, it does not parse records and as a consequence does not have Keys."); }
        }

        public LineEnum(Stream sourceStream, int bufferSize = 32768)
        {
            this._bufferSize = bufferSize;
            this._inputStream = sourceStream;
            LoopIterations = 0;
        }

        private bool InputStreamIsEmpty()
        {
            return !(_count > 0);
        }

        private bool TextBufferHasLine()
        {
            if (String.IsNullOrEmpty(_textBuffer))
            {
                return false;
            }
            bool hasNewlineChar = Regex.Match(_textBuffer, @"(\r|\n|\r\n)", RegexOptions.Singleline).Success;

            if (!hasNewlineChar)
            {
                return (InputStreamIsEmpty() == true && String.IsNullOrEmpty(_textBuffer));
            }
            else
            {
                return true;
            }
        }

        private bool AppendTextBuffer()
        {
            if (!InputStreamIsEmpty())
            {
                byte[] buffer = new byte[_bufferSize];
                _count = _inputStream.Read(buffer, 0, buffer.Length);
                _textBuffer = _textBuffer + System.Text.Encoding.UTF8.GetString(buffer).TrimEnd('\0');

                return true;
            }
            else
            {
                return false;
            }
        }

        public bool _textBufferLoadLine()
        {
            if (TextBufferHasLine())
            {
                return true;
            }

            while (!InputStreamIsEmpty())
            {
                if (TextBufferHasLine())
                {
                    return true;
                }
                else
                {
                    AppendTextBuffer();
                }
            }

            return TextBufferHasLine();
        }

        private string TextBufferPullLine()
        {
            //Trim leading return chars
            _textBuffer = _textBuffer.TrimStart(new char[] { '\n', '\r' });

            string line = "";
            while (Regex.Match(line, @"^\s*$", RegexOptions.Singleline).Success && _textBufferLoadLine())
            {
                //Pull all non-newline/non-return characters until newline
                line = Regex.Match(_textBuffer, @"^([^\r^\n]+)(\r|\n)").Value;
                //And remove the sequence from the source string
                _textBuffer = Regex.Replace(_textBuffer, @"^([^\r^\n]+)(\r|\n)", "", RegexOptions.Singleline);

                line = line.Trim(new char[] { '\n', '\r' });
             }

            return line.Trim();
        }

        public string Next()
        {
            return TextBufferPullLine();
        }

        public IEnumerable Gen()
        {
            while (true)
            {
                string s = "";

                while (_textBufferLoadLine() && String.IsNullOrWhiteSpace(s))
                {
                    s = Next();
                }

                if (!String.IsNullOrWhiteSpace(s))
                {
                    LoopIterations++;
                    yield return s;
                }
                else
                {
                    yield break;
                }
            }
        }

    }
}


text:
import '../../config';
import webpack from 'webpack';
import webpackDevServer from './dev-server';
import webpackDevConfig from './config.development';
import webpackStagingConfig from './config.staging';
import webpackProductionConfig from './config.production';

let compiler = {};

switch (process.env.NODE_ENV) {
  case 'development': {
    const { SERVER_HOST, SERVER_PORT } = process.env;
    const proxyConfig = {
      '/api': {
        target: `http://${SERVER_HOST}:${SERVER_PORT}`,
        changeOrigin: true,
        headers: {
          Referer: `http://${SERVER_HOST}:${SERVER_PORT}/`
        }
      }
    };

    webpackDevServer(webpackDevConfig, proxyConfig);
    break;
  }
  case 'staging': {
    compiler = webpack(webpackStagingConfig);
    compiler.run(resultHandler);
    break;
  }
  case 'production': {
    compiler = webpack(webpackProductionConfig);
    compiler.run(resultHandler);
    break;
  }
}

function resultHandler(err, stats) {
  if (err) throw err;

  for(let stat of stats.stats) {
    process.stdout.write(stat.toString({
        colors: true,
        modules: false,
        children: false,
        chunks: false,
        chunkModules: false
      }) + '\n');
  }
}


text:
/**
 * @Title: UserRest.java
 * @Package com.ynswet.homecloud.common.rest
 * @Description: TODO
 * @author 李玉鹏
 * @date 2015年5月12日 下午4:11:00
 * @version V1.0
 *
Copy
 *
Company:广州合光信息科技有限公司

 */
package com.ynswet.system.sc.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ynswet.common.rest.BaseRest;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import com.ynswet.common.domain.ListJsonStructure;
import com.ynswet.common.domain.SingleJsonStructure;
import com.ynswet.common.util.DateTimeUtils;
import com.ynswet.system.sc.domain.Res;
import com.ynswet.system.sc.domain.User;
import com.ynswet.system.sc.domain.Userlogin;
import com.ynswet.system.sc.model.CommonVariableModel;
import com.ynswet.system.sc.realm.UserManager;
import com.ynswet.system.sc.repository.UserRepository;
import com.ynswet.system.sc.repository.UserloginRepository;
import com.ynswet.system.sc.service.UserService;
import com.ynswet.system.sc.util.PasswordHelper;
import com.ynswet.system.sc.util.SystemVariableUtils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;

/**
 *
 * 类功能说明
 *
Title: UserRest.java

 * @author 孙越
 * @date 2015年8月5日 下午4:21:59
 * 类修改者	修改日期
 * 修改说明
 * @version V1.0
 *
Description:立翔云

 *
Copyright: Copyright (c) 2015

 *
Company:广州合光信息科技有限公司

 */
@RestController
@RequestMapping("/user")
public class UserRest extends BaseRest {

	@Autowired
	private UserService userService;

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private UserloginRepository userloginRepository;

	@Autowired
	private PasswordHelper passwordHelper;

	@Autowired
	private UserManager userManager;

	@Autowired
	private EhCacheManager ehCacheManager;

	/**
	 * 当前用户修改密码
	 *
	 * @param oldPassword
	 *            旧密码
	 * @param newPassword
	 *            新密码
	 *
	 * @return String
	 */

	@RequestMapping(value="/changePassword",method = RequestMethod.POST)
	@ResponseBody
	public SingleJsonStructure changePassword(
			@RequestParam("uid") Integer uid,
			@RequestParam("openid") String openid,
			@RequestParam("oldPassword") String oldPassword,
			@RequestParam("newPassword") String newPassword) {
		SingleJsonStructure json = new SingleJsonStructure();
		User user = userRepository.findByUidAndOpenid(uid,openid);
		if(user!=null){
			Userlogin userlogin = userloginRepository.findByLoginString(user.getCell());
			String pwd = passwordHelper.getPassword(userlogin, oldPassword);
			if (pwd.equals(userlogin.getPassword())) {
				List<Userlogin> userloginList = userloginRepository.findByUid(userlogin.getUid());
				for (Userlogin ul : userloginList) {
					ul.setPassword(newPassword);
					passwordHelper.encryptPassword(ul);
					userloginRepository.save(ul);
				}
				userloginRepository.flush();
				json.setSuccess(true);
				json.setMsg("密码修改成功");
			}else{
				json.setSuccess(false);
				json.setMsg("原密码错误");
			}
		}else{
			json.setSuccess(false);
			json.setMsg("用户不存在");
		}
		return json;
	}

	/**
	 * url:/ynlxhealth/user
	 * 函数功能说明:添加用户
	 * @author 李玉鹏
	 * @date 2015年5月13日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param user
	 * @return void
	 * @throws
	 */
	@RequestMapping(method = RequestMethod.POST)
	public SingleJsonStructure saveUser(@ModelAttribute User user){
		SingleJsonStructure json = new SingleJsonStructure();
		User checkUser = userRepository.checkUserUniqueness(user.getCell(), user.getIdNo());
		if(null!=checkUser){
			json.setSuccess(false);
			json.setMsg(BaseRest.SAVE_FAILURE);
		}else{
			user.setCreateTime(DateTimeUtils.getSystemCurrentTimeMillis());
			user.setModifyTime(DateTimeUtils.getSystemCurrentTimeMillis());
			user.setStatus("0");
			user.setSecPassword("123456");
			user.setBindPassword("654321");
			User saveUser = userRepository.saveAndFlush(user);
			List<String> loginStringList=new ArrayList<String>();
			loginStringList.add(saveUser.getCell());
			loginStringList.add(saveUser.getIdNo());
			List<Userlogin> listlogin = new ArrayList<Userlogin>();
			for(String loginString:loginStringList){
				Userlogin userlogin = new Userlogin();
				userlogin.setPassword(BaseRest.DEFAULT_PASSWORD);
				userlogin.setUid(saveUser.getUid());
				userlogin.setStatus(saveUser.getStatus());
				userlogin.setLoginString(loginString);
				userlogin = passwordHelper.encryptPassword(userlogin);
				listlogin.add(userlogin);
			}
			userloginRepository.save(listlogin);
			userloginRepository.flush();
			json.setRows(saveUser.getUid());
			json.setMsg(BaseRest.SAVE_SUCCESS);
		}
		return json;
	}

	/**
	 * url:/ynlxhealth/user/{uids}
	 * 函数功能说明:删除用户
	 * @author 李玉鹏
	 * @date 2015年5月14日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param uids
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/{uids}",method = RequestMethod.DELETE)
	public SingleJsonStructure deleteUsers (@PathVariable String uids) {
		if(!uids.isEmpty()){
			String[] arrUids = uids.split(",");
			CacheManager cm= ehCacheManager.getCacheManager();
			Cache cache=cm.getCache("shiroAuthenticationCache");
			for(String uid : arrUids){
				userRepository.delete(Integer.valueOf(uid));
				userRepository.flush();
				List<Userlogin> list= userloginRepository.findByUid(Integer.valueOf(uid));//需要清除缓存的uid
				for(Userlogin ul:list){
					cache.remove(ul.getLoginString());//登录账号全清空
				}
			}
		}
		SingleJsonStructure json = new SingleJsonStructure();
		json.setMsg(BaseRest.DELTE_SUCCESS);
		return json;
	}

	/**
	 * url:/ynlxhealth/user
	 * 函数功能说明:查询所有的用户
	 * @author 李玉鹏
	 * @date 2015年5月14日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @return
	 * @return ListJsonStructure<User>
	 * @throws
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ListJsonStructure<User> findAlls() {
		List<User> listUsers = userRepository.findAll();
		ListJsonStructure<User> json = new ListJsonStructure<User>();
		json.setRows(listUsers);
		return json;

	}

	/**
	 *
	 * 函数功能说明
	 * @author 刘培琪
	 * @date 2015年8月3日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @return
	 * @return ListJsonStructure<User>
	 * @throws
	 */
	@RequestMapping(value="userType",method = RequestMethod.GET)
	public ListJsonStructure<User> findAllEmp() {
		List<User> listUsers = userRepository.findAllEmp();
		ListJsonStructure<User> json = new ListJsonStructure<User>();
		json.setRows(listUsers);
		return json;

	}

	/**
	 * url:/ynlxhealth/user/toPage
	 * 函数功能说明:分页查询用户
	 * @author 李玉鹏
	 * @date 2015年5月14日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param page
	 * @param @param rows
	 * @param @return
	 * @return ListJsonStructure<User>
	 * @throws
	 */
	@RequestMapping(value="/toPage",method = RequestMethod.GET)
	public ListJsonStructure<User> findAlltoPage(
			@RequestParam("page")int page,
			@RequestParam("rows")int size) {
		Pageable pager = new PageRequest(page-1, size);
		Page<User> list = userRepository.findAll(pager);
		ListJsonStructure<User> json = new ListJsonStructure<User>();
		json.setRows(list.getContent());
		json.setTotal((int) list.getTotalElements());
		return json;
	}

	/**
	 * url:/ynlxhealth/user/items/toPage
	 * 函数功能说明:根据条件分页查询用户
	 * @author 李玉鹏
	 * @date 2015年5月25日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param userName
	 * @param @param phone
	 * @param @param pageSize
	 * @param @param rows
	 * @param @return
	 * @return ListJsonStructure<User>
	 * @throws
	 */
	@RequestMapping(value="/searchByItems",method = RequestMethod.GET)
	public ListJsonStructure<User> findByUserName(
			@RequestParam("userName")String userName,
			@RequestParam("phone")String phone,
			@RequestParam("page")int page,
			@RequestParam("rows")int rows
			) {
		Pageable pageable = new PageRequest(rows, page);
		Page<User> pages = userRepository.findByUserName(userName, pageable);
		ListJsonStructure<User> json = new ListJsonStructure<User>();
		json.setRows(pages.getContent());
		json.setTotal((int) pages.getTotalElements());
		return json;
	}

	/**
	 *
	 * 函数功能说明
	 * @author 李玉鹏
	 * @date 2015年5月28日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param key
	 * @param @param value
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/searchByKeyValue",method = RequestMethod.GET)
	public SingleJsonStructure searchByKeyValue(
			@RequestParam("key")String key,
			@RequestParam("value")String value) {
		User user = null ;
		switch (key) {
		case "cell":
			user = userRepository.findByCell(value);
			break;
		case "email":
			user = userRepository.findByEmail(value);
			break;
		case "idNo":
			user = userRepository.findByIdNo(value);
			break;
		case "userName":
			user = userRepository.findByUserName(value);
			break;
		default:
			break;
		}
		SingleJsonStructure json = new SingleJsonStructure();
		if(user==null){
			json.setSuccess(false);
		}
		json.setRows(user);
		return json;
	}

	/**
	 *
	 * 函数功能说明
	 * @author 李玉鹏
	 * @date 2015年5月28日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param key
	 * @param @param value
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/searchByKeyValueLike/toPage",method = RequestMethod.GET)
	public ListJsonStructure<User> searchByKeyValueLikeToPage(
			@RequestParam("key")String key,
			@RequestParam("value")String value,
			@RequestParam("page")int page,
			@RequestParam("rows")int rows
			) {
		Page<User> pages = null ;
		Pageable pageable = new PageRequest(page-1, rows);
		switch (key) {
			case "cell":
				pages = userRepository.findByCellLike(value,pageable);
				break;
			case "email":
				pages = userRepository.findByEmailLike(value,pageable);
				break;
			case "idNo":
				pages = userRepository.findByIdNoLike(value,pageable);
				break;
			case "userName":
				pages = userRepository.findByUserNameLike(value,pageable);
				break;
			default:
			break;
		}
		ListJsonStructure<User> json = new ListJsonStructure<User>();
		json.setRows(pages.getContent());
		json.setTotal((int) pages.getTotalElements());
		return json;
	}

	/**
	 * url:/ynlxhealth/user/checkEmail
	 * 函数功能说明:检查用户邮箱唯一性
	 * @author 李玉鹏
	 * @date 2015年5月27日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param email
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/checkEmail",method = RequestMethod.POST)
	public boolean checkByEmail(@RequestParam("email")String email) {
		User user = userRepository.findByEmail(email);
		if(null!=user){
			return false;
		}else{
			return true;
		}
	}

	/**
	 * url:/ynlxhealth/user/checkCell
	 * 函数功能说明:检查用户联系手机唯一性
	 * @author 李玉鹏
	 * @date 2015年5月27日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param cell
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/checkCell",method = RequestMethod.POST)
	public boolean checkByCell(@RequestParam("cell")String cell) {
		User user = userRepository.findByCell(cell);
		if(null!=user){
			return false;
		}else{
			return true;
		}
	}

	/**
	 * url:/ynlxhealth/user/checkIdNo
	 * 函数功能说明:检查用户证件号唯一性
	 * @author 李玉鹏
	 * @date 2015年5月27日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param idNo
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/checkIdNo",method = RequestMethod.POST)
	public boolean checkByIdNo(@RequestParam("idNo")String idNo) {
		User user = userRepository.findByIdNo(idNo);
		if(null!=user){
			return false;
		}else{
			return true;
		}
	}

	/**
	 *
	 * 获取当前用户资源(小区)
	 * @author 张明坤
	 * @date 2015年6月22日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @return
	 * @return ListJsonStructure<Res>
	 * @throws
	 */
	@RequestMapping(value="/searchCurCommunity",method = RequestMethod.GET)
	public ListJsonStructure<Res> searchCurCommunity() {
		ListJsonStructure<Res> json = new ListJsonStructure<Res>();
		CommonVariableModel cm = SystemVariableUtils.getCommonVariableModel();
		Userlogin userlogin =cm.getUserlogin();
		Integer uid=userlogin.getUid();
		List<Res> resList=userManager.getRessByUserId(uid);
		List<Res> comList=new ArrayList<Res>();
		for(Res res:resList){
			if(res.getResType().equals("C")){
				comList.add(res);
			}
		}
		json.setRows(comList);
		json.setTotal(comList.size());
		return json;
	}

	/**
	 * url:/ynlxhealth/user/{uid}
	 * 函数功能说明:更新用户
	 * @author 李玉鹏
	 * @date 2015年5月13日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param uid
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/{uid}",method = RequestMethod.GET)
	public SingleJsonStructure updateUser(@PathVariable Integer uid) {
		// TODO Auto-generated method stub
		User user = userRepository.findOne(uid);
		SingleJsonStructure json = new SingleJsonStructure();
		json.setMsg(BaseRest.UPDATE_SUCCESS);
		json.setRows(user);
		json.setSuccess(true);
		return json;
	}

	/**
	 * url:/ynlxhealth/user/addUser/{}
	 * 函数功能说明:为客户添加成员
	 * @author 孙越
	 * @date 2015年7月29日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param user
	 * @return void
	 * @throws
	 */
	@RequestMapping(value="/addUser/{obj}",method = RequestMethod.POST)
	public Integer saveCustomerUser(@ModelAttribute User user,@PathVariable String obj){
		System.out.println("获取到了?"+obj);
		if(!obj.isEmpty()){
			String [] arrIds = obj.split(",");
			user.setUserName(arrIds[1]);
			user.setGender(arrIds[2]);
			user.setCell(arrIds[3]);
			user.setEmail(arrIds[5]);
			user.setIdNo(arrIds[4]);
		}

		Timestamp createTime = new Timestamp(System.currentTimeMillis());
		user.setCreateTime(createTime);
		user.setIdType("0");
		user.setUserType("c");
		user.setEducation("0");
		user.setCell2("0");
		user.setMarriage("0");
		user.setBlood("0");
		user.setModifyTime(DateTimeUtils.getSystemCurrentTimeMillis());
		user.setStatus("0");
		user.setNote("客户成员");
		User users=userRepository.saveAndFlush(user);
		Integer uid=users.getUid();
		return uid;
	}
	/**
	 * url:ynlxhealth/user/
	 * 函数功能说明:为房屋添加住户
	 * @author 孙越
	 * @date 2015年8月22日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param user
	 * @param @param obj
	 * @param @return
	 * @return Integer
	 * @throws
	 */
	@RequestMapping(value="/addUser",method = RequestMethod.POST)
	public SingleJsonStructure saveHouseUser(@ModelAttribute User user){
		Timestamp createTime = new Timestamp(System.currentTimeMillis());
		user.setCreateTime(createTime);
		User users=userRepository.saveAndFlush(user);
		SingleJsonStructure json = new SingleJsonStructure();
		json.setMsg(BaseRest.SAVE_SUCCESS);
		json.setRows(users.getUid());
		return json;
	}
	/**
	 * url:/ynlxhealth/user
	 * 函数功能说明:查询房屋下的用户
	 * @author 孙越
	 * @date 2015年7月30日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param user
	 * @return void
	 * @throws
	 */
	@RequestMapping(value="/searchUserByUid",method = RequestMethod.GET)
	public List<User> searchUserByOrgidAndRoleId(@RequestParam  String UID) {
		List<User> list=new ArrayList<User>();
		if(!UID.isEmpty()){
			String [] arrIds = UID.split(",");
			for(int i = 0;i<arrIds.length;i++){
				User user=new User();
				user=userRepository.findUserByUid(Integer.valueOf(arrIds[i]));
				list.add(user);
			}
		}
		return list;
	}
	/**
	 * url:/business/user/updateCUser
	 * 函数功能说明:修改客户成员信息
	 * @author 孙越
	 * @date 2015年8月4日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param Product
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/updateCUser/{obj}",method = RequestMethod.POST)
	public SingleJsonStructure save(@RequestParam String obj){
		String [] arrIds =obj.split(",");
		Integer uid=Integer.parseInt(arrIds[0]);
		String userName=arrIds[1];
		String gender=arrIds[2];
		String cell=arrIds[3];
		User user = userRepository.findOne(uid);
		user.setUserName(userName);
		user.setGender(gender);
		user.setCell(cell);
		userRepository.saveAndFlush(user);
		SingleJsonStructure json = new SingleJsonStructure();
		json.setMsg(BaseRest.SAVE_SUCCESS);
		return json;
	}
	/**
	 * url:/user/searchByorgids
	 * 函数功能说明:查当前用户组织下的用户
	 * @author 张毕思
	 * @date 2015年10月26日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param page
	 * @param @param size
	 * @param @return
	 * @return ListJsonStructure<User>
	 * @throws
	 */
	@RequestMapping(value="/searchByorgids",method = RequestMethod.GET)
	public ListJsonStructure<Map<String,Object>> searchByorgids(
			@RequestParam("orgids")String orgids,
			@RequestParam("page")int page,
			@RequestParam("rows")int size) {
		Pageable pageable = new PageRequest(page-1, size);
		ListJsonStructure<Map<String,Object>> json =null;
		List<Integer> list = new ArrayList<Integer>();
		if(!orgids.isEmpty()){
			String [] arrOrgids = orgids.split(",");
			for(int i=0;i<arrOrgids.length;i++){
				list.add(Integer.valueOf(arrOrgids[i]));
			}
			json=userService.findInOrgids(list, pageable);
		}else{
			json=new ListJsonStructure<Map<String,Object>>();
		}
		json.setMsg(BaseRest.FIND_SUCCESS);
		return json;
	}

	/**
	 * url:/user/searchByOrgidAndValue
	 * 函数功能说明:条件查询当前用户组织下的用户
	 * @author 张毕思
	 * @date 2015年10月26日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param page
	 * @param @param size
	 * @param @return
	 * @return ListJsonStructure<User>
	 * @throws
	 */
	@RequestMapping(value="/searchByOrgidAndValue",method = RequestMethod.GET)
	public ListJsonStructure<Map<String,Object>> searchByOrgidAndValue(
			@RequestParam("orgids")String orgids,
			@RequestParam("value")String value,
			@RequestParam("page")int page,
			@RequestParam("rows")int size) {
		List<Integer> list = new ArrayList<Integer>();
		Pageable pageable = new PageRequest(page-1, size);
		ListJsonStructure<Map<String,Object>> json=null;
		if(!orgids.isEmpty()){
			String [] arrOrgids = orgids.split(",");
			for(int i=0;i<arrOrgids.length;i++){
				list.add(Integer.valueOf(arrOrgids[i]));
			}
			json = userService.searchByValue(list,value, pageable);
		}else{
			json = new ListJsonStructure<Map<String,Object>>();
		}
		json.setMsg(BaseRest.FIND_SUCCESS);
		return json;
	}

	/**
	 *
	 * 函数功能说明
	 * @author 李玉鹏
	 * @date 2015年5月28日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param key
	 * @param @param value
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/searchByCell",method = RequestMethod.GET)
	public SingleJsonStructure searchByCellAndUidNotInCustomer(
			@RequestParam("cell")String cell) {
		SingleJsonStructure json = new SingleJsonStructure();
		//User user = userRepository.searchByCellAndUidNotInCustomer(cell);
		User user = userRepository.findByCell(cell);
		if(user==null){
			json.setSuccess(false);
		}
		json.setRows(user);
		return json;
	}

	/**
	 *
	 * 函数功能说明:根据用户手机号或身份证或邮箱查找用户
	 * @author 刘培琪
	 * @date 2015年12月30日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param value(可以是手机号、身份证、邮箱)
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/findByItem",method = RequestMethod.GET)
	public SingleJsonStructure findByItem(@RequestParam(value="value")String value){
		SingleJsonStructure json = new SingleJsonStructure();
		User user = userRepository.findByItem(value);
		if(null == user){
			json.setSuccess(false);
		}
		json.setRows(user);
		return json;
	}

	/**
	 * url:/ynlxhealth/user/update/{uid}
	 * 函数功能说明:业务办理更新用户
	 * @author 李玉鹏
	 * @date 2015年5月13日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param user
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/update/info",method = RequestMethod.POST)
	public SingleJsonStructure updateUserInfo(@ModelAttribute User user) {
		SingleJsonStructure json = new SingleJsonStructure();
		User oldUsr = userRepository.findByCell(user.getCell());
		user.setUid(oldUsr.getUid());
		user.setModifyTime(DateTimeUtils.getSystemCurrentTimeMillis());
		user.setCreateTime(oldUsr.getCreateTime());
		user.setSecPassword(oldUsr.getSecPassword());
		user.setBindPassword(oldUsr.getBindPassword());
		//
		user.setHeight(oldUsr.getHeight());
		user.setWeight(oldUsr.getWeight());
		user.setGradSchool(oldUsr.getGradSchool());
		user.setMajor(oldUsr.getMajor());
		user.setGraduationDate(oldUsr.getGraduationDate());
		user.setOccupation(oldUsr.getOccupation());
		user.setJobTitle(oldUsr.getJobTitle());
		user.setZip(oldUsr.getZip());
		//
		if(user.getStatus()==null){
			user.setStatus("0");
		}
		User updateUser = userRepository.saveAndFlush(user);
		json.setMsg(BaseRest.UPDATE_SUCCESS);
		json.setRows(updateUser.getUid());
		System.out.println("修改房屋住户成员------------------"+json.getRows());
		return json;
	}

	/**
	 * url:/ynlxhealth/user/update/{uid}
	 * 函数功能说明:业务办理更新用户
	 * @author 李玉鹏
	 * @date 2015年5月13日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param user
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/update/info/{uid}",method = RequestMethod.POST)
	public SingleJsonStructure updateUserInfo(@PathVariable Integer uid,@ModelAttribute User user) {
		SingleJsonStructure json = new SingleJsonStructure();
		User oldUsr = userRepository.findOne(uid);
		user.setModifyTime(DateTimeUtils.getSystemCurrentTimeMillis());
		user.setCreateTime(oldUsr.getCreateTime());
		user.setSecPassword(oldUsr.getSecPassword());
		user.setBindPassword(oldUsr.getBindPassword());
		if(user.getStatus()==null){
			user.setStatus("0");
		}
		User updateUser = userRepository.saveAndFlush(user);
		json.setMsg(BaseRest.UPDATE_SUCCESS);
		json.setRows(updateUser.getUid());
		System.out.println("修改房屋住户成员------------------"+json.getRows());
		return json;
	}

	/**
	 * url:/ynlxhealth/user/update/{uid}
	 * 函数功能说明:业务办理更新用户
	 * @author 李玉鹏
	 * @date 2015年5月13日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param user
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/findByCell",method = RequestMethod.GET)
	public SingleJsonStructure findByCell(@RequestParam("cell")String cell) {
		SingleJsonStructure json = new SingleJsonStructure();
		User user = userRepository.findByCell(cell);
		if(user==null){
			json.setSuccess(true);
			return json;
		}
		json.setRows(user);
		json.setMsg(BaseRest.FIND_SUCCESS);
		json.setSuccess(false);
		return json;
	}

	/**
	 * url:/ynlxhealth/user/update/{uid}
	 * 函数功能说明:业务办理更新用户
	 * @author 李玉鹏
	 * @date 2015年5月13日
	 * 修改者名字 修改日期
	 * 修改内容
	 * @param @param user
	 * @param @return
	 * @return SingleJsonStructure
	 * @throws
	 */
	@RequestMapping(value="/findByIdNo",method = RequestMethod.GET)
	public SingleJsonStructure findByIdNo(@RequestParam("idNo")String idNo) {
		SingleJsonStructure json = new SingleJsonStructure();
		User user = userRepository.findByIdNo(idNo);
		if(user==null){
			json.setSuccess(true);
			return json;
		}
		json.setRows(user);
		json.setMsg(BaseRest.FIND_SUCCESS);
		json.setSuccess(false);
		return json;
	}

}


text:
'use strict'

var test = require('tape')

test('Sanity Check', function (t) {
  t.ok(NGNX.Loader !== undefined, 'NGNX.Loader exists.')
  t.end()
})

test('Synchronous Loading', {
  timeout: 3000
}, function (t) {
  NGNX.Loader({
    sync: [
      'https://cdnjs.cloudflare.com/ajax/libs/accounting.js/0.4.1/accounting.min.js',
      'https://cdnjs.cloudflare.com/ajax/libs/bricks.js/1.7.0/bricks.min.js'
    ]
  }, function (imported) {
    t.pass('Callback triggered')
    t.end()
  })
})


text:
'use strict';
//# sourceMappingURL=IEdmModel.js.map


text:
/**
 * Some app config stuff for global use
 */

var path = require('path');

exports["root"]           = __dirname;
exports["client"]			    = path.join( __dirname, "client" );
exports["clientApp"]		  = path.join( exports["client"], "app" );
exports["clientTmp"]		  = path.join( exports["client"], ".tmp" );
exports["clientTest"]	    = path.join( exports["client"], "test" );
exports["server"]         = path.join( __dirname, "server" );
exports["serverApp"]      = path.join( exports["server"], "app" );
exports["serverTest"]     = path.join( exports["server"], "test" );
exports["serverTestPort"] = 2455;
exports["serverPort"]     = 8000;
exports["serverTestArgs"] = ['--forceexit', '--verbose', '--color', '--captureExceptions', '--growl'];
exports["serverTestExec"] = path.join( __dirname, 'node_modules/jasmine-node/bin/jasmine-node' );
exports["dist"]				    = path.join( __dirname, "public" );


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Copy text to another element</title>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

This is program to copy text using javascript.

      <form action="#">

          <input type="text" class="form-control" id="input1">

          <input type="text" class="form-control" id="input2">

        <button class="btn btn-primary" onclick="copyText()">Copy text</button>
      </form>


text:
package mysql

import (
	"github.com/jkomoros/boardgame"
	"github.com/jkomoros/boardgame/storage/internal/test"
	"github.com/jkomoros/boardgame/storage/mysql/connect"
	"github.com/mattes/migrate"
	"github.com/workfit/tester/assert"
	"log"
	"os"
	"testing"
)

const (
	testDSN          = "root:root@tcp(localhost:3306)/TEMPORARY_DATABASE_boardgame_test"
	pathToMigrations = "$GOPATH/src/github.com/jkomoros/boardgame/storage/mysql/migrations/"
)

//If outputTables is true, then will print create_tables.sql
const outputTables = false

func TestOutputTables(t *testing.T) {
	if !outputTables {
		return
	}

	filename := "create_tables.sql"

	log.Println("Outputing tables to", filename)

	if _, err := os.Stat(filename); err == nil {
		log.Println("That file already exists. Quitting. Delete it if you want to create a new one.")
		return
	}

	f, err := os.Create(filename)

	if err != nil {
		log.Println("Couldn't open file:", err)
	}

	defer f.Close()

	manager := NewStorageManager(true)
	manager.Connect("root:root@tcp(localhost:3306)/boardgame_test")

	logger := log.New(f, "", 0x0)

	manager.dbMap.TraceOn("", logger)

	manager.dbMap.CreateTablesIfNotExists()

}

func GetTestDatabase(t *testing.T) *StorageManager {

	db, err := connect.Db(testDSN, true, true)

	if err != nil {
		t.Fatal("Couldn't get db: " + err.Error())
		return nil
	}

	m, err := connect.Migrations(db)

	if err != nil {
		t.Fatal("Couldn't get migrations: " + err.Error())
		return nil
	}

	if err := m.Up(); err != nil {
		if err != migrate.ErrNoChange {
			t.Fatal("Couldn't upgrade test database: ", err.Error())
			return nil
		}
	}

	m.Close()

	return NewStorageManager(true)

}

func TestStorageManager(t *testing.T) {

	test.Test(func() test.StorageManager {
		return GetTestDatabase(t)
	}, "mysql", testDSN, t)

}

func TestWinnersConversion(t *testing.T) {
	tests := []struct {
		input       string
		result      []boardgame.PlayerIndex
		expectError bool
	}{
		{
			"",
			nil,
			false,
		},
		{
			"1,2",
			[]boardgame.PlayerIndex{1, 2},
			false,
		},
		{
			"-1",
			[]boardgame.PlayerIndex{-1},
			false,
		},
		{
			"1,2,",
			nil,
			true,
		},
	}

	for i, test := range tests {
		winners, err := stringToWinners(test.input)

		if test.expectError {
			assert.For(t, i).ThatActual(err).IsNotNil()
			continue
		} else {
			assert.For(t, i).ThatActual(err).IsNil()
		}

		assert.For(t, i).ThatActual(winners).Equals(test.result).ThenDiffOnFail()

		reInput := winnersToString(test.result)

		assert.For(t, i).ThatActual(reInput).Equals(test.input)
	}
}


text:
layout: default
---
{% include breadcrumb.html %}

{{ page.title }}

{{ content }}

{% include pagination.html %}


text:
.site-header {
  background-image: url("/images/background.jpg");
}

.thumb-button {
  display: inline-block;
}

.comment-area-separator-question {
  margin-top: 12px;
  border-bottom: 2px solid #337ab7;
}

.comment-area-separator-answer {
  margin-top: 12px;
  border-bottom: 2px solid #e3e3e3;
}

.question-detail {
  margin-top: 12px;
}


text:
from __future__ import unicode_literals

import re
from datetime import date

from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select
from django.utils.translation import ugettext_lazy as _

from .ee_counties import COUNTY_CHOICES

idcode = re.compile(r'^([1-6])(\d\d)(\d\d)(\d\d)(?:\d{3})(\d)$')
zipcode = re.compile(r'^[1-9]\d{4}$')
bregcode = re.compile(r'^[1-9]\d{7}$')

class EEZipCodeField(RegexField):
    """
    A form field that validates input as a Estonian zip code. Valid codes
    consist of five digits; first digit cannot be 0.
    """
    default_error_messages = {
        'invalid': _('Enter a zip code in the format XXXXX.'),
    }

    def __init__(self, max_length=None, min_length=None, *args, **kwargs):
        super(EEZipCodeField, self).__init__(zipcode, max_length, min_length, *args, **kwargs)

class EECountySelect(Select):
    """
    A Select widget that uses a list of Estonian counties as its choices.
    """
    def __init__(self, attrs=None):
        super(EECountySelect, self).__init__(attrs, choices=COUNTY_CHOICES)

class EEPersonalIdentificationCode(Field):
    """A form field that validates input as an Estonian personal identification code.

    See: https://www.riigiteataja.ee/akt/106032012004
    """
    default_error_messages = {
        'invalid_format': _('Enter an 11-digit Estonian personal identification code.'),
        'invalid': _('Enter a valid Estonian personal identification code.'),
    }

    @staticmethod
    def ee_checksum(value):
        """Takes a string of digits as input, returns check digit."""

        for i in (1, 3):
            check = 0
            for c in value:
                check += i * int(c)
                i = (i % 9) + 1
            check %= 11
            if check < 10:
                return check
            # If check==10 then we do another loop starting at i=3

        return check % 10

    def clean(self, value):
        super(EEPersonalIdentificationCode, self).clean(value)
        if value in EMPTY_VALUES:
            return ''

        match = re.match(idcode, value)
        if not match:
            raise ValidationError(self.error_messages['invalid_format'])

        century, year, month, day, check = map(int, match.groups())

        if check != self.ee_checksum(value[:10]):
            raise ValidationError(self.error_messages['invalid'])

        # Century digit also encodes gender:
        # 1 - male born in 18xx
        # 2 - female born in 18xx
        # 3 - male born in 19xx
        # ...
        year += 1800 + 100 * ((century - 1) // 2)
        try:
            date(year, month, day)
        except ValueError:
            raise ValidationError(self.error_messages['invalid'])

        return value

class EEBusinessRegistryCode(Field):
    """A form field that validates input as an
    Estonian business registration code.

    .. versionadded:: 1.2
    """
    default_error_messages = {
        'invalid_format': _('Enter an 8-digit Estonian business registry code.'),
        'invalid': _('Enter a valid Estonian business registry code.'),
    }

    def clean(self, value):
        value = super(EEBusinessRegistryCode, self).clean(value)
        if value in EMPTY_VALUES:
            return ''
        value = value.strip()

        match = re.match(bregcode, value)
        if not match:
            raise ValidationError(self.error_messages['invalid_format'])

        check = int(value[7])

        if check != EEPersonalIdentificationCode.ee_checksum(value[:7]):
            raise ValidationError(self.error_messages['invalid'])

        return value


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStructures.Queue {
    class Program {
        static void Main (string[] args) {
            var random = new Random();
            var queue = new Queue<int>();
            for (int i = 0; i < 10; i++) {
                queue.Enqueue(random.Next(0,100));
            }

            foreach (var item in queue) {
                Console.WriteLine(item);
            }

            for (int i = 0; i < 11; i++) {
                queue.Dequeue();
            }

            Console.ReadKey();
        }
    }
}


text:
inline void* mmap(void* addr, size_t length, int prot, int flags, int fd, size_t offset) {
    if (prot & ~(PROT_READ | PROT_WRITE | PROT_EXEC))
        return MAP_FAILED;
    if (fd == -1) {
        if (!(flags & MAP_ANONYMOUS) || offset)
            return MAP_FAILED;
    } else if (flags & MAP_ANONYMOUS)
        return MAP_FAILED;

    DWORD protect;
    if (prot & PROT_WRITE) {
        if (prot & PROT_EXEC)
            protect = PAGE_EXECUTE_READWRITE;
        else
            protect = PAGE_READWRITE;
    } else if (prot & PROT_EXEC) {
        if (prot & PROT_READ)
            protect = PAGE_EXECUTE_READ;
        else
            protect = PAGE_EXECUTE;
    } else
        protect = PAGE_READONLY;

    size_t end = length + offset;
    const DWORD dwEndLow = (sizeof(size_t) > sizeof(DWORD)) ? DWORD(end & 0xFFFFFFFFL) : DWORD(end);
    const DWORD dwEndHigh = (sizeof(size_t) > sizeof(DWORD)) ? DWORD((end >> 32) & 0xFFFFFFFFL) : DWORD(0);
    const DWORD dwOffsetLow = (sizeof(size_t) > sizeof(DWORD)) ? DWORD(offset & 0xFFFFFFFFL) : DWORD(offset);
    const DWORD dwOffsetHigh = (sizeof(size_t) > sizeof(DWORD)) ? DWORD((offset >> 32) & 0xFFFFFFFFL) : DWORD(0);

    HANDLE h = (fd != -1) ? HANDLE(uv_get_osfhandle(fd)) : INVALID_HANDLE_VALUE;
    HANDLE fm = CreateFileMapping(h, nullptr, protect, dwEndHigh, dwEndLow, nullptr);
    if (fm == nullptr)
        return MAP_FAILED;

    DWORD dwDesiredAccess;
    if (prot & PROT_WRITE)
        dwDesiredAccess = FILE_MAP_WRITE;
    else
        dwDesiredAccess = FILE_MAP_READ;
    if (prot & PROT_EXEC)
        dwDesiredAccess |= FILE_MAP_EXECUTE;
    if (flags & MAP_PRIVATE)
        dwDesiredAccess |= FILE_MAP_COPY;

    void* map = MapViewOfFile(fm, dwDesiredAccess, dwOffsetHigh, dwOffsetLow, length);
    CloseHandle(fm);

    return (map != nullptr) ? map : MAP_FAILED;
}

inline int munmap(void* addr, size_t length) {
    if (UnmapViewOfFile(addr))
        return 0;

    errno = GetLastError();
    return -1;
}

inline int msync(void* addr, size_t length, int flags) {
    if (FlushViewOfFile(addr, length))
        return 0;

    errno = GetLastError();
    return -1;
}

inline int madvise(void* addr, size_t length, int advice) {
    return 0;   // Unsupported on Windows
}

inline int mincore(void *addr, size_t length, unsigned char *vec) {
    errno = ENOSYS;
    return -1;
}


text:
package org.apache.polygene.library.sql.generator.implementation.grammar.common.datatypes;

import org.apache.polygene.library.sql.generator.grammar.common.datatypes.SmallInt;

/**
 * @author Stanislav Muhametsin
 */
public final class SmallIntImpl
    implements SmallInt
{
    public SmallIntImpl()
    {
    }

    /**
     * Returns {@link SmallInt}.
     */
    public Class<SmallInt> getImplementedType()
    {
        return SmallInt.class;
    }

    /**
     * The singleton instance of {@code SMALLINT}.
     */
    public static final SmallInt INSTANCE = new SmallIntImpl();
}


text:
module.exports = LoadsImporters

const resolve = require.resolve

function LoadsImporters (importers) {
  const load = importers.load.bind(importers)

  /*
  load(
    require('./create_root_portfolio.js'),
    { uri: resolve('./create_root_portfolio.js'), id: 'portfolios/root' }
  )
  */
}


text:
from common.challenge import MatasanoChallenge
from common.tools.padders import PKCS7Padder, PKCS7Unpadder
from common.tools.padders import InvalidPaddingException

class Set2Challenge15(MatasanoChallenge):

    STRING = 'ICE ICE BABY'
    SIZE = 16

    def _test_valid_padding(self):
        padded_string = PKCS7Padder(self.STRING).value(self.SIZE)
        unpadded_string = PKCS7Unpadder(padded_string).value()
        return unpadded_string == self.STRING

    def _test_invalid_padding(self):
        ill_padded_string = self.STRING + chr(5)*4
        if not self._assert_raises(InvalidPaddingException,
                                   PKCS7Unpadder(ill_padded_string).value):
            return False

        ill_padded_string = self.STRING + chr(1) + chr(2) + chr(3) + chr(4)
        if not self._assert_raises(InvalidPaddingException,
                                   PKCS7Unpadder(ill_padded_string).value):
            return False
        return True

    def validate(self):
        valid_padding = self._test_valid_padding()
        invalid_padding = self._test_invalid_padding()
        return valid_padding and invalid_padding