text:
require 'sequel/core'

module Sequel
  # Lets you create a Model subclass with its dataset already set.
  # +source+ should be an instance of one of the following classes:
  #
  # Database :: Sets the database for this model to +source+.
  #             Generally only useful when subclassing directly
  #             from the returned class, where the name of the
  #             subclass sets the table name (which is combined
  #             with the +Database+ in +source+ to create the
  #             dataset to use)
  # Dataset :: Sets the dataset for this model to +source+.
  # other :: Sets the table name for this model to +source+. The
  #          class will use the default database for model
  #          classes in order to create the dataset.
  #
  # The purpose of this method is to set the dataset/database automatically
  # for a model class, if the table name doesn't match the implicit
  # name.  This is neater than using set_dataset inside the class,
  # doesn't require a bogus query for the schema.
  #
  #   # Using a symbol
  #   class Comment < Sequel::Model(:something)
  #     table_name # => :something
  #   end
  #
  #   # Using a dataset
  #   class Comment < Sequel::Model(DB1[:something])
  #     dataset # => DB1[:something]
  #   end
  #
  #   # Using a database
  #   class Comment < Sequel::Model(DB1)
  #     dataset # => DB1[:comments]
  #   end
  def self.Model(source)
    if Sequel::Model.cache_anonymous_models && (klass = Sequel.synchronize{Model::ANONYMOUS_MODEL_CLASSES[source]})
      return klass
    end
    klass = if source.is_a?(Database)
      c = Class.new(Model)
      c.db = source
      c
    else
      Class.new(Model).set_dataset(source)
    end
    Sequel.synchronize{Model::ANONYMOUS_MODEL_CLASSES[source] = klass} if Sequel::Model.cache_anonymous_models
    klass
  end

  # <tt>Sequel::Model</tt> is an object relational mapper built on top of Sequel core.  Each
  # model class is backed by a dataset instance, and many dataset methods can be
  # called directly on the class.  Model datasets return rows as model instances,
  # which have fairly standard ORM instance behavior.
  #
  # <tt>Sequel::Model</tt> is built completely out of plugins.  Plugins can override any class,
  # instance, or dataset method defined by a previous plugin and call super to get the default
  # behavior.  By default, <tt>Sequel::Model</tt> loads two plugins, <tt>Sequel::Model</tt>
  # (which is itself a plugin) for the base support, and <tt>Sequel::Model::Associations</tt>
  # for the associations support.
  #
  # You can set the +SEQUEL_NO_ASSOCIATIONS+ constant or environment variable to
  # make Sequel not load the associations plugin by default.
  class Model
    # Cache anonymous models created by Sequel::Model()
    @cache_anonymous_models = true

    # Map that stores model classes created with <tt>Sequel::Model()</tt>, to allow the reopening
    # of classes when dealing with code reloading.
    ANONYMOUS_MODEL_CLASSES = {}

    # Class methods added to model that call the method of the same name on the dataset
    DATASET_METHODS = (Dataset::ACTION_METHODS + Dataset::QUERY_METHODS +
      [:eager, :eager_graph, :each_page, :each_server, :print]) - [:and, :or, :[], :[]=, :columns, :columns!]

    # Class instance variables to set to nil when a subclass is created, for -w compliance
    EMPTY_INSTANCE_VARIABLES = [:@overridable_methods_module, :@db]

    # Boolean settings that can be modified at the global, class, or instance level.
    BOOLEAN_SETTINGS = [:typecast_empty_string_to_nil, :typecast_on_assignment, :strict_param_setting, \
      :raise_on_save_failure, :raise_on_typecast_failure, :require_modification, :use_after_commit_rollback, :use_transactions]

    # Hooks that are called before an action.  Can return false to not do the action.  When
    # overriding these, it is recommended to call +super+ as the last line of your method,
    # so later hooks are called before earlier hooks.
    BEFORE_HOOKS = [:before_create, :before_update, :before_save, :before_destroy, :before_validation]

    # Hooks that are called after an action.  When overriding these, it is recommended to call
    # +super+ on the first line of your method, so later hooks are called after earlier hooks.
    AFTER_HOOKS = [:after_initialize, :after_create, :after_update, :after_save, :after_destroy,
      :after_validation, :after_commit, :after_rollback, :after_destroy_commit, :after_destroy_rollback]

    # Hooks that are called around an action.  If overridden, these methods must call super
    # exactly once if the behavior they wrap is desired.  The can be used to rescue exceptions
    # raised by the code they wrap or ensure that some behavior is executed no matter what.
    AROUND_HOOKS = [:around_create, :around_update, :around_save, :around_destroy, :around_validation]

    # Empty instance methods to create that the user can override to get hook/callback behavior.
    # Just like any other method defined by Sequel, if you override one of these, you should
    # call +super+ to get the default behavior (while empty by default, they can also be defined
    # by plugins).  See the {"Model Hooks" guide}[link:files/doc/model_hooks_rdoc.html] for
    # more detail on hooks.
    HOOKS = BEFORE_HOOKS + AFTER_HOOKS

    # Class instance variables that are inherited in subclasses.  If the value is <tt>:dup</tt>, dup is called
    # on the superclass's instance variable when creating the instance variable in the subclass.
    # If the value is +nil+, the superclass's instance variable is used directly in the subclass.
    INHERITED_INSTANCE_VARIABLES = {:@allowed_columns=>:dup, :@dataset_methods=>:dup,
      :@dataset_method_modules=>:dup, :@primary_key=>nil, :@use_transactions=>nil,
      :@raise_on_save_failure=>nil, :@require_modification=>nil,
      :@restricted_columns=>:dup, :@restrict_primary_key=>nil,
      :@simple_pk=>nil, :@simple_table=>nil, :@strict_param_setting=>nil,
      :@typecast_empty_string_to_nil=>nil, :@typecast_on_assignment=>nil,
      :@raise_on_typecast_failure=>nil, :@plugins=>:dup, :@setter_methods=>nil,
      :@use_after_commit_rollback=>nil, :@fast_pk_lookup_sql=>nil,
      :@fast_instance_delete_sql=>nil}

    # Regular expression that determines if a method name is normal in the sense that
    # it could be used literally in ruby code without using send.  Used to
    # avoid problems when using eval with a string to define methods.
    NORMAL_METHOD_NAME_REGEXP = /\A[A-Za-z_][A-Za-z0-9_]*\z/

    # Regular expression that determines if the method is a valid setter name
    # (i.e. it ends with =).
    SETTER_METHOD_REGEXP = /=\z/

    @allowed_columns = nil
    @db = nil
    @db_schema = nil
    @dataset_method_modules = []
    @dataset_methods = {}
    @overridable_methods_module = nil
    @plugins = []
    @primary_key = :id
    @raise_on_save_failure = true
    @raise_on_typecast_failure = true
    @require_modification = nil
    @restrict_primary_key = true
    @restricted_columns = nil
    @setter_methods = nil
    @simple_pk = nil
    @simple_table = nil
    @strict_param_setting = true
    @typecast_empty_string_to_nil = true
    @typecast_on_assignment = true
    @use_after_commit_rollback = true
    @use_transactions = true

    Sequel.require %w"default_inflections inflections plugins base exceptions errors", "model"
    if !defined?(::SEQUEL_NO_ASSOCIATIONS) && !ENV.has_key?('SEQUEL_NO_ASSOCIATIONS')
      Sequel.require 'associations', 'model'
      plugin Model::Associations
    end

    # The setter methods (methods ending with =) that are never allowed
    # to be called automatically via +set+/+update+/+new+/etc..
    RESTRICTED_SETTER_METHODS = instance_methods.map{|x| x.to_s}.grep(SETTER_METHOD_REGEXP)
  end
end


text:
package boq.cctags.client;

import net.minecraft.server.ServerListenThread;
import net.minecraft.server.ThreadMinecraftServer;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import boq.cctags.IProxy;
import boq.cctags.tag.EntityTag;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.client.registry.RenderingRegistry;

public class ClientProxy implements IProxy {

    @Override
    public void registerRenderers() {
        EntityTagRenderer tagRender = new EntityTagRenderer();
        RenderingRegistry.registerEntityRenderingHandler(EntityTag.class, tagRender);
        MinecraftForge.EVENT_BUS.register(tagRender);
    }

    @Override
    public World getClientWorld() {
        return FMLClientHandler.instance().getClient().theWorld;
    }

    @Override
    public boolean isServer() {
        Thread thr = Thread.currentThread();
        return thr instanceof ThreadMinecraftServer || thr instanceof ServerListenThread;
    }
}

redpajama_set_name: RedPajamaGithub


text:
module.exports = {
    entry: "./src/entry-editor.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.js$/, exclude: /node_modules|3rd_party/, loader: "babel-loader?optional=runtime" }
        ]
    },
    devtool: 'source-map'
}


text:
@interface FirstViewController ()

@end

@implementation FirstViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = self.title;
    [self refreshControl];
    [self fetchAnnouncements];
}

- (IBAction)refreshTriggered:(id)sender {
    [self fetchAnnouncements];
    [sender endRefreshing];
}

- (void)fetchAnnouncements
{
    NSLog(@"Can reach Google: %s", [self canReachGoogle] ? "Cake" : "No Cake");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData* data = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString: @"http://django.sianware.com/app/json/announcements/"]];
        if (data == nil) {
            NSLog(@"canReachGoogle: %s", [self canReachGoogle] ? "Sucess" : "FAIL");
            if([self canReachGoogle]) {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"App Club Unreachable"
                                                                    message:@"The Canyons App Club servers are not reachable. This could be due to maintanance, or something unexpected has happended."
                                                                   delegate:nil
                                                          cancelButtonTitle:@"Okay"
                                                          otherButtonTitles:nil];
                    [alert show];
                });
            } else {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No network connection"
                                                                    message:@"You must be connected to the internet to use this app."
                                                                   delegate:nil
                                                          cancelButtonTitle:@"Okay, I'll get interwebz"
                                                          otherButtonTitles:nil];
                    [alert show];
                });
            }
        } else {
            NSError* error;
            NSArray *incomingAnnouncements = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
            refreshDataIdentical = [incomingAnnouncements isEqualToArray:announcements];
            // # # # # # Good ol' fashion logging
            if(refreshDataIdentical) {
                NSLog(@"Refresh data is identical to previously loaded data...");
            } else {
                NSLog(@"OMG NEW DATAZ");
            }
            // # # # # #

            if(!refreshDataIdentical) {
                announcements = incomingAnnouncements;
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"Reloading Table data");
                    [self.tableView reloadData];
                });
            }
        }
    });
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"Announcements.count: %lu", (unsigned long)announcements.count);
    return announcements.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"AnnouncementCell";

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    NSDictionary *announcement = [announcements objectAtIndex:indexPath.row];
    cell.textLabel.text = [[announcement objectForKey:@"fields"] objectForKey:@"title"];
    cell.detailTextLabel.text = [[announcement objectForKey:@"fields"] objectForKey:@"content"];
    return cell;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showAnnouncementDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        NSDictionary *object = announcements[indexPath.row];
        [[segue destinationViewController] setDetailItem:object];
    }
}

- (bool) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    int code = (int)[httpResponse statusCode];
    if (code == 200) {
        NSLog(@"We can hit Google! -- Success!!");
        return true;
    } else {
        NSLog(@"We're failing to reach Google...");
        return false;
    }
}

- (bool) canReachGoogle {
    NSString *serverAddress = @"http://google.com/blank.html";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverAddress]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                       timeoutInterval:1];

    [request setHTTPMethod: @"GET"];
//    NSError *requestError;
//    NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];

    NSURLConnection *urlConnection = [NSURLConnection connectionWithRequest:request delegate:self];
    NSURLResponse *urlResponse = nil;
//    if([NSURLConnection canHandleRequest:request]) {
    NSLog(@"%d", [self connection:urlConnection didReceiveResponse:urlResponse]);
    return [self connection:urlConnection didReceiveResponse:urlResponse];
//    } else {
//        return NO;
//    }
}

// # # # # # # # # # # # # # # # # # #
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}
// # # # # # # # # # # # # # # # # # #

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
import React,{Component} from 'react';
import ReactDOM from 'react-dom';
// import ajax
import { ajax } from 'api/ajax';
import List from '../../components/List/List'
import './index.css'

class ComponentBase extends Component{

  constructor(props, context) {
    super(props, context);
  }

  componentDidMount(){

  }

  render() {
    return (

基类
        <Crop/>

    )
  }
}

class Crop extends Component{
  constructor(props, context) {
    super(props, context);
    this.state = {
      data: [],
      metaData:{},
      num : 1,
      flagData : false,
      isAjax:false
    }
  }
  componentWillMount(){

  }
  componentDidMount(){
    this.init();
    //this.ajaxRquest();
  }
  init = () => {
    if($summer.os=='pc'){
      this.ajaxRquest(10);
    }else{
      summer.on("ready",this.ready);
    }
  }
  ready = () => {
    let _this = this;
    //this.ajaxRquest();
    let id = "1";//随便设置一个
    if(summer.getStorage('userinfo')){
      id=summer.getStorage('userinfo').id;
    }
    let myCorp=summer.getStorage(id+'myCorp') ? summer.getStorage(id+'myCorp'):[];
    if(myCorp && myCorp.length !=0){
      _this.setState({
        data:myCorp,
        isAjax:true
      })
    }else {
      _this.ajaxRquest();
    }
    summer.setRefreshHeaderInfo({
      visible: true,
      bgColor: '#ffffff',
      textColor: '#4d4d4d',
      textDown: '下拉刷新...',
      textUp: '松开刷新...',
      showTime: true,
      autoRefresh: false
    }, function (ret, err) {
      _this.ajaxRquest();
      summer.refreshHeaderLoadDone();
    });
    // 上拉刷新
    summer.setRefreshFooterInfo({
      visible: true,
      bgColor: '#ffffff',
      textColor: '#4d4d4d',
      textDown: '下拉刷新...',
      textUp: '松开刷新...',
      showTime: true,
    }, function (ret, err) {
      _this.ajaxRquest(_this.state.num + 1);

    });
  }

  listClick =(id) =>{
    let param = {
      componentId: "cardView",
      componentName: "cardView",
      componentOpenType: "createAndOpen",// createAndOpen | openIfExists | openIfExistOrCreateOpen
      componentParams:{
        id: id,
        startPage: "../FI/Home.html"
      },
      callback: function(){}
    };
    summer.openComponent(param);
  }

  ajaxRquest =(n=1) => {
    let _this = this;
    let param = {
      "pageNum" : n
    };
    let ua = navigator.userAgent;
    let osType = {
      ios: !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
      android: ua.indexOf('Android') > -1 || ua.indexOf('Linux') > -1, //android终端或uc浏览器
    }
    let os = $summer.os;
    if(osType.ios){
      os = "ios";
    }else if(osType.android){
      os="android";
    }
    //debugger;
    ajax({
      "type": "get",
      //"url": "/user/load",
      "url": "/userlink/getMyCorpUser",
      "param":{
        "meta": JSON.stringify({
            "clientType": os,
            "componentId":"list001"
        }),
        "id":"just a demo"
      },
    },function(data){
      //debugger;
      _this.setState({
        isAjax:true
      })
      if (data.flag == 0){
        if(data.metaData){
          _this.setState({metaData : data.metaData});
        }
        var listData = data.data;
        if (n == 1){
          if(summer.getStorage('userinfo')){
            let id=summer.getStorage('userinfo').id;
            summer.setStorage(id+'myCorp',listData);
          }
          _this.setState({data : listData});
          _this.setState({num : 1});
          _this.setState({flagData:true});
        }else{
          summer.refreshFooterLoadDone();
          if(!listData.length){
            summer.toast({
              msg : "没有数据了"
            });
            return;
          }
          let num = _this.state.num;
          num += 1;
          _this.setState({num : num});
          let dataArr = _this.state.data;
          let conData = dataArr.concat(listData);
          _this.setState({data : conData});
        }
      }else{  // 请求成功但数据格式错误
        summer.toast({
          msg : data.msg
        });
      }
    },function(res){
      console.log(res);
    });
  }
  closeFn =() => {

        summer.closeComponent({
            componentId: "Corp"
        });
  }

  render() {
    let content=null;
    if(this.state.data.length==0 && !this.state.isAjax){
      content=
    }else {
      content=<List data={this.state.data} flagData={this.state.flagData} metaData={this.state.metaData} listFn={this.listClick}/>
    }
    return (

                    返回

联系人

          {content}

    )
  }
}
//ReactDOM.render(<Crop/>, document.querySelector("#app"))
ReactDOM.render(<ComponentBase/>, document.querySelector("#app"))


text:
var Hookz = require("../");
var Assert = require('assert');
var _ = require('underscore');

describe('addHookOnce', function () {

  context("basic usage", function() {
    var hooker = {
      counter1 : 0 ,
      counter2 : 0
    };
    var hookable = {
      ___a : function () { return this; },
      ___b : function () { return this; },
      ___c : function () { return this; }
    };

    Hookz.call(hooker);
    Hookz.call(hookable);

    var callback1 = function () { hooker.counter1 += 1; };
    var callback2 = function () { hooker.counter2 += 1; };

    it("hooked methods should run just once", function () {
      hooker.addHookOnce(hookable, 'a', callback1);
      hooker.addHookOnce(hookable, 'b', callback2);
      hookable.a().a().a();
      hookable.b().b().b().b();
      Assert.strictEqual(hooker.counter1, 1);
      Assert.strictEqual(hooker.counter2, 1);
    });

    it("hookable methods can be removed", function() {
      hooker.removeHook();
      hooker.counter1 = 0;
      hooker.counter2 = 0;
      hooker.addHookOnce(hookable, 'a', callback1);
      hookable.a().a();
      hooker.addHookOnce(hookable, 'b', callback2);
      hooker.removeHook();
      hookable.a().b();
      Assert.strictEqual(hooker.counter1, 1);
      Assert.strictEqual(hooker.counter2, 0);
    });

    it("addHook, addHookOnce and removeHook", function() {
      hooker.removeHook();
      hooker.counter1 = 0;
      hooker.counter2 = 0;
      hooker.addHookOnce(hookable, 'a', callback1);
      hookable.a().a();
      hooker.addHook(hookable, 'a', callback1);
      hooker.removeHook();
      hookable.a().a();
      Assert.strictEqual(hooker.counter1, 1);
    });
  });

  context("variant one", function() {

    var hooker = { counter : 0 }, ctx = {};

    var hookable = {
      ___a : function () { return this; }
    };

    var callback = function () { hooker.counter += 1;};

    Hookz.call(hooker);
    Hookz.call(hookable);

    // var f = function(){ ok(true); };
    // var a = Hookz.call({}).once('event', f);
    // var b = Hookz.call({}).on('event', f);
    hooker.addHookOnce(hookable, 'a', callback);
    hooker.addHook(hookable, 'a', callback);
    hookable.a().a().a();

    it("counter should be 4", function () {
      Assert.strictEqual(hooker.counter, 4);
    });
  });

  context("variant two", function() {
    var hooker = { counter : 0 }, ctx = {};

    var hookable = {
      ___a : function () { return this; }
    };

    var callback = function () { hooker.counter += 1;};

    Hookz.call(hooker);
    Hookz.call(hookable);

    it("counter should be 3", function () {
      hooker
        .addHookOnce(hookable, 'a', callback)
        .addHook(hookable, 'a', callback);
      hookable.a().a();
      Assert.strictEqual(hooker.counter, 3);
    });
  });

  context("with removeHook", function() {
    var hooker = { counter : 0 }, ctx = {};

    var hookable = {
      ___a : function () { return this; }
    };

    var callback = function () { hooker.counter += 1;};

    Hookz.call(hooker);
    Hookz.call(hookable);

    it("counter should be 0", function () {
      hooker.addHookOnce(hookable, 'a', callback);
      hooker.removeHook(hookable, 'a', callback);
      hookable.a();
      Assert.strictEqual(hooker.counter, 0);
    });
  });

  context("cleans up references after the hookMethod has fired", function() {
    var hooker = {};

    var hookable = {
      ___a : function () {},
      ___b : function () {}
    };

    Hookz.call(hooker);
    Hookz.call(hookable);

    var callback1 = function () {};
    var callback2 = function () {};

    it("without context ", function () {
      hooker.addHookOnce(hookable, 'a', callback1);
      hookable.a();
      Assert.strictEqual(_.size(hooker._listeningTo), 0);
      Assert.strictEqual(_.size(hookable._listeners), 0);
    });

    it("with hook maps", function() {
      hooker.addHookOnce(hookable, {
        a : callback1,
        b : callback2
      });
      hookable.a();
      Assert.strictEqual(_.size(hooker._listeningTo), 1);
      Assert.strictEqual(_.size(hookable._listeners), 1);
      hookable.b();
      Assert.strictEqual(_.size(hooker._listeningTo), 0);
      Assert.strictEqual(_.size(hookable._listeners), 0);
    });

    it("with hook maps binds the correct `this`", function() {
      hooker.addHookOnce(hookable, {
        a : function () { Assert.strictEqual(hooker, this)}
      });
      hookable.a();
    });
  });

  context("empty callback doesn't throw an error", function(){
    var hooker = {};

    var hookable = {
      ___a : function () {return this;}
    };

    Hookz.call(hooker);
    Hookz.call(hookable);

    it("there is no error", function () {
      hooker.addHookOnce(hookable, 'a', null);
      hookable.a();
    });
  });

  context("with hook maps", function() {
    var hooker = { counter : 0 };

    var hookable = {
      ___a : function () { return this; },
      ___b : function () { return this; },
      ___c : function () { return this; }
    };

    var callback = function () { hooker.counter += 1;};

    Hookz.call(hooker);
    Hookz.call(hookable);

    hooker.addHookOnce(hookable, {
      a : callback,
      b : callback,
      c : callback
    });

    it("counter should be 1", function () {
      hookable.a();
      Assert.strictEqual(hooker.counter, 1);
    });

    it("counter should be 2", function () {
      hookable.a().b();
      Assert.strictEqual(hooker.counter, 2);
    });

    it("counter should be 3", function () {
      hookable.c();
      Assert.strictEqual(hooker.counter, 3);
    });

    it("counter should be 3", function () {
      hookable.a().b().c();
      Assert.strictEqual(hooker.counter, 3);
    });
  });

  context("with removeHook only by context", function() {
    var hooker = { counter : 0 };
    var ctx = {};

    var hookable = {
      ___a : function () { return this; }
    };

    var callback = function () { hooker.counter += 1;};

    Hookz.call(hooker);
    Hookz.call(hookable);

    it("counter should be 0", function () {
      hooker.addHookOnce(hookable, 'a', callback, ctx);
      hooker.removeHook(null, null, ctx);
      hookable.a().a().a();
      Assert.strictEqual(hooker.counter, 0);
    });
  });

  context("with asynchronous hooks", function() {
    var hooker = { counter : 0 };

    var hookable = {
      ___a : function () { return this; }
    };

    Hookz.call(hooker);
    Hookz.call(hookable);

    it("counter should be 1", function (done) {
      var callback = function () {
        setTimeout(function () {
          hooker.counter += 1;
          if (hooker.counter > 1) throw new Error('This should not be thrown');
        }, 20);
      };
      hooker.addHookOnce(hookable, 'a', callback);
      hookable.a().a();
      setTimeout(done, 50);
    });
  });

  context("with multiple hooks.", function() {
    var hooker = { counter : 0 };

    var hookable = {
      ___a : function () { return this; },
      ___b : function () { return this; }
    };

    Hookz.call(hooker);
    Hookz.call(hookable);

    var callback = function () { hooker.counter += 1;};

    it('counter should be 2', function () {
      hooker.addHookOnce(hookable, 'a b', callback);
      hookable.a().b().a().b();
      Assert.strictEqual(hooker.counter, 2);
    });
  });

  context("removeHook during iteration with addHookOnce.", function() {
    var hooker = { counter : 0 };

    var hookable = {
      ___a : function () { return this; }
    };

    Hookz.call(hooker);
    Hookz.call(hookable);

    var callback = function () { hooker.counter += 1; this.removeHook(hookable, 'a', callback); };

    it("counter should be 2", function () {
      hooker.addHook(hookable, 'a', callback);
      hooker.addHookOnce(hookable, 'a', callback);
      hookable.a().a().a().a();
      Assert.strictEqual(hooker.counter, 2);
    });
  });

  context("addHookOnce without a callback is a noop", function() {
    var hooker = {};

    var hookable = {
      ___a : function () { return this; }
    };

    Hookz.call(hooker);
    Hookz.call(hookable);

    function callback () {
      throw new Error("this should not be thrown");
    }

    it("there should be nothing", function () {
      hooker.addHookOnce(hookable,'a');
      hookable.a();
    });
  });

  context("addHookOnce with space-separated hooks", function() {
    var hooker = { counter : 0 };

    var hookable = {
      ___a : function () { return this; },
      ___b : function () { return this; }
    };

    Hookz.call(hooker);
    Hookz.call(hookable);

    var callback = function () { hooker.counter += 1; };

    hooker.addHookOnce(hookable, 'a b', callback);

    it("counter should be 1", function  () {
      hookable.a().a().a().a();;
      Assert.strictEqual(hooker.counter, 1);
    });

    it("counter should be 2", function () {
      hookable.b().b().a().a().b().b();
      Assert.strictEqual(hooker.counter, 2);
    });
  });

});


text:
<?php

namespace Ach\PoManagerBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PoItemRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PoItemRepository extends EntityRepository
{

	public function findPoNum($poNum, $filterDate, $exact)
	{
		$query = $this->_em->createQuery('SELECT i FROM AchPoManagerBundle:PoItem i JOIN i.po p WHERE p.num like :num AND i.dueDate >= :earliest AND i.dueDate <= :latest');

	if($exact)
	{
		$query->setParameter('num', $poNum);
	}
	else
	{
		$query->setParameter('num', '%' . $poNum . '%');
	}

	$query->setParameter('earliest', $filterDate['earliest']);
	$query->setParameter('latest', $filterDate['latest']);

	return $query->getResult();
	}

	public function findPn($pn, $filterDate, $exact)
	{
		$query = $this->_em->createQuery('SELECT i FROM AchPoManagerBundle:PoItem i JOIN i.revision r JOIN r.product p WHERE p.pn like :pn AND i.dueDate >= :earliest AND i.dueDate <= :latest ORDER BY i.dueDate DESC');

	if($exact)
	{
		$query->setParameter('pn', $pn);
	}
	else
	{
		$query->setParameter('pn', '%' . $pn . '%');
	}

	$query->setParameter('earliest', $filterDate['earliest']);
	$query->setParameter('latest', $filterDate['latest']);

	return $query->getResult();
	}

	public function findCustPn($custPn, $filterDate, $exact)
	{
	$query = $this->_em->createQuery('SELECT i FROM AchPoManagerBundle:PoItem i JOIN i.revision r JOIN r.product p WHERE p.custPn like :custPn AND i.dueDate >= :earliest AND i.dueDate <= :latest ORDER BY i.dueDate DESC');

	if($exact)
	{
		$query->setParameter('custPn', $custPn);
	}
	else
	{
		$query->setParameter('custPn', '%' . $custPn . '%');
	}

	$query->setParameter('earliest', $filterDate['earliest']);
	$query->setParameter('latest', $filterDate['latest']);

	return $query->getResult();
	}

	public function findDescription($desc, $filterDate)
	{
	$query = $this->_em->createQuery('SELECT i FROM AchPoManagerBundle:PoItem i JOIN i.revision r JOIN r.product p WHERE p.description like :desc AND i.dueDate >= :earliest AND i.dueDate <= :latest');

	$query->setParameter('desc', '%' . $desc . '%');
	$query->setParameter('earliest', $filterDate['earliest']);
	$query->setParameter('latest', $filterDate['latest']);

	return $query->getResult();
	}

	public function findPoItemByProdManager($prodManagerId, $statusName = "%")
	{
		$query = $this->_em->createQuery('SELECT p FROM AchPoManagerBundle:PoItem p JOIN p.status s JOIN p.revision r JOIN r.product d JOIN d.prodManager c WHERE s.name like :statusName AND c.id = :prodManagerId ORDER BY p.dueDate');
		$query->setParameter('prodManagerId', $prodManagerId);
		$query->setParameter('statusName', $statusName);
		return $query->getResult();
	}

	public function findPoItemByStatusShippingManager($shippingManagerId, $statusName1 = "", $statusName2 = "")
	{
	$query = $this->_em->createQuery('SELECT p FROM AchPoManagerBundle:PoItem p JOIN p.status s JOIN p.revision r JOIN r.product d JOIN d.shippingManager a WHERE (s.name = :statusName1 OR s.name = :statusName2) AND a.id = :shippingManagerId ORDER BY p.dueDate');
	$query->setParameter('statusName1', $statusName1);
	$query->setParameter('statusName2', $statusName2);
	$query->setParameter('shippingManagerId', $shippingManagerId);
	return $query->getResult();
	}

	public function sumQtyPoNum($bpo)
	{
		$query = $this->_em->createQuery('SELECT sum(i.qty) as total FROM AchPoManagerBundle:PoItem i JOIN i.po p JOIN p.bpo b WHERE b.id = :bpoId');
		$query->setParameter('bpoId', $bpo->getId());
		return $query->getOneOrNullResult();
	}

	/*public function findPoItemByStatusBillingManager($statusId, $billingManagerId)
	{
	$query = $this->_em->createQuery('SELECT p FROM AchPoManagerBundle:PoItem p JOIN p.status s JOIN p.revision r JOIN r.product d JOIN d.billingManager a WHERE s.id = :statusId AND a.id = :billingManagerId');
	$query->setParameter('statusId', $statusId);
	$query->setParameter('billingManagerId', $billingManagerId);
	return $query->getResult();
	}*/

	public function findLatestPn($pn)
	{
		$query = $this->_em->createQuery('SELECT i FROM AchPoManagerBundle:PoItem i JOIN i.revision r JOIN r.product p WHERE p.pn like :pn ORDER BY i.dueDate DESC');
	$query->setMaxResults(1);
	$query->setParameter('pn', $pn);

	return $query->getOneOrNullResult();
	}

}


text:
package core.framework.internal.kafka;

import core.framework.internal.json.JSONMapper;
import core.framework.internal.log.ActionLog;
import core.framework.internal.log.LogLevel;
import core.framework.internal.log.LogManager;
import core.framework.json.JSON;
import core.framework.kafka.BulkMessageHandler;
import core.framework.kafka.Message;
import core.framework.kafka.MessageHandler;
import core.framework.util.Strings;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.header.internals.RecordHeaders;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.io.IOException;
import java.time.Duration;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.verify;

/**
 * @author neo
 */
@ExtendWith(MockitoExtension.class)
class MessageListenerThreadTest {
    @Mock
    MessageHandler<TestMessage> messageHandler;
    @Mock
    Consumer<byte[], byte[]> consumer;
    @Mock
    BulkMessageHandler<TestMessage> bulkMessageHandler;
    private MessageListenerThread thread;
    private LogManager logManager;

    @BeforeEach
    void createKafkaMessageListenerThread() {
        logManager = new LogManager();
        thread = new MessageListenerThread("listener-thread-1", consumer, new MessageListener(null, null, logManager, 300_000L));
    }

    @Test
    void header() {
        var headers = new RecordHeaders();
        headers.add("header", Strings.bytes("value"));
        assertThat(thread.header(headers, "header")).isEqualTo("value");
        assertThat(thread.header(headers, "nonExisted")).isNull();
    }

    @Test
    void messages() throws IOException {
        ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>("topic", 0, 1, Strings.bytes("key"), Strings.bytes("{}"));
        record.headers().add(MessageHeaders.HEADER_CLIENT, Strings.bytes("client"));
        record.headers().add(MessageHeaders.HEADER_REF_ID, Strings.bytes("refId"));
        record.headers().add(MessageHeaders.HEADER_CORRELATION_ID, Strings.bytes("correlationId"));
        var actionLog = new ActionLog(null, null);
        List<Message<TestMessage>> messages = thread.messages(List.of(record), actionLog, JSONMapper.reader(TestMessage.class));

        assertThat(messages).hasSize(1);
        assertThat(messages.get(0).key).isEqualTo("key");
        assertThat(actionLog.context.get("key")).containsExactly("key");
        assertThat(actionLog.clients).containsExactly("client");
        assertThat(actionLog.refIds).containsExactly("refId");
        assertThat(actionLog.correlationIds).containsExactly("correlationId");
    }

    @Test
    void checkConsumerDelay() {
        var actionLog = logManager.begin(null, null);
        thread.checkConsumerDelay(actionLog, actionLog.date.minusSeconds(5).toEpochMilli(), Duration.ofSeconds(3).toNanos());
        assertThat(actionLog.stats).containsEntry("consumer_delay", (double) Duration.ofSeconds(5).toNanos());
        assertThat(actionLog.result).isEqualTo(LogLevel.WARN);
        assertThat(actionLog.errorCode()).isEqualTo("LONG_CONSUMER_DELAY");

        actionLog = logManager.begin(null, null);
        thread.checkConsumerDelay(actionLog, actionLog.date.minus(Duration.ofMinutes(16)).toEpochMilli(), Duration.ofSeconds(30).toNanos());
        assertThat(actionLog.stats).containsEntry("consumer_delay", (double) Duration.ofMinutes(16).toNanos());
        assertThat(actionLog.result).isEqualTo(LogLevel.ERROR);
        assertThat(actionLog.errorCode()).isEqualTo("LONG_CONSUMER_DELAY");

        actionLog = logManager.begin(null, null);
        thread.checkConsumerDelay(actionLog, actionLog.date.minusSeconds(1).toEpochMilli(), Duration.ofSeconds(6).toNanos());
        assertThat(actionLog.stats).containsEntry("consumer_delay", (double) Duration.ofSeconds(1).toNanos());
        assertThat(actionLog.errorCode()).isNull();
    }

    @Test
    void key() {
        assertThat(thread.key(new ConsumerRecord<>("topic", 0, 0, null, null)))
            .isNull();

        assertThat(thread.key(new ConsumerRecord<>("topic", 0, 0, Strings.bytes("key"), null)))
            .isEqualTo("key");
    }

    @Test
    void handle() throws Exception {
        var key = "key";
        var message = new TestMessage();
        message.stringField = "value";
        var record = new ConsumerRecord<>("topic", 0, 0, Strings.bytes(key), Strings.bytes(JSON.toJSON(message)));
        record.headers().add(MessageHeaders.HEADER_TRACE, Strings.bytes("true"));
        record.headers().add(MessageHeaders.HEADER_CLIENT, Strings.bytes("client"));
        thread.handle("topic", new MessageProcess<>(messageHandler, null, TestMessage.class), List.of(record));

        verify(messageHandler).handle(eq(key), argThat(value -> "value".equals(value.stringField)));
    }

    @Test
    void handleWithNullKey() throws Exception {
        var message = new TestMessage();
        message.stringField = "value";
        var record = new ConsumerRecord<>("topic", 0, 0, (byte[]) null, Strings.bytes(JSON.toJSON(message)));
        record.headers().add(MessageHeaders.HEADER_TRACE, Strings.bytes("true"));
        record.headers().add(MessageHeaders.HEADER_CLIENT, Strings.bytes("client"));
        record.headers().add(MessageHeaders.HEADER_TRACE, Strings.bytes("cascade"));
        thread.handle("topic", new MessageProcess<>(messageHandler, null, TestMessage.class), List.of(record));

        verify(messageHandler).handle(isNull(), argThat(value -> "value".equals(value.stringField)));
    }

    @Test
    void handleBulk() throws Exception {
        var key = "key";
        var message = new TestMessage();
        message.stringField = "value";
        var record = new ConsumerRecord<>("topic", 0, 0, Strings.bytes(key), Strings.bytes(JSON.toJSON(message)));
        record.headers().add(MessageHeaders.HEADER_CORRELATION_ID, Strings.bytes("correlationId"));
        record.headers().add(MessageHeaders.HEADER_REF_ID, Strings.bytes("refId"));
        thread.handleBulk("topic", new MessageProcess<>(null, bulkMessageHandler, TestMessage.class), List.of(record));

        verify(bulkMessageHandler).handle(argThat(value -> value.size() == 1
                                                           && key.equals(value.get(0).key)
                                                           && "value".equals(value.get(0).value.stringField)));
    }

    @Test
    void shutdown() {
        thread.shutdown();
        verify(consumer).wakeup();
    }
}


text:
@interface DVTSourceFileCodeCoverageRange : NSObject <NSCoding>
{
    BOOL _executable;
    unsigned long long _line;
    unsigned long long _column;
    unsigned long long _length;
}

@property(readonly, nonatomic) BOOL executable; // @synthesize executable=_executable;
@property(readonly, nonatomic) unsigned long long length; // @synthesize length=_length;
@property(readonly, nonatomic) unsigned long long column; // @synthesize column=_column;
@property(readonly, nonatomic) unsigned long long line; // @synthesize line=_line;
- (id)description;
@property(readonly, nonatomic) int executionCount;
- (BOOL)isExecutable;
- (id)initWithCoder:(id)arg1;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithLine:(unsigned long long)arg1 column:(unsigned long long)arg2 length:(unsigned long long)arg3;

@end


text:
<!DOCTYPE html>
<title>Test that the cue is not styled when video is in a shadow tree and style is in a document.</title>
<script src="../media-controls.js"></script>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<style>
video::cue(.red, .red2) { color:red }
video::cue(.green) { color:green }
</style>
<div id='host'>
</div>
<script>
async_test(function(t) {
    var host = document.getElementById('host');
    var shadowRoot = host.attachShadow({mode: 'open'});
    shadowRoot.innerHTML = '<video controls ><track src="captions-webvtt/styling-lifetime.vtt" kind="captions" default></video>';
    var video = shadowRoot.querySelector('video');
    video.src = '../content/test.ogv';
    video.id = "testvideo";
    video.onseeked = t.step_func_done(function() {
        var cueNode = textTrackCueElementByIndex(video, 0).firstChild.firstElementChild;
        assert_equals(getComputedStyle(cueNode).color, "rgb(255, 255, 255)");
        cueNode = cueNode.nextElementSibling;
        assert_equals(getComputedStyle(cueNode).color, "rgb(255, 255, 255)");
        cueNode = cueNode.nextElementSibling;
        assert_equals(getComputedStyle(cueNode).color, "rgb(255, 255, 255)");
    });
    video.currentTime = 0.6;
});
</script>


text:
title: 'Perfect for snoozing on…'
author: jeffcressman
excerpt: Our newly built bench from a pallet and old kitchen drawers.
layout: post
permalink: /2011/07/perfect-for-snoozing-on/
categories:
  - Uncategorized
---

Our newly built bench from a pallet and old kitchen drawers.


text:
#include <moonstone/chain/exceptions.hpp>
#include <moonstone/chain/protocol/confidential.hpp>
#include <moonstone/chain/confidential_evaluator.hpp>
#include <moonstone/chain/confidential_object.hpp>
#include <moonstone/chain/database.hpp>
#include <moonstone/chain/fba_accumulator_id.hpp>
#include <moonstone/chain/hardfork.hpp>

#include <fc/smart_ref_impl.hpp>

namespace moonstone { namespace chain {

void_result transfer_to_blind_evaluator::do_evaluate( const transfer_to_blind_operation& o )
{ try {
   const auto& d = db();

   const auto& atype = o.amount.asset_id(db());
   FC_ASSERT( atype.allow_confidential() );
   FC_ASSERT( !atype.is_transfer_restricted() );
   FC_ASSERT( !(atype.options.flags & white_list) );

   for( const auto& out : o.outputs )
   {
      for( const auto& a : out.owner.account_auths )
         a.first(d); // verify all accounts exist and are valid
   }
   return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }

void_result transfer_to_blind_evaluator::do_apply( const transfer_to_blind_operation& o )
{ try {
   db().adjust_balance( o.from, -o.amount );

   const auto& add = o.amount.asset_id(db()).dynamic_asset_data_id(db());  // verify fee is a legit asset
   db().modify( add, [&]( asset_dynamic_data_object& obj ){
      obj.confidential_supply += o.amount.amount;
      FC_ASSERT( obj.confidential_supply >= 0 );
   });
   for( const auto& out : o.outputs )
   {
      db().create<blinded_balance_object>( [&]( blinded_balance_object& obj ){
          obj.asset_id   = o.amount.asset_id;
          obj.owner      = out.owner;
          obj.commitment = out.commitment;
      });
   }
   return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }

void transfer_to_blind_evaluator::pay_fee()
{
   if( db().head_block_time() >= HARDFORK_563_TIME )
      pay_fba_fee( fba_accumulator_id_transfer_to_blind );
   else
      generic_evaluator::pay_fee();
}

void_result transfer_from_blind_evaluator::do_evaluate( const transfer_from_blind_operation& o )
{ try {
   const auto& d = db();
   o.fee.asset_id(d);  // verify fee is a legit asset
   const auto& bbi = d.get_index_type<blinded_balance_index>();
   const auto& cidx = bbi.indices().get<by_commitment>();
   for( const auto& in : o.inputs )
   {
      auto itr = cidx.find( in.commitment );
      FC_ASSERT( itr != cidx.end() );
      FC_ASSERT( itr->asset_id == o.fee.asset_id );
      FC_ASSERT( itr->owner == in.owner );
   }
   return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }

void_result transfer_from_blind_evaluator::do_apply( const transfer_from_blind_operation& o )
{ try {
   db().adjust_balance( o.fee_payer(), o.fee );
   db().adjust_balance( o.to, o.amount );
   const auto& bbi = db().get_index_type<blinded_balance_index>();
   const auto& cidx = bbi.indices().get<by_commitment>();
   for( const auto& in : o.inputs )
   {
      auto itr = cidx.find( in.commitment );
      FC_ASSERT( itr != cidx.end() );
      db().remove( *itr );
   }
   const auto& add = o.amount.asset_id(db()).dynamic_asset_data_id(db());  // verify fee is a legit asset
   db().modify( add, [&]( asset_dynamic_data_object& obj ){
      obj.confidential_supply -= o.amount.amount + o.fee.amount;
      FC_ASSERT( obj.confidential_supply >= 0 );
   });
   return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }

void transfer_from_blind_evaluator::pay_fee()
{
   if( db().head_block_time() >= HARDFORK_563_TIME )
      pay_fba_fee( fba_accumulator_id_transfer_from_blind );
   else
      generic_evaluator::pay_fee();
}

void_result blind_transfer_evaluator::do_evaluate( const blind_transfer_operation& o )
{ try {
   const auto& d = db();
   o.fee.asset_id(db());  // verify fee is a legit asset
   const auto& bbi = db().get_index_type<blinded_balance_index>();
   const auto& cidx = bbi.indices().get<by_commitment>();
   for( const auto& out : o.outputs )
   {
      for( const auto& a : out.owner.account_auths )
         a.first(d); // verify all accounts exist and are valid
   }
   for( const auto& in : o.inputs )
   {
      auto itr = cidx.find( in.commitment );
      MOONSTONE_ASSERT( itr != cidx.end(), blind_transfer_unknown_commitment, "", ("commitment",in.commitment) );
      FC_ASSERT( itr->asset_id == o.fee.asset_id );
      FC_ASSERT( itr->owner == in.owner );
   }
   return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }

void_result blind_transfer_evaluator::do_apply( const blind_transfer_operation& o )
{ try {
   db().adjust_balance( o.fee_payer(), o.fee ); // deposit the fee to the temp account
   const auto& bbi = db().get_index_type<blinded_balance_index>();
   const auto& cidx = bbi.indices().get<by_commitment>();
   for( const auto& in : o.inputs )
   {
      auto itr = cidx.find( in.commitment );
      MOONSTONE_ASSERT( itr != cidx.end(), blind_transfer_unknown_commitment, "", ("commitment",in.commitment) );
      db().remove( *itr );
   }
   for( const auto& out : o.outputs )
   {
      db().create<blinded_balance_object>( [&]( blinded_balance_object& obj ){
          obj.asset_id   = o.fee.asset_id;
          obj.owner      = out.owner;
          obj.commitment = out.commitment;
      });
   }
   const auto& add = o.fee.asset_id(db()).dynamic_asset_data_id(db());
   db().modify( add, [&]( asset_dynamic_data_object& obj ){
      obj.confidential_supply -= o.fee.amount;
      FC_ASSERT( obj.confidential_supply >= 0 );
   });

   return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }

void blind_transfer_evaluator::pay_fee()
{
   if( db().head_block_time() >= HARDFORK_563_TIME )
      pay_fba_fee( fba_accumulator_id_blind_transfer );
   else
      generic_evaluator::pay_fee();
}

} } // moonstone::chain


text:
import {AccountDetailsComponent} from './account-details/account-details.component';
import {AccountsListComponent} from './accounts-list/accounts-list.component';
import {AmountComponent} from './amount/amount.component';
import {LoadingCardComponent} from './loading-card/loading-card.component';
import {TransactionsListComponent} from './transactions-list/transactions-list.component';

export const components = [
    AccountDetailsComponent, AccountsListComponent, AmountComponent, LoadingCardComponent,
    TransactionsListComponent
];


text:
import setuptools

setuptools.setup(
    name="MarkovChainBibleBot",
    version="0.1.0",
    url="https://github.com/salvor7/MarkovChainBibleBot",

    author="Andrew AH Brown",
    author_email="andrew.ah.brown@gmail.com",

    description="An absurdist bible quote generating bot, released on twitter.",
    long_description=open('README.rst').read(),

    packages=setuptools.find_packages(),

    install_requires=[],

    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
)


text:
#include "lp_ticker_api.h"

#if DEVICE_LOWPOWERTIMER

#include "common_rtc.h"

void lp_ticker_init(void)
{
    common_rtc_init();
}

uint32_t lp_ticker_read()
{
    return (uint32_t)common_rtc_64bit_us_get();
}

void lp_ticker_set_interrupt(timestamp_t timestamp)
{
    common_rtc_set_interrupt(timestamp,
        LP_TICKER_CC_CHANNEL, LP_TICKER_INT_MASK);
}

void lp_ticker_fire_interrupt(void)
{
    uint32_t closest_safe_compare = common_rtc_32bit_ticks_get() + 2;

    nrf_rtc_cc_set(COMMON_RTC_INSTANCE, LP_TICKER_CC_CHANNEL, RTC_WRAP(closest_safe_compare));
    nrf_rtc_event_enable(COMMON_RTC_INSTANCE, LP_TICKER_INT_MASK);
}

void lp_ticker_disable_interrupt(void)
{
    nrf_rtc_event_disable(COMMON_RTC_INSTANCE, LP_TICKER_INT_MASK);
}

void lp_ticker_clear_interrupt(void)
{
    nrf_rtc_event_clear(COMMON_RTC_INSTANCE, LP_TICKER_EVENT);
}

#endif // DEVICE_LOWPOWERTIMER


text:
#include "GLFW/glfw3.h"

using namespace Lag;

//GLOBAL REFERENCE FOR CALLBACKS
GLFWRenderWindow *glfwRenderWindow;

void Lag::windowCloseCallback(GLFWwindow *window) {
    glfwRenderWindow->onCloseNotify(*glfwRenderWindow);
}

void Lag::windowSizeCallback(GLFWwindow *window, int width, int height) {
    if(width > 0 && height > 0)
        glfwRenderWindow->resize(static_cast<uint32>(width), static_cast<uint32>(height));
}

void Lag::windowPosCallback(GLFWwindow *window, int xpos, int ypos) {
    glfwRenderWindow->onMoveNotify(*glfwRenderWindow, xpos, ypos);
}

void Lag::windowFocusCallback(GLFWwindow *window, int focused) {
    glfwRenderWindow->onFocusChangeNotify(*glfwRenderWindow, focused == GLFW_FOCUSED);
}

void Lag::errorCallback(int error, const char *description) {
    LogManager::getInstance().log(LogType::ERROR, LogVerbosity::NORMAL, "GLFWRenderWindow",
                                  "Error " + std::to_string(error) + ": " + description);
}

GLFWRenderWindow::GLFWRenderWindow(const InitializationParameters &parameters) :
        RenderWindow(parameters) {
    glfwRenderWindow = this;
}

bool GLFWRenderWindow::loadImplementation() {
    glfwSetErrorCallback(errorCallback);

    if (!glfwInit()) {
        LogManager::getInstance().log(LogType::ERROR, LogVerbosity::NORMAL, "GLFWRenderWindow", "Cannot initialize GLFW.");
        return false;
    }
    else {
        glfwWindowHint(GLFW_SAMPLES, initializationParameters.MSAAsamples);
        glfwWindowHint(GLFW_SRGB_CAPABLE, initializationParameters.sRGB ? true : false);
        glfwWindowHint(GLFW_DOUBLEBUFFER, true);

        glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef ENABLE_DEBUG
        glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true);
#else
        glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, false);
#endif

        window = glfwCreateWindow(initializationParameters.width, initializationParameters.height,
                                  initializationParameters.title.c_str(), nullptr, nullptr);

        if (window == nullptr) {
            LogManager::getInstance().log(LogType::ERROR, LogVerbosity::NORMAL, "GLFWRenderWindow", "Cannot build GLFW window.");
            return false;
        }

        glfwSetWindowCloseCallback(window, windowCloseCallback);
        glfwSetWindowSizeCallback(window, windowSizeCallback);
        glfwSetWindowPosCallback(window, windowPosCallback);
        glfwSetWindowFocusCallback(window, windowFocusCallback);

        glfwMakeContextCurrent(window);
        if (!glfwGetCurrentContext()) {
            LogManager::getInstance().log(LogType::ERROR, LogVerbosity::NORMAL,
                                          "GLFWRenderWindow", "Cannot build OpenGL context.");
            return false;
        }

        glfwSwapInterval(initializationParameters.vsync ? true : true);
        setVirtualCursor(false);

        LogManager::getInstance().log(LogType::INFO, LogVerbosity::NORMAL,
                                      "GLFWRenderWindow", "Initialized successfully.");

        return true;
    }
}

void GLFWRenderWindow::unloadImplementation() {
    glfwSetWindowCloseCallback(window, nullptr);
    glfwSetWindowSizeCallback(window, nullptr);
    glfwSetWindowPosCallback(window, nullptr);
    glfwSetWindowFocusCallback(window, nullptr);

    glfwDestroyWindow(window);
    glfwTerminate();

    LogManager::getInstance().log(LogType::INFO, LogVerbosity::NORMAL,
                                  "GLFWRenderWindow", "Destroyed successfully.");
}

void GLFWRenderWindow::processEvents() {
    glfwPollEvents();
}

void GLFWRenderWindow::swapBuffers() {
    glfwSwapBuffers(window);
}

void GLFWRenderWindow::setVirtualCursor(bool value) {
    virtualCursor = value;
    int v = value ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL;
    glfwSetInputMode(window, GLFW_CURSOR, v);
}

bool GLFWRenderWindow::isVirtualCursorEnabled() {
    return virtualCursor;
}


text:
package com.replash;

import com.replash.commands.CommandTreeNode;

public class ParentCommand implements BasicCommand {
    @Override
    public void execute(CommandContext executionContext) throws Exception {
        CommandTreeNode node = executionContext.getResolutionContext().getNode();
        executionContext.getRuntime().getHelpCommandHandler().printHelp(executionContext, node);
    }
}


text:
// -*- Mode: C++; -*-
//                            Package   : omniORB
// objectStub.h               Created on: 04/09/2000
//                            Author    : Sai-Lai Lo (sll)
//
//    Copyright (C) 2000 AT&T Research Cambridge
//
//    This file is part of the omniORB library
//
//    The omniORB library is free software; you can redistribute it and/or
//    modify it under the terms of the GNU Library General Public
//    License as published by the Free Software Foundation; either
//    version 2 of the License, or (at your option) any later version.
//
//    This library is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//    Library General Public License for more details.
//
//    You should have received a copy of the GNU Library General Public
//    License along with this library; if not, write to the Free
//    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
//    02111-1307, USA
//
//
// Description:
//

/*
  $Log: objectStub.h,v $
  Revision 1.1.6.1  2003/03/23 21:03:45  dgrisby
  Start of omniORB 4.1.x development branch.

  Revision 1.1.4.1  2001/04/18 17:18:15  sll
  Big checkin with the brand new internal APIs.
  These files were relocated and scoped with the omni namespace.

  Revision 1.1.2.1  2000/09/27 17:30:30  sll
  *** empty log message ***

*/

OMNI_NAMESPACE_BEGIN(omni)

//////////////////////////////////////////////////////////////////////
class omni_is_a_CallDesc : public omniCallDescriptor {
public:
  inline omni_is_a_CallDesc(const char* op,
			    int oplen, const char* i_1,
			    CORBA::Boolean upcall=0)
    : omniCallDescriptor(lcfn, op, oplen, 0, 0, 0, upcall),
      a_1((char*)i_1)
    {}

  inline ~omni_is_a_CallDesc() {
    if (is_upcall()) { _CORBA_String_helper::free(a_1); }
  }

  void marshalArguments(cdrStream&);
  void unmarshalReturnedValues(cdrStream&);
  void unmarshalArguments(cdrStream&);
  void marshalReturnedValues(cdrStream&);

  static void lcfn(omniCallDescriptor* cd, omniServant* servant);

  char*    a_1;
  CORBA::Boolean result;
};

//////////////////////////////////////////////////////////////////////
class omni_non_existent_CallDesc : public omniCallDescriptor {
public:
  inline omni_non_existent_CallDesc(const char* op, int oplen,
				    CORBA::Boolean upcall=0)
    : omniCallDescriptor(lcfn, op, oplen, 0, 0, 0, upcall)
    {}

  void unmarshalReturnedValues(cdrStream&);
  void marshalReturnedValues(cdrStream&);

  static void lcfn(omniCallDescriptor* cd, omniServant* servant);

  CORBA::Boolean result;
};

//////////////////////////////////////////////////////////////////////
class omni_interface_CallDesc : public omniCallDescriptor {
public:
  inline omni_interface_CallDesc(const char* op, int oplen,
				 CORBA::Boolean upcall=0)
    : omniCallDescriptor(lcfn, op, oplen, 0, 0, 0, upcall)
    {}

  void unmarshalReturnedValues(cdrStream&);
  void marshalReturnedValues(cdrStream&);

  inline CORBA::Object_ptr result() { return pd_result._retn(); }

  static void lcfn(omniCallDescriptor* cd, omniServant* servant);

  CORBA::Object_var pd_result;
};

OMNI_NAMESPACE_END(omni)


text:
## FILE FORMATTING for amazon valid values file
##
##		(EXAMPLE CSV FILE - /httpd/static/definitions/amz/example.csv)
##
##		*****(these comments are primarily to aid in constructing the amazon valid values file to be imported)
##
##		-	FIELD ATTRIBUTE DECLARATION
##			-	the attributes that determine the fields fucntion behavior
##			- 	should all be in the first cell of the cvs file separated by commas (ie. "type, xmlpath etc")
##			-	valid attributes:
##
##				- 	ns -	 							the zoovy field type. ie. 'select', 'textbox' etc
##				- 	type - 							the zoovy field type. ie. 'select', 'textbox' etc
##				- 	xmlpath - 						the path used for the attribute in the xml. ie. ClothingAccessories.ClassificationData.ID
##				- 	amz_attrib -					the amazon attribute name to be used in the xml
##				- 	amz-format - 					the format determines how the attribute will be validated. ie Text.
##				- 	Title - 							the attribute title dispalyed in the zoovy ui
##				- 	mandatory -						determines whether this is a mandatroy field
##				- 	amz-max-length - 				max allowed length of value
##				- 	amz-min-length - 				min allowed length of value
##				- 	id -								zoovy attribute
##				- 	max-allowed-lines - 			max allowed lines (only applies to text lists)
##				- 	aum -								allowed units of measure for attirubute saparated by a comma (ie. CM,IN)
##				- 	amazon-allow-blank -			specifies if a value can be blank (currently only used for the files hidden attribute)
##
##				variation specific attributes
##				-	vkey - Variation keyword of the field (ie Size)
##				-	variation-type - determines thpe of variation attribute it is (ie Parentage)
##
##				hidden field specific attributes (added by brian. i'm not sure they do anything but since they were added by brian i left them in place)
##				-	PROMPT - see example.csv
##				-	DATA - see example.csv
##
##		- 	FIELD NAMES
##			-	the 2nd line in the file should always contain the field names (amazon flat file field names - not necessarily the same as the xsd value
##				or Zoovy equivalunt attribute. (ie Shoe-Closure-Type)
##			-	the field names will be listed left to right,  each field on a new column
##			-  the data is used for sorting later in the code and for references purposes only
##				- 	it is currently not saved in the json - we may save in the json in the future
##
##		-	FIELD ATTRIBUTE VALUES
##			-	the rows directly after the the attribute declaration line. They should
##			-	these are the values corresponding to the attribute tpe(ie if the row is for 'type' the row will consist of values like 'select' or 'textbox')
##			-	there should be 1 row for every field attribute used (ie type values might be on row 2 and xmlpath values on row 3)
##			-	it is not necessary for to have a value for every field. you may add a value in one column and leave the others black if the field doesnt need
##				that attribute.
##
##		-	VALID VALUES
##			-	amazon usually gives a lists of allowed values for a specific field.
##			-	when they do we create a select list for the field which the merchants saved value is validated against.
##			-	valid values take up all rows after the field attribute rows.

use strict;
use lib "/httpd/modules";
use Data::Dumper;
use JSON::XS;
use File::Slurp;
use Text::CSV_XS;
use IO::Scalar;
require Text::CSV;

my $ERROR = '';
my %params = ();
foreach my $arg (@ARGV) {
	if ($arg !~ /=/) { $ERROR = "parameters and values must be separated  by ="; }
	my ($k,$v) = split(/=/,$arg);
	$params{$k} = $v;
	}

my $source_file = '';
my $destination_file = '';

if ((not defined $params{'source_file'}) || (not defined $params{'destination_file'})) {
	$ERROR = "source_file and destination_file are required parameters";
	}
else {
	$source_file = $params{'source_file'};
	$destination_file = $params{'destination_file'};
	}

my @rows = ();
## parse data from amazon valid values file

my $csv = Text::CSV_XS->new ({ binary => 1 });
open (CSV, "<", $source_file) or die $!;

while (<CSV>) {
	my $status = $csv->parse($_);
	my @columns = $csv->fields();
	push @rows, [@columns];
	}

my $attrib_row = shift @rows;
## a reference of field attributes to be used - only the column contains data
my $attributes = shift @$attrib_row;
my @attribs = split (/,/, $attributes); #@attribs is now an array of all field attribute names (ie (id,aum)

## a reference of field names
my $field_ref = shift @rows;

## %FIELD_ATTRIB_DATA is a hash of all field attribute values
##		- 	each column number corresponds to the same element number in @attribs. (ie if element 0 in @attribs is type, column 0 of FIELD_ATTRIB_VALUES contains
##			all of the type data for every field)
my %FIELD_ATTRIB_DATA = ();

foreach my $attrib(@attribs) {
	my $row = shift @rows;
	$FIELD_ATTRIB_DATA{$attrib} = $row;
	}

## everything left in @rows should be valid values
my @valid_values = @rows;

close CSV;

## take a column count to ensure the correct field attribute data is matched with the correct field
my $element_count = 0;

my $combined_field_data = [];
foreach my $field (@$field_ref) {
	my $field_data = ();

	if (lc($FIELD_ATTRIB_DATA{'type'}[$element_count]) eq 'select') {
		## fields with a type of 'select' should always have valid values so we need to make a select list containing the values.
		##		-	these are called options in the json
		my $options = [];
		push @{$options}, {T => "", V => ""};

		foreach my $value (@valid_values){
			# @valid_values contains rows of valid values so we need to pull the relevant value to this field from each row of valid values
			if ($value->[$element_count] ne '') {
				push @{$options}, {p => $value->[$element_count], v => $value->[$element_count]};
				}
			}
		$field_data->{'options'} = $options;
		}
	foreach my $attrib (@attribs) {
		if ($FIELD_ATTRIB_DATA{$attrib}[$element_count] ne '') {
#			print "$attrib value is $FIELD_ATTRIB_DATA{$attrib}[$element_count]\n";
			## if the field attribute does not have a corresponding value don't add to $field_data
			if ($attrib eq 'amz-format') {
				$FIELD_ATTRIB_DATA{$attrib}[$element_count] = ucfirst($FIELD_ATTRIB_DATA{$attrib}[$element_count]);
				## amz_format should always be formatted with an uc first letter.
				}
			elsif ($attrib eq 'type') {
				$FIELD_ATTRIB_DATA{$attrib}[$element_count] = lc($FIELD_ATTRIB_DATA{$attrib}[$element_count]);
				## type should always be formatted entirely in lower case.
				}
			$field_data->{$attrib} = $FIELD_ATTRIB_DATA{$attrib}[$element_count];
#			print Dumper($field_data);
			}
		}

	push @$combined_field_data, $field_data;
	$element_count ++;
	}

# Convert data to a json format and copy to file.
my $coder = JSON::XS->new->ascii->pretty->allow_nonref;
my $pretty_printed_unencoded = $coder->encode ($combined_field_data);
open F, ">$destination_file";
print F $pretty_printed_unencoded;
close F;

print $pretty_printed_unencoded;

exit;


text:
package ar.com.larreta.commons.security;

import java.util.Collection;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import ar.com.larreta.commons.domain.User;

public class UserAuthenticationToken extends UsernamePasswordAuthenticationToken implements AuthenticationToken {

	private User user;
	private SessionInfo info = new SessionInfo();

	public SessionInfo getInfo() {
		return info;
	}

	public UserAuthenticationToken(Object principal, Object credentials,
			Collection<? extends GrantedAuthority> authorities) {
		super(principal, credentials, authorities);
	}

	public UserAuthenticationToken(User user, Collection<? extends GrantedAuthority> authorities){
		this(user.getNick(), user.getPassword(), authorities);
		this.user = user;
	}

	public User getUser() {
		return user;
	}
}


text:
<?php
class Kwc_Box_Favicon_Component extends Kwc_Basic_Image_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['componentName'] = trlKwfStatic('Favicon');
        $ret['dimensions'] = array(
            array('width'=>16, 'height'=>16, 'scale'=>Kwf_Media_Image::SCALE_ORIGINAL)
        );
        return $ret;
    }

    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $ret['imageUrl'] = $this->getImageUrl();
        return $ret;
    }
}


text:
<!DOCTYPE html>

    <title>Table of Contents - Rubinius</title>
    <meta content='text/html;charset=utf-8' http-equiv='content-type'>
    <meta content='en' http-equiv='content-language'>
    <meta content='Rubinius is an implementation of the Ruby programming language. The Rubinius bytecode virtual machine is written in C++. The bytecode compiler is written in pure Ruby. The vast majority of the core library is also written in Ruby, with some supporting primitives that interact with the VM directly.' name='description'>
    <meta content='Less Than Three. <3. http://less.thanthree.com' name='author'>
    <link href='/' rel='home'>
    <link href='/' rel='start'>

    <link href='/doc/en/what-is-rubinius' rel='next' title='What is Rubinius?'>

    <link href="/stylesheets/blueprint/screen.css" media="screen" rel="stylesheet" type="text/css" />
    <link href="/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
    <link href="/stylesheets/blueprint/print.css" media="print" rel="stylesheet" type="text/css" />

    <link href="/stylesheets/pygments.css" media="screen" rel="stylesheet" type="text/css" />

Home

Blog

Documentation

Projects

Roadmap

Releases

          1.2.3

  Languages:

de

en

es

fr

ja

pl

pt-br

ru

Table of Contents

What is Rubinius?

Getting Started

Requirements

Building

Running Rubinius

Troubleshooting

Contributing

Communication

Style Guide

Ruby

Scripts

Methods

Constants

Classes & Modules

Blocks & Procs

Local Variables

Instance Variables

Class Variables

Global Variables

Specs

RubySpec

Compiler Specs

Build System

Bootstrapping

Virtual Machine

Instructions

Custom Dispatch Logic

Bytecode Compiler

Parser Stage

AST

Generator Stage

Encoder Stage

Packager Stage

Writer Stage

Printers

Transformations

Customizing the Pipeline

JIT Compiler

Garbage Collector

Nursery

Young Generation

Mature Generation

Large Objects

Rubinius Systems

Primitives

FFI

Concurrency

IO

C-API

Tools

Debugger

Profiler

Memory Analysis

How-To

Write a Ticket

Write a Ruby Spec

Fix a Failing Spec

Write Benchmarks

Write a Blog Post

Write Documentation

Translate Documentation

Appendix A - Glossary

Appendix B - Reading List

Index of Terms

Please enable JavaScript to view the comments powered by Disqus.

Follow Rubinius on Twitter

Fork Rubinius on github

An Engine Yard project

              Site design by
              Less Than Three


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>dynamic_string_buffer::data (3 of 3 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../data.html" title="dynamic_string_buffer::data">
<link rel="prev" href="overload2.html" title="dynamic_string_buffer::data (2 of 3 overloads)">
<link rel="next" href="../dynamic_string_buffer.html" title="dynamic_string_buffer::dynamic_string_buffer">

Home
Libraries
People
FAQ
More

dynamic_string_buffer::data
          (3 of 3 overloads)

            DynamicBuffer_v2: Get a sequence of
            buffers that represents the underlying memory.

const_buffers_type data(
    std::size_t pos,
    std::size_t n) const;

            Parameters

pos

                  Position of the first byte to represent in the buffer sequence

n

                  The number of bytes to return in the buffer sequence. If the underlying
                  memory is shorter, the buffer sequence represents as many bytes
                  as are available.

            Remarks

            The returned object is invalidated by any dynamic_string_buffer
            or basic_string member function that resizes or erases the
            string.

Copyright © 2003-2021 Christopher
      M. Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package org.apache.archiva.consumers.core.repository;

/**
 *
 *
 */
public class RepositoryPurgeException
    extends Exception
{
    public RepositoryPurgeException( )
    {
        super( );
    }

    public RepositoryPurgeException( String message, Throwable cause )
    {
        super( message, cause );
    }

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

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


text:
layout: relation
title: 'nmod:comp'
shortdef: 'comparative modifier of an adjective or adverb'
---

This subtype of [nmod]() is used for marking comparative modifier of an [adjective](tr-pos/Adj) or [adverb](tr-pos/Adv).

~~~ sdparse
Türkiye'den sıcak bir ülke \n A country warmer than Turkey
nmod:comp(sıcak, Türkiye'den)
~~~

~~~ sdparse
Benden çok okudu . \n He\/she read more than me (more than I did)
nmod:comp(çok, Benden)
~~~


text:
package com.bestxty.study.boot.vaadin;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.math.BigInteger;
import java.util.*;

/**
 * @author jiangtaiyang
 * Created by jiangtaiyang on 2017/9/26.
 */
@Component
public class DocParser implements CommandLineRunner {

    private List<String> files = new ArrayList<>();

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private ItemRepository itemRepository;

    public DocParser() {
        File dir = new File("F:\\大赛命题资料\\选择题");
        File[] filePathArr = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return !pathname.isHidden() && pathname.getName().endsWith(".docx");
            }
        });
        System.out.println("filePathArr = " + Arrays.asList(filePathArr));
        for (File file : filePathArr) {
            files.add(file.getAbsolutePath());
        }
    }

    @Override
    public void run(String... args) throws Exception {
//        customerRepository.deleteAll();
//        itemRepository.deleteAll();
//
//        for (String file : files) {
//            parser(file);
//        }
        export();

    }

    private void export() throws IOException {
        Collection<Customer> customers = (Collection<Customer>) customerRepository.findAll();
        List<String> names = new ArrayList<>();
        for (Customer customer : customers) {
            String title = customer.getName();
            if (!names.contains(title)) {
                names.add(title);
            }
        }
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        Map<String, Object> jsonMap = new HashMap<>();
        List<Map<String, Object>> jsonData = new ArrayList<>();
        for (String name : names) {
            Map<String, Object> map = new HashMap<>();
            List<Customer> customerList = customerRepository.findByName(name);
            map.put("data", customerList);
            map.put("name", name);
            jsonData.add(map);
        }

        jsonMap.put("subjects", jsonData);
        System.err.println(objectMapper.writeValueAsString(jsonMap));
        FileCopyUtils.copy(objectMapper.writeValueAsBytes(jsonMap), new File("D:\\subject.json"));
    }

    private void parser(String filePath) throws IOException {
        File file = new File(filePath);
        String fileName = file.getName();
        InputStream is = new FileInputStream(file);
        XWPFDocument doc = new XWPFDocument(is);
        List<XWPFParagraph> paras = doc.getParagraphs();
        Customer subject = null;
        int subjectId = 1;
        long customerId = -1L;
        for (XWPFParagraph para : paras) {
            String content = para.getText();
            content = StringUtils.trimWhitespace(content);
            content = trim160(content);
            if (isEmpty(content)) continue;
            String numFmt = para.getNumFmt();
            BigInteger numId = para.getNumID();
            BigInteger numIlvl = para.getNumIlvl();

            if (isEmpty(numFmt) && numId == null && numIlvl == null) continue;

            System.out.println(String.format("fmt=%s,numId=%d,numIlvl=%d;content=%s.",
                    numFmt, numId, numIlvl, content));
            if (isDecimal(numFmt)) {
                subject = new Customer();
                subject.setIndex(subjectId++);
                subject.setName(fileName);
                subject.setTitle(content);
                customerId = customerRepository.save(subject).getId();
            }

            if (isUpperLetter(numFmt)) {
                Item item = new Item();
                item.setCustomerId(customerId);
                item.setContent(content);
                itemRepository.save(item);
            }
        }
    }

    private static String trim160(String str) {
        if (!StringUtils.hasLength(str)) {
            return str;
        }
        StringBuilder sb = new StringBuilder(str);
        while (sb.length() > 0 && is160Whitespace(sb.charAt(0))) {
            sb.deleteCharAt(0);
        }
        while (sb.length() > 0 && is160Whitespace(sb.charAt(sb.length() - 1))) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();

//        return str.replaceAll("[\\u00A0]+", "");
    }

    private static boolean is160Whitespace(char ch) {
        return ((int) ch) == 160;
    }

    private static boolean isEmpty(String str) {
        return null == str || "".equals(str);
    }

    private static boolean isDecimal(String numFmt) {
        return "decimal".equals(numFmt);
    }

    private static boolean isUpperLetter(String numFmt) {
        return "upperLetter".equals(numFmt);
    }

//
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import className from 'classnames';
import { deprecated } from 'prop-types-extra';

import omitProps from '../../util/omitProps';

import css from './Card.css';
import DefaultCardHeader from './headers/DefaultCardHeader';

export default class Card extends React.Component {
  static propTypes = {
    bodyClass: PropTypes.string,
    cardClass: PropTypes.string,
    cardStyle: PropTypes.oneOf([
      'default',
      'negative',
      'positive',
    ]),
    children: PropTypes.oneOfType([
      PropTypes.node,
      PropTypes.arrayOf(PropTypes.node),
    ]).isRequired,
    hasMargin: deprecated(
      PropTypes.bool,
      'Margin bottom is added by default now. Use "marginBottom0" prop to remove the margin instead.'
    ),
    headerClass: PropTypes.string,
    headerComponent: PropTypes.oneOfType([PropTypes.node, PropTypes.string, PropTypes.func]),
    headerEnd: PropTypes.oneOfType([
      PropTypes.node,
      PropTypes.arrayOf(PropTypes.node),
    ]),
    headerProps: PropTypes.object,
    headerStart: PropTypes.oneOfType([
      PropTypes.node,
      PropTypes.arrayOf(PropTypes.node),
    ]).isRequired,
    marginBottom0: PropTypes.bool,
    roundedBorder: PropTypes.bool,
  }

  static defaultProps = {
    cardStyle: 'default',
    headerComponent: DefaultCardHeader,
  }

  getCardStyle = () => {
    return className(
      css.card,
      css[this.props.cardStyle],
      { [`${css.marginBottom0}`]: this.props.marginBottom0 },
      { [`${css.roundedBorder}`]: this.props.roundedBorder },
      this.props.cardClass,
    );
  }

  render() {
    const {
      bodyClass,
      headerComponent: HeaderComponent,
      children
    } = this.props;

    const customProps = omitProps(this.props, [
      'bodyClass',
      'cardClass',
      'cardStyle',
      'children',
      'hasMargin',
      'headerClass',
      'headerComponent',
      'headerEnd',
      'headerProps',
      'headerStart',
      'marginBottom0',
      'roundedBorder',
    ]);

    return (
      <div
        className={this.getCardStyle()}
        {...customProps}
      >
        <HeaderComponent {...this.props} />
        <div
          data-test-card-body
          className={`${css.body} ${bodyClass || ''}`}
        >
          {children}
        </div>
      </div>
    );
  }
}


text:
using System;
using System.Reflection;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;

namespace OpenSim.Region.PhysicsModule.ODE
{
    [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ODEPhysicsScene")]
    public class OdeModule : INonSharedRegionModule
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private bool m_Enabled = false;
        private IConfigSource m_config;
        private OdeScene  m_scene;

       #region INonSharedRegionModule

        public string Name
        {
            get { return "OpenDynamicsEngine"; }
        }

        public string Version
        {
            get { return "1.0"; }
        }

        public Type ReplaceableInterface
        {
            get { return null; }
        }

        public void Initialise(IConfigSource source)
        {
            IConfig config = source.Configs["Startup"];
            if (config != null)
            {
                string physics = config.GetString("physics", string.Empty);
                if (physics == Name)
                {
                    m_config = source;
                    m_Enabled = true;
                }
            }
        }

        public void Close()
        {
        }

        public void AddRegion(Scene scene)
        {
            if (!m_Enabled)
                return;

            if (Util.IsWindows())
                Util.LoadArchSpecificWindowsDll("ode.dll");

            // Initializing ODE only when a scene is created allows alternative ODE plugins to co-habit (according to
            // http://opensimulator.org/mantis/view.php?id=2750).
            SafeNativeMethods.InitODE();

            m_scene = new OdeScene(scene, m_config, Name, Version);
        }

        public void RemoveRegion(Scene scene)
        {
            if (!m_Enabled || m_scene == null)
                return;

            m_scene.Dispose();
            m_scene = null;
        }

        public void RegionLoaded(Scene scene)
        {
            if (!m_Enabled || m_scene == null)
                return;

            m_scene.RegionLoaded();
        }
        #endregion
    }
}


text:
#elif defined(_WIN32)
#include "WindowsIncludes.h" // Sleep
#elif defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3)

#else
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#endif

#include "RakSleep.h"

void RakSleep(unsigned int ms)
{
#ifdef _WIN32
	Sleep(ms);
#elif defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3)

#else
	//Single thread sleep code thanks to Furquan Shaikh, http://somethingswhichidintknow.blogspot.com/2009/09/sleep-in-pthread.html
	//Modified slightly from the original
	pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER;
	pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER;
	struct timespec timeToWait;
	struct timeval now;
	int rt;

	gettimeofday(&now,NULL);

	long seconds = ms/1000;
	long nanoseconds = (ms - seconds * 1000) * 1000000;
	timeToWait.tv_sec = now.tv_sec + seconds;
	timeToWait.tv_nsec = now.tv_usec*1000 + nanoseconds;

	if (timeToWait.tv_nsec >= 1000000000)
	{
	        timeToWait.tv_nsec -= 1000000000;
	        timeToWait.tv_sec++;
	}

	pthread_mutex_lock(&fakeMutex);
	rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait);
	pthread_mutex_unlock(&fakeMutex);
#endif
}


text:
namespace Htc.Vita.Core.Runtime
{
    public static partial class UserManager
    {
        internal class WindowsUserInfo
        {
            public Interop.Windows.WindowsTerminalServiceConnectState State { get; set; }
            public string Domain { get; set; }
            public string Username { get; set; }
        }
    }
}


text:
/* First created by JCasGen Mon May 26 21:43:19 EDT 2008 */
package org.apache.uima.calaisType.entity;

import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.JCasRegistry;
import org.apache.uima.jcas.cas.TOP_Type;

import org.apache.uima.calaisType.Entity;

/**
 * Updated by JCasGen Mon May 26 21:43:19 EDT 2008
 * XML source: C:/a/Eclipse/3.3/apache/OpenCalaisAnnotatorGroovy/src/main/descriptors/CalaisTestCollectionReader.xml
 * @generated */
public class SportsEvent extends Entity {
  /** @generated
   * @ordered
   */
  public final static int typeIndexID = JCasRegistry.register(SportsEvent.class);
  /** @generated
   * @ordered
   */
  public final static int type = typeIndexID;
  /** @generated  */
  public              int getTypeIndexID() {return typeIndexID;}

  /** Never called.  Disable default constructor
   * @generated */
  protected SportsEvent() {}

  /** Internal - constructor used by generator
   * @generated */
  public SportsEvent(int addr, TOP_Type type) {
    super(addr, type);
    readObject();
  }

  /** @generated */
  public SportsEvent(JCas jcas) {
    super(jcas);
    readObject();
  }

  /** <!-- begin-user-doc -->
    * Write your own initialization here
    * <!-- end-user-doc -->
  @generated modifiable */
  private void readObject() {}

  //*--------------*
  //* Feature: canonicalForm

  /** getter for canonicalForm - gets
   * @generated */
  public String getCanonicalForm() {
    if (SportsEvent_Type.featOkTst && ((SportsEvent_Type)jcasType).casFeat_canonicalForm == null)
      jcasType.jcas.throwFeatMissing("canonicalForm", "org.apache.uima.calaisType.entity.SportsEvent");
    return jcasType.ll_cas.ll_getStringValue(addr, ((SportsEvent_Type)jcasType).casFeatCode_canonicalForm);}

  /** setter for canonicalForm - sets
   * @generated */
  public void setCanonicalForm(String v) {
    if (SportsEvent_Type.featOkTst && ((SportsEvent_Type)jcasType).casFeat_canonicalForm == null)
      jcasType.jcas.throwFeatMissing("canonicalForm", "org.apache.uima.calaisType.entity.SportsEvent");
    jcasType.ll_cas.ll_setStringValue(addr, ((SportsEvent_Type)jcasType).casFeatCode_canonicalForm, v);}
  }


text:
using System;
using System.ComponentModel.DataAnnotations;

namespace MMMWrapper.Models
{
    public class M3BlanketAgreementLinePrice
    {
        public int Company { get; set; }
        [StringLength(10)]
        public string CustomerNumber { get; set; }
        [StringLength(7)]
        public string BlanketAgreementNumber { get; set; }
        public DateTime FromDate { get; set; }
        [StringLength(2)]
        public string Priority { get; set; }
        [StringLength(15)]
        public string StartValue1 { get; set; }
        [StringLength(15)]
        public string StartValue2 { get; set; }
        [StringLength(15)]
        public string StartValue3 { get; set; }
        [StringLength(15)]
        public string StartValue4 { get; set; }
        public DateTime StartDate { get; set; }
        public double LowestQuantityLimit { get; set; }
        public double SalesPrice { get; set; }
        public double SalesPriceQuantity { get; set; }
        public double Discount { get; set; }
        public double DiscountAmountPerUnit { get; set; }
        public double NetPriceUsed { get; set; }
    }
}


text:
<!DOCTYPE html>

        <title>HabitiFit-2.5</title>

       <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
       <link rel="stylesheet" href="css/style.css" type="text/css" />

HabitiFit

How to Use:

 Authenticate with FitBit, then fill in your habitica api data (press submit)!

  Pick the metrics you'd like to use and fill in their values.  Press submit.

Go into habitica and create a habit with a name identical to the field you filled out. Repeat for multiple metrics

 That's it! Every three or so minutes, the page will automatically poll FitBit's api and update your habitica profile according to your metrics!

In-depth instructions can be found  on the wiki

                  Authenticate with FitBit

Please report bugs or feature requests here!

                  <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                      Your FitBit access code has expired.  Please re-authenticate.  Note: This is not a valid logout

               Refresh Fitbit Data

Steps Today:

Calories Out Today:

Miles Walked Today:

                  Reset All Data (logout)

Pick Whichever Metrics You'd Like to Track!

You'll need to have a habit whose text is the same as the input form.

i.e. "500 steps taken"

                            <input type="checkbox" aria-label="..." id="track_steps">

                        <input type="text" id="steps_value" class="form-control">
                        steps taken

                            <input type="checkbox" aria-label="..." id="track_miles">

                        <input type="text" id="miles_value" class="form-control">
                        miles traveled

                            <input type="checkbox" aria-label="..." id="track_calories">

                        <input type="text" id="calories_value" class="form-control">
                        calories burned

Submit

Habitica Stats:

User:

Class:

Level:

XP:

Enter Habitica Data Here:

                       User Id
                       <input  class="form-control" type="text" id="user_id"/>

                       Api Token
                      <input class="form-control" name="searchTxt" type="password" id="api_token"/>

Submit

Made with ♥ by Lamikins


text:
package HIndex_274;

import java.util.Arrays;

/**
 * Given an array of citations (each citation is a non-negative integer) of a researcher,
 * write a function to compute the researcher's h-index.
 *
 * According to the definition of h-index on Wikipedia:
 * "A scientist has index h if h of his/her N papers have at least h citations each,
 * and the other N − h papers have no more than h citations each."
 *
 * For example, given citations = [3, 0, 6, 1, 5],
 * which means the researcher has 5 papers in total and each of them
 * had received 3, 0, 6, 1, 5 citations respectively.
 * Since the researcher has 3 papers with at least 3 citations each
 * and the remaining two with no more than 3 citations each, his h-index is 3.
 *
 * Note: If there are several possible values for h,
 * the maximum one is taken as the h-index.
 */
public class Solution {
    public int hIndex2(int[] citations) {
        if(citations.length==0) return 0;
        Arrays.sort(citations);
        int count = 0,pointer = citations.length-1;
        for(int i=citations.length;;i--){
            while(pointer>-1&&citations[pointer]>=i){
                pointer--;
                count++;
            }
            if(count>=i) return i;
        }
    }

    // solution above is slow
    // use counting sort instead
    public int hIndex(int[] citations){
        int[] count = new int[citations.length+1];
        for(int i:citations){
            int key = i>citations.length?citations.length:i;
            count[key]++;
        }
        int index = count.length-1;
        for(int papers=count[index];papers<index;papers+=count[index])
            index--;
        return index;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.hIndex(new int[]{10,10,10,10}));
        System.out.println(s.hIndex(new int[]{0,0,0,0}));
        System.out.println(s.hIndex(new int[]{0}));
        System.out.println(s.hIndex(new int[]{100}));
        System.out.println(s.hIndex(new int[]{4}));
    }
}


text:
puppet-phantomjs
===============

Simple puppet module that installs PhantomJS - headless WebKit scriptable with a Javascript API.

Using
-----

	class { 'phantomjs':
		package_version => '1.9.7',
		package_update => true,
		install_dir => '/usr/local/bin',
		source_dir => '/opt',
	}

The module pulls in *curl*, *bzip2* and *libfontconfig1* if you haven't defined those packages yourself.


text:
This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).

## start app

```bash
# npm start
```

## start storybook

```bash
# npm run storybook
```

## information

In the sample we show both a component being decorated by translate hoc using a [storybook decorator](https://storybook.js.org/basics/writing-stories/#using-decorators) to wrap the `I18nextProvider` around the decorated component and a pure component just expecting a t function which we pass in with a mock function.


text:
Salvattore
==========
[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/rnmp/salvattore?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

[![](http://files.bandd.co/zQf5+)](http://salvattore.com/)

Salvattore is a library agnostic JS script that will help you organize your HTML elements according to the number of columns you specify, like jQuery Masonry.

Features
--------
* __No requirements:__ Salvattore is a standalone script, it will work right away after being referenced in your HTML page.
* __Extremely lightweight:__ about 2.7KB (minified and gzipped.)
* __CSS-driven configuration:__ the number of columns is defined in CSS and the styling is left to the user.
* __Media queries ready:__ the same parameters can be used inside media queries for better results on different devices.
* __Wide browser support:__ modern browsers and IE9+

### Upcoming
* __Balanced columns:__ to keep all columns about the same height.

To find out more and see it in action, please visit [our website.](http://salvattore.com)

You can also [follow us](http://twitter.com/salvattorejs) on Twitter.

Methods
--------------------------
Methods can be called on the globally exposed `salvattore` object for advanced usage.

```javascript
var grid = document.querySelector('#grid');
var item = document.createElement('article');

salvattore.appendElements(grid, [item]);
item.outerHTML = 'I've been appended!';
```

Method | Argument | Description
------ | -------- | -----------
appendElements | grid : DOM object, elements: Array of DOM objects | Adds elements to the end of a grid.
prependElements | grid : DOM object, elements: Array of DOM objects | Adds elements to a beginning of a grid. _Adds multiple elements one by one before each other, so note the order._
registerGrid | grid : DOM object | Adds a new grid to salvattore. Which is initialized automatically then.
recreateColumns | grid : DOM object | Removes all the columns from the grid, and adds them again.
rescanMediaQueries | | Checks stylesheets and selectors for media queries again. Recreates the columns for all grids afterwards.

How to contribute
-----------------
We use Gulp to add polyfills and minify the script in the `dist/` folder. To make changes to the script itself, please edit `src/salvattore.js` and send us a pull request.

### Share feedback & ideas
You can even contribute by using Salvattore and sharing bugs, ideas or solutions on the Issues page.
Protip: if you're posting a bug please share all the relevant data and ideally a live URL so that we can debug (yeah we do that!)


text:
///<reference path="../lib/definitions.d.ts"/>

import * as fs   from "fs";

/**
 * optional, external settings file name
 * @type {string}
 */
const GULP_SETTINGS: string = "./gulp-tasks/settings/gulp-settings.json";

/**
 * typical default settings
 * @type {Settings}
 */
const DEFAULT_SETTINGS: Settings = {
  buildTsconfig:     "./tsconfig.json",
  buildRenaming:     { dirname: "" },
  compileOutput:     "./release",
  coverageReport:    "text",
  declarationOutput: "./release",
  jsonSchemas:       "./gulp-tasks/settings/schema-sources.json",
  jsonSchemasOutput: "json-schemas",
  srcPath:           "./src",
  testsMainFile:     "./tests/index-tests.js",
  testsPath:         "./tests",
  testsTsconfig:     "./tests/tsconfig.json",
  tsLintRules:       "./tslint.json"
};

/**
 * settings for gulp tasks, merging of default settings and, if it exists, external settings file
 * @type {Settings}
 */
export const settings: Settings = Object.assign({}, DEFAULT_SETTINGS, fs.exists(GULP_SETTINGS) ? require(GULP_SETTINGS) || {} : {});


text:
namespace ui {

namespace {

bool IsRandRAvailable() {
  int randr_version_major = 0;
  int randr_version_minor = 0;
  static bool is_randr_available = XRRQueryVersion(
      base::MessagePumpX11::GetDefaultXDisplay(),
      &randr_version_major, &randr_version_minor);
  return is_randr_available;
}

// Get the EDID data from the |output| and stores to |edid|.
// Returns true if EDID property is successfully obtained. Otherwise returns
// false and does not touch |edid|.
bool GetEDIDProperty(XID output, std::vector<uint8_t>* edid) {
  if (!IsRandRAvailable())
    return false;

  Display* display = base::MessagePumpX11::GetDefaultXDisplay();

  static Atom edid_property = XInternAtom(
      base::MessagePumpX11::GetDefaultXDisplay(),
      RR_PROPERTY_RANDR_EDID, false);

  bool has_edid_property = false;
  int num_properties = 0;
  Atom* properties = XRRListOutputProperties(display, output, &num_properties);
  for (int i = 0; i < num_properties; ++i) {
    if (properties[i] == edid_property) {
      has_edid_property = true;
      break;
    }
  }
  XFree(properties);
  if (!has_edid_property)
    return false;

  Atom actual_type;
  int actual_format;
  unsigned long bytes_after;
  unsigned long nitems = 0;
  unsigned char* prop = NULL;
  XRRGetOutputProperty(display,
                       output,
                       edid_property,
                       0,                // offset
                       128,              // length
                       false,            // _delete
                       false,            // pending
                       AnyPropertyType,  // req_type
                       &actual_type,
                       &actual_format,
                       &nitems,
                       &bytes_after,
                       &prop);
  DCHECK_EQ(XA_INTEGER, actual_type);
  DCHECK_EQ(8, actual_format);
  edid->assign(prop, prop + nitems);
  XFree(prop);
  return true;
}

// Gets some useful data from the specified output device, such like
// manufacturer's ID, product code, and human readable name. Returns false if it
// fails to get those data and doesn't touch manufacturer ID/product code/name.
// NULL can be passed for unwanted output parameters.
bool GetOutputDeviceData(XID output,
                         uint16_t* manufacturer_id,
                         std::string* human_readable_name) {
  std::vector<uint8_t> edid;
  if (!GetEDIDProperty(output, &edid))
    return false;

  bool result = ParseOutputDeviceData(
      edid, manufacturer_id, human_readable_name);
  return result;
}

}  // namespace

bool GetDisplayId(XID output_id,
                  uint8_t output_index,
                  int64_t* display_id_out) {
  std::vector<uint8_t> edid;
  if (!GetEDIDProperty(output_id, &edid))
    return false;

  bool result = GetDisplayIdFromEDID(edid, output_index, display_id_out);
  return result;
}

std::string GetDisplayName(RROutput output) {
  std::string display_name;
  GetOutputDeviceData(output, NULL, &display_name);
  return display_name;
}

bool GetOutputOverscanFlag(RROutput output, bool* flag) {
  std::vector<uint8_t> edid;
  if (!GetEDIDProperty(output, &edid))
    return false;

  bool found = ParseOutputOverscanFlag(edid, flag);
  return found;
}

}  // namespace ui