text:
using namespace std;

void IRSCoding::checkParams() {
    if (k <= 0 || m <= 0 || w <= 0)
        throw std::invalid_argument("Invalid Coding Parameters");
	if (w != 8)
        throw std::invalid_argument("Invalid Coding Parameters (w = 8)");
}

vector<ERL_NIF_TERM> IRSCoding::doEncode(ERL_NIF_TERM dataBin) {
    unsigned char* blocks[k + m];

    ErlNifBinary data;
    enif_inspect_binary(env, dataBin, &data);

    size_t dataSize = data.size;
    size_t blockSize = roundTo((roundTo(dataSize, k*w) / (k*w)), 16) * w;

    size_t offset = 0;
    size_t remain = dataSize;
    int filled = 0;
    while(remain >= blockSize) {
        blocks[filled] = data.data + offset;
        offset += blockSize;
        remain -= blockSize;
        filled++;
    }
    ErlNifBinary tmp;
    enif_alloc_binary((k + m - filled) * blockSize, &tmp);
    memset(tmp.data, 0, (k + m - filled) * blockSize);
    memcpy(tmp.data, data.data + offset, remain);
    offset = 0;
    for(int i = filled; i < k + m; ++i, offset += blockSize) {
        blocks[i] = tmp.data + offset;
    }

    uint8_t encode_matrix[(k + m) * k];
    uint8_t g_tbls[k * m * 32];
    gf_gen_cauchy1_matrix(encode_matrix, k + m, k);
    ec_init_tables(k, m, &encode_matrix[k * k], g_tbls);
    ec_encode_data(blockSize, k, m, g_tbls, blocks, &blocks[k]);

    vector<ERL_NIF_TERM> blockList;
    for(int i = 0; i < filled; ++i) {
        blockList.push_back(enif_make_sub_binary(env, dataBin, i * blockSize, blockSize));
    }
    ERL_NIF_TERM tmpBin = enif_make_binary(env, &tmp);
    offset = 0;
    for(int i = filled; i < k + m; ++i, offset += blockSize) {
        blockList.push_back(enif_make_sub_binary(env, tmpBin, offset, blockSize));
    }

    return blockList;
}

ERL_NIF_TERM IRSCoding::doDecode(vector<ERL_NIF_TERM> blockList, vector<int> blockIdList, size_t dataSize) {

    set<int> availSet(blockIdList.begin(), blockIdList.end());
    if (availSet.size() < (unsigned int)k)
        throw std::invalid_argument("Not Enough Blocks");
    else if (availSet.size() < blockIdList.size()) {
        throw std::invalid_argument("Blocks should be unique");
    }

    size_t blockSize;
    unsigned char* availBlocks[k + m];

    ErlNifBinary blocks[k + m];
    for(size_t i = 0; i < blockIdList.size(); ++i) {
        int blockId = blockIdList[i];
        enif_inspect_binary(env, blockList[i], &blocks[blockId]);
        blockSize = blocks[blockId].size;
        availBlocks[i] = blocks[blockId].data;
    }

    bool needFix = false;
    int dataErasures = 0;
    vector<int> outBlockIdList;
    ErlNifBinary tmpBin;
    enif_alloc_binary(blockSize * k, &tmpBin);
    unsigned char* outBlocks[k];

    for(int i = 0; i < k; ++i)
        if (availSet.count(i) == 0) {
            needFix = true;
            outBlockIdList.push_back(i);
            outBlocks[dataErasures] = tmpBin.data + i * blockSize;
            ++dataErasures;
        } else {
            memcpy(tmpBin.data + i * blockSize, blocks[i].data, blockSize);
        }

    if (!needFix) {
        ERL_NIF_TERM allBlocksBin = enif_make_binary(env, &tmpBin);
        ERL_NIF_TERM bin = enif_make_sub_binary(env, allBlocksBin, 0, dataSize);
        return bin;
    }

    uint8_t encode_matrix[(k + m) * k];
    uint8_t g_tbls[k * m * 32];
    uint8_t decode_matrix[(k + m) * k];
    gf_gen_cauchy1_matrix(encode_matrix, k + m, k);
    gf_gen_decode_matrix(encode_matrix, decode_matrix, blockIdList, outBlockIdList);
    ec_init_tables(k, dataErasures, decode_matrix, g_tbls);
    ec_encode_data(blockSize, k, dataErasures, g_tbls, availBlocks, outBlocks);

    ERL_NIF_TERM allBlocksBin = enif_make_binary(env, &tmpBin);
    ERL_NIF_TERM bin = enif_make_sub_binary(env, allBlocksBin, 0, dataSize);
    return bin;
}

vector<ERL_NIF_TERM> IRSCoding::doRepair(vector<ERL_NIF_TERM> blockList, vector<int> blockIdList, vector<int> repairList) {

    set<int> availSet(blockIdList.begin(), blockIdList.end());
    if (availSet.size() < (unsigned int)k)
        throw std::invalid_argument("Not Enough Blocks");
    else if (availSet.size() < blockIdList.size()) {
        throw std::invalid_argument("Blocks should be unique");
    }

    size_t blockSize;
    unsigned char* availBlocks[k + m];

    ErlNifBinary blocks[k + m];
    for(size_t i = 0; i < blockIdList.size(); ++i) {
        int blockId = blockIdList[i];
        enif_inspect_binary(env, blockList[i], &blocks[blockId]);
        blockSize = blocks[blockId].size;
        availBlocks[i] = blocks[blockId].data;
    }

    int outSize = repairList.size();
    ErlNifBinary tmpBin;
    enif_alloc_binary(blockSize * k, &tmpBin);
    unsigned char* outBlocks[outSize];

    for(int i = 0; i < outSize; ++i) {
        outBlocks[i] = tmpBin.data + i * blockSize;
    }

    uint8_t encode_matrix[(k + m) * k];
    uint8_t g_tbls[k * m * 32];
    uint8_t decode_matrix[(k + m) * k];
    gf_gen_cauchy1_matrix(encode_matrix, k + m, k);
    gf_gen_decode_matrix(encode_matrix, decode_matrix, blockIdList, repairList);
    ec_init_tables(k, outSize, decode_matrix, g_tbls);
    ec_encode_data(blockSize, k, outSize, g_tbls, availBlocks, outBlocks);

    vector<ERL_NIF_TERM> repairBlocks;
    ERL_NIF_TERM outBlockBin = enif_make_binary(env, &tmpBin);
    for(size_t i = 0; i < repairList.size(); ++i){
        ERL_NIF_TERM block = enif_make_sub_binary(env, outBlockBin, i * blockSize, blockSize);
        repairBlocks.push_back(block);
    }

    return repairBlocks;
}

void IRSCoding::gf_gen_decode_matrix(
        unsigned char* encode_matrix,
        unsigned char* decode_matrix,
        vector<int> availBlockIdList,
        vector<int> outBlockIdList) {
    unsigned char invert_matrix[(k + m) * k];
    unsigned char temp_matrix[(k + m) * k];
    for(int i = 0; i < k; ++i){
        int blockId = availBlockIdList[i];
        for(int j = 0; j < k; ++j) {
            temp_matrix[i * k + j] = encode_matrix[blockId * k + j];
        }
    }
    if (gf_invert_matrix(temp_matrix, invert_matrix, k) < 0)
        throw std::invalid_argument("Non Invertible");
    for(size_t i = 0; i < outBlockIdList.size(); ++i) {
        int blockId = outBlockIdList[i];
        if (blockId < k) {
            for(int j = 0; j < k; ++j) {
                decode_matrix[k * i + j] = invert_matrix[k * blockId + j];
            }
        } else {
            for(int j = 0; j < k; ++j) {
                unsigned char s = 0;
                for(int l = 0; l < k; ++l) {
                    s ^= gf_mul(invert_matrix[l * k + j],
                            encode_matrix[k * blockId + l]);
                }
                decode_matrix[k * i + j] = s;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
;(function($){
	$.fn.blankBox = function(){
		var el = 'blank-box-el';
		return this.each(function(){
			var t = $(this);
			var d = t.data(el) || $('<div/>').addClass(el).insertAfter(t);
			d.hide();
			d.height(t.height()).width(t.width());
			if(/^(fixed|absolute)$/.test(t.css('position'))) d.show();
			t.data(el, d);
		});
	}
	$.fn.responsiveClass = function( classNames ){
		if(!classNames) return this;
		var w = $(window).width();
		return this.each(function(){
			var t = $(this);
			var className;
			for(var i in classNames){
				var name = classNames[i]
				t.removeClass(name);
				if(w >= i) className = name;
			}
			t.addClass(className).data('responsive-class-name', className);
		});
	}
	$.fn.getResponsiveClass = function(){
		return this.data('responsive-class-name');
	}
	$.fn.fitHeight = function(){
		return this.each(function(){
			var t = $(this).height('auto');
			var parent = t.parent();
			var h = parent.height();
			var sum = 0;
			parent.find('> *').each(function(idx){
				var e = $(this);
				if(t[0] != e[0] && !(/^(fixed|absolute)$/.test(e.css('position')))){
					sum += e.outerHeight();
				}
			});
			t.height(parent.height() - sum);
		});
	}
})(jQuery);
;(function($){
	var app = $.easyEditor = function(){
		var o = this;
		o.init();
	}
	$.extend(app.prototype,{
		init : function(){
			var o = this;

			// set parameter
			o.el = {
				saveName : $('input.my-save-name'),
				saveList : $('ul.my-save-list'),
				saveBtn : $('a.my-save-btn'),
				runBtn : $('a.run-button'),
				loadBtn : $('a.my-load-btn')
			};
			o.pa = {
				timer : '',
				saveNameDefaultValue : o.el.saveName.prop('defaultValue'),
				selectCode : sessionStorage.getItem('select-code')
			};
			if(o.pa.selectCode == null) o.pa.selectCode = o.pa.saveNameDefaultValue;

			//bind event
			$('a.my-del-btn').on('click', function(){
				$.each(o.api, function(i){
					o.api[i].clearStorage();
				});
				o.deleteCodeList(o.pa.selectCode);
				o.loadCodeList();
				if(o.isSampleCode(o.pa.selectCode)){
					alert('Initialized ' + o.pa.selectCode + ' !')
					o.reloadPage();
				}
				else{
					sessionStorage.removeItem('select-code');
					alert('Deleted ' + o.pa.selectCode + ' !')
				}

			});
			o.el.loadBtn.on('click', function(){
				o.toggleSaveList();
				return false;
			});
			o.el.saveList.on('click','a',function(){
				var name = $(this).text();
				sessionStorage.setItem('select-code',name);
				o.reloadPage();
			});
			o.el.saveBtn.on('click', function(){
				var name = o.el.saveName.val();
				if(!name) return;
				$.each(o.api, function(i){
					o.api[i].saveCodeToStorage(name);
				});
				var list = o.getSaveList();
				list[name] = 1;
				o.saveCodeList(list);
				o.loadCodeList();
				alert('save as '+(name));
			});
			o.el.runBtn.on('click', function(){
				if($('html').hasClass('my-mobile')){
					var demoTop = $('div.my-panel-demo').position().top;
					if(demoTop > $('html').scrollTop() + $(window).height()-100){
						$('html,body').animate({scrollTop:demoTop - $('div.my-header').outerHeight()});
					}
				}
			});
			$(window).on('resize', function(){
				if(o.pa.timer) clearTimeout(o.pa.timer);
				o.pa.timer = setTimeout(function(){
					o.adjustLayout();
				},0);
			});

			//rendar
			o.loadCodeList();
			if(o.pa.selectCode){
				o.el.saveName.val(o.pa.selectCode);
			}
			if(!o.pa.selectCode || o.isSampleCode(o.pa.selectCode)){
				$('a.my-del-btn').text('初期化');
			}

			o.loadSample();
			o.api = $('.easy-editor-code textarea.code').exCodePrettify({
				api : true,
				container : 'div.my-contents-demo',
				showDemo : true,
				editCode : true,
				saveLabel : 'APPLY',
				autoSaveToStorage : false,
				autoLoadFromStorage : true,
				savePrefix : o.el.saveName.val(),
				behaveJS : false
			});
			o.adjustLayout();
		},
		isSampleCode : function(codeId){
			var o = this;
			return o.getSaveList()[o.pa.selectCode] == 9;
		},
		loadSample : function(){
			var o = this;
			$('div.easy-editor-sample').each(function(){
				var t = $(this);
				if(t.data('code-id') == o.pa.selectCode){
					$('div.easy-editor-code').html(t.html());
				}
			});
		},
		getSaveList : function(){
			var o = this;
			var list = JSON.parse(localStorage.getItem('save-list')) || {};
			$('div.easy-editor-sample').each(function(){
				list[$(this).data('code-id')] = 9;
			});
			return list;
		},
		saveCodeList : function(json){
			var o = this;
			localStorage.setItem('save-list',JSON.stringify(json));
		},
		deleteCodeList : function(key){
			var o = this;
			var list = o.getSaveList();
			delete list[key];
			o.saveCodeList(list);
		},
		loadCodeList : function(){
			var o = this;
			o.el.saveList.html('');
			var list = o.getSaveList();
			var add = function(text){
				$('<a/>').prop('href','javascript:void(0)').text(text).wrap('<li/>').parent().appendTo(o.el.saveList);
			}
			for(var i in list) add(i);
		},
		toggleSaveList : function(method){
			var o = this;
			var panel = $('div.my-tool-b');
			var method = method || (panel.is(':hidden') ? 'show' : 'hide');
			o.el.loadBtn.removeClass('show-toggle');
			if(method == 'show'){
				o.el.loadBtn.addClass('show-toggle');
			}
			$('div.my-tool-b')[method]();
			o.adjustLayout();
		},
		adjustLayout : function(){
			var rClass = $('html').responsiveClass( {0:'my-mobile',600:'my-pc'} ).getResponsiveClass();
			$('div.my-header').blankBox();
			if(rClass == 'my-pc'){
				$('div.my-main').fitHeight();
			}
			else{
				$('div.my-main').height('auto');
			}
		},
		reloadPage : function(){
			setTimeout(function(){location.reload();},100);
		}
	});
})(jQuery);


text:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using Approve.RuleCenter;
using Approve.Common;
using Approve.EntityBase;

public partial class Share_Sys_CardNoSelect : System.Web.UI.Page
{
    Share sh = new Share();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ControlBind();
            ShowInfo();
        }
    }

    private void ControlBind()
    {
        //批次
        DataTable dt = sh.getBatchTable("666");
        t_FBatchId.DataSource = dt;
        t_FBatchId.DataTextField = "FName";
        t_FBatchId.DataValueField = "FID";
        t_FBatchId.DataBind();
        t_FBatchId.Items.Insert(0, new ListItem("请选择", ""));
    }

    //条件
    private string GetCon()
    {
        StringBuilder sb = new StringBuilder();
        if (!string.IsNullOrEmpty(t_FLockLabelNumber.Text.Trim()))
        {
            sb.Append(" and FLockLabelNumber like '%" + t_FLockLabelNumber.Text.Trim() + "%'");
        }
        if (!string.IsNullOrEmpty(t_FBatchId.SelectedValue))
        {
            sb.Append(" and FBatchId = '" + t_FBatchId.SelectedValue + "'");
        }
        if (!string.IsNullOrEmpty(t_FBatchId.SelectedValue))
        {
            sb.Append(" and FBatchId = '" + t_FBatchId.SelectedValue + "'");
        }
        return sb.ToString();
    }

    private void ShowInfo()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(" select * from CF_Sys_Lock where fisdeleted=0  and fstate=0 ");//fstate=0:未使用的
        sb.Append(GetCon());
        sb.Append(" Order By FBatchId ");

        this.Pager1.className = "dbShare";
        this.Pager1.sql = sb.ToString();
        this.Pager1.pagecount = 10;
        this.Pager1.controltopage = "DG_List";
        this.Pager1.controltype = "DataGrid";
        this.Pager1.dataBind();
    }

    protected void DG_List_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemIndex > -1)
        {
            e.Item.Cells[0].Text = (e.Item.ItemIndex + 1 + this.Pager1.pagecount * (this.Pager1.curpage - 1)).ToString();
            string FID = EConvert.ToString(DataBinder.Eval(e.Item.DataItem, "FID"));
            string FBatchId = EConvert.ToString(DataBinder.Eval(e.Item.DataItem, "FBatchId"));
            e.Item.Cells[3].Text = sh.getBatchName(FBatchId);
        }
    }
    protected void DG_List_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        if (e.CommandName == "cnSelect")
        {
            string fId = e.CommandArgument.ToString();
            this.RegisterStartupScript(Guid.NewGuid().ToString(), "<script>returnValue='" + fId + "';window.close();</script>");
        }
    }

    protected void btnQuery_Click(object sender, EventArgs e)
    {
        ShowInfo();
    }

}


text:
package com.tle.core.item.standard.operations.workflow;

import com.dytech.edge.exceptions.WorkflowException;
import com.tle.beans.item.HistoryEvent;
import com.tle.core.item.standard.workflow.nodes.TaskStatus;

public abstract class SpecificTaskOperation extends TaskOperation {
  private String taskId;

  public SpecificTaskOperation(String taskId) {
    this.taskId = taskId;
  }

  public TaskStatus getTaskStatus() {
    return (TaskStatus) getNodeStatus(taskId);
  }

  @SuppressWarnings("nls")
  public void checkWeCanModerate() {
    if (!getTaskStatus().canCurrentUserModerate(this)) {
      throw new WorkflowException("Current user can't moderate this step");
    }
  }

  protected void addMessage(char type, String message) {
    addMessage(type, message, null);
  }

  protected void addMessage(char type, String message, String uuid) {
    addMessage(taskId, type, message, uuid);
  }

  protected void setStepFromTask(HistoryEvent event) {
    setStepFromTask(event, taskId);
  }
}


text:
This is accent a minimal, mobile friendly theme for Jekyll

It features:

Customizable accent

Comments with Disqus

Permalinks for headers

Guest Posts

Author's Page

Author's Profile Picture, Short Bio.

Pagination using jekyll-paginate

Syntax Highlighting for code

RSS Feed

Google Analytics

A 404 page.

Full Documentation on the Demo website.


text:
@class NSString;

@interface EnterpriseBrandAttr : MMObject <WCDBCoding>
{
    unsigned int qyUin;
    unsigned int userUin;
    unsigned int userFlag;
    unsigned int wwExposeTimes;
    unsigned int wwMaxExposeTimes;
    NSString *userName;
    long long m___rowID;
}

+ (const basic_string_a490aa4c *)getWCDBPrimaryColumnName;
+ (const struct WCDBIndexHelper *)getWCDBIndexArray;
+ (unsigned long long)getWCDBIndexArrayCount;
+ (const map_0e718273 *)getFileValueTagIndexMap;
+ (id)getFileValueTypeTable;
+ (const map_0e718273 *)getPackedValueTagIndexMap;
+ (id)getPackedValueTypeTable;
+ (const map_7a576766 *)getValueNameIndexMap;
+ (id)getValueTable;
+ (id)dummyObject;
@property(nonatomic) long long __rowID; // @synthesize __rowID=m___rowID;
@property(nonatomic) unsigned int wwMaxExposeTimes; // @synthesize wwMaxExposeTimes;
@property(nonatomic) unsigned int wwExposeTimes; // @synthesize wwExposeTimes;
@property(nonatomic) unsigned int userFlag; // @synthesize userFlag;
@property(nonatomic) unsigned int userUin; // @synthesize userUin;
@property(nonatomic) unsigned int qyUin; // @synthesize qyUin;
@property(retain, nonatomic) NSString *userName; // @synthesize userName;
- (void).cxx_destruct;
- (const map_0e718273 *)getValueTagIndexMap;
- (id)getValueTypeTable;
- (const WCDBCondition_c6db074e *)db_wwMaxExposeTimes;
- (const WCDBCondition_c6db074e *)db_wwExposeTimes;
- (const WCDBCondition_c6db074e *)db_userFlag;
- (const WCDBCondition_c6db074e *)db_userUin;
- (const WCDBCondition_c6db074e *)db_qyUin;
- (const WCDBCondition_22fabacd *)db_userName;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
__author__  = 'Sal Aguinaga'
__license__ = "GPL"
__version__ = "0.1.0"
__email__   = "saguinag@nd.edu"

from tweepy import StreamListener, Stream
import pprint as pp
import json, time, sys, csv
from HTMLParser import HTMLParser
import sys, os, argparse
import time, datetime

## http://stackoverflow.com/questions/23531608/how-do-i-save-streaming-tweets-in-json-via-tweepy

def twitter_authentication():

  ## authentication
  fileNamePaht = "../.env/keys.tsv"
  keys_dict = dict()
  with open(fileNamePaht, 'r') as f:
    inreader = csv.reader(f,delimiter='\t')
    for row in inreader:
      keys_dict[row[0]] = row[1]

    return keys_dict
#
#follow_acc = ['759251'] #cnn id
#track_words = ['New Zealand flag'] # if remove ReTweets, add '-RT' in the word
# http://stackoverflow.com/questions/32445553/tweepy-not-finding-results-that-should-be-there

class Listener(StreamListener):
  def __init__(self, api = None, fprefix = 'streamer'):
    self.api = api or API()
    self.counter = 0
    self.fprefix = fprefix
    self.output  = open(fprefix + '.json', 'a')

  def on_status(self, status):
    status = json.loads(HTMLParser().unescape(status))
    if 'indiana' or 'weather' in stats.lower():
        # status.created_at is datetime object and status.text is the tweet's text
        text = '::'.join([str(status.created_at), status.text, status.author.screen_name]) + '\n'
        f.write(text)

def given_screenname_getfollowers():
	import tweepy
	import json
	import numpy as np
	import shelve

	auth_keys = twitter_authentication()
	CONSUMER_KEY = auth_keys['CONSUMER_KEY']
	CONSUMER_SECRET = auth_keys['CONSUMER_SECRET']
	OAUTH_TOKEN=auth_keys['OAUTH_TOKEN']
	OAUTH_TOKEN_SECRET = auth_keys['OAUTH_TOKEN_SECRET']

	# print len (CONSUMER_KEY), len(CONSUMER_SECRET)
	# print len(OAUTH_TOKEN), len(OAUTH_TOKEN_SECRET)

	## OAuth process, using the keys and tokens
	auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
	auth.set_access_token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

	## Creation of the actual interface, using authentication
	api = tweepy.API(auth)

	#
	##  From the tq list of tweets, we get those that interacted
	##  with these tweets and we get a list of their followers to
	##  to build a graph that expands:
	##  (pub) -> tq_tweet -> user -> user_followers_list
	#

	fname = 'datasets/tw_users_list_topic1.txt'
	fname = "Results/clustered_relevant_users.tsv"

	scrn_names_lst=[]
	try:
		scrn_names_lst = np.loadtxt(fname,dtype=str)
	except Exception, e:
		with open (fname) as f:
			lines = f.readlines()
			for l in lines:
				scrn_names_lst.append([x.lstrip('[').rstrip(']') for x in l.split()])

	import itertools
	chain = itertools.chain(*scrn_names_lst)
	scrn_names_list = [xfor x in list(chain) if x]

	fids = []
	usr_followers_d = {}
	for scrnm in scrn_names_lst:
		scr
		try:
			for page in tweepy.Cursor(api.followers_ids, screen_name=scrnm).pages():
				fids.extend(page)
				time.sleep(60)
		except Exception, e:
				print '___ error:', e, 'skipping user:',scrnm
				continue

		print len(fids)
		usr_followers_d[scrnm] = fids

	myShelve = shelve.open('Results/tusr_citing_has_follower_network.shl')
	myShelve['usr_followers_d'] = usr_followers_d
	myShelve.update(usr_followers_d)
	myShelve.close()

def load_follower_network_tobuild_graph():
  import shelve

  myShelve = shelve.open('tusr_citing_has_follower_network.shl')
  usr_followers_d = myShelve['usr_followers_d']
  myShelve.close()

  print 'Read shelf done'
  for k,v in usr_followers_d.items():
    print k,v
    break

if __name__=='__main__':
  given_screenname_getfollowers()
  load_follower_network_tobuild_graph()
  print 'Done'


text:
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

namespace Kafka.Protocol
{
    static class Error
    {
        public static bool IsPartitionOkForClients(ErrorCode code)
        {
            return code == ErrorCode.NoError
                   || code == ErrorCode.ReplicaNotAvailable;
        }

        public static bool IsPartitionErrorRecoverableForProducer(ErrorCode code)
        {
            switch (code)
            {
                case ErrorCode.LeaderNotAvailable:
                case ErrorCode.NotLeaderForPartition:
                case ErrorCode.RequestTimedOut:
                case ErrorCode.UnknownTopicOrPartition:
                case ErrorCode.InvalidMessage:
                case ErrorCode.InvalidMessageSize:
                case ErrorCode.NotEnoughReplicas:
                case ErrorCode.NotEnoughReplicasAfterAppend:
                    return true;

                default:
                    return false;
            }
        }
    }

    enum ErrorCode : short
    {
        ///No error--it worked!
        NoError = 0,

        ///An unexpected server error
        Unknown = -1,

        ///The requested offset is outside the range of offsets maintained by the server for the given
        /// topic/partition.
        OffsetOutOfRange = 1,

        ///This indicates that a message contents does not match its CRC
        InvalidMessage = 2,

        ///This request is for a topic or partition that does not exist on this broker.
        UnknownTopicOrPartition = 3,

        ///The message has a negative size
        InvalidMessageSize = 4,

        ///This error is thrown if we are in the middle of a leadership election and there is currently
        /// no leader for this partition and hence it is unavailable for writes.
        LeaderNotAvailable = 5,

        ///This error is thrown if the client attempts to send messages to a replica that is not
        /// the leader for some partition. It indicates that the clients metadata is out of date.
        NotLeaderForPartition = 6,

        ///This error is thrown if the request exceeds the user-specified time limit in the request
        RequestTimedOut = 7,

        ///This is not a client facing error and is used only internally by intra-cluster
        /// broker communication
        BrokerNotAvailable = 8,

        ///Unused
        ReplicaNotAvailable = 9,

        ///The server has a configurable maximum message size to avoid unbounded memory allocation.
        /// This error is thrown if the client attempt to produce a message larger than this maximum.
        MessageSizeTooLarge = 10,

        ///Internal error code for broker-to-broker communication
        StaleControllerEpoch = 11,

        ///If you specify a string larger than configured maximum for offset metadata
        OffsetMetadataTooLarge = 12,

        ///  The broker returns this error code for an offset fetch request if it is still loading offsets (after a leader change for that offsets topic partition)
        OffsetsLoadInProgress = 14,

        ///  The broker returns this error code for consumer metadata requests or offset commit requests
        /// if the offsets topic has not yet been created
        ConsumerCoordinatorNotAvailable = 15,

        /// The broker returns this error code if it receives an offset fetch or commit request for a consumer group that it is not a coordinator for
        NotCoordinatorForConsumer = 16,

        ///
        /// For a request which attempts to access an invalid topic (e.g. one which has an illegal name), or if an attempt is made to write to an internal topic (such as the consumer offsets topic).
        ///
        InvalidTopic = 17,

        ///
        /// If a message batch in a produce request exceeds the maximum configured segment size.
        ///
        MessageSetSizeTooLarge = 18,

        ///
        /// Returned from a produce request when the number of in-sync replicas is lower than the configured minimum and requiredAcks is -1.
        ///
        NotEnoughReplicas = 19,

        ///
        /// Returned from a produce request when the message was written to the log, but with fewer in-sync replicas than required.
        ///
        NotEnoughReplicasAfterAppend = 20,

        /// Returned from a produce request if the requested requiredAcks is invalid (anything other than -1, 1, or 0).
        InvalidRequiredAcks	= 21,

        ///
        /// Returned from group membership requests (such as heartbeats) when the generation id provided in the request is not the current generation.
        ///
        IllegalGeneration = 22,

        ///
        /// Returned in join group when the member provides a protocol type or set of protocols which is not compatible with the current group.
        ///
        InconsistentGroupProtocol = 23,

        ///
        /// Returned in join group when the groupId is empty or null.
        ///
        InvalidGroupId = 24,

        ///
        /// Returned from group requests (offset commits/fetches, heartbeats, etc) when the memberId is not in the current generation.
        ///
        UnknownMemberId = 25,

        ///
        /// Return in join group when the requested session timeout is outside of the allowed range on the broker
        ///
        InvalidSessionTimeout = 26,

        ///
        /// Returned in heartbeat requests when the coordinator has begun rebalancing the group. This indicates to the client that it should rejoin the group.
        ///
        RebalanceInProgress = 27,

        ///
        /// This error indicates that an offset commit was rejected because of oversize metadata.
        ///
        InvalidCommitOffsetSize = 28,

        ///
        /// Returned by the broker when the client is not authorized to access the requested topic.
        ///
        TopicAuthorizationFailed = 29,

        ///
        /// Returned by the broker when the client is not authorized to access a particular groupId.
        ///
        GroupAuthorizationFailed = 30,

        ///
        /// Returned by the broker when the client is not authorized to use an inter-broker or administrative API.
        ///
        ClusterAuthorizationFailed = 31,

        ///
        /// The timestamp of the message is out of acceptable range.
        ///
        InvalidTimestamp = 32,

        ///
        /// The broker does not support the requested SASL mechanism.
        ///
        UnsupportedSaslMechanism = 33,

        ///
        /// Request is not valid given the current SASL state.
        ///
        IllegalSaslState = 34,

        ///
        /// The version of API is not supported.
        ///
        UnsupportedVersion = 35,

        ///
        ///
        ///
        TopicAlreadyExists = 36,

        ///
        /// Number of partitions is invalid.
        ///
        InvalidPartitions = 37,

        ///
        /// Replication-factor is invalid.
        ///
        InvalidReplicationFactor = 38,

        ///
        /// Replica assignment is invalid.
        ///
        InvalidReplicaAssignment = 39,

        ///
        /// Configuration is invalid.
        ///
        InvalidConfig = 40,

        ///
        /// This is not the correct controller for this cluster.
        ///
        NotController = 41,

        ///
        /// This most likely occurs because of a request being malformed by the client library or the message was sent to an incompatible broker. See the broker logs for more details.
        ///
        InvalidRequest = 42,

        ///
        /// The message format version on the broker does not support the request.
        ///
        UnsupportedForMessageFormat = 43,

        ///
        /// Request parameters do not satisfy the configured policy.
        ///
        PolicyViolation = 44,

        // Local error, not from brokers
        LocalError = -42,

        ///
        /// Deserialization on one message failed (bad Crc, magic number or compression)
        ///
        DeserializationError = -43,
    }
}


text:
'use strict';

let express = require('express');
let User = require('mongoose').model('User');
let passport = require('passport');

let router = express.Router();

router.post('/', User.exCreate);
router.put('/', User.exEdit);
router.get('/me', User.exGetLoggedUser);
router.get('/:id', User.exGet);
router.get('/', User.exGetAll);

module.exports = router;


text:
echo
echo "This script demonstrates parsing an environment variable"
echo "Uses an invented encoding:"
echo " - major parts delimited by /"
echo " - minor parts delimited by :"
echo

# parse major and minor parts with IFS scan
function parse_with_ifs() {
  local value=$1
  local old_IFS="$IFS"
  local major_parts
  local major_part
  local minor_parts
  local minor_part

  echo "parse_with_ifs: ${value}"

  IFS=/ major_parts=( $value )

  echo "Major parts count: ${#major_parts[@]}"

  for major_part in ${major_parts[@]}
  do
    echo "loop with major_part==${major_part}"
    IFS=: minor_parts=( $major_part )
    for minor_part in ${minor_parts[@]}
    do
      echo "  loop with minor_part==${minor_part}"
    done
  done
  echo

  IFS="${old_IFS}"
}

# parse major with IFS and minor parts with parameter substitution
function parse_with_ifs_and_parameter_substitution() {
  local value=$1
  local old_IFS="$IFS"
  local major_parts

  echo "parse_with_ifs_and_parameter_substitution: ${value}"

  IFS=/ major_parts=( $value )
  IFS="${old_IFS}"

  echo "Major parts count: ${#major_parts[@]}"

  for major_part in ${major_parts[@]}
  do
    echo "loop with major_part==${major_part}"
    first_part=${major_part%:*}
    second_part=${major_part#*:}
    echo "  first_part==${first_part}"
    echo "  second_part==${second_part}"

  done
  echo
}

parse_with_ifs "part1:part2"
parse_with_ifs "part1:part2/part3:part4/part5:part6"
parse_with_ifs_and_parameter_substitution "part1:part2"
parse_with_ifs_and_parameter_substitution "part1:part2/part3:part4/part5:part6"


text:
<!doctype html>

        <meta charset="utf-8">

        <title>oldweb.today</title>

        <meta name="description" content="Web Archiving + Emulation = oldweb.today">
        <meta name="author" content="Ilya Kreymer, Dragan Espenschied">

        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

        <link rel="stylesheet" href="css/reveal.css">
        <link rel="stylesheet" href="css/theme/white.css" id="theme">

        <link rel="stylesheet" href="lib/css/zenburn.css">

oldweb.today

Web Archiving + Emulation

Ilya Kreymer & Dragan Espenschied

                    14 Web Arrchives
 Part of "the Collaborative Archive of the Web"
Thank you!

Memento Aggregation

Uses ODU Memento Aggregator by Sawood Alam

Aggregates from multiple TimeGate API calls

Finds closest match from available archives

Any unaltered web archive can be included

Memento Aggregation

Requested date and actual date

Count and date range of embeds

List the archives used

Can surface additional metadata

Why oldweb.today?

Common Web Archive Replay Problems

and possible Solutions!

Web Archive 'leaks' to live web

Live leaks not possible

Improperly rewritten dynamic urls

No Rewriting needed!

Pages "don't appear the same" (no <blink>, etc..)

Use era-appropriate browsers

Flash, Java, Shockwave, other legacy content

Pre-configured environments

Architecture and Concepts

A layered Architecture

Web archives provide Web pages

Web pages running in Browsers

Browsers running in Emulators

Emulators running in Containers

Containers running in a VM

Screen of container streamed to client

Differences from other
 Emulation Frameworks

Designed specifically for web archives

The browser is the platform for web pages

The OS is secondary to the browser

Timing latency less critical for the web

Web (HTTP) emulation

Not general Internet emulation

HTTP hasn't changed much since 1.0 release

HTTP can route all traffic through a Proxy Server

A Proxy Server can be used to serve archived content

Difficult to configure manually just to view an archive...

...but easy if pre-configured in a "container"

Containers

More lightweight than VMs, use less resources

'Contain' programs, data and file systems that can be deployed rapidly

oldweb.today supports roughly 5-6 browser containers per CPU (Amazon EC2)

Docker is a popular, open-source container system

Cultural Impact

The web as performative media

oldweb.today makes the variability of the web tangible.

The web has, since the advent of client-side scripting in 1995, been a software delivery system rather than a document delivery system.

Software Curation

Absence of technically technically complex artifacts in classic web archives

As web archiving techniques improve (for instance with Webrecorder), the preservation of software environments that the web can be performed within becomes essential.

oldweb.today features "typical web browsing environments."

Curation of environments enables access.

Evolt browser archive, Browser diagram

User feedback and press

Favorite Quotes

How I surfed the web 1990s-style

Travel Log

Travel Back In Time To The Ancient Internet

Perception of Time

Browse the web like it's 1999

The Matrix

This Site Lets You Browse the Web Like a Real Human Person From the 90s

Users, not Software!

Surfing old websites using Netscape Navigator, like an Internet hipster

Activity vs Atrifact

Take a trip down the AOL and dial-up era.

Folklore

Oldweb.today lets you revisit how painfully slow and ugly the Web used to be

No Comment!!1

"Nostalgia"

Reduced speed perceived as authentic

Transparent medium becomes opaque again

Users keep requesting exotic environments.

Future Work

Audio Support

Automated Browser Suggestions

Additional and Refined Browser Environments

Webrecorder Integration

Webrecorder is our main development focus

Provides high fidelity Web Archiving for All

User-driven, personalized archiving

Hosted service and free, open-source software

Sneak preview: Record and Replay Flash with containerized browsers

Current Webrecorder

Containerized Browsers (Upcoming Release)

oldweb.today is 100% open source

https://github.com/ikreymer/netcapsule

Contributors welcome!

Ilya Kreymer

Dragan Espenschied

oldweb.today@rhizome.org

Join our Webrecorder Workshop on Friday, 9:00!

Track 2 — Hekla

                oldweb.today

                rhizome.org


text:
<Record>
<Term>Droxacin</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Quinolone Compound</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Anti-Infective Agent/Antibiotic/Quinolone Compound/Droxacin Sodium</ClassificationPath>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Anti-Infective Agent/Antibiotic/Quinolone Compound/Droxacin</ClassificationPath>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Antibiotic</BroaderTerm>
<BroaderTerm>Quinolone Compound</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Droxacin Sodium</BroaderTerm>
<BroaderTerm>Anti-Infective Agent</BroaderTerm>
<BroaderTerm>Droxacin</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>DROXACIN</Synonym>
<Synonym>Droxacin Sodium</Synonym>
<Synonym>DROXACIN SODIUM</Synonym>
<Synonym>Droxacin</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
var express = require("express"),
    app = express(),

    bodyParser = require('body-parser'),
    errorHandler = require('errorhandler'),
    methodOverride = require('method-override'),
    hostname = process.env.HOSTNAME || 'localhost',
    port = parseInt(process.env.PORT, 10) || 4567;

app.use(methodOverride());

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(express.static(__dirname + '/public'));

app.use(errorHandler({
    dumpExceptions: true,
    showStack: true
}));

app.get("/", function (req, res) {
    res.redirect("/index.html");
});

console.log("Simple server listening at http://" + hostname + ":" + port);

app.listen(port, hostname);


text:
using ::jace::VmLoader;
using ::jace::WrapperVmLoader;
using ::jace::JNIException;

BEGIN_NAMESPACE_2( jace, helper )
extern JavaVM* javaVM;
END_NAMESPACE_2( jace, helper )

#include <string>
using std::string;

#ifdef SUPPORTS_SSTREAM
  #include <sstream>
  using std::stringstream;
#else
  #include <strstream>
  using std::strstream;
#endif

// A quick hack to get a string representation for any value
// This should probably go into some framework utility class
//
#ifdef SUPPORTS_SSTREAM

  template <class T> string toString( T value ) {
    stringstream stream;
    stream << value;
    return stream.str();
  }

#else

  template <class T> string toString( T value ) {
    strstream stream;
    stream << value;
    return string( stream.str(), stream.pcount() );
  }

#endif

WrapperVmLoader::WrapperVmLoader( JNIEnv* env ) {

	jint result = env->GetJavaVM( &::jace::helper::javaVM );

  if ( result != 0 ) {
    string msg = string( "WrapperVmLoader::WrapperVmLoader\n" ) +
                  "Unable to retrieve the JVM from the JNIEnv* object. The specific JNI error code is " +
                  toString( result );
    throw JNIException( msg );
  }

	jniVersion = env->GetVersion();
}

WrapperVmLoader::WrapperVmLoader( ) {

	if ( ::jace::helper::javaVM == 0 ) {
    string msg = string( "WrapperVmLoader::WrapperVmLoader\n" ) +
                  "javaVM must be non-null";
    throw JNIException( msg );
	}

  JNIEnv* env;
  jint result = ::jace::helper::javaVM->AttachCurrentThread( reinterpret_cast<void**>( &env ), 0 );

  if ( result != 0 ) {
    string msg = "JNIHelper::attach\n" \
                 "Unable to attach the current thread. The specific JNI error code is " +
                 toString( result );
    throw JNIException( msg );
  }

	jniVersion = env->GetVersion();
}

void WrapperVmLoader::loadVm() throw ( JNIException ) {
	// The JVM has already been loaded by someone else, so we do nothing.
}

void WrapperVmLoader::unloadVm() {
	// We didn't load the JVM, so we don't get to unload it.
}

jint WrapperVmLoader::version() {
	return jniVersion;
}

jint WrapperVmLoader::createJavaVM( JavaVM **pvm, void **env, void * ) {

	if ( pvm == 0 || env == 0 )
		return JNI_EINVAL;
	*env = helper::attach();
	*pvm = ::jace::helper::javaVM;
	return JNI_OK;
}

jint WrapperVmLoader::getCreatedJavaVMs( JavaVM **vmBuf, jsize bufLen, jsize *nVMs ) {

	if ( bufLen < 1 || vmBuf == 0 )
		return JNI_EINVAL;
	*vmBuf = ::jace::helper::javaVM;
	*nVMs = 1;

  return JNI_OK;
}

VmLoader* WrapperVmLoader::clone() const {
	return new WrapperVmLoader();
}


text:
package org.killbill.billing.entitlement.dao;

import java.util.UUID;

import org.joda.time.DateTime;
import org.killbill.billing.callcontext.InternalCallContext;
import org.killbill.billing.entitlement.api.BlockingState;
import org.killbill.billing.entitlement.api.BlockingStateType;
import org.killbill.billing.junction.DefaultBlockingState;
import org.killbill.billing.util.dao.TableName;
import org.killbill.billing.util.entity.dao.EntityModelDao;
import org.killbill.billing.util.entity.dao.EntityModelDaoBase;

public class BlockingStateModelDao extends EntityModelDaoBase implements EntityModelDao<BlockingState> {

    private UUID blockableId;
    private BlockingStateType type;
    private String state;
    private String service;
    private Boolean blockChange;
    private Boolean blockEntitlement;
    private Boolean blockBilling;
    private DateTime effectiveDate;
    private boolean isActive;

    public BlockingStateModelDao() { /* For the DAO mapper */ }

    public BlockingStateModelDao(final UUID id, final UUID blockableId, final BlockingStateType blockingStateType, final String state, final String service, final Boolean blockChange, final Boolean blockEntitlement,
                                 final Boolean blockBilling, final DateTime effectiveDate, final boolean isActive, final DateTime createDate, final DateTime updateDate) {
        super(id, createDate, updateDate);
        this.blockableId = blockableId;
        this.effectiveDate = effectiveDate;
        this.type = blockingStateType;
        this.state = state;
        this.service = service;
        this.blockChange = blockChange;
        this.blockEntitlement = blockEntitlement;
        this.blockBilling = blockBilling;
        this.isActive = isActive;
    }

    public BlockingStateModelDao(final BlockingState src, final InternalCallContext context) {
        this(src, context.getCreatedDate(), context.getUpdatedDate());
    }

    public BlockingStateModelDao(final BlockingState src, final DateTime createdDate, final DateTime updatedDate) {
        this(src.getId(), src.getBlockedId(), src.getType(), src.getStateName(), src.getService(), src.isBlockChange(),
             src.isBlockEntitlement(), src.isBlockBilling(), src.getEffectiveDate(), true, createdDate, updatedDate);
    }

    public UUID getBlockableId() {
        return blockableId;
    }

    public String getState() {
        return state;
    }

    public String getService() {
        return service;
    }

    public Boolean getBlockChange() {
        return blockChange;
    }

    public Boolean getBlockEntitlement() {
        return blockEntitlement;
    }

    public Boolean getBlockBilling() {
        return blockBilling;
    }

    public BlockingStateType getType() {
        return type;
    }

    public DateTime getEffectiveDate() {
        return effectiveDate;
    }

    public void setBlockableId(final UUID blockableId) {
        this.blockableId = blockableId;
    }

    public void setType(final BlockingStateType type) {
        this.type = type;
    }

    public void setState(final String state) {
        this.state = state;
    }

    public void setService(final String service) {
        this.service = service;
    }

    public void setBlockChange(final Boolean blockChange) {
        this.blockChange = blockChange;
    }

    public void setBlockEntitlement(final Boolean blockEntitlement) {
        this.blockEntitlement = blockEntitlement;
    }

    public void setBlockBilling(final Boolean blockBilling) {
        this.blockBilling = blockBilling;
    }

    public void setEffectiveDate(final DateTime effectiveDate) {
        this.effectiveDate = effectiveDate;
    }

    public void setIsActive(final boolean isActive) {
        this.isActive = isActive;
    }

    // TODO required for jdbi binder
    public boolean getIsActive() {
        return isActive;
    }

    public boolean isActive() {
        return isActive;
    }

    public static BlockingState toBlockingState(final BlockingStateModelDao src) {
        if (src == null) {
            return null;
        }
        return new DefaultBlockingState(src.getId(), src.getBlockableId(), src.getType(), src.getState(), src.getService(), src.getBlockChange(), src.getBlockEntitlement(), src.getBlockBilling(),
                                        src.getEffectiveDate(), src.getCreatedDate(), src.getUpdatedDate(), src.getRecordId());
    }

    @Override
    public TableName getTableName() {
        return TableName.BLOCKING_STATES;
    }

    @Override
    public TableName getHistoryTableName() {
        return TableName.BLOCKING_STATES;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("BlockingStateModelDao");
        sb.append("{blockableId=").append(blockableId);
        sb.append(", state='").append(state).append('\'');
        sb.append(", service='").append(service).append('\'');
        sb.append(", blockChange=").append(blockChange);
        sb.append(", blockEntitlement=").append(blockEntitlement);
        sb.append(", blockBilling=").append(blockBilling);
        sb.append(", isActive=").append(isActive);
        sb.append('}');
        return sb.toString();
    }
}


text:
<?php

namespace YAML\Node;

use YAML\Node\AbstractNode;

class TupleNode
{
    protected $key;
    protected $value;

    public function __construct(NodeInterface $key, NodeInterface $value)
    {
        $this->key = $key;
        $this->value = $value;
    }

    public function __toString()
    {
        return sprintf('Tuple(key=%s, value=%s)', $this->key, $this->value);
    }

    public function getKey()
    {
        return $this->key;
    }

    public function getValue()
    {
        return $this->value;
    }
}


text:
author: robmyers
comments: true
date: 2007-09-15 10:24:22+00:00
layout: post
slug: links-for-2007-09-14
title: links for 2007-09-14
wordpress_id: 1489
categories:
- links
---

  *

[Groklaw - SCO Files For Chapter 11 Bankruptcy](http://www.groklaw.net/article.php?story=20070914152904577)

"The SCO Group Files Chapter 11"

(tags: [hahaha](http://del.icio.us/robmyers/hahaha) [SCO](http://del.icio.us/robmyers/SCO) [DIAF](http://del.icio.us/robmyers/DIAF))

  *

[The Joneses have left the building… « Where are the Joneses?](http://wherearethejoneses.com/2007/09/14/the-joneses-have-left-the-building/)

"Well, the search is on hold for now. At least until either a) Michael is located or b) we can recruit someone else to help (any offers gratefully received)."

(tags: [where-are-the-joneses](http://del.icio.us/robmyers/where-are-the-joneses))

  *

[Ghost of a flea: How to dance goth](http://www.ghostofaflea.com/archives/009675.html)

"The Flea's ongoing commitment to the explication of goth culture finds new heuristic promise in the form of these video illustrations."

(tags: [goth](http://del.icio.us/robmyers/goth) [gloomcow](http://del.icio.us/robmyers/gloomcow) [bat](http://del.icio.us/robmyers/bat) [dance](http://del.icio.us/robmyers/dance))

  *

[Trent Reznor to China: download our music, don't buy it from pirates - Boing Boing](http://www.boingboing.net/2007/09/13/trent-reznor-to-chin.html)

"If you can find and buy our legal CDs, I express my thanks for your support. If you cannot find it, I think that downloading from the Internet is a more acceptable option than buying pirated CDs"

(tags: [notes-towards-free-culture](http://del.icio.us/robmyers/notes-towards-free-culture))


text:
namespace gorc {
    struct uninit_constructor_tag { };
    static constexpr uninit_constructor_tag uninit_constructor = { };

    struct deserialization_constructor_tag { };
    static constexpr deserialization_constructor_tag deserialization_constructor = { };
}


text:
getJasmineRequireObj().toBeUndefined = function() {

  function toBeUndefined() {
    return {
      compare: function(actual) {
        return {
          pass: void 0 === actual
        };
      }
    };
  }

  return toBeUndefined;
};


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use app\models\b2b2c\common\Constant;

/* @var $this yii\web\View */
/* @var $model app\models\b2b2c\Quotation */
/* @var $form yii\widgets\ActiveForm */
?>

<?= Html::encode($this->title) ?>

				<button type="button" class="btn btn-box-tool"
					data-widget="collapse" data-toggle="tooltip" title="Collapse">

				</button>

	    <?php $form = ActiveForm::begin([
	    	'options' => [
						'enctype' => 'multipart/form-data',
						'class' => 'form-horizontal',
				],
				'fieldConfig' => [
						'template' => "{label}\n
{input}
\n
{error}
",
						'labelOptions' => [
								'class' => 'col-lg-2 control-label'
						]
				],
	    ]); ?>

    	<?php //echo $form->errorSummary($model);?>

	    <?= $form->field($model, 'code')->textInput(['maxlength' => true]) ?>

    <?php // eho $form->field($model, 'vip_id')->textInput(['maxlength' => true]) ?>

    <?php // echo $form->field($model, 'vip_id')->dropDownList(\yii\helpers\ArrayHelper::map($vipList, "id", "vip_name"), ['prompt' => Yii::t('app', 'select_prompt')]) ?>

    <?= $form->field($model, 'order_amt')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'deposit_amount')->textInput(['maxlength' => true]) ?>

    <?php //  echo $form->field($model, 'create_date')->textInput() ?>

    <?= $form->field($model, 'create_date')->widget(dosamigos\datetimepicker\DateTimePicker::className(), [
    		'language' => Yii::$app->language,
    		'clientOptions' => [
    				'autoclose' => true,
    				'format' => Constant::DATE_TIME_PICKER_FORMAT,
    				'todayBtn' => true,
    			]
          ]) ?>

    <?php // echo $form->field($model, 'update_date')->textInput() ?>

    <?= $form->field($model, 'update_date')->widget(dosamigos\datetimepicker\DateTimePicker::className(), [
    		'language' => Yii::$app->language,
    		'clientOptions' => [
    				'autoclose' => true,
    				'format' => Constant::DATE_TIME_PICKER_FORMAT,
    				'todayBtn' => true,
    			]
          ]) ?>

    <?= $form->field($model, 'memo')->textarea(['rows' => 6]) ?>

    <?php // echo $form->field($model, 'status')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'status')->dropDownList(\yii\helpers\ArrayHelper::map($statusList, "id", "param_val"), ['prompt' => Yii::t('app', 'select_prompt')]) ?>

    <?= $form->field($model, 'consignee')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'mobile')->textInput(['maxlength' => true]) ?>

    <?php // echo $form->field($model, 'service_date')->textInput() ?>

     <?= $form->field($model, 'service_date')->widget(\dosamigos\datepicker\DatePicker::className(), [
    		'language' => Yii::$app->language,
    		'clientOptions' => [
    				'autoclose' => true,
    				'format' => Constant::DATE_PICKER_FORMAT,
    			]
          ]) ?>

    <?= $form->field($model, 'budget_amount')->textInput(['maxlength' => true]) ?>

    <?php //echo $form->field($model, 'related_service')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'related_services')->checkboxList(\yii\helpers\ArrayHelper::map($relatedServiceList, "id", "param_val"), ['prompt' => Yii::t('app', 'select_prompt')]) ?>

    <?php // echo $form->field($model, 'service_style')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'service_style')->dropDownList(\yii\helpers\ArrayHelper::map($serviceStyleList, "id", "param_val"), ['prompt' => Yii::t('app', 'select_prompt')]) ?>

    <?php // echo $form->field($model, 'merchant_id')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'merchant_id')->dropDownList(\yii\helpers\ArrayHelper::map($merchantList, "id", "vip_name"), ['prompt' => Yii::t('app', 'select_prompt')]) ?>

	        <?php  if ($model->isNewRecord) {echo Html::submitButton(Yii::t('app', '提交'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']);}?>

	        <?php // echo if (!($model->isNewRecord)) {echo Html::a('添加订单明细',['create-quotation-detail', 'quotation_id'=>$model->id],['class' => 'btn btn-success']);}?>

    	<?php ActiveForm::end(); ?>


text:
import { connect } from "react-redux";
import PhotoBrowser from "../components/photo_browser";
import { setMediaViewerState } from "../ducks/media_viewer";
import { onFileDrop } from "../ducks/observation";
import { setFlaggingModalState } from "../ducks/flagging_modal";

function mapStateToProps( state ) {
  return {
    config: state.config,
    observation: state.observation
  };
}

function mapDispatchToProps( dispatch ) {
  return {
    onFileDrop: ( droppedFiles, rejectedFiles, e ) => {
      dispatch( onFileDrop( droppedFiles, rejectedFiles, e ) );
    },
    setMediaViewerState: ( key, value ) => {
      dispatch( setMediaViewerState( key, value ) );
    },
    setFlaggingModalState: state => dispatch( setFlaggingModalState( state ) )
  };
}

const PhotoBrowserContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)( PhotoBrowser );

export default PhotoBrowserContainer;


text:
A Xamarin.Forms app that encrypts media and documents in a SQLite db locally or in the cloud.

## Introduction

This app is the first Xamarin.Forms (XF) app that I want to bring in a state that is ready for public release.

## Roadmap

### Target Platforms
- UWP
- iOS
- Android

### Planned Features
- Add or create Images, Videos and Documents
- AES Encryption and Decryption
- SQLite database
- Storage Options: Local device or shared with OneDrive
- Custom Renderers on all platforms for usable UIs

## Progress
- I am learning MVVM now and will try to implement it here. As far as it makes sense I will also try to build upon the SOLID principles.
- Started implementing [MediaPlugin](https://github.com/jamesmontemagno/MediaPlugin) for Camera and Gallery access
- Started implementing [SQLite](https://github.com/praeclarum/sqlite-net) as data backendxamarin, following [this guide](https://developer.xamarin.com/guides/xamarin-forms/working-with/databases/)
- Implemented [Vibration](https://github.com/jamesmontemagno/VibratePlugin) so that the device vibrates when you enter a wrong passcode
- Implemented [Permissions](https://github.com/jamesmontemagno/PermissionsPlugin)
- Started testing [PCLCrypto](https://github.com/AArnott/PCLCrypto). I want to use it for the AES encryption and decryption but first I need to learn how to implement it correctly

## Screenshots (nothing here is final yet)


text:
package releasedirfakes

import (
	"sync"

	boshrel "github.com/cloudfoundry/bosh-cli/release"
	boshrelman "github.com/cloudfoundry/bosh-cli/release/manifest"
	"github.com/cloudfoundry/bosh-cli/releasedir"
	semver "github.com/cppforlife/go-semi-semantic/version"
)

type FakeReleaseIndex struct {
	LastVersionStub        func(name string) (*semver.Version, error)
	lastVersionMutex       sync.RWMutex
	lastVersionArgsForCall []struct {
		name string
	}
	lastVersionReturns struct {
		result1 *semver.Version
		result2 error
	}
	lastVersionReturnsOnCall map[int]struct {
		result1 *semver.Version
		result2 error
	}
	ContainsStub        func(boshrel.Release) (bool, error)
	containsMutex       sync.RWMutex
	containsArgsForCall []struct {
		arg1 boshrel.Release
	}
	containsReturns struct {
		result1 bool
		result2 error
	}
	containsReturnsOnCall map[int]struct {
		result1 bool
		result2 error
	}
	AddStub        func(boshrelman.Manifest) error
	addMutex       sync.RWMutex
	addArgsForCall []struct {
		arg1 boshrelman.Manifest
	}
	addReturns struct {
		result1 error
	}
	addReturnsOnCall map[int]struct {
		result1 error
	}
	ManifestPathStub        func(name, version string) string
	manifestPathMutex       sync.RWMutex
	manifestPathArgsForCall []struct {
		name    string
		version string
	}
	manifestPathReturns struct {
		result1 string
	}
	manifestPathReturnsOnCall map[int]struct {
		result1 string
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakeReleaseIndex) LastVersion(name string) (*semver.Version, error) {
	fake.lastVersionMutex.Lock()
	ret, specificReturn := fake.lastVersionReturnsOnCall[len(fake.lastVersionArgsForCall)]
	fake.lastVersionArgsForCall = append(fake.lastVersionArgsForCall, struct {
		name string
	}{name})
	fake.recordInvocation("LastVersion", []interface{}{name})
	fake.lastVersionMutex.Unlock()
	if fake.LastVersionStub != nil {
		return fake.LastVersionStub(name)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	return fake.lastVersionReturns.result1, fake.lastVersionReturns.result2
}

func (fake *FakeReleaseIndex) LastVersionCallCount() int {
	fake.lastVersionMutex.RLock()
	defer fake.lastVersionMutex.RUnlock()
	return len(fake.lastVersionArgsForCall)
}

func (fake *FakeReleaseIndex) LastVersionArgsForCall(i int) string {
	fake.lastVersionMutex.RLock()
	defer fake.lastVersionMutex.RUnlock()
	return fake.lastVersionArgsForCall[i].name
}

func (fake *FakeReleaseIndex) LastVersionReturns(result1 *semver.Version, result2 error) {
	fake.LastVersionStub = nil
	fake.lastVersionReturns = struct {
		result1 *semver.Version
		result2 error
	}{result1, result2}
}

func (fake *FakeReleaseIndex) LastVersionReturnsOnCall(i int, result1 *semver.Version, result2 error) {
	fake.LastVersionStub = nil
	if fake.lastVersionReturnsOnCall == nil {
		fake.lastVersionReturnsOnCall = make(map[int]struct {
			result1 *semver.Version
			result2 error
		})
	}
	fake.lastVersionReturnsOnCall[i] = struct {
		result1 *semver.Version
		result2 error
	}{result1, result2}
}

func (fake *FakeReleaseIndex) Contains(arg1 boshrel.Release) (bool, error) {
	fake.containsMutex.Lock()
	ret, specificReturn := fake.containsReturnsOnCall[len(fake.containsArgsForCall)]
	fake.containsArgsForCall = append(fake.containsArgsForCall, struct {
		arg1 boshrel.Release
	}{arg1})
	fake.recordInvocation("Contains", []interface{}{arg1})
	fake.containsMutex.Unlock()
	if fake.ContainsStub != nil {
		return fake.ContainsStub(arg1)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	return fake.containsReturns.result1, fake.containsReturns.result2
}

func (fake *FakeReleaseIndex) ContainsCallCount() int {
	fake.containsMutex.RLock()
	defer fake.containsMutex.RUnlock()
	return len(fake.containsArgsForCall)
}

func (fake *FakeReleaseIndex) ContainsArgsForCall(i int) boshrel.Release {
	fake.containsMutex.RLock()
	defer fake.containsMutex.RUnlock()
	return fake.containsArgsForCall[i].arg1
}

func (fake *FakeReleaseIndex) ContainsReturns(result1 bool, result2 error) {
	fake.ContainsStub = nil
	fake.containsReturns = struct {
		result1 bool
		result2 error
	}{result1, result2}
}

func (fake *FakeReleaseIndex) ContainsReturnsOnCall(i int, result1 bool, result2 error) {
	fake.ContainsStub = nil
	if fake.containsReturnsOnCall == nil {
		fake.containsReturnsOnCall = make(map[int]struct {
			result1 bool
			result2 error
		})
	}
	fake.containsReturnsOnCall[i] = struct {
		result1 bool
		result2 error
	}{result1, result2}
}

func (fake *FakeReleaseIndex) Add(arg1 boshrelman.Manifest) error {
	fake.addMutex.Lock()
	ret, specificReturn := fake.addReturnsOnCall[len(fake.addArgsForCall)]
	fake.addArgsForCall = append(fake.addArgsForCall, struct {
		arg1 boshrelman.Manifest
	}{arg1})
	fake.recordInvocation("Add", []interface{}{arg1})
	fake.addMutex.Unlock()
	if fake.AddStub != nil {
		return fake.AddStub(arg1)
	}
	if specificReturn {
		return ret.result1
	}
	return fake.addReturns.result1
}

func (fake *FakeReleaseIndex) AddCallCount() int {
	fake.addMutex.RLock()
	defer fake.addMutex.RUnlock()
	return len(fake.addArgsForCall)
}

func (fake *FakeReleaseIndex) AddArgsForCall(i int) boshrelman.Manifest {
	fake.addMutex.RLock()
	defer fake.addMutex.RUnlock()
	return fake.addArgsForCall[i].arg1
}

func (fake *FakeReleaseIndex) AddReturns(result1 error) {
	fake.AddStub = nil
	fake.addReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeReleaseIndex) AddReturnsOnCall(i int, result1 error) {
	fake.AddStub = nil
	if fake.addReturnsOnCall == nil {
		fake.addReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.addReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeReleaseIndex) ManifestPath(name string, version string) string {
	fake.manifestPathMutex.Lock()
	ret, specificReturn := fake.manifestPathReturnsOnCall[len(fake.manifestPathArgsForCall)]
	fake.manifestPathArgsForCall = append(fake.manifestPathArgsForCall, struct {
		name    string
		version string
	}{name, version})
	fake.recordInvocation("ManifestPath", []interface{}{name, version})
	fake.manifestPathMutex.Unlock()
	if fake.ManifestPathStub != nil {
		return fake.ManifestPathStub(name, version)
	}
	if specificReturn {
		return ret.result1
	}
	return fake.manifestPathReturns.result1
}

func (fake *FakeReleaseIndex) ManifestPathCallCount() int {
	fake.manifestPathMutex.RLock()
	defer fake.manifestPathMutex.RUnlock()
	return len(fake.manifestPathArgsForCall)
}

func (fake *FakeReleaseIndex) ManifestPathArgsForCall(i int) (string, string) {
	fake.manifestPathMutex.RLock()
	defer fake.manifestPathMutex.RUnlock()
	return fake.manifestPathArgsForCall[i].name, fake.manifestPathArgsForCall[i].version
}

func (fake *FakeReleaseIndex) ManifestPathReturns(result1 string) {
	fake.ManifestPathStub = nil
	fake.manifestPathReturns = struct {
		result1 string
	}{result1}
}

func (fake *FakeReleaseIndex) ManifestPathReturnsOnCall(i int, result1 string) {
	fake.ManifestPathStub = nil
	if fake.manifestPathReturnsOnCall == nil {
		fake.manifestPathReturnsOnCall = make(map[int]struct {
			result1 string
		})
	}
	fake.manifestPathReturnsOnCall[i] = struct {
		result1 string
	}{result1}
}

func (fake *FakeReleaseIndex) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.lastVersionMutex.RLock()
	defer fake.lastVersionMutex.RUnlock()
	fake.containsMutex.RLock()
	defer fake.containsMutex.RUnlock()
	fake.addMutex.RLock()
	defer fake.addMutex.RUnlock()
	fake.manifestPathMutex.RLock()
	defer fake.manifestPathMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

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

var _ releasedir.ReleaseIndex = new(FakeReleaseIndex)


text:
package org.optaplanner.webexamples.cloudbalancing;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.http.HttpSession;

import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.api.solver.SolverFactory;
import org.optaplanner.core.api.solver.event.BestSolutionChangedEvent;
import org.optaplanner.core.api.solver.event.SolverEventListener;
import org.optaplanner.examples.cloudbalancing.domain.CloudBalance;
import org.optaplanner.examples.cloudbalancing.persistence.CloudBalancingGenerator;

public class CloudBalancingWebAction {

    private static ExecutorService solvingExecutor = Executors.newFixedThreadPool(4);

    public void setup(HttpSession session) {
        terminateEarly(session);

        SolverFactory<CloudBalance> solverFactory = SolverFactory.createFromXmlResource(
                "org/optaplanner/examples/cloudbalancing/solver/cloudBalancingSolverConfig.xml");
        Solver<CloudBalance> solver = solverFactory.buildSolver();
        session.setAttribute(CloudBalancingSessionAttributeName.SOLVER, solver);

        // Load a problem with 40 computers and 120 processes
        CloudBalance unsolvedSolution = new CloudBalancingGenerator(true).createCloudBalance(100, 300);
        session.setAttribute(CloudBalancingSessionAttributeName.SHOWN_SOLUTION, unsolvedSolution);
    }

    public void solve(final HttpSession session) {
        final Solver<CloudBalance> solver = (Solver<CloudBalance>) session.getAttribute(CloudBalancingSessionAttributeName.SOLVER);
        final CloudBalance unsolvedSolution = (CloudBalance) session.getAttribute(CloudBalancingSessionAttributeName.SHOWN_SOLUTION);

        solver.addEventListener(new SolverEventListener<CloudBalance>() {
            @Override
            public void bestSolutionChanged(BestSolutionChangedEvent<CloudBalance> event) {
                CloudBalance bestSolution = event.getNewBestSolution();
                session.setAttribute(CloudBalancingSessionAttributeName.SHOWN_SOLUTION, bestSolution);
            }
        });
        solvingExecutor.submit(new Runnable() {
            @Override
            public void run() {
                solver.solve(unsolvedSolution);
            }
        });
    }

    public void terminateEarly(HttpSession session) {
        final Solver<CloudBalance> solver = (Solver<CloudBalance>) session.getAttribute(CloudBalancingSessionAttributeName.SOLVER);
        if (solver != null) {
            solver.terminateEarly();
            session.setAttribute(CloudBalancingSessionAttributeName.SOLVER, null);
        }
    }

}


text:
from nltk.tokenize import MWETokenizer
from nltk.corpus import stopwords
from nltk.tokenize import WhitespaceTokenizer
from unidecode import unidecode
from nltk.stem import WordNetLemmatizer
import string
import os
import nltk
whitespace_tokenizer = WhitespaceTokenizer()
wnl = WordNetLemmatizer()

from spacy.en import English
nlp = English()

# This is for multi-word-phrases.
MWE = []
path = "/".join(os.path.realpath(__file__).split("/")[:-2]) + '/input/'
print 'path', path
with open(path+'STREUSLE2.1-mwes.tsv') as f:
    for line in f.readlines():
        multiword_expression = line.split('\t')[0].split()[1:]
        MWE.append(multiword_expression)
MWE_tokenizer = MWETokenizer(MWE, separator='-')
# Add whatever additional custom multi-word-expressions.
MWE_tokenizer.add_mwe((  'dive', 'bar'))
# Stopwords
stops = set(stopwords.words("english") + stopwords.words("spanish"))
keep_list = ['after', 'during', 'not', 'between', 'other', 'over', 'under',
             'most', ' without', 'nor', 'no', 'very', 'against','don','aren']
stops = set([word for word in stops if word not in keep_list])

table = string.maketrans("","")

sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
whitespace_tokenizer = WhitespaceTokenizer()

def get_noun_chunks(words):
    '''
    Get noun chunks from spacy's library.

    words : A list of sentences where each sentence is a list of tokens.
    '''
    doc = nlp(u". ".join(words)) # Join the sentences. back into natural text and process with spacy.
    # Pull out chunks and add them.
    chunks = [u"-".join(chunk.orth_.split()) for chunk in doc.noun_chunks if len(chunk.orth_.split())>1]
    return chunks

def clean_text(text):
    """Clean and lower string.  Cleaning removes all punctuation
    Parameters
    ----------
        text : in string format
    Returns
    -------
        text_clean : clean text input in string format
    """

    return text.lower().translate(table, string.punctuation.replace('-',''))

def clean_nltk(string):
    '''
    Handles the NLP cleaning, stemming, and multiword expression work for a given search phrase.
    This is required to convert input into the model vocab space.

    The process includes:
        -lowercasing
        -tokenize
        -removal of punctuation
        -multi-word-expression merging
        -stop-word-removal
        -Stemming (actually lematization)

    Parameters
    -------------
    string : string to tokenize.

    Returns
    --------------
    tokenized: Tokenized cleaned sentence
    '''
    text_cleaned = clean_text(string)

    noun_chunks = map(lambda x: get_noun_chunks(x), [[text_cleaned,],])
    noun_chunks = [x for x in noun_chunks if x != []][0]

    # Multiword expression tokenizer
    text_tokenize = whitespace_tokenizer.tokenize(text_cleaned)
    #text_tokenize = MWE_tokenizer.tokenize(text_tokenize)

    # remove stop words
    text_filtered = [word for word in text_tokenize if word not in stops]
    # Stem words

    # text_stemmed = map(lambda x: [stemmer.stem(word) for word in x], text_filtered)
    # unstem with the simplest word.  This helps readability of results...
    text_stemmed = [wnl.lemmatize(word) for word in text_filtered]

    text_stemmed = text_stemmed + noun_chunks
    return text_stemmed

#  Adapted, but much improved from  ----   https://github.com/titipata/yelp_dataset_challenge

def clean_text(text):
    """Clean and lower string
    Parameters
    ----------
        text : in string format
    Returns
    -------
        text_clean : clean text input in string format
    """
    return text.lower().translate(table, string.punctuation.replace('-',''))

def clean_and_tokenize(text):
    """
    1. Divide review into sentences
    2. clean words
    3. tokenize
    4. multiword tokenize
    5. remove stop words
    6. stem words
    Returns
    ------
        text_filtered: list of word in sentence
    """
    # Splits into sentences.
    sentence = sent_detector.tokenize(unidecode(text))
    # Clean text: (remove) Remove extra puncuations marks...
    text_clean = map(clean_text, sentence)

    noun_chunks = map(lambda x: get_noun_chunks(x), [text_clean,])
    noun_chunks = [x for x in noun_chunks if x != []]

    # Multiword expression tokenizer
    text_tokenize = map(lambda x: whitespace_tokenizer.tokenize(x), text_clean)
    #text_tokenize = map(lambda x: MWE_tokenizer.tokenize(x), text_tokenize)

    # remove stop words
    text_filtered = map(lambda x: [word for word in x if word not in stops], text_tokenize)
    # lemmetize words (stemming removes too much...)
#     text_stemmed = map(lambda x: [wnl.lemmatize(word)
#                                   if wnl.lemmatize(word).endswith('e')
#                                   else stemmer.stem(word)
#                                   for word in x], text_filtered)
    text_stemmed = map(lambda x: [wnl.lemmatize(word) for word in x], text_filtered)
    #text_stemmed = map(lambda x: [stemmer.stem(word) for word in x], text_filtered)

    text_stemmed = text_stemmed + noun_chunks

    return text_stemmed

if __name__ == "__main__":
    clean_nltk(['bars around here',])


text:
module IncludeReservedItemsInStockLocationAttributes
  def stock_location_attributes
    super | [:reserved_items]
  end
end
Spree::Api::ApiHelpers.prepend IncludeReservedItemsInStockLocationAttributes


text: * add documentation


text:
class Spinach::Features::DashboardHelp < Spinach::FeatureSteps
  include SharedAuthentication
  include SharedPaths
  include SharedMarkdown

  step 'I visit the help page' do
    visit help_path
  end

  step 'I visit the "Rake Tasks" help page' do
    visit help_page_path("raketasks", "maintenance")
  end

  step 'I should see "Rake Tasks" page markdown rendered' do
    expect(page).to have_content "Gather information about GitLab and the system it runs on"
  end

  step 'Header "Rebuild project satellites" should have correct ids and links' do
    header_should_have_correct_id_and_link(2, 'Check GitLab configuration', 'check-gitlab-configuration', '.documentation')
  end
end


text:
from __future__ import division

import warnings
import numpy as np
import scipy.sparse as sp

from .base import BaseEstimator, ClassifierMixin, RegressorMixin
from .externals.six.moves import xrange
from .utils import check_random_state
from .utils.validation import check_array
from sklearn.utils import deprecated
from sklearn.utils.random import random_choice_csc
from sklearn.utils.multiclass import class_distribution

class DummyClassifier(BaseEstimator, ClassifierMixin):
    """
    DummyClassifier is a classifier that makes predictions using simple rules.

    This classifier is useful as a simple baseline to compare with other
    (real) classifiers. Do not use it for real problems.

    Parameters
    ----------
    strategy : str
        Strategy to use to generate predictions.

        * "stratified": generates predictions by respecting the training
          set's class distribution.
        * "most_frequent": always predicts the most frequent label in the
          training set.
        * "uniform": generates predictions uniformly at random.
        * "constant": always predicts a constant label that is provided by
          the user. This is useful for metrics that evaluate a non-majority
          class

    random_state : int seed, RandomState instance, or None (default)
        The seed of the pseudo random number generator to use.

    constant : int or str or array of shape = [n_outputs]
        The explicit constant as predicted by the "constant" strategy. This
        parameter is useful only for the "constant" strategy.

    Attributes
    ----------
    classes_ : array or list of array of shape = [n_classes]
        Class labels for each output.

    n_classes_ : array or list of array of shape = [n_classes]
        Number of label for each output.

    class_prior_ : array or list of array of shape = [n_classes]
        Probability of each class for each output.

    n_outputs_ : int,
        Number of outputs.

    outputs_2d_ : bool,
        True if the output at fit is 2d, else false.

    `sparse_output_` : bool,
        True if the array returned from predict is to be in sparse CSC format.
        Is automatically set to True if the input y is passed in sparse format.

    """

    def __init__(self, strategy="stratified", random_state=None,
                 constant=None):
        self.strategy = strategy
        self.random_state = random_state
        self.constant = constant

    def fit(self, X, y, sample_weight=None):
        """Fit the random classifier.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.

        y : array-like, shape = [n_samples] or [n_samples, n_outputs]
            Target values.

        sample_weight : array-like of shape = [n_samples], optional
            Sample weights.

        Returns
        -------
        self : object
            Returns self.
        """
        if self.strategy not in ("most_frequent", "stratified", "uniform",
                                 "constant"):
            raise ValueError("Unknown strategy type.")

        if self.strategy == "uniform" and sp.issparse(y):
            y = y.toarray()
            warnings.warn('A local copy of the target data has been converted '
                          'to a numpy array. Predicting on sparse target data '
                          'with the uniform strategy would not save memory '
                          'and would be slower.',
                          UserWarning)

        self.sparse_output_ = sp.issparse(y)

        if not self.sparse_output_:
            y = np.atleast_1d(y)

        self.output_2d_ = y.ndim == 2
        if y.ndim == 1:
            y = np.reshape(y, (-1, 1))

        self.n_outputs_ = y.shape[1]

        if self.strategy == "constant":
            if self.constant is None:
                raise ValueError("Constant target value has to be specified "
                                 "when the constant strategy is used.")
            else:
                constant = np.reshape(np.atleast_1d(self.constant), (-1, 1))
                if constant.shape[0] != self.n_outputs_:
                    raise ValueError("Constant target value should have "
                                     "shape (%d, 1)." % self.n_outputs_)

        (self.classes_,
         self.n_classes_,
         self.class_prior_) = class_distribution(y, sample_weight)

        if self.strategy == "constant":
            for k in range(self.n_outputs_):
                # Checking in case of constant strategy if the constant
                # provided by the user is in y.
                if constant[k] not in self.classes_[k]:
                    raise ValueError("The constant target value must be "
                                     "present in training data")

        if self.n_outputs_ == 1 and not self.output_2d_:
            self.n_classes_ = self.n_classes_[0]
            self.classes_ = self.classes_[0]
            self.class_prior_ = self.class_prior_[0]

        return self

    def predict(self, X):
        """
        Perform classification on test vectors X.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            Input vectors, where n_samples is the number of samples
            and n_features is the number of features.

        Returns
        -------
        y : array, shape = [n_samples] or [n_samples, n_outputs]
            Predicted target values for X.
        """
        if not hasattr(self, "classes_"):
            raise ValueError("DummyClassifier not fitted.")

        X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
        # numpy random_state expects Python int and not long as size argument
        # under Windows
        n_samples = int(X.shape[0])
        rs = check_random_state(self.random_state)

        n_classes_ = self.n_classes_
        classes_ = self.classes_
        class_prior_ = self.class_prior_
        constant = self.constant
        if self.n_outputs_ == 1:
            # Get same type even for self.n_outputs_ == 1
            n_classes_ = [n_classes_]
            classes_ = [classes_]
            class_prior_ = [class_prior_]
            constant = [constant]
        # Compute probability only once
        if self.strategy == "stratified":
            proba = self.predict_proba(X)
            if self.n_outputs_ == 1:
                proba = [proba]

        if self.sparse_output_:
            class_prob = None
            if self.strategy == "most_frequent":
                classes_ = [np.array([cp.argmax()]) for cp in class_prior_]

            elif self.strategy == "stratified":
                class_prob = class_prior_

            elif self.strategy == "uniform":
                    raise ValueError("Sparse target prediction is not "
                                     "supported with the uniform strategy")

            elif self.strategy == "constant":
                classes_ = [np.array([c]) for c in constant]

            y = random_choice_csc(n_samples, classes_, class_prob,
                                  self.random_state)
        else:
            if self.strategy == "most_frequent":
                y = np.tile([classes_[k][class_prior_[k].argmax()] for
                             k in range(self.n_outputs_)], [n_samples, 1])

            elif self.strategy == "stratified":
                y = np.vstack(classes_[k][proba[k].argmax(axis=1)] for
                              k in range(self.n_outputs_)).T

            elif self.strategy == "uniform":
                ret = [classes_[k][rs.randint(n_classes_[k], size=n_samples)]
                       for k in range(self.n_outputs_)]
                y = np.vstack(ret).T

            elif self.strategy == "constant":
                y = np.tile(self.constant, (n_samples, 1))

            if self.n_outputs_ == 1 and not self.output_2d_:
                y = np.ravel(y)

        return y

    def predict_proba(self, X):
        """
        Return probability estimates for the test vectors X.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            Input vectors, where n_samples is the number of samples
            and n_features is the number of features.

        Returns
        -------
        P : array-like or list of array-lke of shape = [n_samples, n_classes]
            Returns the probability of the sample for each class in
            the model, where classes are ordered arithmetically, for each
            output.
        """
        if not hasattr(self, "classes_"):
            raise ValueError("DummyClassifier not fitted.")

        X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
        # numpy random_state expects Python int and not long as size argument
        # under Windows
        n_samples = int(X.shape[0])
        rs = check_random_state(self.random_state)

        n_classes_ = self.n_classes_
        classes_ = self.classes_
        class_prior_ = self.class_prior_
        constant = self.constant
        if self.n_outputs_ == 1 and not self.output_2d_:
            # Get same type even for self.n_outputs_ == 1
            n_classes_ = [n_classes_]
            classes_ = [classes_]
            class_prior_ = [class_prior_]
            constant = [constant]

        P = []
        for k in xrange(self.n_outputs_):
            if self.strategy == "most_frequent":
                ind = np.ones(n_samples, dtype=int) * class_prior_[k].argmax()
                out = np.zeros((n_samples, n_classes_[k]), dtype=np.float64)
                out[:, ind] = 1.0

            elif self.strategy == "stratified":
                out = rs.multinomial(1, class_prior_[k], size=n_samples)

            elif self.strategy == "uniform":
                out = np.ones((n_samples, n_classes_[k]), dtype=np.float64)
                out /= n_classes_[k]

            elif self.strategy == "constant":
                ind = np.where(classes_[k] == constant[k])
                out = np.zeros((n_samples, n_classes_[k]), dtype=np.float64)
                out[:, ind] = 1.0

            P.append(out)

        if self.n_outputs_ == 1 and not self.output_2d_:
            P = P[0]

        return P

    def predict_log_proba(self, X):
        """
        Return log probability estimates for the test vectors X.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            Input vectors, where n_samples is the number of samples
            and n_features is the number of features.

        Returns
        -------
        P : array-like or list of array-like of shape = [n_samples, n_classes]
            Returns the log probability of the sample for each class in
            the model, where classes are ordered arithmetically for each
            output.
        """
        proba = self.predict_proba(X)
        if self.n_outputs_ == 1:
            return np.log(proba)
        else:
            return [np.log(p) for p in proba]

class DummyRegressor(BaseEstimator, RegressorMixin):
    """
    DummyRegressor is a regressor that makes predictions using
    simple rules.

    This regressor is useful as a simple baseline to compare with other
    (real) regressors. Do not use it for real problems.

    Parameters
    ----------
    strategy : str
        Strategy to use to generate predictions.

        * "mean": always predicts the mean of the training set
        * "median": always predicts the median of the training set
        * "constant": always predicts a constant value that is provided by
          the user.

    constant : int or float or array of shape = [n_outputs]
        The explicit constant as predicted by the "constant" strategy. This
        parameter is useful only for the "constant" strategy.

    Attributes
    ----------
    constant_ : float or array of shape [n_outputs]
        Mean or median of the training targets or constant value given the by
        the user.

    n_outputs_ : int,
        Number of outputs.

    outputs_2d_ : bool,
        True if the output at fit is 2d, else false.
    """

    def __init__(self, strategy="mean", constant=None):
        self.strategy = strategy
        self.constant = constant

    @property
    @deprecated('This will be removed in version 0.17')
    def y_mean_(self):
        if self.strategy == 'mean':
            return self.constant_
        raise AttributeError

    def fit(self, X, y):
        """Fit the random regressor.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.

        y : array-like, shape = [n_samples] or [n_samples, n_outputs]
            Target values.

        Returns
        -------
        self : object
            Returns self.
        """

        if self.strategy not in ("mean", "median", "constant"):
            raise ValueError("Unknown strategy type: %s, "
                             "expected 'mean', 'median' or 'constant'"
                             % self.strategy)

        y = check_array(y, accept_sparse='csr', ensure_2d=False)
        self.output_2d_ = (y.ndim == 2)

        if self.strategy == "mean":
            self.constant_ = np.reshape(np.mean(y, axis=0), (1, -1))

        elif self.strategy == "median":
            self.constant_ = np.reshape(np.median(y, axis=0), (1, -1))

        elif self.strategy == "constant":
            if self.constant is None:
                raise TypeError("Constant target value has to be specified "
                                "when the constant strategy is used.")

            self.constant = check_array(self.constant,
                                        accept_sparse=['csr', 'csc', 'coo'],
                                        ensure_2d=False)

            if self.output_2d_ and self.constant.shape[0] != y.shape[1]:
                raise ValueError(
                    "Constant target value should have "
                    "shape (%d, 1)." % y.shape[1])

            self.constant_ = np.reshape(self.constant, (1, -1))

        self.n_outputs_ = np.size(self.constant_)  # y.shape[1] is not safe
        return self

    def predict(self, X):
        """
        Perform classification on test vectors X.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            Input vectors, where n_samples is the number of samples
            and n_features is the number of features.

        Returns
        -------
        y : array, shape = [n_samples]  or [n_samples, n_outputs]
            Predicted target values for X.
        """
        if not hasattr(self, "constant_"):
            raise ValueError("DummyRegressor not fitted.")

        X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
        n_samples = X.shape[0]

        y = np.ones((n_samples, 1)) * self.constant_

        if self.n_outputs_ == 1 and not self.output_2d_:
            y = np.ravel(y)

        return y


text:
.. _experimental:

Experimental features
=====================

This section documents experimental Scrapy features that may become stable in
future releases, but whose API is not yet stable. Use them with caution, and
subscribe to the `mailing lists <http://scrapy.org/community/>`_ to get
notified of any changes.

Since it's not revised so frequently, this section may contain documentation
which is outdated, incomplete or overlapping with stable documentation (until
it's properly merged) . Use at your own risk.

.. warning::

   This documentation is a work in progress. Use at your own risk.

*No experimental features at this time*


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

<title>ComponentFilterTable (ARX GUI Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.deidentifier.arx.gui.view.impl.common

Class ComponentFilterTable

java.lang.Object

org.deidentifier.arx.gui.view.impl.common.ComponentFilterTable

public class ComponentFilterTable
extends java.lang.Object

This class implements a table, in which properties can be filtered.

Constructor Summary

Constructors

Constructor and Description

ComponentFilterTable(org.eclipse.swt.widgets.Composite parent,
                    Controller controller,
                    java.util.List<java.lang.String> properties)

Creates a new instance.

Method Summary

Methods

Modifier and Type
Method and Description

void
addEntry(java.lang.String entry,
        java.util.List<java.lang.String> properties)

Adds a new entry, i.e., a row in the table

void
addSelectionListener(org.eclipse.swt.events.SelectionListener listener)

Adds a selection listener.

void
clear()

Clears the table.

void
dispose()

Disposes this widget.

java.util.List<java.lang.String>
getEntries()

Returns the entries.

java.util.List<java.lang.String>
getProperties()

Returns the properties.

java.lang.String
getSelectedEntry()

Returns the currently selected entry.

java.lang.String
getSelectedProperty()

Returns the currently selected property.

boolean
isSelected(java.lang.String entry,
          java.lang.String property)

Returns whether the given property is selected for the given entry.

void
removeSelectionListener(org.eclipse.swt.events.SelectionListener listener)

Removes a selection listener.

void
setEnabled(boolean enabled)

Enable/disable.

void
setLayoutData(java.lang.Object layoutData)

Sets layout data.

void
setProperties(java.util.List<java.lang.String> properties)

Sets new properties.

void
setSelected(java.lang.String entry,
           java.lang.String property,
           boolean selected)

Sets the given property selected for the given entry .

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ComponentFilterTable

public ComponentFilterTable(org.eclipse.swt.widgets.Composite parent,
                    Controller controller,
                    java.util.List<java.lang.String> properties)

Creates a new instance.

Parameters:

parent -

controller -

properties -

Method Detail

addEntry

public void addEntry(java.lang.String entry,
            java.util.List<java.lang.String> properties)

Adds a new entry, i.e., a row in the table

Parameters:

entry -

properties -

addSelectionListener

public void addSelectionListener(org.eclipse.swt.events.SelectionListener listener)

Adds a selection listener.

Parameters:

listener -

clear

public void clear()

Clears the table.

dispose

public void dispose()

Disposes this widget.

getEntries

public java.util.List<java.lang.String> getEntries()

Returns the entries.

Returns:

getProperties

public java.util.List<java.lang.String> getProperties()

Returns the properties.

Returns:

getSelectedEntry

public java.lang.String getSelectedEntry()

Returns the currently selected entry.

Returns:

getSelectedProperty

public java.lang.String getSelectedProperty()

Returns the currently selected property.

Returns:

isSelected

public boolean isSelected(java.lang.String entry,
                 java.lang.String property)

Returns whether the given property is selected for the given entry.

Parameters:

entry -

property -

Returns:

removeSelectionListener

public void removeSelectionListener(org.eclipse.swt.events.SelectionListener listener)

Removes a selection listener.

Parameters:

listener -

setEnabled

public void setEnabled(boolean enabled)

Enable/disable.

Parameters:

enabled -

setLayoutData

public void setLayoutData(java.lang.Object layoutData)

Sets layout data.

Parameters:

layoutData -

setProperties

public void setProperties(java.util.List<java.lang.String> properties)

Sets new properties. Clears the table

Parameters:

properties -

setSelected

public void setSelected(java.lang.String entry,
               java.lang.String property,
               boolean selected)

Sets the given property selected for the given entry .

Parameters:

entry -

property -

selected -

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using System.Runtime.Serialization;
using NakedFramework.Facade.Translation;
using NakedFramework.Rest.Snapshot.Constants;
using NakedFramework.Rest.Snapshot.RelTypes;
using NakedFramework.Rest.Snapshot.Utility;

namespace NakedFramework.Rest.Snapshot.Representation;

[DataContract]
public class RefValueRepresentation : Representation {
    protected RefValueRepresentation(IOidStrategy oidStrategy, RelType relType, RestControlFlags flags) : base(oidStrategy, flags) => Href = relType.GetUri().AbsoluteUri;

    [DataMember(Name = JsonPropertyNames.Href)]
    public string Href { get; set; }

    public static RefValueRepresentation Create(IOidStrategy oidStrategy, RelType relType, RestControlFlags flags) => new(oidStrategy, relType, flags);
}


text:
/* Style additions courtesy of HTML5Boilerplate Responsive */
audio,
canvas,
iframe,
img,
svg,
video {
    vertical-align: middle;
}

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

textarea {
    resize: vertical;
}

body {
	background-color: #0B89E6;
	color: white;
}

.wrapper {
    width: 80%;
    margin: 4% 10%;
    background-color: white;
    color: #0B89E6;
    height: 86%;
}


text:
/**
 * @author Geert Fokke [geert@sector22.com]
 * @www sector22.com
 * @module sector22/utils
 */

/**
 * A pool to recycle items in.
 * @param createItemCallback {function} - Function to call to create a new item
 * @param resetItemCallback {function} - Function to call to reset an items value when it is recycled.
 * @param opt_limit {number=100} - Sets a limit for the number of items that can be created, set to -1 for no limit
 * @constructor
 */
function Pool(createItemCallback, resetItemCallback, opt_limit) {

    var _this = this;
    var _createItemCallback = createItemCallback;
    var _resetItemCallback = resetItemCallback;
    var _reserve = [];
    var _reserveLength = 0; // Cache length for speed.
    var _inUse = [];
    var _inUseLength = 0; // Cache length for speed.
    var _limit = (typeof opt_limit === 'number' && opt_limit > 0) ? opt_limit : 100;
    var _initialized = false;

    /**
     * @function init
     * @param opt_initSize {number=} - Number of initial items that will be created for the pool
     */
    _this.init = function (opt_initSize) {
        if (opt_initSize) {
            // Fill the pool with an initial number of items
            for (var i = 0; i < opt_initSize; i++) {
                _reserve.push(_createItemCallback());
                _reserveLength += 1;
            }
        }
        _initialized = true;
    }

    /**
     *  If an item is available or the limit has not been reached:
     *  it will retrieve the item not in use or create a new item, and put it onto the inUse collection
     * @function useItem
     * @param item {object} - Item that is used, can be null!
     */
    _this.useItem = function () {
        if (_reserveLength > 0) {
            var item = _reserve.pop();
            _reserveLength -= 1;
        }
        else if (!_limit || _inUseLength < _limit) {
            item = _createItemCallback();
        } else {
            return;
        }

        _inUse.push(item);
        _inUseLength += 1;

        return item;
    }

    /**
     * Removes an items that is being used and recycles it into the reserve.
     * @function recycleItem
     * @param item {object} - item to recycle, must be in the inUse collection!
     */
    _this.recycleItem = function (item) {

        var index = _inUse.indexOf(item);
        if (index < 0) {
            throw new Error('Out of bounds! Item is not in use! item: ' + item);
            return;
        }

        _inUse.splice(index, 1);
        _inUseLength -= 1;

        _resetItemCallback(item);

        _reserve.push(item);
        _reserveLength += 1;
    }

    /**
     * Useful for setting special properties on the initial pool items.
     * @returns {boolean} - whether the pool is initialized (filled the pool with the number of init items)
     * @readonly
     */
    Object.defineProperty(this, 'initialized', {
        get: function () {
            return _initialized;
        }
    });

    /**
     * @returns {number} - number of items in use
     * @readonly
     */
    Object.defineProperty(this, 'inUseLength', {
        get: function () {
            return _inUseLength;
        }
    });

    /**
     * @returns {number} - number of items in the reserve
     * @readonly
     */
    Object.defineProperty(this, 'reserveLength', {
        get: function () {
            return _reserveLength;
        }
    });

    /**
     * @returns {array} - Collection of items that are in use.
     * @readonly
     */
    Object.defineProperty(this, 'inUse', {
        enumerable: true,
        configurable: false,
        writable: false,
        value: _inUse
    })

    /**
     * @returns {boolean} - whether an item is available or limit has not been reached yet.
     * @readonly
     */
    Object.defineProperty(this, 'itemAvailable', {
        get: function () {
            return _reserveLength > 0 || !_limit || _inUseLength < _limit;
        }
    });

}

module.exports = Pool;


text:
class CreateInvoices < ActiveRecord::Migration[5.2]
  def change
    create_table :invoices do |t|
      t.integer :invoiceable_id
      t.string :invoiceable_type
      t.string :slug
      t.integer :amount
      t.string :status
      t.belongs_to :user, foreign_key: true
      t.text :description
      t.string :stripe_customer_id
      t.string :card_token
      t.datetime :paid_at
      t.string :paid_method
      t.timestamps
    end
    add_index :invoices, :slug, unique: true
  end
end