text:
package org.elasticsearch.search.aggregations.metrics.cardinality;

import com.carrotsearch.hppc.BitMixer;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.RandomAccessOrds;
import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.RamUsageEstimator;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.lease.Releasable;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.LongArray;
import org.elasticsearch.common.util.ObjectArray;
import org.elasticsearch.index.fielddata.SortedBinaryDocValues;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.LeafBucketCollector;
import org.elasticsearch.search.aggregations.metrics.NumericMetricsAggregator;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.aggregations.support.ValuesSource;

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

/**
 * An aggregator that computes approximate counts of unique values.
 */
public class CardinalityAggregator extends NumericMetricsAggregator.SingleValue {

    private final int precision;
    private final ValuesSource valuesSource;

    // Expensive to initialize, so we only initialize it when we have an actual value source
    @Nullable
    private HyperLogLogPlusPlus counts;

    private Collector collector;

    public CardinalityAggregator(String name, ValuesSource valuesSource, int precision,
            AggregationContext context, Aggregator parent, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) throws IOException {
        super(name, context, parent, pipelineAggregators, metaData);
        this.valuesSource = valuesSource;
        this.precision = precision;
        this.counts = valuesSource == null ? null : new HyperLogLogPlusPlus(precision, context.bigArrays(), 1);
    }

    @Override
    public boolean needsScores() {
        return valuesSource != null && valuesSource.needsScores();
    }

    private Collector pickCollector(LeafReaderContext ctx) throws IOException {
        if (valuesSource == null) {
            return new EmptyCollector();
        }

        if (valuesSource instanceof ValuesSource.Numeric) {
            ValuesSource.Numeric source = (ValuesSource.Numeric) valuesSource;
            MurmurHash3Values hashValues = source.isFloatingPoint() ? MurmurHash3Values.hash(source.doubleValues(ctx)) : MurmurHash3Values.hash(source.longValues(ctx));
            return new DirectCollector(counts, hashValues);
        }

        if (valuesSource instanceof ValuesSource.Bytes.WithOrdinals) {
            ValuesSource.Bytes.WithOrdinals source = (ValuesSource.Bytes.WithOrdinals) valuesSource;
            final RandomAccessOrds ordinalValues = source.ordinalsValues(ctx);
            final long maxOrd = ordinalValues.getValueCount();
            if (maxOrd == 0) {
                return new EmptyCollector();
            }

            final long ordinalsMemoryUsage = OrdinalsCollector.memoryOverhead(maxOrd);
            final long countsMemoryUsage = HyperLogLogPlusPlus.memoryUsage(precision);
            // only use ordinals if they don't increase memory usage by more than 25%
            if (ordinalsMemoryUsage < countsMemoryUsage / 4) {
                return new OrdinalsCollector(counts, ordinalValues, context.bigArrays());
            }
        }

        return new DirectCollector(counts, MurmurHash3Values.hash(valuesSource.bytesValues(ctx)));
    }

    @Override
    public LeafBucketCollector getLeafCollector(LeafReaderContext ctx,
            final LeafBucketCollector sub) throws IOException {
        postCollectLastCollector();

        collector = pickCollector(ctx);
        return collector;
    }

    private void postCollectLastCollector() {
        if (collector != null) {
            try {
                collector.postCollect();
                collector.close();
            } finally {
                collector = null;
            }
        }
    }

    @Override
    protected void doPostCollection() {
        postCollectLastCollector();
    }

    @Override
    public double metric(long owningBucketOrd) {
        return counts == null ? 0 : counts.cardinality(owningBucketOrd);
    }

    @Override
    public InternalAggregation buildAggregation(long owningBucketOrdinal) {
        if (counts == null || owningBucketOrdinal >= counts.maxBucket() || counts.cardinality(owningBucketOrdinal) == 0) {
            return buildEmptyAggregation();
        }
        // We need to build a copy because the returned Aggregation needs remain usable after
        // this Aggregator (and its HLL++ counters) is released.
        HyperLogLogPlusPlus copy = new HyperLogLogPlusPlus(precision, BigArrays.NON_RECYCLING_INSTANCE, 1);
        copy.merge(0, counts, owningBucketOrdinal);
        return new InternalCardinality(name, copy, pipelineAggregators(), metaData());
    }

    @Override
    public InternalAggregation buildEmptyAggregation() {
        return new InternalCardinality(name, null, pipelineAggregators(), metaData());
    }

    @Override
    protected void doClose() {
        Releasables.close(counts, collector);
    }

    private static abstract class Collector extends LeafBucketCollector implements Releasable {

        public abstract void postCollect();

    }

    private static class EmptyCollector extends Collector {

        @Override
        public void collect(int doc, long bucketOrd) {
            // no-op
        }

        @Override
        public void postCollect() {
            // no-op
        }

        @Override
        public void close() {
            // no-op
        }
    }

    private static class DirectCollector extends Collector {

        private final MurmurHash3Values hashes;
        private final HyperLogLogPlusPlus counts;

        DirectCollector(HyperLogLogPlusPlus counts, MurmurHash3Values values) {
            this.counts = counts;
            this.hashes = values;
        }

        @Override
        public void collect(int doc, long bucketOrd) {
            hashes.setDocument(doc);
            final int valueCount = hashes.count();
            for (int i = 0; i < valueCount; ++i) {
                counts.collect(bucketOrd, hashes.valueAt(i));
            }
        }

        @Override
        public void postCollect() {
            // no-op
        }

        @Override
        public void close() {
            // no-op
        }

    }

    private static class OrdinalsCollector extends Collector {

        private static final long SHALLOW_FIXEDBITSET_SIZE = RamUsageEstimator.shallowSizeOfInstance(FixedBitSet.class);

        /**
         * Return an approximate memory overhead per bucket for this collector.
         */
        public static long memoryOverhead(long maxOrd) {
            return RamUsageEstimator.NUM_BYTES_OBJECT_REF + SHALLOW_FIXEDBITSET_SIZE + (maxOrd + 7) / 8; // 1 bit per ord
        }

        private final BigArrays bigArrays;
        private final RandomAccessOrds values;
        private final int maxOrd;
        private final HyperLogLogPlusPlus counts;
        private ObjectArray<FixedBitSet> visitedOrds;

        OrdinalsCollector(HyperLogLogPlusPlus counts, RandomAccessOrds values, BigArrays bigArrays) {
            if (values.getValueCount() > Integer.MAX_VALUE) {
                throw new IllegalArgumentException();
            }
            maxOrd = (int) values.getValueCount();
            this.bigArrays = bigArrays;
            this.counts = counts;
            this.values = values;
            visitedOrds = bigArrays.newObjectArray(1);
        }

        @Override
        public void collect(int doc, long bucketOrd) {
            visitedOrds = bigArrays.grow(visitedOrds, bucketOrd + 1);
            FixedBitSet bits = visitedOrds.get(bucketOrd);
            if (bits == null) {
                bits = new FixedBitSet(maxOrd);
                visitedOrds.set(bucketOrd, bits);
            }
            values.setDocument(doc);
            final int valueCount = values.cardinality();
            for (int i = 0; i < valueCount; ++i) {
                bits.set((int) values.ordAt(i));
            }
        }

        @Override
        public void postCollect() {
            final FixedBitSet allVisitedOrds = new FixedBitSet(maxOrd);
            for (long bucket = visitedOrds.size() - 1; bucket >= 0; --bucket) {
                final FixedBitSet bits = visitedOrds.get(bucket);
                if (bits != null) {
                    allVisitedOrds.or(bits);
                }
            }

            final org.elasticsearch.common.hash.MurmurHash3.Hash128 hash = new org.elasticsearch.common.hash.MurmurHash3.Hash128();
            try (LongArray hashes = bigArrays.newLongArray(maxOrd, false)) {
                for (int ord = allVisitedOrds.nextSetBit(0); ord < DocIdSetIterator.NO_MORE_DOCS; ord = ord + 1 < maxOrd ? allVisitedOrds.nextSetBit(ord + 1) : DocIdSetIterator.NO_MORE_DOCS) {
                    final BytesRef value = values.lookupOrd(ord);
                    org.elasticsearch.common.hash.MurmurHash3.hash128(value.bytes, value.offset, value.length, 0, hash);
                    hashes.set(ord, hash.h1);
                }

                for (long bucket = visitedOrds.size() - 1; bucket >= 0; --bucket) {
                    final FixedBitSet bits = visitedOrds.get(bucket);
                    if (bits != null) {
                        for (int ord = bits.nextSetBit(0); ord < DocIdSetIterator.NO_MORE_DOCS; ord = ord + 1 < maxOrd ? bits.nextSetBit(ord + 1) : DocIdSetIterator.NO_MORE_DOCS) {
                            counts.collect(bucket, hashes.get(ord));
                        }
                    }
                }
            }
        }

        @Override
        public void close() {
            Releasables.close(visitedOrds);
        }

    }

    /**
     * Representation of a list of hash values. There might be dups and there is no guarantee on the order.
     */
    static abstract class MurmurHash3Values {

        public abstract void setDocument(int docId);

        public abstract int count();

        public abstract long valueAt(int index);

        /**
         * Return a {@link MurmurHash3Values} instance that computes hashes on the fly for each double value.
         */
        public static MurmurHash3Values hash(SortedNumericDoubleValues values) {
            return new Double(values);
        }

        /**
         * Return a {@link MurmurHash3Values} instance that computes hashes on the fly for each long value.
         */
        public static MurmurHash3Values hash(SortedNumericDocValues values) {
            return new Long(values);
        }

        /**
         * Return a {@link MurmurHash3Values} instance that computes hashes on the fly for each binary value.
         */
        public static MurmurHash3Values hash(SortedBinaryDocValues values) {
            return new Bytes(values);
        }

        private static class Long extends MurmurHash3Values {

            private final SortedNumericDocValues values;

            public Long(SortedNumericDocValues values) {
                this.values = values;
            }

            @Override
            public void setDocument(int docId) {
                values.setDocument(docId);
            }

            @Override
            public int count() {
                return values.count();
            }

            @Override
            public long valueAt(int index) {
                return BitMixer.mix64(values.valueAt(index));
            }
        }

        private static class Double extends MurmurHash3Values {

            private final SortedNumericDoubleValues values;

            public Double(SortedNumericDoubleValues values) {
                this.values = values;
            }

            @Override
            public void setDocument(int docId) {
                values.setDocument(docId);
            }

            @Override
            public int count() {
                return values.count();
            }

            @Override
            public long valueAt(int index) {
                return BitMixer.mix64(java.lang.Double.doubleToLongBits(values.valueAt(index)));
            }
        }

        private static class Bytes extends MurmurHash3Values {

            private final org.elasticsearch.common.hash.MurmurHash3.Hash128 hash = new org.elasticsearch.common.hash.MurmurHash3.Hash128();

            private final SortedBinaryDocValues values;

            public Bytes(SortedBinaryDocValues values) {
                this.values = values;
            }

            @Override
            public void setDocument(int docId) {
                values.setDocument(docId);
            }

            @Override
            public int count() {
                return values.count();
            }

            @Override
            public long valueAt(int index) {
                final BytesRef bytes = values.valueAt(index);
                org.elasticsearch.common.hash.MurmurHash3.hash128(bytes.bytes, bytes.offset, bytes.length, 0, hash);
                return hash.h1;
            }
        }
    }
}


text:
package com.google.zxing.client.android.wifi;

import java.util.regex.Pattern;

import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.util.Log;

import com.google.zxing.client.result.WifiParsedResult;

/**
 * Wifi配置管理器
 *
 * @author lijian
 * @date 2017-9-3 下午10:14:49
 */
public final class WifiConfigManager extends
		AsyncTask<WifiParsedResult, Object, Object> {
	private static final String TAG = WifiConfigManager.class.getSimpleName();

	/** 十六进制数字 */
	private static final Pattern HEX_DIGITS = Pattern.compile("[0-9A-Fa-f]+");

	private final WifiManager wifiManager;

	/**
	 * Wifi配置管理器
	 *
	 * @param wifiManager
	 */
	public WifiConfigManager(WifiManager wifiManager) {
		this.wifiManager = wifiManager;
	}

	@Override
	protected Object doInBackground(WifiParsedResult... args) {
		WifiParsedResult theWifiResult = args[0];
		// 启动WiFi,否则无效
		if (!wifiManager.isWifiEnabled()) {
			Log.i(TAG, "启用WiFi...");
			if (wifiManager.setWifiEnabled(true)) {
				Log.i(TAG, "Wi-fi 启用");
			} else {
				Log.w(TAG, "Wi-fi 无法启用!");
				return null;
			}
			// 这很快发生,但需要等待启用。 有点忙等?
			int count = 0;
			while (!wifiManager.isWifiEnabled()) {
				if (count >= 10) {
					Log.i(TAG, "太长时间启用wifi,退出");
					return null;
				}
				Log.i(TAG, "仍在等待wifi启用...");
				try {
					Thread.sleep(1000L);
				} catch (InterruptedException ie) {
					// continue
				}
				count++;
			}
		}
		String networkTypeString = theWifiResult.getNetworkEncryption();
		NetworkType networkType;
		try {
			networkType = NetworkType.forIntentValue(networkTypeString);
		} catch (IllegalArgumentException ignored) {
			Log.w(TAG, "网络类型不良 请参阅NetworkType值: " + networkTypeString);
			return null;
		}
		if (networkType == NetworkType.NO_PASSWORD) {
			changeNetworkUnEncrypted(wifiManager, theWifiResult);
		} else {
			String password = theWifiResult.getPassword();
			if (password != null && !password.isEmpty()) {
				if (networkType == NetworkType.WEP) {
					changeNetworkWEP(wifiManager, theWifiResult);
				} else if (networkType == NetworkType.WPA) {
					changeNetworkWPA(wifiManager, theWifiResult);
				}
			}
		}
		return null;
	}

	/**
	 * 更新网络:创建新网络或修改现有网络
	 *
	 * @param wifiManager
	 *            wifi管理器
	 * @param config
	 *            新的网络配置
	 */
	private static void updateNetwork(WifiManager wifiManager,
			WifiConfiguration config) {
		Integer foundNetworkID = findNetworkInExistingConfig(wifiManager,
				config.SSID);
		if (foundNetworkID != null) {
			Log.i(TAG, "删除网络的旧配置 " + config.SSID);
			wifiManager.removeNetwork(foundNetworkID);
			wifiManager.saveConfiguration();
		}
		int networkId = wifiManager.addNetwork(config);
		if (networkId >= 0) {
			// 尝试禁用当前网络并启动新的网络
			if (wifiManager.enableNetwork(networkId, true)) {
				Log.i(TAG, "与网络关联 " + config.SSID);
				wifiManager.saveConfiguration();
			} else {
				Log.w(TAG, "无法启用网络 " + config.SSID);
			}
		} else {
			Log.w(TAG, "无法添加网络 " + config.SSID);
		}
	}

	/**
	 * 改变网络共同点
	 *
	 * @param wifiResult
	 * @return
	 */
	private static WifiConfiguration changeNetworkCommon(
			WifiParsedResult wifiResult) {
		WifiConfiguration config = new WifiConfiguration();
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.clear();
		config.allowedProtocols.clear();
		// Android API坚持认为必须引用ascii SSID来正确处理
		config.SSID = quoteNonHex(wifiResult.getSsid());
		config.hiddenSSID = wifiResult.isHidden();
		return config;
	}

	/**
	 * 添加WEP网络
	 *
	 * @param wifiManager
	 * @param wifiResult
	 */
	private static void changeNetworkWEP(WifiManager wifiManager,
			WifiParsedResult wifiResult) {
		WifiConfiguration config = changeNetworkCommon(wifiResult);
		config.wepKeys[0] = quoteNonHex(wifiResult.getPassword(), 10, 26, 58);
		config.wepTxKeyIndex = 0;
		config.allowedAuthAlgorithms
				.set(WifiConfiguration.AuthAlgorithm.SHARED);
		config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
		config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
		config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
		config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
		config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
		updateNetwork(wifiManager, config);
	}

	/**
	 * 添加WPA or WPA2网络
	 *
	 * @param wifiManager
	 * @param wifiResult
	 */
	private static void changeNetworkWPA(WifiManager wifiManager,
			WifiParsedResult wifiResult) {
		WifiConfiguration config = changeNetworkCommon(wifiResult);
		// 64位长的十六进制密码不被引用
		config.preSharedKey = quoteNonHex(wifiResult.getPassword(), 64);
		config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
		config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); // For WPA
		config.allowedProtocols.set(WifiConfiguration.Protocol.RSN); // For WPA2
		config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
		config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
		config.allowedPairwiseCiphers
				.set(WifiConfiguration.PairwiseCipher.TKIP);
		config.allowedPairwiseCiphers
				.set(WifiConfiguration.PairwiseCipher.CCMP);
		config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
		config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
		updateNetwork(wifiManager, config);
	}

	/**
	 * 添加一个开放的,不安全的网络(更改网络未加密)
	 *
	 * @param wifiManager
	 * @param wifiResult
	 */
	private static void changeNetworkUnEncrypted(WifiManager wifiManager,
			WifiParsedResult wifiResult) {
		WifiConfiguration config = changeNetworkCommon(wifiResult);
		config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
		updateNetwork(wifiManager, config);
	}

	/**
	 * 查找现有配置中的网络
	 *
	 * @param wifiManager
	 * @param ssid
	 * @return
	 */
	private static Integer findNetworkInExistingConfig(WifiManager wifiManager,
			String ssid) {
		Iterable<WifiConfiguration> existingConfigs = wifiManager
				.getConfiguredNetworks();
		if (existingConfigs != null) {
			for (WifiConfiguration existingConfig : existingConfigs) {
				String existingSSID = existingConfig.SSID;
				if (existingSSID != null && existingSSID.equals(ssid)) {
					return existingConfig.networkId;
				}
			}
		}
		return null;
	}

	/**
	 * 引用十六进制
	 *
	 * @param value
	 * @param allowedLengths
	 * @return
	 */
	private static String quoteNonHex(String value, int... allowedLengths) {
		return isHexOfLength(value, allowedLengths) ? value
				: convertToQuotedString(value);
	}

	/**
	 * 如果尚未引用,则将传入的字符串括在双引号内
	 *
	 * @param s
	 *            输入字符串
	 * @return 引用的字符串,形式为"input"。 如果输入字符串为空,则返回null
	 */
	private static String convertToQuotedString(String s) {
		if (s == null || s.isEmpty()) {
			return null;
		}
		// 如果已经被引用,按原样返回
		if (s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"') {
			return s;
		}
		return '\"' + s + '\"';
	}

	/**
	 * 是否十六进制长度
	 *
	 * @param value
	 *            输入检查
	 * @param allowedLengths
	 *            允许的长度,如果有的话
	 * @return 如果value是十六进制数字的非null,非空字符串,并且如果允许的长度被赋予,则为true,具有允许的长度
	 */
	private static boolean isHexOfLength(CharSequence value,
			int... allowedLengths) {
		if (value == null || !HEX_DIGITS.matcher(value).matches()) {
			return false;
		}
		if (allowedLengths.length == 0) {
			return true;
		}
		for (int length : allowedLengths) {
			if (value.length() == length) {
				return true;
			}
		}
		return false;
	}

}

redpajama_set_name: RedPajamaGithub


text:
    Comment:
    {{item.comment}}


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Article.is_featured'
        db.add_column(u'articles_article', 'is_featured',
                      self.gf('django.db.models.fields.BooleanField')(default=False, db_index=True),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'Article.is_featured'
        db.delete_column(u'articles_article', 'is_featured')

    models = {
        u'articles.article': {
            'Meta': {'object_name': 'Article'},
            'content_detail': ('ckeditor.fields.RichTextField', [], {}),
            'content_list': ('ckeditor.fields.RichTextField', [], {}),
            'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_featured': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
            'meta_description': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
            'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'blank': 'True', 'populate_from': "'title'", 'unique': 'True', 'null': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '256'})
        }
    }

    complete_apps = ['articles']


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package examen1;

/**
 *
 * @author David
 */
public class estudiante extends persona{
    private String carrera;

    public estudiante(String carrera, String nombre, int edad, String id, String id_boleto, String dept, int dinero) {
        super(nombre, edad, id, id_boleto, dept, dinero);
        this.carrera = carrera;
    }

    public estudiante() {
        super();
    }

    public String getCarrera() {
        return carrera;
    }

    public void setCarrera(String carrera) {
        this.carrera = carrera;
    }

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

}


text:
import unittest

import rdflib # needed for eval(repr(...)) below
from rdflib.term import Literal, URIRef

# these are actually meant for test_term.py, which is not yet merged into trunk

class TestMd5(unittest.TestCase):
    def testMd5(self):
        self.assertEqual(rdflib.URIRef("http://example.com/").md5_term_hash(),
                         "40f2c9c20cc0c7716fb576031cceafa4")
        self.assertEqual(rdflib.Literal("foo").md5_term_hash(),
                         "da9954ca5f673f8ab9ebd6faf23d1046")

class TestLiteral(unittest.TestCase):
    def setUp(self):
        pass

    def test_repr_apostrophe(self):
        a = rdflib.Literal("'")
        b = eval(repr(a))
        self.assertEquals(a, b)

    def test_repr_quote(self):
        a = rdflib.Literal('"')
        b = eval(repr(a))
        self.assertEquals(a, b)

    def test_backslash(self):
        d = r"""
<rdf:RDF
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:foo="http://example.org/foo#">
    <rdf:Description>
      <foo:bar>a\b</foo:bar>
    </rdf:Description>
</rdf:RDF>
"""
        g = rdflib.Graph()
        g.parse(data=d)
        a = rdflib.Literal('a\\b')
        b = list(g.objects())[0]
        self.assertEquals(a, b)

    def test_literal_from_bool(self):
        l = rdflib.Literal(True)
        XSD_NS = rdflib.Namespace(u'http://www.w3.org/2001/XMLSchema#')
        self.assertEquals(l.datatype, XSD_NS["boolean"])

class TestNew(unittest.TestCase):
    def testCantPassLangAndDatatype(self):
        self.assertRaises(TypeError,
           Literal, 'foo', lang='en', datatype=URIRef("http://example.com/"))

    def testDatatypeGetsAutoURIRefConversion(self):
        # drewp disapproves of this behavior, but it should be
        # represented in the tests
        x = Literal("foo", datatype="http://example.com/")
        self.assert_(isinstance(x.datatype, URIRef))

        x = Literal("foo", datatype=Literal("pennies"))
        self.assertEqual(x.datatype, URIRef("pennies"))

class TestRepr(unittest.TestCase):
    def testOmitsMissingDatatypeAndLang(self):
        self.assertEqual(repr(Literal("foo")), "rdflib.term.Literal(u'foo')")

    def testOmitsMissingDatatype(self):
        self.assertEqual(repr(Literal("foo", lang='en')),
                         "rdflib.term.Literal(u'foo', lang='en')")

    def testOmitsMissingLang(self):
        self.assertEqual(
            repr(Literal("foo", datatype=URIRef('http://example.com/'))),
            "rdflib.term.Literal(u'foo', datatype=rdflib.term.URIRef('http://example.com/'))")

    def testSubclassNameAppearsInRepr(self):
        class MyLiteral(Literal):
            pass
        x = MyLiteral(u"foo")
        self.assertEqual(repr(x), "MyLiteral(u'foo')")

if __name__ == "__main__":
    unittest.main()


text:
import { Component } from "@angular/core";
import { PeopleService } from "app/people.service";
import { State } from "clarity-angular";

@Component({
    styleUrls: ['./home.component.scss'],
    templateUrl: './home.component.html',
    providers: [ PeopleService ]
})
export class HomeComponent {
    users = [{id: 1, name:"Luke"},{id:2, name:"Han"}];
    people = [];
    currentPage = 1;
    total = 0;

    loading = true;

    constructor(private peopleService: PeopleService){

    }

    refresh(state: State){
            this.loading = true;
            this.peopleService.get(this.currentPage).subscribe(data => {
            console.log(data);
            this.people = data;
            this.total = data.count;
            this.loading = false;
        });

    }

}


text:
author: alex
categories:
- descargas
mainclass: descargas
date: 2016-08-06 16:15:22
lastmod: 2017-07-07T18:30:46+01:00
description: Descarga un manual de git completo de forma gratuita
image: git-tutorial-centered.jpg
tags:
- git
- libros
- guias
title: Manual De Git Gratuito
---

> **NOTA** También puedes consultar nuestra [Chuleta de comandos GIT](/mini-tutorial-y-chuleta-de-comandos-git/ "Git: Mini Tutorial y chuleta de comandos")

Delve into the world of Git version source control with this compact guide that discusses the features of this popular control system!

Git is, without any doubt, the most popular version control system. Ironically, there are other version control systems easier to learn and to use, but, despite that, Git is the favorite option for developers, which is quite clarifying about the powerfulness of Git.

In this guide, we will cover all the topics needed to know in order to use Git properly, from explaining what is it and how it differs from other tools, to its usage, covering also advanced topics and practices that can suppose an added value to the process of version controlling.

With this free eBook you will also receive weekly news, tips and special offers delivered to your inbox courtesy of Java Code Geeks.

  Descárgala ahora

Visita la página [Manuales gratuitos][1] o consulta el [catálogo completo][2].

[1]: https://elbauldelprogramador.com/manuales-gratuitos/
[2]: http://elbauldelprogramador.tradepub.com/category/information-technology/1207/ "Catálogo completo de Guías gratuítas "


text:
class HaystackError(Exception):
    """A generic exception for all others to extend."""
    pass

class SearchBackendError(HaystackError):
    """Raised when a backend can not be found."""
    pass

class SearchFieldError(HaystackError):
    """Raised when a field encounters an error."""
    pass

class MissingDependency(HaystackError):
    """Raised when a library a backend depends on can not be found."""
    pass

class NotHandled(HaystackError):
    """Raised when a model is not handled by the router setup."""
    pass

class MoreLikeThisError(HaystackError):
    """Raised when a model instance has not been provided for More Like This."""
    pass

class FacetingError(HaystackError):
    """Raised when incorrect arguments have been provided for faceting."""
    pass

class SpatialError(HaystackError):
    """Raised when incorrect arguments have been provided for spatial."""
    pass

class StatsError(HaystackError):
    "Raised when incorrect arguments have been provided for stats"
    pass


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Checkboxes - showWhenThis</title>
  <link rel="stylesheet" href="style.css">

      Show #checkboxes .additional_information:
      <input type="checkbox" name="show_additional_information" value="hide" checked="checked" />

      Showing #checkboxes .additional_information


text:
@extends('layouts.app')
@section('content')

			Tambah Rekam Medis

		{!! Form::open(['route' => 'medis.store'])!!}
		@include('medis._form')
		{!! Form::close() !!}

@endsection


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_MATH_CONSTRAINTS_MATRIX_H_
#define _BLAZE_MATH_CONSTRAINTS_MATRIX_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <blaze/math/typetraits/IsMatrix.h>

namespace blaze {

//=================================================================================================
//
//  MUST_BE_MATRIX_TYPE CONSTRAINT
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Constraint on the data type.
// \ingroup math_constraints
//
// In case the given data type \a T is not a N-dimensional matrix type, a compilation error
// is created.
*/
#define BLAZE_CONSTRAINT_MUST_BE_MATRIX_TYPE(T) \
   static_assert( ::blaze::IsMatrix_v<T>, "Non-matrix type detected" )
//*************************************************************************************************

//=================================================================================================
//
//  MUST_NOT_BE_MATRIX_TYPE CONSTRAINT
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Constraint on the data type.
// \ingroup math_constraints
//
// In case the given data type \a T is a N-dimensional matrix type, a compilation error
// is created.
*/
#define BLAZE_CONSTRAINT_MUST_NOT_BE_MATRIX_TYPE(T) \
   static_assert( !::blaze::IsMatrix_v<T>, "Matrix type detected" )
//*************************************************************************************************

} // namespace blaze

#endif


text:
/**
 *
 */
package com.nec.harvest.repository.impl;

import com.nec.crud.CrudRepositoryImpl;
import com.nec.harvest.model.MoveTransfer;
import com.nec.harvest.repository.MoveTransferRepository;

/**
 * {@link MoveTransferRepository}
 *
 * @author QuanDK
 *
 */
public class MoveTransferRepositoryImpl extends CrudRepositoryImpl<MoveTransfer, String> implements MoveTransferRepository {

}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('manager', '0007_build_sha256'),
    ]

    operations = [
        migrations.AddField(
            model_name='package',
            name='ignore',
            field=models.BooleanField(default=False),
        ),
    ]


text:
Summary:

* Marten uses Roslyn so start up time is long enough to be noticable. There is a workaround: https://github.com/JasperFx/marten/issues/289
* JSON support in PostgreSQL is excellent so if something can't be done via Marten it can be done directly via NpgsqlCommand and raw SQL.
* Searching using date ranges is a bit painful but it is a problem with JSON that simply doesn't have date/time data type.
* As of now LINQ queries are not complied and cached and not all operators are implemented. Check docs for details.
* Performance of concurrent inserts is not great when the default UpsertMode is left in place: https://github.com/JasperFx/marten/issues/296. When UpsertMode is changed to Standard then I get the following numbers on my laptop (i7 + SSD + 50 connections):
	* 10k concurrent users, each user persists 1 document. 714 documents / second
	* 10k concurrent users, each user persists 10 documents. 2777 documents / second
	* 1k concurrent users, each user persists 10 documents. 3333 documents / second
* Performance of concurrent queries is fine.
* API is easy to use and is based on RavenDB.
* PGAdmin is a decent tool but nowhere close as good as Sql Management Studio.


text:
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2007 Frederico Caldeira Knabben

== BEGIN LICENSE ==

Licensed under the terms of any of the following licenses at your
choice:

 - GNU General Public License Version 2 or later (the "GPL")
   http://www.gnu.org/licenses/gpl.html

 - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
   http://www.gnu.org/licenses/lgpl.html

 - Mozilla Public License Version 1.1 or later (the "MPL")
   http://www.mozilla.org/MPL/MPL-1.1.html

== END LICENSE ==

This is the integration file for Python.
"""

import cgi
import os
import re
import string

def escape(text, replace=string.replace):
    """Converts the special characters '<', '>', and '&'.

    RFC 1866 specifies that these characters be represented
    in HTML as < > and & respectively. In Python
    1.5 we use the new string.replace() function for speed.
    """
    text = replace(text, '&', '&') # must be done 1st
    text = replace(text, '<', '<')
    text = replace(text, '>', '>')
    text = replace(text, '"', '"')
    text = replace(text, "'", ''')
    return text

# The FCKeditor class
class FCKeditor(object):
	def __init__(self, instanceName):
		self.InstanceName = instanceName
		self.BasePath = '/fckeditor/'
		self.Width = '100%'
		self.Height = '200'
		self.ToolbarSet = 'Default'
		self.Value = '';

		self.Config = {}

	def Create(self):
		return self.CreateHtml()

	def CreateHtml(self):
		HtmlValue = escape(self.Value)
		Html = "
"

		if (self.IsCompatible()):
			File = "fckeditor.html"
			Link = "%seditor/%s?InstanceName=%s" % (
					self.BasePath,
					File,
					self.InstanceName
					)
			if (self.ToolbarSet is not None):
				Link += "&ToolBar=%s" % self.ToolbarSet

			# Render the linked hidden field
			Html += "<input type=\"hidden\" id=\"%s\" name=\"%s\" value=\"%s\" style=\"display:none\" />" % (
					self.InstanceName,
					self.InstanceName,
					HtmlValue
					)

			# Render the configurations hidden field
			Html += "<input type=\"hidden\" id=\"%s___Config\" value=\"%s\" style=\"display:none\" />" % (
					self.InstanceName,
					self.GetConfigFieldString()
					)

			# Render the editor iframe
			Html += "" % (
					self.InstanceName,
					Link,
					self.Width,
					self.Height
					)
		else:
			if (self.Width.find("%%") < 0):
				WidthCSS = "%spx" % self.Width
			else:
				WidthCSS = self.Width
			if (self.Height.find("%%") < 0):
				HeightCSS = "%spx" % self.Height
			else:
				HeightCSS = self.Height

			Html += "<textarea name=\"%s\" rows=\"4\" cols=\"40\" style=\"width: %s; height: %s;\" wrap=\"virtual\">%s</textarea>" % (
					self.InstanceName,
					WidthCSS,
					HeightCSS,
					HtmlValue
					)
		Html += "
"
		return Html

	def IsCompatible(self):
		if (os.environ.has_key("HTTP_USER_AGENT")):
			sAgent = os.environ.get("HTTP_USER_AGENT", "")
		else:
			sAgent = ""
		if (sAgent.find("MSIE") >= 0) and (sAgent.find("mac") < 0) and (sAgent.find("Opera") < 0):
			i = sAgent.find("MSIE")
			iVersion = float(sAgent[i+5:i+5+3])
			if (iVersion >= 5.5):
				return True
			return False
		elif (sAgent.find("Gecko/") >= 0):
			i = sAgent.find("Gecko/")
			iVersion = int(sAgent[i+6:i+6+8])
			if (iVersion >= 20030210):
				return True
			return False
		elif (sAgent.find("Opera/") >= 0):
			i = sAgent.find("Opera/")
			iVersion = float(sAgent[i+6:i+6+4])
			if (iVersion >= 9.5):
				return True
			return False
		elif (sAgent.find("AppleWebKit/") >= 0):
			p = re.compile('AppleWebKit\/(\d+)', re.IGNORECASE)
			m = p.search(sAgent)
			if (m.group(1) >= 522):
				return True
			return False
		else:
			return False

	def GetConfigFieldString(self):
		sParams = ""
		bFirst = True
		for sKey in self.Config.keys():
			sValue = self.Config[sKey]
			if (not bFirst):
				sParams += "&"
			else:
				bFirst = False
			if (sValue):
				k = escape(sKey)
				v = escape(sValue)
				if (sValue == "true"):
					sParams += "%s=true" % k
				elif (sValue == "false"):
					sParams += "%s=false" % k
				else:
					sParams += "%s=%s" % (k, v)
		return sParams


text:
namespace MassTransit.TestFramework.ForkJoint.Futures
{
    using Contracts;

    public class FryShakeFuture :
        Future<OrderFryShake, FryShakeCompleted>
    {
        public FryShakeFuture()
        {
            ConfigureCommand(x => x.CorrelateById(context => context.Message.OrderLineId));

            SendRequest<OrderFry>(x =>
                {
                    x.UsingRequestInitializer(context => new
                    {
                        OrderId = context.Saga.CorrelationId,
                        OrderLineId = InVar.Id,
                        context.Message.Size,
                    });

                    x.TrackPendingRequest(message => message.OrderLineId);
                })
                .OnResponseReceived<FryCompleted>(x =>
                {
                    x.CompletePendingRequest(message => message.OrderLineId);
                });

            SendRequest<OrderShake>(x =>
                {
                    x.UsingRequestInitializer(context => new
                    {
                        OrderId = context.Saga.CorrelationId,
                        OrderLineId = InVar.Id,
                        context.Message.Flavor,
                        context.Message.Size,
                    });

                    x.TrackPendingRequest(message => message.OrderLineId);
                })
                .OnResponseReceived<ShakeCompleted>(x =>
                {
                    x.CompletePendingRequest(message => message.OrderLineId);
                });

            WhenAllCompleted(x => x.SetCompletedUsingInitializer(context =>
            {
                var message = context.GetCommand<OrderFryShake>();

                return new {Description = $"{message.Size} {message.Flavor} FryShake({context.Saga.Results.Count})"};
            }));
        }
    }
}


text:
var express = require('express');
var router = express.Router();
var db = require('./query')

/* GET users listing. */
router.get('/', function(req, res, next) {

  db.getOrders(req, res, next)

});

module.exports = router;


text:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router'

import { SharedModule } from '../shared/shared.module';

import { ProfileComponent } from './profile.component';

@NgModule({
  declarations: [ProfileComponent],
  imports: [
    SharedModule,
    RouterModule.forChild([
      { path: '', component: ProfileComponent, pathMatch: 'full' }
    ])
  ]
})
export class ProfileModule {

}


text:
using System;
using System.Linq;
using System.Web.Mvc;
using MileageStats.Domain.Models;
using MileageStats.Web.Authentication;
using System.Net;
using MileageStats.Domain.Handlers;
using MileageStats.Web.Properties;

namespace MileageStats.Web.Controllers
{
    [Authorize]
    public class ProfileController : BaseController
    {
        private readonly GetCountries _getCountries;
        private readonly IFormsAuthentication _formsAuthentication;
        private readonly UpdateUser _updateUser;

        public ProfileController(
            UpdateUser updateUser,
            GetUserByClaimId getUser,
            GetCountries getCountries,
            IFormsAuthentication formsAuthentication)
            : base(getUser, null)
        {
            _updateUser = updateUser;
            _getCountries = getCountries;
            _formsAuthentication = formsAuthentication;
        }

        [HttpGet]
        public ActionResult Edit()
        {
            return SetupProfileForm(CurrentUser);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Edit(User user, string action = null)
        {
            if (action == "cancel")
            {
                //Reset user profile with current user info
                user.Country = CurrentUser.Country;
                user.DisplayName = CurrentUser.DisplayName;
            }

            user.UserId = CurrentUserId;
            user.HasRegistered = true;

            _updateUser.Execute(user);

            var ticket = _formsAuthentication.GetAuthenticationTicket(HttpContext);

            if (ticket != null)
            {
                _formsAuthentication.SetAuthCookie(HttpContext,
                    UserAuthenticationTicketBuilder.CreateAuthenticationTicket(
                    user, ticket.IssueDate, ticket.IsPersistent));
            }

            if (ModelState.IsValid || action == "cancel")
            {
                if (Request.IsAjaxRequest())
                    return new HttpStatusCodeResult((int)HttpStatusCode.OK, Messages.ProfileController_ProfileUpdated);

                if(action != "cancel")
                {
                    this.SetConfirmationMessage(Messages.ProfileController_ProfileUpdated);
                }

                return RedirectToAction("Index", "Dashboard");
            }

            if (Request.IsAjaxRequest())
                return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest, Messages.ProfileController_InvalidData);

            return SetupProfileForm(user);
        }

        private ActionResult SetupProfileForm(User user)
        {
            ViewBag.CountryList = _getCountries.GetCountrySelectList();

            return new ContentTypeAwareResult(user);
        }
    }
}


text:
[Docker image](https://registry.hub.docker.com/u/sodre90/rpi-couchpotato/) for running CouchPotato on a Raspberry PI.

## Usage

You can run the image with the following command.

    docker run -d -p 5050:5050 -v /path/to/movies:/movies -v /path/to/config:/config --restart=always --name couchpotato sodre90/rpi-couchpotato

Note the `--restart=always` parameter, that will restart the Docker container every time it stops. We need that because CouchPotato will update itself periodically and restart the process, causing the Docker container to stop.

## Build

You can **optionally** build the image `sodre90/rpi-couchpotato` with the latest CouchPotato sources. To do that just execute the following command once you have checked out the [source repository](https://github.com/sodre90/docker-rpi-couchpotato).

    docker build -t sodre90/rpi-couchpotato .


text:
package org.osjava.signals.natives.view;

import java.util.ArrayList;
import java.util.List;

import org.osjava.signals.natives.NativeAPIAdapterSignal.NativeAPIAdapterDelegate;
import org.osjava.signals.natives.NativeAPIAdapterSignal.NativeAPIAdapterSignal2;

import android.view.View;

public class ViewOnViewAttachedToWindowSignal extends NativeAPIAdapterSignal2<View, View> {

	private final static String ADAPTER_NAME = "android.view.View$OnAttachStateChangeListener";

	private final static String LISTENER_NAME = "addOnAttachStateChangeListener";

	private final static List<String> METHOD_NAME = new ArrayList<String>();

	static {
		METHOD_NAME.add("onViewAttachedToWindow");
		METHOD_NAME.add("onViewDetachedFromWindow");
	}

	/**
	 * Private constructor
	 *
	 * @param target
	 *            to be used when applying the listeners
	 */
	private ViewOnViewAttachedToWindowSignal(View target) {

		final Class<?>[] parameterTypes = { View.class };

		createProxy(ADAPTER_NAME, LISTENER_NAME, parameterTypes, new TargetListener(), METHOD_NAME);
		setTarget(target);
	}

	/**
	 * Create a newInstance of ViewOnViewAttachedToWindowSignal
	 *
	 * @param View
	 *            target to apply the listener when executing a dispatch
	 * @return {@link ViewOnViewAttachedToWindowSignal}
	 */
	public static ViewOnViewAttachedToWindowSignal newInstance(final View target) {
		return new ViewOnViewAttachedToWindowSignal(target);
	}

	private final class TargetListener implements NativeAPIAdapterDelegate {

		@SuppressWarnings("unused")
		public void onViewAttachedToWindow(View v) {

			try {
				dispatch(getTarget(), v);
			} catch (Throwable t) {
				throw new RuntimeException(t);
			}
		}

		@SuppressWarnings("unused")
		public void onViewDetachedFromWindow(View v) {

		}
	}
}


text:
package org.zstack.test.storage.backup;

import org.zstack.header.storage.backup.BackupStorageDetachExtensionPoint;
import org.zstack.header.storage.backup.BackupStorageException;
import org.zstack.header.storage.backup.BackupStorageInventory;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

public class BackupStorageDetachExtension implements BackupStorageDetachExtensionPoint {
    CLogger logger = Utils.getLogger(BackupStorageDetachExtensionPoint.class);
    boolean preventChange = false;
    boolean beforeCalled = false;
    boolean afterCalled = false;
    String expectedBackStorageUuid;
    String expectedZoneUuid;

    @Override
    public void preDetachBackupStorage(BackupStorageInventory inventory, String zoneUuid) throws BackupStorageException {
        if (preventChange) {
            throw new BackupStorageException("Prevent detaching backup storage on purpose");
        }
    }

    @Override
    public void beforeDetachBackupStorage(BackupStorageInventory inventory, String zoneUuid) {
        if (inventory.getUuid().equals(expectedBackStorageUuid) && zoneUuid.equals(expectedZoneUuid)) {
            beforeCalled = true;
        } else {
            String err = String.format("beforeDetachBackupStorage: expected backup storage uuid: %s zone uuid: %s but got backup storage uuid: %s zone uuid: %s", expectedBackStorageUuid, expectedZoneUuid, inventory.getUuid(), zoneUuid);
            logger.warn(err);
        }
    }

    @Override
    public void failToDetachBackupStorage(BackupStorageInventory inventory, String zoneUuid) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterDetachBackupStorage(BackupStorageInventory inventory, String zoneUuid) {
        if (inventory.getUuid().equals(expectedBackStorageUuid) && zoneUuid.equals(expectedZoneUuid)) {
            afterCalled = true;
        } else {
            String err = String.format("afterDetachBackupStorage: expected backup storage uuid: %s zone uuid: %s but got backup storage uuid: %s zone uuid: %s", expectedBackStorageUuid, expectedZoneUuid, inventory.getUuid(), zoneUuid);
            logger.warn(err);
        }
    }

    public boolean isPreventChange() {
        return preventChange;
    }

    public void setPreventChange(boolean preventChange) {
        this.preventChange = preventChange;
    }

    public boolean isBeforeCalled() {
        return beforeCalled;
    }

    public void setBeforeCalled(boolean beforeCalled) {
        this.beforeCalled = beforeCalled;
    }

    public boolean isAfterCalled() {
        return afterCalled;
    }

    public void setAfterCalled(boolean afterCalled) {
        this.afterCalled = afterCalled;
    }

    public String getExpectedBackStorageUuid() {
        return expectedBackStorageUuid;
    }

    public void setExpectedBackStorageUuid(String expectedBackStorageUuid) {
        this.expectedBackStorageUuid = expectedBackStorageUuid;
    }

    public String getExpectedZoneUuid() {
        return expectedZoneUuid;
    }

    public void setExpectedZoneUuid(String expectedZoneUuid) {
        this.expectedZoneUuid = expectedZoneUuid;
    }

}


text:
package async.wsdl_hello_lit.client.handlers;

import java.util.Set;

import javax.xml.namespace.QName;
import jakarta.xml.ws.handler.MessageContext;
import jakarta.xml.ws.handler.soap.SOAPHandler;
import jakarta.xml.ws.handler.soap.SOAPMessageContext;
import jakarta.xml.soap.*;

public class SOAPTestHandler implements SOAPHandler<SOAPMessageContext> {

    public Set<QName> getHeaders() {
        return null;
    }

    public boolean handleMessage(SOAPMessageContext smc) {
        try {
            SOAPMessage message = smc.getMessage();
            SOAPBody body = message.getSOAPBody();

            SOAPElement paramElement =
                (SOAPElement) body.getFirstChild();
            int number = Integer.parseInt(paramElement.getValue());
            paramElement.setValue(String.valueOf(++number));
        } catch (SOAPException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return true;
    }

    public boolean handleFault(SOAPMessageContext context) {
        return true;
    }

    public void close(MessageContext context) {}

}


text:
Simple web page for slideshow between sessions.

## Features
- automatic rotation of web pages in fullscreen
- configurable duration for each slide
- configurable refresh

## Slides from DevFest 2013
in "slides" folder you can find prepared slides for conference partners presentation and countdown to sessions


text:
        <title>Cfn Graph</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

                    Cfn Graph by Matthew Shea

                            Template (JSON)
                            <textarea id="input_cfn" class="form-control" oninput="handle_json_change();"></textarea>

                                Analysis

Nodes:

Edges:

Cycles:

Broken Edges:

                    Graph

                    Samples
                    <button style="margin:5px;" class="btn btn-info" onclick="load_template('tableau-cluster')">Tableau Cluster</button>
                    <button style="margin:5px;" class="btn btn-info" onclick="load_template('vpc-dns')">VPC w/ DNS</button>
                    <button style="margin:5px;" class="btn btn-info" onclick="load_template('elb-autoscaling')">ELB w/ AutoScaling</button>

                                Filters

                                    <input checked="checked" type="checkbox" class="custom-control-input" id="include_parameters" onchange="handle_json_change();" >

                                    Parameters

                                    <input type="checkbox" class="custom-control-input" id="include_pseudos" onchange="handle_json_change();" >

                                    Pseudo

                                    <input checked="checked" type="checkbox" class="custom-control-input" id="include_conditions" onchange="handle_json_change();" >

                                    Conditions

                                    <input checked="checked" type="checkbox" class="custom-control-input" id="include_missings" onchange="handle_json_change();" >

                                    Missing

                                    <input type="checkbox" class="custom-control-input" id="include_outputs" onchange="handle_json_change();" >

                                    Outputs

                    Legend

                            Nodes
                            Edges

                            Resource
                            Parameter
                            Pseudo
                            Missing
                            Condition
                            Output

                            Ref
                            Fn::Sub
                            Fn::GetAtt
                            Condition

Modal Header

                        <button type="button" class="close" data-dismiss="modal">×</button>

                                    Resource JSON

                                    Upstream Dependencies

                                    Downstream Dependencies

                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
.class interface abstract Landroid/support/v4/view/accessibility/AccessibilityManagerCompatIcs$AccessibilityStateChangeListenerBridge;
.super Ljava/lang/Object;
.source "AccessibilityManagerCompatIcs.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/view/accessibility/AccessibilityManagerCompatIcs;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x608
    name = "AccessibilityStateChangeListenerBridge"
.end annotation

# virtual methods
.method public abstract onAccessibilityStateChanged(Z)V
.end method


text:
#include <Inventor/actions/SoGLRenderAction.h>
#include <Inventor/actions/SoHandleEventAction.h>
#include <Inventor/actions/SoSearchAction.h>
#include <Inventor/sensors/SoFieldSensor.h>
#include "SoXipOverlaySearchContour.h"
#include  <xip/inventor/overlay/SoXipManipulableShape.h>
#include "SoXipShapeList.h"
#include <xip/inventor/overlay/XipOverlayUtils.h>

SO_NODE_SOURCE( SoXipOverlaySearchContour );

SoXipOverlaySearchContour::SoXipOverlaySearchContour()
{
	SO_NODE_CONSTRUCTOR( SoXipOverlaySearchContour );

	// Inputs
	SO_NODE_ADD_FIELD( numNodesUpToContainer,       (1) );
	SO_NODE_ADD_FIELD(                 label,      ("") );
	SO_NODE_ADD_FIELD(                  type,      ("") );
	SO_NODE_ADD_FIELD(                closed,   (FALSE) );
	SO_NODE_ADD_FIELD(              selected,   (FALSE) );
	SO_NODE_ADD_FIELD(             searchAll,   (FALSE) );
	SO_NODE_ADD_FIELD(                search,        () );
	label.setNum(0);

	// Outputs
	SO_NODE_ADD_FIELD(                 point, (0, 0, 0) );
	SO_NODE_ADD_FIELD(            coordIndex,       (0) );
	point.setNum(0);
	coordIndex.setNum(0);

	m_doSearch = FALSE;

	mSearchSensor = new SoFieldSensor( searchSensorCB, this );
	mSearchSensor->attach( &search );
}

SoXipOverlaySearchContour::~SoXipOverlaySearchContour()
{
	if( mSearchSensor )
	{
		delete mSearchSensor;
		mSearchSensor = 0;
	}
}

void
SoXipOverlaySearchContour::initClass()
{
	SO_NODE_INIT_CLASS( SoXipOverlaySearchContour, SoNode, "Node" );
}

void
SoXipOverlaySearchContour::searchSensorCB( void* userData, SoSensor* sensor )
{
	((SoXipOverlaySearchContour *) userData)->m_doSearch = TRUE;
}

void
SoXipOverlaySearchContour::GLRender( SoGLRenderAction* action )
{
	doAction( action );
}

void
SoXipOverlaySearchContour::handleEvent( SoHandleEventAction* action )
{
	doAction( action );
}

SoNodeList
SoXipOverlaySearchContour::selectMatches( const SoNodeList& shapes )
{
	SoNodeList nodes = shapes;

	SbString classTypeName = type.getValue();
	if( classTypeName.getLength() )
	{
		SoType classType = SoType::fromName( classTypeName );
		if( classType.isBad() || !classType.isDerivedFrom( SoXipShape::getClassTypeId() ) )
		{
			SoDebugError::post( __FILE__, "Invalid Type" );
			return SoNodeList();
		}

		for( int i = 0; i < nodes.getLength(); ++ i )
		{
			if( ! nodes[i]->isOfType( classType ) )
				nodes.remove( i -- );
		}
	}

	for( int labelIndex = 0; labelIndex < label.getNum(); ++ labelIndex )
	{
		const SbString& labelSearch = label[labelIndex];
		if( labelSearch.getLength() )
		{
			for( int i = 0; i < nodes.getLength(); ++ i )
			{
				SoXipShape* shape = (SoXipShape *) nodes[i];
				if( shape->label.find( labelSearch ) == -1 )
					nodes.remove( i -- );
			}
		}
	}

	if( selected.getValue() )
	{
		for( int i = 0; i < nodes.getLength(); ++ i )
		{
			SoXipShape* shape = (SoXipShape *) nodes[i];
			if( !shape->isSelected() )
				nodes.remove( i -- );
		}
	}

	return nodes;
}

void
SoXipOverlaySearchContour::doAction( SoAction* action )
{
	if( !m_doSearch )
		return ;

	m_doSearch = FALSE;

	const SoFullPath* path = (SoFullPath *) action->getCurPath();

	SoNodeList nodes = XipOverlayUtils::loadOverlaysFromNode(
		path->getNodeFromTail( numNodesUpToContainer.getValue() ),
		SoXipManipulableShape::getClassTypeId(),
		searchAll.getValue() );

	SoMFVec3f pointTmp;
	SoMFInt32 coordIndexTmp;

	SoNodeList matches = selectMatches( nodes );

	for( int i = 0; i < matches.getLength(); ++ i )
	{
		SoXipManipulableShape* shape = (SoXipManipulableShape *) matches[i];
		appendContour( shape, pointTmp, coordIndexTmp );
	}

	int numPoints  = pointTmp.getNum();
	int numIndices = coordIndexTmp.getNum();

	point.setNum( numPoints );
	coordIndex.setNum( numIndices );

	if( numPoints )
		point.setValues( 0, numPoints, pointTmp.getValues(0) );

	if( numIndices )
		coordIndex.setValues( 0, numIndices, coordIndexTmp.getValues(0) );
}

void
SoXipOverlaySearchContour::appendContour( SoXipManipulableShape*
  shape, SoMFVec3f& accumulatePoint, SoMFInt32& accumulateCoordIndex )
{
	if( closed.getValue() && !shape->isClosed() )
		return ;

	int oldNumPoints = accumulatePoint.getNum();
	int oldNumIndices = accumulateCoordIndex.getNum();

	SoMFVec3f linePoints;
	SoMFInt32 lineIndices;
	SbBool closed;
	shape->extractGeometries( linePoints, lineIndices, closed );

	accumulatePoint.setValues( oldNumPoints, linePoints.getNum(),
								 	linePoints.getValues(0) );
	accumulateCoordIndex.setValues( oldNumIndices,
									lineIndices.getNum(), lineIndices.getValues(0) );

	int* indPtr = accumulateCoordIndex.startEditing();

  if( !indPtr )
	{
	  return;
	}

	indPtr += oldNumIndices;

  for( int i = 0; i < lineIndices.getNum(); ++ i, ++ indPtr )
	{
	  if( *indPtr != -1 )
		{
		  *indPtr += oldNumPoints;
	  }
	}

	accumulateCoordIndex.finishEditing();
}


text:
#import "AdViewAdapterAdChina.h"
#import "AdViewViewImpl.h"
#import "AdViewConfig.h"
#import "AdViewAdNetworkConfig.h"
#import "AdViewDelegateProtocol.h"
#import "AdViewLog.h"
#import "AdViewAdNetworkAdapter+Helpers.h"
#import "AdViewAdNetworkRegistry.h"
#import "AdChinaBannerView.h"
#import "SingletonAdapterBase.h"

#import "AdChinaLocationManager.h"

#define KADCHINA_DETAULT_FRAME (CGRectMake(0,0,KADVIEW_WIDTH,64))
#define KADCHINA_LANDSCAPE_FRAME (CGRectMake(0,0,KLANDSCAPE_WIDTH,45))

#define ADCHINA_FRAME_AUTO		0

@interface AdViewAdapterAdChinaImpl : SingletonAdapterBase <AdChinaBannerViewDelegate> {
}
- (NSString *)adSpaceId;

@end

static AdViewAdapterAdChinaImpl *gAdChinaImpl = nil;

@implementation AdViewAdapterAdChina

+ (AdViewAdNetworkType)networkType {
    return AdViewAdNetworkTypeADCHINA;
}

+ (void)load {
	if(NSClassFromString(@"AdChinaBannerView") != nil) {
		[[AdViewAdNetworkRegistry sharedBannerRegistry] registerClass:self];
	}
}

- (void)getAd {
	if (nil == gAdChinaImpl)
		gAdChinaImpl = [[AdViewAdapterAdChinaImpl alloc] init];
	mDelegate = gAdChinaImpl;
	[mDelegate setAdapterValue:YES ByAdapter:self];

	AdChinaBannerView *adView = (AdChinaBannerView*)[mDelegate getIdelAdView];
	if (nil == adView) {
		[adViewView adapter:self didFailAd:nil];
		return;
	}

	[adView setAnimationMask:AnimationMaskNone];
	[adView setRefreshInterval:DisableRefresh];

#if ADCHINA_FRAME_AUTO
	UIDeviceOrientation orientation;
	if ([self.adViewDelegate respondsToSelector:@selector(adViewCurrentOrientation)]) {
		orientation = [self.adViewDelegate adViewCurrentOrientation];
	}
	else {
		orientation = [UIDevice currentDevice].orientation;
	}

	if (UIDeviceOrientationIsLandscape(orientation)) {
		[adView setAdFrame:KADCHINA_LANDSCAPE_FRAME];
	} else {
		[adView setAdFrame:KADCHINA_DETAULT_FRAME];
	}
#else
    CGRect r = adView.frame;
    r.origin = CGPointMake(0, 0);
	r.size = self.sSizeAd;
    adView.frame = r;
#endif

	self.adNetworkView = adView;
}

- (BOOL)canMultiBeingDelegate {
    return NO;
}

- (BOOL)shouldSendExMetric {
    return NO;
}

- (void)stopBeingDelegate {
    AdChinaBannerView *adView = (AdChinaBannerView *)self.adNetworkView;
	AWLogInfo(@"--AdChina stopBeingDelegate--");
    if (adView != nil) {
#if 0
        [mDelegate addIdelAdChinaView:adView];
#else
        //to test if adchina view can be alloced and released. if fail, should resue.
        self.adNetworkView = nil;
#endif
        [mDelegate setAdapterValue:NO ByAdapter:self];
        [adView setViewControllerForBrowser:nil];
        self.adNetworkView = nil;
    }
	mDelegate = nil;
}

- (void)updateSizeParameter {
    /*
     * auto for iphone, auto for ipad,
     * 320x50, 300x250,
     * 480x60, 728x90
     */
    CGSize sizeArr[] = {BannerSizeDefault,BannerSizeDefault,
        CGSizeMake(320, 48),BannerSizeSquare,
        BannerSizeVideo,BannerSizeDefault};

    [self setSizeParameter:nil size:sizeArr];
}

#if ADCHINA_FRAME_AUTO
- (void)rotateToOrientation:(UIInterfaceOrientation)orientation {
	AdChinaView *adView = (AdChinaView *)self.adNetworkView;
	if (adView == nil) return;
	if (UIDeviceOrientationIsLandscape(orientation)) {
		[adView setAdFrame:KADCHINA_LANDSCAPE_FRAME];
	} else {
		[adView setAdFrame:KADCHINA_DETAULT_FRAME];
	}
}
#endif

- (void)dealloc {

}

@end

@implementation AdViewAdapterAdChinaImpl

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return NO;
}

- (UIView*)makeAdView {
	AdChinaBannerView	*ret;

    Class adChinaViewClass = NSClassFromString (@"AdChinaBannerView");
    Class adChinaLocationClass = NSClassFromString(@"AdChinaLocationManager");
    [adChinaLocationClass setLocationServiceEnabled:[mAdapter helperUseGpsMode]];
    if (0 == adChinaViewClass) {
        AWLogInfo(@"no adchina lib, can not create.");
        return nil;
    }
    [mAdapter updateSizeParameter];
    ret = [adChinaViewClass requestAdWithAdSpaceId:[self adSpaceId] delegate:self
                                             adSize:mAdapter.sSizeAd];
    [ret setViewControllerForBrowser:[mAdapter.adViewDelegate viewControllerForPresentingModalView]];

	return ret;
}

- (void)dealloc {
}

#pragma mark AdChinaDelegate methods

/**
 *	Be sure to return the id you get from AdChina
 */
- (NSString *)adSpaceId {
	NSString *appID = @"";

	if ([mAdapter.adViewDelegate respondsToSelector:@selector(adChinaApIDString)]) {
		appID = [mAdapter.adViewDelegate adChinaApIDString];
	}
	else {
		appID = mAdapter.networkConfig.pubId;
	}
	return appID;
	//return @"69329";
}

- (void)didReceiveAd:(AdChinaBannerView *)adView {
    if (nil != adView) {
		AWLogInfo(@"AdChina: Did receive ad:%@", NSStringFromCGSize(adView.frame.size));
    }

	if (![self isAdViewValid:adView]) return;

	[mAdapter.adViewView adapter:mAdapter didReceiveAdView:adView];

    [mAdapter.adViewView adapter:mAdapter shouldReport:adView DisplayOrClick:YES];
    AWLogInfo(@"AdChina: Did show banner");
}

//- (void)didGetBanner:(AdChinaBannerView *)adView {
//	if (nil != adView) {
//		AWLogInfo(@"AdChina: Did receive ad:%@", NSStringFromCGSize(adView.frame.size));
//    }
//
//	if (![self isAdViewValid:adView]) return;
//
//	[mAdapter.adViewView adapter:mAdapter didReceiveAdView:adView];
//}

- (void)didFailedToReceiveAd:(AdChinaBannerView *)adView {
    AWLogInfo(@"AdChina: Failed to receive ad");

	if (![self isAdViewValid:adView]) return;

	[mAdapter.adViewView adapter:mAdapter didFailAd:nil];
}

//- (void)didFailToGetBanner:(AdChinaBannerView *)adView
//{
//	AWLogInfo(@"AdChina: Failed to receive ad");
//
//	if (![self isAdViewValid:adView]) return;
//
//	[mAdapter.adViewView adapter:mAdapter didFailAd:nil];
//}

- (void)didEnterFullScreenMode
{
	[mAdapter helperNotifyDelegateOfFullScreenModal];
	AWLogInfo(@"AdChina: Did click on an ad");
}

- (void)didExitFullScreenMode
{
	[mAdapter helperNotifyDelegateOfFullScreenModalDismissal];
	AWLogInfo(@"AdChina: Did back from ad web");
}

- (void)didClickBanner:(AdChinaBannerView *)adView {
    [mAdapter.adViewView adapter:mAdapter shouldReport:adView DisplayOrClick:NO];
    AWLogInfo(@"AdChina: Did click banner");
}

- (NSString *)phoneNumber
{
	return @"";		// return user's phone number if possible
}

- (Sex)gender
{
	return SexUnknown;		// return user's gender if possible
}

- (NSString *)postalCode
{
	return @"";		// return user's postcode if possible
}

- (NSString *)dateOfBirth
{
	return @"";		// return user's birthday if possible
}

@end


text:
// vim: softtabstop=2 tabstop=2 tw=120

#ifndef FIXED_LENGTH_STRING_H
#define FIXED_LENGTH_STRING_H

#include <Arduino.h>

#include "settings.h"

class FixedLengthString {
  public:

    FixedLengthString(char* buffer, size_t size);

    size_t Length() const;

    operator const char*() const;

    bool Add(char character);

    FixedLengthString& Clear();

    size_t MaxLength();

  private:

    FixedLengthString(const FixedLengthString&);
    FixedLengthString& operator =(const FixedLengthString&);

    char* buffer;
    size_t max_len;
    size_t len;
};

template<unsigned int M> class AllocatedFixedLengthString : public FixedLengthString {
  public:

    AllocatedFixedLengthString() : FixedLengthString(buffer, M + 1) {}

  private:

    char buffer[M + 1];
};

#endif // FIXED_LENGTH_STRING_H


text:
<phpunit bootstrap="bootstrap.php">
    <testsuites>
        <testsuite name="RayGunolog">
            <directory>MeadSteve/RayGunolog</directory>
        </testsuite>
    </testsuites>
</phpunit>


text:
{-# LANGUAGE PatternSynonyms #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Fun.PrettyPrinter (singleLine) where

import ClassyPrelude
import Numeric                      (showHex, showOct)
import Text.PrettyPrint.Leijen.Text (Doc, Pretty, displayTStrict, double, dquotes, integer, parens,
                                     pretty, renderOneLine, sep, squotes, textStrict)

import Fun.SExpression (Atom (..), Expression (..), Literal (..))

singleLine :: Expression -> Text
singleLine x = displayTStrict . renderOneLine $ pprint x
-- displayTStrict . renderPretty 0.6 100 <$> pprint x

pprint :: Expression -> Doc
pprint (List xs _)            = parens . sep $ pprint <$> xs
pprint (Atom (Ident s) _)     = textStrict s
pprint (Atom (Keyword s) _)   = textStrict s
pprint (Atom (Type s) _)      = textStrict (":" <> s)
pprint (Atom (Operator s) _)  = textStrict s
pprint (Atom (Literal lit) _) = pretty lit

instance Pretty Literal where
    pretty (String x)     = dquotes . textStrict $ x
    pretty (Char x)       = squotes . textStrict $ x
    pretty (Integer 16 x) = textStrict . pack $ "0x" <> showHex x ""
    pretty (Integer 8 x)  = textStrict . pack $ "0"  <> showOct x ""
    pretty (Integer _ x)  = integer x -- 10 or 0 are supported
    pretty (Double x)     = double x
    pretty (Bool True)    = textStrict "true"
    pretty (Bool False)   = textStrict "false"


text:
This repository includes the following example scripts:

* **[MLP](https://github.com/snap-stanford/ogb/blob/master/examples/nodeproppred/arxiv/mlp.py)**: Full-batch MLP training based on paper features and optional Node2Vec features (`--use_node_embedding`). For training with Node2Vec features, this script requires node embeddings be saved in `embedding.pt`. To generate them, please run `python node2vec.py` [requires `torch-geometric>=1.5.0`].
* **[GNN](https://github.com/snap-stanford/ogb/blob/master/examples/nodeproppred/arxiv/gnn.py)**: Full-batch GNN training using either the GCN or GraphSAGE operator (`--use_sage`) [requires `torch-geometric>=1.6.0`].

## Training & Evaluation

```
# Run with default config
python gnn.py

# Run with custom config
python gnn.py --hidden_channels=128
```

## Getting Raw Texts

The tsv file that maps paper IDs into their titles and abstracts are available [here](https://snap.stanford.edu/ogb/data/misc/ogbn_arxiv/titleabs.tsv.gz).
There are three columns: paperid \t title \t abstract.
You can obtain the paper ID for each node at `mapping/nodeidx2paperid.csv.gz` of the downloaded dataset directory.


text:
package com.shcem.trace;

import com.github.kristofa.brave.*;
import com.shcem.constants.SystemDefine;
import com.shcem.util.TraceReporter;
import com.shcem.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zipkin.Span;
import zipkin.reporter.AsyncReporter;

public class BraveGenerator {

	private Logger logger= LoggerFactory.getLogger(BraveGenerator.class.getName());
	private Brave brave = null;
	private ServerRequestInterceptor serverRequestInterceptor = null;
	private ServerResponseInterceptor serverResponseInterceptor = null;
	private ClientRequestInterceptor clientRequestInterceptor = null;
	private ClientResponseInterceptor clientResponseInterceptor = null;

	/**
	 * 取得Brave
	 */
	public BraveGenerator(String serviceName, String mode, TraceReporter reporter) {

		String[] spSvcName = serviceName.split("\\.");
		String svcName = spSvcName[spSvcName.length - 1];

		AsyncReporter<Span> report = reporter.getReport(mode);

		if (report == null) {
			logger.debug("Trace Reporter is null, please restart web app server!");
			return;
		}

		Sampler.create((float) 1.0);
		brave = new Brave.Builder(svcName).reporter(report).traceSampler(Sampler.ALWAYS_SAMPLE).build();

		serverRequestInterceptor = brave.serverRequestInterceptor();
		serverResponseInterceptor = brave.serverResponseInterceptor();
		clientRequestInterceptor = brave.clientRequestInterceptor();
		clientResponseInterceptor = brave.clientResponseInterceptor();
	}

	/**
	 * send Trace
	 */
	public SpanId sendTrace(String mode, String differ, long traceId, long spanId, long parentId, String methodName,
			String serviceName, String requestId, String content, String spanName, String clientSpanName) {

		if (!SystemDefine.MODE_UAT.equals(mode) && !SystemDefine.MODE_DEPLOY.equals(mode)) {

			// send trace only in uat and deploy
			return null;
		}

		if (brave == null) {
			return null;
		}

		if (!SystemDefine.TRACELOG_TYPE_S.equals(differ) && !SystemDefine.TRACELOG_TYPE_R.equals(differ)
				&& !SystemDefine.TRACELOG_TYPE_S_CLIENT.equals(differ) && !SystemDefine.TRACELOG_TYPE_R_CLIENT.equals(differ)
				&& !SystemDefine.TRACELOG_TYPE_S_SERVER.equals(differ)
				&& !SystemDefine.TRACELOG_TYPE_R_SERVER.equals(differ)) {
			// Do nothing
			return null;
		}

		if (StringUtils.isEmpty(methodName)) {
			// Do nothing
			return null;
		}

		SpanId spanIdObj = null;

		// send trace
		if (SystemDefine.TRACELOG_TYPE_S.equals(differ)) {

			/**
			 * 发送服务端和客户端
			 */
			serverRequestInterceptor.handle(
					new ServerRequestAdapterImpl(spanName, serviceName, traceId, spanId, parentId, requestId, content));

			ClientRequestAdapterImpl clientRequestAdapterImpl = new ClientRequestAdapterImpl(clientSpanName,
					serviceName, requestId, content);
			clientRequestInterceptor.handle(clientRequestAdapterImpl);

			spanIdObj = clientRequestAdapterImpl.getSpanId();
		} else if (SystemDefine.TRACELOG_TYPE_S_SERVER.equals(differ)) {

			/**
			 * 仅发送服务端
			 */
			serverRequestInterceptor.handle(
					new ServerRequestAdapterImpl(spanName, serviceName, traceId, spanId, parentId, requestId, content));
		} else if (SystemDefine.TRACELOG_TYPE_S_CLIENT.equals(differ)) {

			/**
			 * 仅发送客户端
			 */
			ClientRequestAdapterImpl clientRequestAdapterImpl = new ClientRequestAdapterImpl(clientSpanName,
					serviceName, requestId, content);
			clientRequestInterceptor.handle(clientRequestAdapterImpl);

			spanIdObj = clientRequestAdapterImpl.getSpanId();
		} else if (SystemDefine.TRACELOG_TYPE_R_CLIENT.equals(differ)) {

			/**
			 * 仅接收客户端
			 */
			clientResponseInterceptor.handle(new ClientResponseAdapterImpl(serviceName, requestId, content));
		} else if (SystemDefine.TRACELOG_TYPE_R_SERVER.equals(differ)) {

			/**
			 * 仅接收服务端
			 */
			serverResponseInterceptor.handle(new ServerResponseAdapterImpl(serviceName, requestId, content));
		} else if (SystemDefine.TRACELOG_TYPE_R.equals(differ)) {

			/**
			 * 接受客户端和服务端
			 */
			clientResponseInterceptor.handle(new ClientResponseAdapterImpl(serviceName, requestId, content));
			serverResponseInterceptor.handle(new ServerResponseAdapterImpl(serviceName, requestId, content));
		}

		return spanIdObj;
	}
}


text:
#ifndef MOQIANG_H
#define MOQIANG_H
#include "Role.h"
class MoQiang : public Role
{
    Q_OBJECT
public:
    MoQiang();
    void normal();
    void AnZhiJieFang();
    void HuanYingXingChen();
	void attacked(QString element, int hitRate,int cardId,bool canLight);
	void moDaned(int nextID,int sourceID, int howMany);
    void AnZhiBiZhang();
    void QiHeiZhiQiang();
    void turnBegin();
    void askForSkill(Command* cmd);
	//void attackAction();

public slots:
    void ChongYing();
    void onOkClicked();
    void onCancelClicked();
    void cardAnalyse();
    void playerAnalyse();
private:
    bool jieFangUsed;     //for【充盈】button
    bool jieFangFirst;
	bool usingChongYing;
};

#endif // MOQIANG_H


text:
using Solid.Bootstrapping;
using Solid.Practices.IoC;
using Solid.Practices.Middleware;

// ReSharper disable once CheckNamespace
namespace Attest.Testing.Context.NUnit
{
    /// <summary>
    /// This middleware registers dependencies for using <see cref="IKeyValueDataStore"/>.
    /// </summary>
    /// <typeparam name="TBootstrapper">The type of the bootstrapper.</typeparam>
    public class UseKeyValueDataStoreMiddleware<TBootstrapper> : IMiddleware<TBootstrapper>
        where TBootstrapper : class, IHaveRegistrator
    {
        /// <inheritdoc />
        public TBootstrapper Apply(TBootstrapper @object)
        {
            @object.Registrator.AddSingleton<IKeyValueDataStore, TestContextKeyValueDataStoreAdapter>();
            return @object;
        }
    }
}


text:
<?php

namespace Coast\Validator\Rule;

use Coast\Validator\Rule;

class Set extends Rule
{
	protected function _validate($value)
	{
		if (!isset($value)) {
			$this->error();
		}
	}
}


text:
using MeTLLib.Providers;
namespace MeTLLib.Providers.Structure
{
    class ConversationDetailsProviderFactory
    {
        private static object instanceLock = new object();
        private static IConversationDetailsProvider instance;
        public static IConversationDetailsProvider Provider{
            get {
                lock(instanceLock){
                    if (instance == null)
                        instance = new FileConversationDetailsProvider();
                    return instance;
                }
            }
        }
    }
}


text:
<?php

require_once "../app/init.php";
$route = new Route();


text:
topic: "Github: Setup"
desc: "Creating your account"
---

For SPIS, you'll need an account at github.com.

To create your account, visit <http://github.com> and sign up.

We encourage you to use your @ucsd.edu email address (or if you already have
a github.com account, to add your @ucsd.edu address.)

Github now provides free access to unlimited public repos to everyone.

With an educational discount, you may be able to have access to create
unlimited number of private repos.   Apply for that at
http://education.github.com

You can also create private repos under the ucsd-cse-spis-2016 organization
at no charge.  You should *never* need to add a credit card to your github
account for any SPIS related activity. If you get asked for one, there is
either a mistake in the instructions, or you may have missed something :-)


text:
var Benchmark = require('benchmark');
var oldTerror = require('terror');
var newTerror = require('../lib/terror');

var MSG = 'Error %value%';
var DATA = {
    value: 'message'
};

var MyOldError = oldTerror.create('MyOldError', {
    MY: MSG
});

var MyNewError = newTerror.create('MyNewError', {
    MY: MSG
});

var suits = [{
    name: 'new Terror(null, message)',
    Old: function () {
        new oldTerror(null, MSG);
    },
    New: function () {
        new newTerror(null, MSG);
    }
}, {
    name: 'Terror.createError(null, message)',
    Old: function () {
        oldTerror.createError(null, MSG);
    },
    New: function () {
        newTerror.createError(null, MSG);
    }
}, {
    name: 'Terror.ensureError(error)',
    Old: function () {
        oldTerror.ensureError(new Error(MSG));
    },
    New: function () {
        newTerror.ensureError(new Error(MSG));
    }
}, {
    name: 'new MyError(null, message)',
    Old: function () {
        new MyOldError(null, MSG);
    },
    New: function () {
        new MyNewError(null, MSG);
    }
}, {
    name: 'MyError.createError(null, message)',
    Old: function () {
        MyOldError.createError(null, MSG);
    },
    New: function () {
        MyNewError.createError(null, MSG);
    }
}, {
    name: 'MyError.createError(code, data)',
    Old: function () {
        MyOldError.createError(MyOldError.CODES.MY, DATA);
    },
    New: function () {
        MyNewError.createError(MyNewError.CODES.MY, DATA);
    }
}, {
    name: 'MyError.ensureError(error, code)',
    Old: function () {
        MyOldError.ensureError(MSG, MyNewError.CODES.MY);
    },
    New: function () {
        MyNewError.createError(MSG, MyNewError.CODES.MY);
    }
}];

function onComplete() {
    console.log('\tFastest is "' + this.filter('fastest').pluck('name') + '"\n');
}

function onStart() {
    console.log(this.name + ':');
}

function onCycle(event) {
    console.log('\t' + String(event.target));
}

var length = suits.length;
var index = 0;

while (index < length) {
    var suit = suits[index++];

    new Benchmark.Suite(suit.name)
        .add('Old', suit.Old)
        .add('New', suit.New)
        .on('start', onStart)
        .on('cycle', onCycle)
        .on('complete', onComplete)
        .run();
}


text:
multiping
====

Command-line utility to setup/conduct/cleanup many-to-many ping environments.

### Description

This ruby script help you to create a lot of IP assigned vlan virtual interfaces and fire pings from/to them. (Two linux hosts may be used as src/dst nodes.)

One line issue of this may relieve you so much to test network reachabilities for many vlan domain.

Log files for each ping source is automatically saved in a directory. You can specify any direction for this purpose with an option.

### Requirement

 - Ruby later than 1.9
    - Developped and tested with ruby 1.9.3p194 on 3.18.0-kali3-amd64
    - No non-standard library is required

 - Open-vSwitch 1.4.2 or later

 - fping
    - Developped and tested with version 3.2 on 3.18.0-kali3-amd64
    - The path to fping executable must exist

 - Linux whose kernel supports network namespace function

### Usage

command-line syntax is like below.

    usage : multping command [command_opts] [command_args]

    [commands]
      add : create svi(s) for each vlans specified with "-v" option
            also assign ip-addr and configure default route

      del : delete existing svi(s)

      ping : start ping and save their logs
             default ping mode is l2(layer2)
             you can switch it to layer3 pinging with "--l3" switch option

      help : displays this "usage"

    [command_options]
      -v vlans... : vlans you want to create a coressponding svi
                    both cisco-like range format and ruby-like range format are accepted
                    (used w/ add command)
      -b bridge_name : bridge name to which svi(s) would be attached
                       (used w/ add command)
                       default is vbr0
      -a assigned_addr : ip address of host section that would be assigned to svi(s)
                         default=1 (meaning x.x.x.1)
                         (used w/ add command)
      -t target_addr : ip address of host section to which ping is fired
                       default=2 (meaning y.y.y.2)
                       (used w/ ping command)
      -x exclude_vlans... : exclude specified vlans from l3 ping targets
                            (used w/ ping command, l3 mode)
      -s specified_vlans... : specify vlans mannually to which ping is fired
                              (used /w ping command, l3 mode)
      -l log_dir : a name of director in which ping logs would be saved
                   default=./pinglog.d
                   (used w/ ping command)
      -T : switch that decide whether time-stamp are appeded to log_dir's name
           defalt=false
           (used w/ ping command)
      --l3 : switch the mode of pinging from l2 ping to l3 ping
             (used w/ ping command)

Logging directory would be created like the hierarchy below.

    multiping ping -l logdir -T

    (Conducting ping..... ,and finish.)

    logdir_20150514_163033/
        logdir_20150514_163033/svi.711.log
        logdir_20150514_163033/svi.712.log

### Tutorial

 - Layer-2 Ping

![layer2_ping](./.figures/fig_tutol_l2.png)

 - Layer-3 Ping

![layer3_ping](./.figures/fig_tutol_l3.png)

### Licence

MIT (https://github.com/YohKmb/nwutils/blob/master/LICENSE)

### Author

Yoh Kamibayashi (https://github.com/YohKmb)


text:
package org.apache.jena.arq;

import static org.junit.Assert.fail;

import java.util.Arrays;
import java.util.regex.Pattern;

import org.apache.jena.JenaRuntime ;

public abstract class AbstractRegexpBasedTest {
	protected static final String SPACE = "\\s+";
	protected static final String OPT_SPACE = "\\s*";
	protected static final String WHERE = "WHERE" + SPACE;
	protected static final String OPEN_CURLY = "\\{" + OPT_SPACE;
	protected static final String CLOSE_CURLY = OPT_SPACE + "\\}";
	protected static final String OPEN_PAREN = "\\(" + OPT_SPACE;
	protected static final String CLOSE_PAREN = OPT_SPACE + "\\)";
	protected static final String QUOTE = "\\\"";
	protected static final String LT = "\\<";
	protected static final String GT = "\\>";
	protected static final String EQ = "=";
	protected static final String DOT = OPT_SPACE+"\\.";
	protected static final String ORDER_BY = "ORDER" + SPACE + "BY" + SPACE;
	protected static final String GROUP_BY = "GROUP" + SPACE + "BY" + SPACE;
	protected static final String HAVING = "HAVING" + SPACE;
	protected static final String PREFIX = "PREFIX" + SPACE;
	protected static final String SELECT = "SELECT" + SPACE;
	protected static final String UNION = "UNION" + SPACE;
	protected static final String LIMIT = "LIMIT" + SPACE;
	protected static final String OFFSET = "OFFSET" + SPACE;
	protected static final String OPTIONAL = "OPTIONAL" + SPACE;
	protected static final String BIND = "BIND";
	protected static final String SEMI = OPT_SPACE+"\\;";

	protected static String quote(String s) {
		return String.format("%s%s%s", QUOTE, s, QUOTE);
	}

	protected static String uri(String s) {
		return String.format("%s%s%s", LT, s, GT);
	}

	/** Regex for rdf:type as a URI or the abbreviation 'a' */
	protected static String regexRDFtype = "("+uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")+"|a)" ;

	protected final String var(String s) {
		return "\\?" + s;
	}

	/** Match the type of a xsd:string typed term.
	 * RDF 1.0 : use ^^xsd:string form.
	 * RDF 1.1 : use untyped form.
	 */
	protected final String presentStringType() {
	    return
	        JenaRuntime.isRDF11 ? "" : "\\^\\^\\<http://www.w3.org/2001/XMLSchema#string\\>" ;
	}

	protected final void assertNotContainsRegex(String expected, String lst) {

		Pattern patt = Pattern.compile(expected, Pattern.DOTALL);

		if (patt.matcher(lst).find()) {
			fail(String.format("%s was found in %s", expected, lst));
		}
	}

	protected final void assertContainsRegex(String expected, String entry) {

		Pattern patt = Pattern.compile(expected, Pattern.DOTALL);
		if (patt.matcher(entry).find()) {
			return;
		}
		fail(String.format("%s not found in %s", expected, entry));
	}

	protected final void assertNotContainsRegex(String expected, String[] lst) {

		Pattern patt = Pattern.compile(expected, Pattern.DOTALL);
		for (String s : lst) {
			if (patt.matcher(s).find()) {
				fail(String.format("%s was found in %s", expected,
						Arrays.asList(lst)));
			}
		}
	}

	protected final void assertContainsRegex(String expected, String[] lst) {
		Pattern patt = Pattern.compile(expected, Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
		for (String s : lst) {
			if (patt.matcher(s).find()) {
				return;
			}
		}
		fail(String.format("%s not found in %s", expected, Arrays.asList(lst)));
	}

}