text:
package org.apache.cassandra.metrics;

import java.util.concurrent.TimeUnit;

import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.*;
import com.yammer.metrics.util.RatioGauge;

import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.io.sstable.SSTableReader;
import org.apache.cassandra.io.sstable.metadata.MetadataCollector;
import org.apache.cassandra.utils.EstimatedHistogram;

/**
 * Metrics for {@link ColumnFamilyStore}.
 */
public class ColumnFamilyMetrics
{
    /** Total amount of data stored in the memtable that resides on-heap, including column related overhead and overwritten rows. */
    public final Gauge<Long> memtableHeapSize;
    /** Total amount of live data stored in the memtable, excluding any data structure overhead */
    public final Gauge<Long> memtableLiveDataSize;
    /** Total amount of data stored in the memtables (2i and pending flush memtables included) that resides on-heap. */
    public final Gauge<Long> allMemtablesHeapSize;
    /** Total amount of live data stored in the memtables (2i and pending flush memtables included) that resides off-heap, excluding any data structure overhead */
    public final Gauge<Long> allMemtablesLiveDataSize;
    /** Total number of columns present in the memtable. */
    public final Gauge<Long> memtableColumnsCount;
    /** Number of times flush has resulted in the memtable being switched out. */
    public final Counter memtableSwitchCount;
    /** Current compression ratio for all SSTables */
    public final Gauge<Double> compressionRatio;
    /** Histogram of estimated row size (in bytes). */
    public final Gauge<long[]> estimatedRowSizeHistogram;
    /** Histogram of estimated number of columns. */
    public final Gauge<long[]> estimatedColumnCountHistogram;
    /** Histogram of the number of sstable data files accessed per read */
    public final Histogram sstablesPerReadHistogram;
    /** (Local) read metrics */
    public final LatencyMetrics readLatency;
    /** (Local) write metrics */
    public final LatencyMetrics writeLatency;
    /** Estimated number of tasks pending for this column family */
    public final Counter pendingFlushes;
    /** Number of SSTables on disk for this CF */
    public final Gauge<Integer> liveSSTableCount;
    /** Disk space used by SSTables belonging to this CF */
    public final Counter liveDiskSpaceUsed;
    /** Total disk space used by SSTables belonging to this CF, including obsolete ones waiting to be GC'd */
    public final Counter totalDiskSpaceUsed;
    /** Size of the smallest compacted row */
    public final Gauge<Long> minRowSize;
    /** Size of the largest compacted row */
    public final Gauge<Long> maxRowSize;
    /** Size of the smallest compacted row */
    public final Gauge<Long> meanRowSize;
    /** Number of false positives in bloom filter */
    public final Gauge<Long> bloomFilterFalsePositives;
    /** Number of false positives in bloom filter from last read */
    public final Gauge<Long> recentBloomFilterFalsePositives;
    /** False positive ratio of bloom filter */
    public final Gauge<Double> bloomFilterFalseRatio;
    /** False positive ratio of bloom filter from last read */
    public final Gauge<Double> recentBloomFilterFalseRatio;
    /** Disk space used by bloom filter */
    public final Gauge<Long> bloomFilterDiskSpaceUsed;
    /** Key cache hit rate  for this CF */
    public final Gauge<Double> keyCacheHitRate;
    /** Tombstones scanned in queries on this CF */
    public final Histogram tombstoneScannedHistogram;
    /** Live cells scanned in queries on this CF */
    public final Histogram liveScannedHistogram;
    /** Disk space used by snapshot files which */
    public final Gauge<Long> trueSnapshotsSize;

    public final Timer coordinatorReadLatency;
    public final Timer coordinatorScanLatency;

    /** Time spent waiting for free memtable space, either on- or off-heap */
    public final Timer waitingOnFreeMemtableSpace;

    private final MetricNameFactory factory;

    public final Counter speculativeRetries;

    // for backward compatibility
    @Deprecated public final EstimatedHistogram sstablesPerRead = new EstimatedHistogram(35);
    @Deprecated public final EstimatedHistogram recentSSTablesPerRead = new EstimatedHistogram(35);

    /**
     * Creates metrics for given {@link ColumnFamilyStore}.
     *
     * @param cfs ColumnFamilyStore to measure metrics
     */
    public ColumnFamilyMetrics(final ColumnFamilyStore cfs)
    {
        factory = new ColumnFamilyMetricNameFactory(cfs);

        memtableColumnsCount = Metrics.newGauge(factory.createMetricName("MemtableColumnsCount"), new Gauge<Long>()
        {
            public Long value()
            {
                return cfs.getDataTracker().getView().getCurrentMemtable().getOperations();
            }
        });
        memtableHeapSize = Metrics.newGauge(factory.createMetricName("MemtableHeapSize"), new Gauge<Long>()
        {
            public Long value()
            {
                return cfs.getDataTracker().getView().getCurrentMemtable().getAllocator().owns();
            }
        });
        memtableLiveDataSize = Metrics.newGauge(factory.createMetricName("MemtableLiveDataSize"), new Gauge<Long>()
        {
            public Long value()
            {
                return cfs.getDataTracker().getView().getCurrentMemtable().getLiveDataSize();
            }
        });
        allMemtablesHeapSize = Metrics.newGauge(factory.createMetricName("AllMemtablesHeapSize"), new Gauge<Long>()
        {
            public Long value()
            {
                long size = 0;
                for (ColumnFamilyStore cfs2 : cfs.concatWithIndexes())
                    size += cfs2.getDataTracker().getView().getCurrentMemtable().getAllocator().owns();
                return size;
            }
        });
        allMemtablesLiveDataSize = Metrics.newGauge(factory.createMetricName("AllMemtablesLiveDataSize"), new Gauge<Long>()
        {
            public Long value()
            {
                long size = 0;
                for (ColumnFamilyStore cfs2 : cfs.concatWithIndexes())
                    size += cfs2.getDataTracker().getView().getCurrentMemtable().getLiveDataSize();
                return size;
            }
        });
        memtableSwitchCount = Metrics.newCounter(factory.createMetricName("MemtableSwitchCount"));
        estimatedRowSizeHistogram = Metrics.newGauge(factory.createMetricName("EstimatedRowSizeHistogram"), new Gauge<long[]>()
        {
            public long[] value()
            {
                long[] histogram = new long[90];
                for (SSTableReader sstable : cfs.getSSTables())
                {
                    long[] rowSize = sstable.getEstimatedRowSize().getBuckets(false);
                    for (int i = 0; i < histogram.length; i++)
                        histogram[i] += rowSize[i];
                }
                return histogram;
            }
        });
        estimatedColumnCountHistogram = Metrics.newGauge(factory.createMetricName("EstimatedColumnCountHistogram"), new Gauge<long[]>()
        {
            public long[] value()
            {
                long[] histogram = new long[90];
                for (SSTableReader sstable : cfs.getSSTables())
                {
                    long[] columnSize = sstable.getEstimatedColumnCount().getBuckets(false);
                    for (int i = 0; i < histogram.length; i++)
                        histogram[i] += columnSize[i];
                }
                return histogram;
            }
        });
        sstablesPerReadHistogram = Metrics.newHistogram(factory.createMetricName("SSTablesPerReadHistogram"), true);
        compressionRatio = Metrics.newGauge(factory.createMetricName("CompressionRatio"), new Gauge<Double>()
        {
            public Double value()
            {
                double sum = 0;
                int total = 0;
                for (SSTableReader sstable : cfs.getSSTables())
                {
                    if (sstable.getCompressionRatio() != MetadataCollector.NO_COMPRESSION_RATIO)
                    {
                        sum += sstable.getCompressionRatio();
                        total++;
                    }
                }
                return total != 0 ? sum / total : 0;
            }
        });
        readLatency = new LatencyMetrics(factory, "Read");
        writeLatency = new LatencyMetrics(factory, "Write");
        pendingFlushes = Metrics.newCounter(factory.createMetricName("PendingFlushes"));
        liveSSTableCount = Metrics.newGauge(factory.createMetricName("LiveSSTableCount"), new Gauge<Integer>()
        {
            public Integer value()
            {
                return cfs.getDataTracker().getSSTables().size();
            }
        });
        liveDiskSpaceUsed = Metrics.newCounter(factory.createMetricName("LiveDiskSpaceUsed"));
        totalDiskSpaceUsed = Metrics.newCounter(factory.createMetricName("TotalDiskSpaceUsed"));
        minRowSize = Metrics.newGauge(factory.createMetricName("MinRowSize"), new Gauge<Long>()
        {
            public Long value()
            {
                long min = 0;
                for (SSTableReader sstable : cfs.getSSTables())
                {
                    if (min == 0 || sstable.getEstimatedRowSize().min() < min)
                        min = sstable.getEstimatedRowSize().min();
                }
                return min;
            }
        });
        maxRowSize = Metrics.newGauge(factory.createMetricName("MaxRowSize"), new Gauge<Long>()
        {
            public Long value()
            {
                long max = 0;
                for (SSTableReader sstable : cfs.getSSTables())
                {
                    if (sstable.getEstimatedRowSize().max() > max)
                        max = sstable.getEstimatedRowSize().max();
                }
                return max;
            }
        });
        meanRowSize = Metrics.newGauge(factory.createMetricName("MeanRowSize"), new Gauge<Long>()
        {
            public Long value()
            {
                long sum = 0;
                long count = 0;
                for (SSTableReader sstable : cfs.getSSTables())
                {
                    sum += sstable.getEstimatedRowSize().mean();
                    count++;
                }
                return count > 0 ? sum / count : 0;
            }
        });
        bloomFilterFalsePositives = Metrics.newGauge(factory.createMetricName("BloomFilterFalsePositives"), new Gauge<Long>()
        {
            public Long value()
            {
                long count = 0L;
                for (SSTableReader sstable: cfs.getSSTables())
                    count += sstable.getBloomFilterFalsePositiveCount();
                return count;
            }
        });
        recentBloomFilterFalsePositives = Metrics.newGauge(factory.createMetricName("RecentBloomFilterFalsePositives"), new Gauge<Long>()
        {
            public Long value()
            {
                long count = 0L;
                for (SSTableReader sstable : cfs.getSSTables())
                    count += sstable.getRecentBloomFilterFalsePositiveCount();
                return count;
            }
        });
        bloomFilterFalseRatio = Metrics.newGauge(factory.createMetricName("BloomFilterFalseRatio"), new Gauge<Double>()
        {
            public Double value()
            {
                long falseCount = 0L;
                long trueCount = 0L;
                for (SSTableReader sstable : cfs.getSSTables())
                {
                    falseCount += sstable.getBloomFilterFalsePositiveCount();
                    trueCount += sstable.getBloomFilterTruePositiveCount();
                }
                if (falseCount == 0L && trueCount == 0L)
                    return 0d;
                return (double) falseCount / (trueCount + falseCount);
            }
        });
        recentBloomFilterFalseRatio = Metrics.newGauge(factory.createMetricName("RecentBloomFilterFalseRatio"), new Gauge<Double>()
        {
            public Double value()
            {
                long falseCount = 0L;
                long trueCount = 0L;
                for (SSTableReader sstable: cfs.getSSTables())
                {
                    falseCount += sstable.getRecentBloomFilterFalsePositiveCount();
                    trueCount += sstable.getRecentBloomFilterTruePositiveCount();
                }
                if (falseCount == 0L && trueCount == 0L)
                    return 0d;
                return (double) falseCount / (trueCount + falseCount);
            }
        });
        bloomFilterDiskSpaceUsed = Metrics.newGauge(factory.createMetricName("BloomFilterDiskSpaceUsed"), new Gauge<Long>()
        {
            public Long value()
            {
                long total = 0;
                for (SSTableReader sst : cfs.getSSTables())
                    total += sst.getBloomFilterSerializedSize();
                return total;
            }
        });
        speculativeRetries = Metrics.newCounter(factory.createMetricName("SpeculativeRetries"));
        keyCacheHitRate = Metrics.newGauge(factory.createMetricName("KeyCacheHitRate"), new RatioGauge()
        {
            protected double getNumerator()
            {
                long hits = 0L;
                for (SSTableReader sstable : cfs.getSSTables())
                    hits += sstable.getKeyCacheHit();
                return hits;
            }

            protected double getDenominator()
            {
                long requests = 0L;
                for (SSTableReader sstable : cfs.getSSTables())
                    requests += sstable.getKeyCacheRequest();
                return Math.max(requests, 1); // to avoid NaN.
            }
        });
        tombstoneScannedHistogram = Metrics.newHistogram(factory.createMetricName("TombstoneScannedHistogram"), true);
        liveScannedHistogram = Metrics.newHistogram(factory.createMetricName("LiveScannedHistogram"), true);
        coordinatorReadLatency = Metrics.newTimer(factory.createMetricName("CoordinatorReadLatency"), TimeUnit.MICROSECONDS, TimeUnit.SECONDS);
        coordinatorScanLatency = Metrics.newTimer(factory.createMetricName("CoordinatorScanLatency"), TimeUnit.MICROSECONDS, TimeUnit.SECONDS);
        waitingOnFreeMemtableSpace = Metrics.newTimer(factory.createMetricName("WaitingOnFreeMemtableSpace"), TimeUnit.MICROSECONDS, TimeUnit.SECONDS);

        trueSnapshotsSize = Metrics.newGauge(factory.createMetricName("SnapshotsSize"), new Gauge<Long>()
        {
            public Long value()
            {
                return cfs.trueSnapshotsSize();
            }
        });
    }

    public void updateSSTableIterated(int count)
    {
        sstablesPerReadHistogram.update(count);
        recentSSTablesPerRead.add(count);
        sstablesPerRead.add(count);
    }

    /**
     * Release all associated metrics.
     */
    public void release()
    {
        readLatency.release();
        writeLatency.release();
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("AllMemtablesDataSize"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("MemtableColumnsCount"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("MemtableDataSize"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("MemtableSwitchCount"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("CompressionRatio"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("EstimatedRowSizeHistogram"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("EstimatedColumnCountHistogram"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("SSTablesPerReadHistogram"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("PendingTasks"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("LiveSSTableCount"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("LiveDiskSpaceUsed"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("TotalDiskSpaceUsed"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("MinRowSize"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("MaxRowSize"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("MeanRowSize"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("BloomFilterFalsePositives"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("RecentBloomFilterFalsePositives"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("BloomFilterFalseRatio"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("RecentBloomFilterFalseRatio"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("BloomFilterDiskSpaceUsed"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("KeyCacheHitRate"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("SpeculativeRetries"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("TombstoneScannedHistogram"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("LiveScannedHistogram"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("CoordinatorReadLatency"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("CoordinatorScanLatency"));
        Metrics.defaultRegistry().removeMetric(factory.createMetricName("SnapshotsSize"));
    }

    class ColumnFamilyMetricNameFactory implements MetricNameFactory
    {
        private final String keyspaceName;
        private final String columnFamilyName;
        private final boolean isIndex;

        ColumnFamilyMetricNameFactory(ColumnFamilyStore cfs)
        {
            this.keyspaceName = cfs.keyspace.getName();
            this.columnFamilyName = cfs.name;
            isIndex = cfs.isIndex();
        }

        public MetricName createMetricName(String metricName)
        {
            String groupName = ColumnFamilyMetrics.class.getPackage().getName();
            String type = isIndex ? "IndexColumnFamily" : "ColumnFamily";

            StringBuilder mbeanName = new StringBuilder();
            mbeanName.append(groupName).append(":");
            mbeanName.append("type=").append(type);
            mbeanName.append(",keyspace=").append(keyspaceName);
            mbeanName.append(",scope=").append(columnFamilyName);
            mbeanName.append(",name=").append(metricName);

            return new MetricName(groupName, type, metricName, keyspaceName + "." + columnFamilyName, mbeanName.toString());
        }
    }

}


text:
<?php
	//mapImage.php
	//returns an image of the map

	$size 			= (isset($_GET['s'])) ? $_GET['s'] 	: 10;
	$transparency 	= (isset($_GET['t'])) ? $_GET['t'] 	: 10;
	$chanel 		= (isset($_GET['c'])) ? $_GET['c'] 	: 0;
	$automate 		= (isset($_GET['a'])) ? true 		: false;

	//draw the map
	$height = $size;
	$width  = $size;

	if($automate){
		for($i = 0; $i < 131; $i += 10){
			$transparency = ($i > 128) ? 127 : $i;

			//setup the canvas and paint a transparent dark all over it
			$canvas = imagecreatetruecolor($width, $height);
		  	imagesavealpha($canvas, true);
		  	$trans_colour = imagecolorallocatealpha($canvas, $chanel, $chanel, $chanel, $transparency);
		    imagefill($canvas, 0, 0, $trans_colour);

   		 	//output to file
			header('Content-type: image/png');
			$filename = "smoke$transparency.png";
			imagepng($canvas, $filename);
			print $filename;
		}
	} else {
		//setup the canvas and paint a transparent dark all over it
		$canvas = imagecreatetruecolor($width, $height);
	  	imagesavealpha($canvas, true);
	  	$trans_colour = imagecolorallocatealpha($canvas, $chanel, $chanel, $chanel, $transparency);
	    imagefill($canvas, 0, 0, $trans_colour);

   	 	//print to screen
		header('Content-type: image/png');
		imagepng($canvas);
	}
?>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<package format="2">
  <name>grid_map_msgs</name>
  <version>1.7.3</version>
  <description>Definition of the multi-layered grid map message type.</description>
  <maintainer email="mwulf@anybotics.com">Maximilian Wulf</maintainer>
  <maintainer email="ynava@anybotics.com">Yoshua Nava</maintainer>
  <license>BSD</license>
  <url type="website">http://github.com/anybotics/grid_map</url>
  <url type="bugtracker">http://github.com/anybotics/grid_map/issues</url>
  <author email="pfankhauser@anybotics.com">Péter Fankhauser</author>
  <buildtool_depend>catkin</buildtool_depend>
  <depend>roscpp</depend>
  <depend>message_generation</depend>
  <depend>std_msgs</depend>
  <depend>geometry_msgs</depend>
  <exec_depend>message_runtime</exec_depend>
</package>


text:
<?php

function wpapp_validate_paypl_ipn() {

    $wpapp_ipn_validated = true;

    // Reading POSTed data directly from POST causes serialization issues with array data in the POST.
    // Instead, read raw POST data from the input stream.
    $raw_post_data = file_get_contents('php://input');
    $raw_post_array = explode('&', $raw_post_data);
    $myPost = array();
    foreach ($raw_post_array as $keyval) {
        $keyval = explode('=', $keyval);
        if (count($keyval) == 2)
            $myPost[$keyval[0]] = urldecode($keyval[1]);
    }

    // read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
    $req = 'cmd=_notify-validate';
    if (function_exists('get_magic_quotes_gpc')) {
        $get_magic_quotes_exists = true;
    }
    foreach ($myPost as $key => $value) {
        if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
            $value = urlencode(stripslashes($value));
        } else {
            $value = urlencode($value);
        }
        $req .= "&$key=$value";
    }

    // Step 2: POST IPN data back to PayPal to validate
    $ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));

    if (!($res = curl_exec($ch))) {
        // error_log("Got " . curl_error($ch) . " when processing IPN data");
        curl_close($ch);
        exit;
    }
    curl_close($ch);

    // Inspect IPN validation result and act accordingly
    if (strcmp ($res, "VERIFIED") == 0) {
        // The IPN is verified, process it
        $wpapp_ipn_validated = true;
    } else if (strcmp ($res, "INVALID") == 0) {
        // IPN invalid, log for manual investigation
        $wpapp_ipn_validated = false;
    }

    if (!$wpapp_ipn_validated) {
        // IPN validation failed. Email the admin to notify this event.
        $admin_email = get_bloginfo('admin_email');
        $subject = 'IPN validation failed for a payment';
        $body = "This is a notification email from the WP Accept PayPal Payment plugin letting you know that a payment verification failed." .
        "\n\nPlease check your paypal account to make sure you received the correct amount in your account before proceeding" .
        wp_mail($admin_email, $subject, $body);
        exit;
    }
}


text:
ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.acronym 'PuSH'
  inflect.acronym 'OParl'
end


text:
package com.skycloud.api.domain.hostinterface;
import java.util.ArrayList;
import java.util.List;

import com.skycloud.api.domain.base.RequestBase;
public class HostInterfaceExistsRequest extends RequestBase{
	public HostInterfaceExistsRequest() {
		super("hostinterface.exists");
	}
	private HostInterfaceExistsParams params = new HostInterfaceExistsParams();
	public void setParams(HostInterfaceExistsParams params) {
		this.params = params;
	}
	public HostInterfaceExistsParams getParams() {
		return params;
	}
	public static class HostInterfaceExistsParams{
		private List<String> dns;
		private List<String> hostid;
		private List<String> interfaceid;
		private List<String> ip;
		private String node;
		private List<String> nodeids;
		public void setDns(List<String> dns) {
			this.dns = dns;
		}
		public List<String> getDns() {
			 if(dns==null){
				dns   = new ArrayList<String>();
				return dns;
			}
			 return dns;
		}
		public void setHostid(List<String> hostid) {
			this.hostid = hostid;
		}
		public List<String> getHostid() {
			 if(hostid==null){
				hostid   = new ArrayList<String>();
				return hostid;
			}
			 return hostid;
		}
		public void setInterfaceid(List<String> interfaceid) {
			this.interfaceid = interfaceid;
		}
		public List<String> getInterfaceid() {
			 if(interfaceid==null){
				interfaceid   = new ArrayList<String>();
				return interfaceid;
			}
			 return interfaceid;
		}
		public void setIp(List<String> ip) {
			this.ip = ip;
		}
		public List<String> getIp() {
			 if(ip==null){
				ip   = new ArrayList<String>();
				return ip;
			}
			 return ip;
		}
		public void setNode(String node) {
			this.node = node;
		}
		public String getNode() {
			return node;
		}
		public void setNodeids(List<String> nodeids) {
			this.nodeids = nodeids;
		}
		public List<String> getNodeids() {
			 if(nodeids==null){
				nodeids   = new ArrayList<String>();
				return nodeids;
			}
			 return nodeids;
		}
	}
}


text:
require 'arbor/model/serialiser'

module Arbor
  module API
    def retrieve(type, id)
      resource = parse_resource_name(type)
      data = get("/rest-v2/#{resource.dasherize}/#{id}")

      unmarshall_data(data, resource)
    end

    def query(type, query = nil)
      resource = parse_resource_name(type)
      query_string = query.build_query_string if query

      data = get("/rest-v2/#{resource.dasherize.tr('/', '_')}?#{query_string}")

      unmarshall_data(data, resource)
    end

    def changelog(type, from_revision = 0)
      resource = parse_resource_name(type)

      data = get("/rest-v2/#{resource.dasherize.tr('/', '_')}/changelog?from-revision=#{from_revision}")

      data['changes'].each do |c|
        c['entityType'] = "change"
        @highest_revision = [highest_revision, BigDecimal.new(c['toRevision'])].max
      end

      unmarshall_data(data, 'changes')
    end

    private
      def unmarshall_data(data, resource)
        singular_resource = resource.singularize.camelize(:lower).gsub('::', '_')
        plural_resource   = resource.camelize(:lower).gsub('::', '_')

        if (res = data[singular_resource])
          Model::Serialiser.parse_resource(res).tap { |obj|
            obj.attach_client(self) if obj.respond_to?(:attach_client)
            obj.lock_attributes = true if obj.respond_to?(:lock_attributes)
          }
        elsif data[plural_resource]
          data[plural_resource].map do |res|
            Model::Serialiser.parse_resource(res).tap { |obj|
              obj.attach_client(self) if obj.respond_to?(:attach_client)
            }
          end
        elsif data.empty?
          []
        elsif data["errors"] || (data["status"] && !data["status"]["success"])
          raise Errors::APIError, "#{data["status"]["code"]} #{data["status"]["reason"]}: #{data["status"]["errors"].join(", ")}"
        elsif (data[:response] && !data["response"]["success"])
          raise Errors::APIError, "#{data["response"]["code"]} #{data["response"]["reason"]}"
        else
          raise Errors::SerialisationError, "Unexpected root key in API data. Expected: #{plural_resource} or #{singular_resource}. Actual data: #{data}"
        end
      end
  end
end


text:
from __future__ import absolute_import

from rest_framework.response import Response

from sentry.api.bases.group import GroupEndpoint
from sentry.api.serializers import serialize
from sentry.models import GroupTagValue, GroupTagKey, TagKey, TagKeyStatus

class GroupTagsEndpoint(GroupEndpoint):
    def get(self, request, group):
        tag_keys = TagKey.objects.filter(
            project=group.project,
            status=TagKeyStatus.VISIBLE,
            key__in=GroupTagKey.objects.filter(
                group=group,
            ).values('key'),
        )

        # O(N) db access
        data = []
        for tag_key in tag_keys:
            total_values = GroupTagValue.get_value_count(group.id, tag_key.key)
            top_values = GroupTagValue.get_top_values(group.id, tag_key.key, limit=10)
            if tag_key.key.startswith('sentry:'):
                key = tag_key.key.split('sentry:', 1)[-1]
            else:
                key = tag_key.key

            data.append({
                'id': str(tag_key.id),
                'key': key,
                'name': tag_key.get_label(),
                'uniqueValues': tag_key.values_seen,
                'totalValues': total_values,
                'topValues': serialize(top_values, request.user),
            })

        return Response(data)


text:
import type { PrismaClientErrorInfo } from '../../common/errors/PrismaClientError'
import { PrismaClientError } from '../../common/errors/PrismaClientError'

export interface DataProxyErrorInfo extends PrismaClientErrorInfo {
  isRetryable?: boolean
}

export abstract class DataProxyError extends PrismaClientError {
  isRetryable: boolean

  constructor(message: string, info: DataProxyErrorInfo) {
    super(message, info)

    this.isRetryable = info.isRetryable ?? true
  }
}


text:
package com.google.mr4c.nativec.jna;

import com.google.mr4c.stats.MR4CStats;
import com.google.mr4c.stats.StatsClient;
import com.google.mr4c.stats.StatsTimer;

import com.sun.jna.Callback;
import com.sun.jna.NativeLibrary;
import com.sun.jna.Memory;
import com.sun.jna.Pointer;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

abstract class JnaUtils {

	private static Protector<Callback> s_cbProt = new Protector<Callback>();
	private static Protector<Pointer> s_ptrProt = new Protector<Pointer>();
	private static Protector<Buffer> s_bufProt = new Protector<Buffer>();
	private static Protector<JnaDataFileSource> s_srcProt = new Protector<JnaDataFileSource>();
	private static Protector<JnaDataFileSink> s_sinkProt = new Protector<JnaDataFileSink>();
	private static Protector<JnaExternalDataset> s_datasetProt = new Protector<JnaExternalDataset>();
	private static Protector<JnaRandomAccessFileSource> s_randSrcProt = new Protector<JnaRandomAccessFileSource>();
	private static Protector<JnaRandomAccessFileSink> s_randSinkProt = new Protector<JnaRandomAccessFileSink>();

	// Algorithm can be loaded and GC'ed multiple times in the same JVM
	// Keep static lib reference here so the lib doesn't reload and try to register twice
	private static Map<String,NativeLibrary> s_loadedLibs = new HashMap<String,NativeLibrary>();

	public static void protectPointer(Object scope, Pointer ptr) {
		s_ptrProt.protect(scope,ptr);
	}

	public static void protectBuffer(Object scope, Buffer buf) {
		s_bufProt.protect(scope,buf);
	}

	public static void protectCallback(Object scope, Callback cb) {
		s_cbProt.protect(scope,cb);
	}

	public static void protectDataset(Object scope, JnaExternalDataset dataset) {
		s_datasetProt.protect(scope,dataset);
	}

	public static void protectSource(Object scope, JnaDataFileSource src) {
		s_srcProt.protect(scope,src);
	}

	public static void releaseSource(Object scope, JnaDataFileSource src) {
		s_srcProt.release(scope,src);
	}

	public static void protectSink(Object scope, JnaDataFileSink sink) {
		s_sinkProt.protect(scope,sink);
	}

	public static void releaseSink(Object scope, JnaDataFileSink sink) {
		s_sinkProt.release(scope,sink);
	}

	public static void protectSource(Object scope, JnaRandomAccessFileSource src) {
		s_randSrcProt.protect(scope,src);
	}

	public static void releaseSource(Object scope, JnaRandomAccessFileSource src) {
		s_randSrcProt.release(scope,src);
	}

	public static void protectSink(Object scope, JnaRandomAccessFileSink sink) {
		s_randSinkProt.protect(scope,sink);
	}

	public static void releaseSink(Object scope, JnaRandomAccessFileSink sink) {
		s_randSinkProt.release(scope,sink);
	}

	public synchronized static NativeLibrary loadLibrary(String name) {
		NativeLibrary lib = s_loadedLibs.get(name);
		if ( lib==null ) {
			lib = loadLibraryWithTiming(name);
			s_loadedLibs.put(name,lib);
		}
		return lib;
	}

	private static NativeLibrary loadLibraryWithTiming(String name) {
		String successName = String.format("mr4c.loadlib.%s.success", name);
		String failureName = String.format("mr4c.loadlib.%s.failure", name);
		StatsTimer timer = new StatsTimer(
			MR4CStats.getClient(),
			successName,
			failureName
		);
		boolean success = false;
		try {
			NativeLibrary result = doLoadLibrary(name);
			success = true;
			return result;
		} finally {
			timer.done(success);
		}
	}

	private static NativeLibrary doLoadLibrary(String name) {
		return NativeLibrary.getInstance(name);
	}

	public static Pointer toNative(String str) {
		Memory mem = new Memory(str.length()+1);
		mem.setString(0, str);
		return mem;
	}

	private static class Protector<T> {

		WeakHashMap<Object,List<T>> s_targetMap = new WeakHashMap<Object,List<T>>();

		void protect(Object scope, T target) {
			List<T> targets = s_targetMap.get(scope);
			if ( targets==null ) {
				targets = new ArrayList<T>();
				s_targetMap.put(scope,targets);
			}
			targets.add(target);
		}

		void release(Object scope, T target) {
			List<T> targets = s_targetMap.get(scope);
			if ( targets==null ) {
				return;
			}
			targets.remove(target);
		}

	}

}


text:
import uuid from 'uuid/v1';

import {
  updateEntity,
  getEntityByKey,
  createEntities,
  getEntities,
} from '../../../../../gcp/datastore/queries';

import buildCircle from '../../../Circle/Mutations/functions/buildCircle';

export default async function createUsername(inputFields, contextUserUid) {
  inputFields.username = inputFields.username.toLowerCase();
  const entityToUpdate = [];
  const userUid = contextUserUid;
  // Make sure username is lowercase

  const checkUsernameDoesNotExist = await getEntities(
    'users',
    [
      {
        property: 'username',
        condition: '=',
        value: inputFields.username,
      },
    ],
    1,
    null,
    'APP',
  );

  if (checkUsernameDoesNotExist.entities[0]) {
    return {
      message: `Username is already in use`,
    };
  }

  const getUser = await getEntityByKey(
    'users',
    contextUserUid,
    contextUserUid,
  ).then(response => response.entity);

  const homePublicUid = await uuid();
  const homePrivateUid = await uuid();

  const homePublic = await buildCircle(
    {
      uid: homePublicUid,
      public: true,
      type: 'LINESMANY',
      title: `${inputFields.username}'s Home`,
      creator: 'APP',
      dateCreated: Date.now(),
      dateUpdated: Date.now(),
      viewers: [userUid],
      editors: [userUid],
    },
    userUid,
  );

  const homePrivate = await buildCircle(
    {
      uid: homePrivateUid,
      public: false,
      type: 'LINESMANY',
      title: `${inputFields.username}'s Private Home`,
      slug: `private`,
      creator: 'APP',
      dateCreated: Date.now(),
      dateUpdated: Date.now(),
      viewers: [userUid],
      editors: [userUid],
    },
    userUid,
  );

  await createEntities([homePublic, homePrivate]);

  function buildField(name) {
    let field;

    function indexedField() {
      field = {
        name,
        value:
          inputFields[name] !== undefined || null
            ? inputFields[name]
            : getUser[name],
      };
    }

    function notIndexedField() {
      field = {
        name,
        value:
          inputFields[name] !== undefined || null
            ? inputFields[name]
            : getUser[name],
        excludeFromIndexes: true,
      };
    }

    const entityData = {
      uid: indexedField,
      email: indexedField,
      dateCreated: indexedField,
      dateUpdated: indexedField,

      default: notIndexedField,
    };
    (entityData[name] || entityData.default)();

    return field;
  }

  Object.keys(getUser).forEach(prop => {
    const object = buildField(prop);
    entityToUpdate.push(object);
  });

  const mergeCreated = [
    {
      name: 'username',
      value: inputFields.username,
    },
    {
      name: 'homePublic',
      value: homePublicUid,
      excludeFromIndexes: true,
    },
    {
      name: 'homePrivate',
      value: homePrivateUid,
      excludeFromIndexes: true,
    },
  ];
  const newEntity = entityToUpdate.concat(mergeCreated);

  return updateEntity(newEntity, contextUserUid);
}


text:
// Copyright 2022 Google LLC
//
// 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
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **

'use strict';

function main(keyString) {
  // [START apikeys_v2_generated_ApiKeys_LookupKey_async]
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. Finds the project that owns the key string value.
   */
  // const keyString = 'abc123'

  // Imports the Apikeys library
  const {ApiKeysClient} = require('@google-cloud/apikeys').v2;

  // Instantiates a client
  const apikeysClient = new ApiKeysClient();

  async function callLookupKey() {
    // Construct request
    const request = {
      keyString,
    };

    // Run request
    const response = await apikeysClient.lookupKey(request);
    console.log(response);
  }

  callLookupKey();
  // [END apikeys_v2_generated_ApiKeys_LookupKey_async]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));


text:
package org.appfuse.util;

import java.beans.PropertyDescriptor;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.model.BaseObject;
import org.appfuse.model.LabelValue;

/**
 * Utility class to convert one object to another.
 *
 *

 * View Source
 *

 *
 * @author Matt Raible
 */
public final class ConvertUtil {
    //~ Static fields/initializers =============================================

    private static Log log = LogFactory.getLog(ConvertUtil.class);

    //~ Methods ================================================================

    /**
     * Method to convert a ResourceBundle to a Map object.
     * @param rb a given resource bundle
     * @return Map a populated map
     */
    public static Map convertBundleToMap(ResourceBundle rb) {
        Map map = new HashMap();

        for (Enumeration keys = rb.getKeys(); keys.hasMoreElements();) {
            String key = (String) keys.nextElement();
            map.put(key, rb.getString(key));
        }

        return map;
    }

    public static Map convertListToMap(List list) {
        Map map = new LinkedHashMap();

        for (Iterator it = list.iterator(); it.hasNext();) {
            LabelValue option = (LabelValue) it.next();
            map.put(option.getLabel(), option.getValue());
        }

        return map;
    }

    /**
     * Method to convert a ResourceBundle to a Properties object.
     * @param rb a given resource bundle
     * @return Properties a populated properties object
     */
    public static Properties convertBundleToProperties(ResourceBundle rb) {
        Properties props = new Properties();

        for (Enumeration keys = rb.getKeys(); keys.hasMoreElements();) {
            String key = (String) keys.nextElement();
            props.put(key, rb.getString(key));
        }

        return props;
    }

    /**
     * Convenience method used by tests to populate an object from a
     * ResourceBundle
     * @param obj an initialized object
     * @param rb a resource bundle
     * @return a populated object
     */
    public static Object populateObject(Object obj, ResourceBundle rb) {
        try {
            Map map = convertBundleToMap(rb);

            BeanUtils.copyProperties(obj, map);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Exception occured populating object: " + e.getMessage());
        }

        return obj;
    }

    /**
     * This method inspects a POJO or Form and figures out its pojo/form
     * equivalent.
     *
     * @param o the object to inspect
     * @return the Class of the persistable object
     * @throws ClassNotFoundException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static Object getOpposingObject(Object o) throws ClassNotFoundException,
                                                InstantiationException,
                                                IllegalAccessException {
        String name = o.getClass().getName();
        if (o instanceof BaseObject) {
            if (log.isDebugEnabled()) {
                log.debug("getting form equivalent of pojo...");
            }

            name = StringUtils.replace(name, "model", "webapp.form");
            name += "Form";
        } else {
            if (log.isDebugEnabled()) {
                log.debug("getting pojo equivalent of form...");
            }
            name = StringUtils.replace(name, "webapp.form", "model");
            name = name.substring(0, name.lastIndexOf("Form"));
        }

        Class obj = Class.forName(name);

        if (log.isDebugEnabled()) {
            log.debug("returning className: " + obj.getName());
        }

        return obj.newInstance();
    }

    /**
     * Convenience method to convert a form to a POJO and back again
     *
     * @param o the object to tranfer properties from
     * @return converted object
     */
    public static Object convert(Object o) throws Exception {
        if (o == null) {
        	return null;
        }
        Object target = getOpposingObject(o);
        BeanUtils.copyProperties(target, o);
        return target;
    }

    /**
     * Convenience method to convert Lists (in a Form) from POJOs to Forms.
     * Also checks for and formats dates.
     *
     * @param o
     * @return
     * @throws Exception
     */
    public static Object convertLists(Object o) throws Exception {
        if (o == null) {
            return null;
        }

        Object target = null;

        PropertyDescriptor[] origDescriptors =
                PropertyUtils.getPropertyDescriptors(o);

        for (int i = 0; i < origDescriptors.length; i++) {
            String name = origDescriptors[i].getName();

            if (origDescriptors[i].getPropertyType().equals(List.class)) {
                List list = (List) PropertyUtils.getProperty(o, name);
                for (int j=0; j < list.size(); j++) {
                    Object origin = list.get(j);
                    target = convert(origin);
                    list.set(j, target);
                }
                PropertyUtils.setProperty(o, name, list);
            }
        }
        return o;
    }
}


text:
'use strict';

var path = require('path');
var fse = require('fs-extra');
var async = require('async');

var less = require('../lib/less.js');

module.exports = function(grunt) {

    // ------------ Abricos Core Builder -------------

    var checkAbricosCore = function(projectDir) {
        var fileModulePhp = path.join(projectDir, 'src', 'index.php');
        var isExists = grunt.file.exists(fileModulePhp);

        return isExists;
    };

    grunt.registerMultiTask('abcore', 'Build Abricos Core', function() {
        var options = this.options({
            directory: process.cwd(),
            buildDir: 'build'
        });

        var projectDir = options.directory;

        var isModule = checkAbricosCore(projectDir);
        if (!isModule) {
            grunt.log.warn('Abricos core "' + projectDir + '" not found.');
            return;
        }

        var srcDir = path.resolve(projectDir, 'src');
        var buildDir = path.resolve(projectDir, options.buildDir);

        var done = this.async();
        var stack = [];

        // LESS
        stack.push(function (stackCallback) {
            var lessSrcDir = path.join(srcDir, 'tt/default/less');
            var lessDestDir = path.join(buildDir, 'tt/default/css');
            less(grunt, lessSrcDir, lessDestDir, options, stackCallback);
        });

        // copy
        stack.push(function(stackCallback){
            fse.copy(srcDir, buildDir, function(err) {
                if (err) {
                    grunt.log.warn(err);
                }
                stackCallback(err);
            });
        });

        // Delete work files
        stack.push(function (stackCallback) {
            var lessDestDir = path.join(buildDir, 'tt/default/less');
            if (grunt.file.exists(lessDestDir)){
                grunt.file.delete(lessDestDir);
            }

            stackCallback(null);
        });

        async.series(stack, function (err) {
            if (err) {
                done(false);
            } else {
                done();
            }
        });
    });
};


text:
<?php

namespace Magento\Framework\View\Test\Unit\Element\Message\Renderer\BlockRenderer;

use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;
use Magento\Framework\View\Element\Message\Renderer\BlockRenderer\Template;

class TemplateTest extends \PHPUnit_Framework_TestCase
{
    public function testGetCacheKeyInfo()
    {
        $helper = new ObjectManager($this);
        $storeMock = $this->getMock('Magento\Store\Api\Data\StoreInterface');
        $storeManager = $this->getMock('Magento\Store\Model\StoreManagerInterface');
        $storeManager->expects(static::once())
            ->method('getStore')
            ->willReturn($storeMock);

        /** @var Template $template */
        $template = $helper->getObject(
            'Magento\Framework\View\Element\Message\Renderer\BlockRenderer\Template',
            [
                'storeManager' => $storeManager
            ]
        );

        $expectedData = [
            'coconut' => 1,
            'swallow' => 1,
            'MESSAGE',
            'MontyPythonAndTheHolyGrail.phtml',
            'GB'
        ];

        $storeMock->expects(static::once())
            ->method('getCode')
            ->willReturn('GB');
        $template->setTemplate('MontyPythonAndTheHolyGrail.phtml');
        $template->setData(
            [
                'coconut' => 1,
                'swallow' => 1
            ]
        );

        static::assertSame($expectedData, $template->getCacheKeyInfo());
    }
}


text:
ScalaJS.impls.scala_collection_GenSeqViewLike$Appended$class__restSeq__Lscala_collection_GenSeqViewLike$Appended__Lscala_collection_GenSeq = (function($$this) {
  return $$this.rest__Lscala_collection_GenTraversable().toSeq__Lscala_collection_GenSeq()
});
ScalaJS.impls.scala_collection_GenSeqViewLike$Appended$class__length__Lscala_collection_GenSeqViewLike$Appended__I = (function($$this) {
  return ($$this.scala$collection$GenSeqViewLike$Appended$$$outer__Lscala_collection_GenSeqViewLike().length__I() + $$this.restSeq__Lscala_collection_GenSeq().length__I())
});
ScalaJS.impls.scala_collection_GenSeqViewLike$Appended$class__apply__Lscala_collection_GenSeqViewLike$Appended__I__O = (function($$this, idx) {
  if ((idx < $$this.scala$collection$GenSeqViewLike$Appended$$$outer__Lscala_collection_GenSeqViewLike().length__I())) {
    return $$this.scala$collection$GenSeqViewLike$Appended$$$outer__Lscala_collection_GenSeqViewLike().apply__I__O(idx)
  } else {
    return $$this.restSeq__Lscala_collection_GenSeq().apply__I__O((idx - $$this.scala$collection$GenSeqViewLike$Appended$$$outer__Lscala_collection_GenSeqViewLike().length__I()))
  }
});
ScalaJS.impls.scala_collection_GenSeqViewLike$Appended$class__$init$__Lscala_collection_GenSeqViewLike$Appended__V = (function($$this) {
  /*<skip>*/
});
//@ sourceMappingURL=GenSeqViewLike$Appended$class.js.map


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Layout</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" /><link href="../demo.css" rel="stylesheet" type="text/css" />

        north

        south

        west

        east

        <input type="button" value="隐藏" onclick="hideHeader()"/>
        <input type="button" value="显示" onclick="showHeader()"/>

        <input type="button" value="折叠" onclick="collapsePanel()"/>
        <input type="button" value="展开" onclick="expandPanel()"/>


text:
@interface Edge : NSObject

@property (nonatomic) double length;
@property (nonatomic) Vertex *firstVertex;
@property (nonatomic) Vertex *secondVertex;

- (id) initWithFirstVertex: (Vertex *)firstVertex secondVertex: (Vertex *)secondVertex length: (double)length;
- (BOOL) isEqual: (id)object;

@end


text:
package functry.function;

@FunctionalInterface
public interface TryTriFunction<T, U, V, R> {

	R apply(T t, U u, V v) throws Throwable;

}


text:
#include "string.h"
#include "vector.h"
#include "map.h"
#include "mempool.h"
#include <exception>

namespace zsl {
class Variant
{
public:
	virtual bool isNull() const = 0;
	virtual int toInt() const = 0;
	virtual double toDouble() const = 0;
	virtual String toString() const = 0;
	virtual Variant *&operator [](int index) throw(std::exception) = 0;
	virtual Variant *&operator [](const char *key) = 0;
	virtual const Variant *&operator [](int index) const;
	virtual const Variant *&operator [](const char *key) const;
};

class IntVariant : public Variant
{
public:
	IntVariant(int i);
	IntVariant(const char *str);
	bool isNull() const;
	int toInt() const;
	double toDouble() const;
	String toString() const;
	Variant *&operator [](int index) throw(std::exception);
	Variant *&operator [](const char *key) ;
	int &data() {return value; }

protected:
	int value;
};

class StringVariant : public Variant
{
public:
	StringVariant(int i);
	StringVariant(const char *str);
	bool isNull() const;
	int toInt() const;
	double toDouble() const;
	String toString() const;
	Variant *&operator [](int index) throw(std::exception);
	Variant *&operator [](const char *key) ;
	String &data() {return value; }

protected:
	String value;
};

class ArrayVariant : public Variant
{
public:
	bool isNull() const;
	int toInt() const;
	double toDouble() const;
	String toString() const;
	Variant *&operator [](int index) throw(std::exception);
	Variant *&operator [](const char *key) ;
	Vector<Variant*> &data() {return value; }

	void insert(int index, Variant *);
	void push_back(Variant *);
protected:
	Vector<Variant*> value;
};

class DictVariant : public Variant
{
public:
	bool isNull() const;
	int toInt() const;
	double toDouble() const;
	String toString() const;
	Variant *&operator [](int index) throw(std::exception);
	Variant *&operator [](const char *key) ;
	Map<String, Variant*> &data() {return value; }
protected:
	Map<String, Variant*> value;
};

class VarFactory
{
public:
	VarFactory() : pool_(syspool_) {}
	VarFactory(MemPool &pool) :pool_(pool) {}

	Variant *create(int arg);
	Variant *create(const char* arg);

	ArrayVariant *createArray();
	DictVariant *createDict();
protected:
	MemPool &pool_;
	SysMemPool syspool_;
};

inline ArrayVariant *VarFactory::createArray()
{
	void *p = pool_.allocate(sizeof(ArrayVariant));
	new (p) ArrayVariant();
	return (ArrayVariant*) p;
}

inline DictVariant *VarFactory::createDict()
{
	void *p = pool_.allocate(sizeof(DictVariant));
	new (p) DictVariant();
	return (DictVariant*)p;
}

inline Variant *VarFactory::create(const int arg)
{
	void *p = pool_.allocate(sizeof(IntVariant));
	new (p) IntVariant(arg);
	return (Variant*) p;
}

inline Variant *VarFactory::create(const char* arg)
{
	void *p = pool_.allocate(sizeof(StringVariant));
	new (p) StringVariant(arg);
	return (Variant*) p;
}

} // end of namespace

#endif


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.signalr.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.signalr.models.ProvisioningState;
import com.azure.resourcemanager.signalr.models.SharedPrivateLinkResourceStatus;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Describes the properties of an existing Shared Private Link Resource. */
@Fluent
public final class SharedPrivateLinkResourceProperties {
    /*
     * The group id from the provider of resource the shared private link resource is for
     */
    @JsonProperty(value = "groupId", required = true)
    private String groupId;

    /*
     * The resource id of the resource the shared private link resource is for
     */
    @JsonProperty(value = "privateLinkResourceId", required = true)
    private String privateLinkResourceId;

    /*
     * Provisioning state of the resource.
     */
    @JsonProperty(value = "provisioningState", access = JsonProperty.Access.WRITE_ONLY)
    private ProvisioningState provisioningState;

    /*
     * The request message for requesting approval of the shared private link resource
     */
    @JsonProperty(value = "requestMessage")
    private String requestMessage;

    /*
     * Status of the shared private link resource
     */
    @JsonProperty(value = "status", access = JsonProperty.Access.WRITE_ONLY)
    private SharedPrivateLinkResourceStatus status;

    /** Creates an instance of SharedPrivateLinkResourceProperties class. */
    public SharedPrivateLinkResourceProperties() {
    }

    /**
     * Get the groupId property: The group id from the provider of resource the shared private link resource is for.
     *
     * @return the groupId value.
     */
    public String groupId() {
        return this.groupId;
    }

    /**
     * Set the groupId property: The group id from the provider of resource the shared private link resource is for.
     *
     * @param groupId the groupId value to set.
     * @return the SharedPrivateLinkResourceProperties object itself.
     */
    public SharedPrivateLinkResourceProperties withGroupId(String groupId) {
        this.groupId = groupId;
        return this;
    }

    /**
     * Get the privateLinkResourceId property: The resource id of the resource the shared private link resource is for.
     *
     * @return the privateLinkResourceId value.
     */
    public String privateLinkResourceId() {
        return this.privateLinkResourceId;
    }

    /**
     * Set the privateLinkResourceId property: The resource id of the resource the shared private link resource is for.
     *
     * @param privateLinkResourceId the privateLinkResourceId value to set.
     * @return the SharedPrivateLinkResourceProperties object itself.
     */
    public SharedPrivateLinkResourceProperties withPrivateLinkResourceId(String privateLinkResourceId) {
        this.privateLinkResourceId = privateLinkResourceId;
        return this;
    }

    /**
     * Get the provisioningState property: Provisioning state of the resource.
     *
     * @return the provisioningState value.
     */
    public ProvisioningState provisioningState() {
        return this.provisioningState;
    }

    /**
     * Get the requestMessage property: The request message for requesting approval of the shared private link resource.
     *
     * @return the requestMessage value.
     */
    public String requestMessage() {
        return this.requestMessage;
    }

    /**
     * Set the requestMessage property: The request message for requesting approval of the shared private link resource.
     *
     * @param requestMessage the requestMessage value to set.
     * @return the SharedPrivateLinkResourceProperties object itself.
     */
    public SharedPrivateLinkResourceProperties withRequestMessage(String requestMessage) {
        this.requestMessage = requestMessage;
        return this;
    }

    /**
     * Get the status property: Status of the shared private link resource.
     *
     * @return the status value.
     */
    public SharedPrivateLinkResourceStatus status() {
        return this.status;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (groupId() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property groupId in model SharedPrivateLinkResourceProperties"));
        }
        if (privateLinkResourceId() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property privateLinkResourceId in model"
                            + " SharedPrivateLinkResourceProperties"));
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(SharedPrivateLinkResourceProperties.class);
}


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

using Microsoft.CodeAnalysis.Host;

namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider
{
    internal interface ILanguageSettingsProviderFactory<TData> : ISettingsProviderFactory<TData>, ILanguageService
    {
    }
}


text:
io.socket.on('connect', function() {
  io.socket.on('user', cometUserMessageReceivedFromServer);

  io.socket.get('/user/subscribe');
});

function cometUserMessageReceivedFromServer(message) {
  console.log('Here\'s the message: ' + message);

  var userId = message.id;

  updateUserInDom(userId, message);

  if (message.verb !== 'destroyed') {
    displayFlashActivity(message);
  }
}

function displayFlashActivity(message) {
  $('#chatAudio')[0].play();
  $('.navbar').after('
' + message.data.name + message.data.action + "
");
  $('.alert').fadeOut(5000);
}

function updateUserInDom(userId, message) {
  var page = document.location.pathname;

  page = page.replace(/(\/)$/, '');

  switch (page) {
    case '/user':
      if (message.verb === 'updated') {
        UserIndexPage.updateUser(userId, message);
      }

      if (message.verb === 'created') {
        UserIndexPage.addUser(message);
      }

      if (message.verb === 'destroyed') {
        UserIndexPage.destroyUser(userId);
      }
      break;
  }
}

var UserIndexPage = {

  updateUser: function(id, message) {
    var $userRow = $('tr[data-id="' + id + '"] td img').first();

    if (message.data.loggedIn) {
      $userRow.attr('src', '/images/icon-online.png');
    } else {
      $userRow.attr('src', '/images/icon-offline.png');
    }
  },

  addUser: function(user) {
    var obj = {
      user: user.data,
      _csrf: window.overlord.csrf || ''
    };
console.log(obj);
      console.log(user.data);
    $('tr:last').after(
      JST['assets/templates/addUser.ejs'](obj)
    );
  },

  destroyUser: function(id) {
    $('tr[data-id="' + id + '"]').remove();
  }
};


text:
/**
 * @author Mat Groves http://matgroves.com/ @Doormat23
 */

var PIXI = (function(){

    var root = this;


text:
+++
title = "Build"
weight = 1
+++

## Build&Deployment

1. Execute the following command to compile and generate the ShardingSphere-Proxy binary package:

```
git clone --depth 1 https://github.com/apache/shardingsphere.git
cd shardingsphere
mvn clean install -Dmaven.javadoc.skip=true -Dcheckstyle.skip=true -Drat.skip=true -Djacoco.skip=true -DskipITs -DskipTests -Prelease
```

The binary packages:
- /shardingsphere-distribution/shardingsphere-proxy-distribution/target/apache-shardingsphere-${latest.release.version}-shardingsphere-proxy-bin.tar.gz

Or get binary package from [download page]( https://shardingsphere.apache.org/document/current/en/downloads/ ).

> Scaling is an experimental feature, if scaling job fail, you could try nightly version, click here to [download nightly build]( https://github.com/apache/shardingsphere#nightly-builds ).

2. Unzip the proxy distribution package, modify the configuration file `conf/config-sharding.yaml`. Please refer to [proxy startup manual](/en/user-manual/shardingsphere-proxy/startup/bin/) for more details.

3. Modify the configuration file `conf/server.yaml`. Please refer to [Mode Configuration](/en/user-manual/shardingsphere-jdbc/yaml-config/mode/) for more details.
Type of `mode` must be `Cluster` for now, please start the registry center before running proxy.

Configuration Example:
```yaml
mode:
  type: Cluster
  repository:
    type: ZooKeeper
    props:
      namespace: governance_ds
      server-lists: localhost:2181
      retryIntervalMilliseconds: 500
      timeToLiveSeconds: 60
      maxRetries: 3
      operationTimeoutMilliseconds: 500
  overwrite: false
```

4. Enable scaling

Way 1. Modify `scalingName` and `scaling` configuration in `conf/config-sharding.yaml`.

Configuration Items Explanation:
```yaml
rules:
- !SHARDING
  # ignored configuration

  scalingName: # Enabled scaling action config name
  scaling:
    <scaling-action-config-name> (+):
      input: # Data read configuration. If it's not configured, then part of its configuration will take effect.
        workerThread: # Worker thread pool size for inventory data ingestion from source. If it's not configured, then use system default value.
        batchSize: # Maximum records count of a DML select operation. If it's not configured, then use system default value.
        rateLimiter: # Rate limit algorithm. If it's not configured, then system will skip rate limit.
          type: # Algorithm type. Options:
          props: # Algorithm properties
      output: # Data write configuration. If it's not configured, then part of its configuration will take effect.
        workerThread: # Worker thread pool size for data importing to target. If it's not configured, then use system default value.
        batchSize: # Maximum records count of a DML insert/delete/update operation. If it's not configured, then use system default value.
        rateLimiter: # Rate limit algorithm. If it's not configured, then system will skip rate limit.
          type: # Algorithm type. Options:
          props: # Algorithm properties
      streamChannel: # Algorithm of channel that connect producer and consumer, used for input and output. If it's not configured, then system will use MEMORY type
        type: # Algorithm type. Options: MEMORY
        props: # Algorithm properties
          block-queue-size: # Property: data channel block queue size. Available for types: MEMORY
      completionDetector: # Completion detect algorithm. If it's not configured, then system won't continue to do next steps automatically.
        type: # Algorithm type. Options: IDLE
        props: # Algorithm properties
          incremental-task-idle-minute-threshold: # If incremental tasks is idle more than so much minutes, then it could be considered as almost completed. Available for types: IDLE
      dataConsistencyChecker: # Data consistency check algorithm. If it's not configured, then system will skip this step.
        type: # Algorithm type. Options: DATA_MATCH, CRC32_MATCH
        props: # Algorithm properties
          chunk-size: # Maximum records count of a query operation for check
```

Configuration Example:
```yaml
rules:
- !SHARDING
  # ignored configuration

  scalingName: default_scaling
  scaling:
    default_scaling:
      input:
        workerThread: 40
        batchSize: 1000
      output:
        workerThread: 40
        batchSize: 1000
      streamChannel:
        type: MEMORY
        props:
          block-queue-size: 10000
      completionDetector:
        type: IDLE
        props:
          incremental-task-idle-minute-threshold: 30
      dataConsistencyChecker:
        type: DATA_MATCH
        props:
          chunk-size: 1000
```

You could customize `completionDetector`, `dataConsistencyChecker` algorithm by implementing SPI. Current implementation could be referenced, please refer to [Dev Manual#Scaling](/en/dev-manual/scaling/) for more details.

Way 2: Configure scaling by DistSQL

Create scaling configuration example:
```sql
CREATE SHARDING SCALING RULE default_scaling (
INPUT(
  WORKER_THREAD=40,
  BATCH_SIZE=1000
),
OUTPUT(
  WORKER_THREAD=40,
  BATCH_SIZE=1000
),
STREAM_CHANNEL(TYPE(NAME=MEMORY, PROPERTIES("block-queue-size"=10000))),
COMPLETION_DETECTOR(TYPE(NAME=IDLE, PROPERTIES("incremental-task-idle-minute-threshold"=3))),
DATA_CONSISTENCY_CHECKER(TYPE(NAME=DATA_MATCH, PROPERTIES("chunk-size"=1000)))
);
```

Please refer to [RDL#Sharding](/en/user-manual/shardingsphere-proxy/distsql/syntax/rdl/rule-definition/sharding/) for more details.

5. Start up ShardingSphere-Proxy:

```
sh bin/start.sh
```

6. Check proxy log `logs/stdout.log`:

```
[INFO ] [main] o.a.s.p.frontend.ShardingSphereProxy - ShardingSphere-Proxy start success
```

It means `proxy` start up successfully.

## Shutdown

```
sh bin/stop.sh
```


text:
layout: post
author: "Greg Wilson"
title: "Summary of Host Survey"
date: 2013-08-14
time: "14:48"
category: ["Community"]
---

  Earlier this summer,
  we asked people who had hosted Software Carpentry bootcamps to give us some retrospective feedback.
  Their answers are summarized below,
  and we'll be adjusting our operations in response.

How much time did you put into organizing your bootcamp?

    Answers were split evenly between "a day or two" and "several days".

What was the total cost?

    With the exception of our Australian double-header
    (where travel costs were clearly an outlier),
    the answers were in the $700-3000 range.

Would you like to host another one?

    22 said "yes",
    3 said "no",
    and 6 can't decide yet.

How do you feel about asking bootcamps to contribute $1500 toward central overheads?

I support this approach	12

I support this approach, but not at this price	5

I am neutral	7

I am opposed to this approach	3

What level and format would you prefer?

Complete beginners / 2 days	7

Complete beginners / 3 days	5

Intermediates / 2 days	13

Intermediates / 3 days	2

Other	3


text:
@interface IDEFramework (IDEKitFrameworkPropertyAdditions)
- (id)navigableItem_image;
- (id)ideInspectedReferenceMessageForChoosingRelativeLocation;
- (BOOL)ideInspectedIsReferenceNameEditable;
@end


text:
.class Lnz/co/telecom/smartphone/fragments/FragBase$8;
.super Ljava/lang/Object;
.source "FragBase.java"

# interfaces
.implements Landroid/view/View$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lnz/co/telecom/smartphone/fragments/FragBase;->showDialog(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lnz/co/telecom/smartphone/fragments/OnDismiss;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lnz/co/telecom/smartphone/fragments/FragBase;

.field final synthetic val$isClickedOK:[Z

.field final synthetic val$subDialog:Landroid/app/Dialog;

# direct methods
.method constructor <init>(Lnz/co/telecom/smartphone/fragments/FragBase;[ZLandroid/app/Dialog;)V
    .locals 0

    .prologue
    .line 805
    iput-object p1, p0, Lnz/co/telecom/smartphone/fragments/FragBase$8;->this$0:Lnz/co/telecom/smartphone/fragments/FragBase;

    iput-object p2, p0, Lnz/co/telecom/smartphone/fragments/FragBase$8;->val$isClickedOK:[Z

    iput-object p3, p0, Lnz/co/telecom/smartphone/fragments/FragBase$8;->val$subDialog:Landroid/app/Dialog;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onClick(Landroid/view/View;)V
    .locals 3
    .param p1, "v"    # Landroid/view/View;

    .prologue
    .line 808
    iget-object v0, p0, Lnz/co/telecom/smartphone/fragments/FragBase$8;->val$isClickedOK:[Z

    const/4 v1, 0x0

    const/4 v2, 0x1

    aput-boolean v2, v0, v1

    .line 809
    iget-object v0, p0, Lnz/co/telecom/smartphone/fragments/FragBase$8;->val$subDialog:Landroid/app/Dialog;

    invoke-virtual {v0}, Landroid/app/Dialog;->dismiss()V

    .line 810
    return-void
.end method


text:
from __future__ import unicode_literals
import json
import os
from django import template
from django.core.urlresolvers import reverse
from django.forms import CheckboxInput, ModelChoiceField, Select, ModelMultipleChoiceField, SelectMultiple
from django.contrib.admin.widgets import RelatedFieldWidgetWrapper
from django.utils.formats import get_format
from django.utils.safestring import mark_safe
from django.utils.encoding import smart_text
from jet import settings, VERSION
from jet.models import Bookmark, PinnedApplication
from jet.utils import get_app_list, get_model_instance_label, get_model_queryset, get_possible_language_codes, \
    get_admin_site

try:
    from urllib.parse import parse_qsl
except ImportError:
    from urlparse import parse_qsl

register = template.Library()

@register.simple_tag
def jet_get_date_format():
    return get_format('DATE_INPUT_FORMATS')[0]

@register.simple_tag
def jet_get_time_format():
    return get_format('TIME_INPUT_FORMATS')[0]

@register.simple_tag
def jet_get_datetime_format():
    return get_format('DATETIME_INPUT_FORMATS')[0]

@register.assignment_tag(takes_context=True)
def jet_get_menu(context):
    if settings.JET_SIDE_MENU_CUSTOM_APPS not in (None, False):
        app_list = get_app_list(context, False)
        app_dict = {}
        models_dict = {}

        for app in app_list:
            app_label = app.get('app_label', app.get('name'))
            app_dict[app_label] = app

            for model in app['models']:
                if app_label not in models_dict:
                    models_dict[app_label] = {}

                models_dict[app_label][model['object_name']] = model

            app['models'] = []

        app_list = []
        settings_app_list = settings.JET_SIDE_MENU_CUSTOM_APPS

        if isinstance(settings_app_list, dict):
            admin_site = get_admin_site(context)
            settings_app_list = settings_app_list.get(admin_site.name, [])

        for item in settings_app_list:
            app_label, models = item

            if app_label in app_dict:
                app = app_dict[app_label]

                for model_label in models:
                    if model_label == '__all__':
                        app['models'] = models_dict[app_label].values()
                        break
                    elif model_label in models_dict[app_label]:
                        model = models_dict[app_label][model_label]
                        app['models'].append(model)

                app_list.append(app)
    else:
        app_list = get_app_list(context)

    current_found = False

    pinned = PinnedApplication.objects.filter(user=context.get('user').pk).values_list('app_label', flat=True)

    all_aps = []
    apps = []
    pinned_apps = []

    for app in app_list:
        if not current_found:
            for model in app['models']:
                if 'admin_url' in model and context['request'].path.startswith(model['admin_url']):
                    model['current'] = True
                    current_found = True
                    break

            if not current_found and context['request'].path.startswith(app['app_url']):
                app['current'] = True
                current_found = True

        if app.get('app_label', app.get('name')) in pinned:
            pinned_apps.append(app)
        else:
            apps.append(app)

        all_aps.append(app)

    return {'apps': apps, 'pinned_apps': pinned_apps, 'all_apps': all_aps}

@register.assignment_tag
def jet_get_bookmarks(user):
    if user is None:
        return None
    return Bookmark.objects.filter(user=user.pk)

@register.filter
def jet_is_checkbox(field):
    return field.field.widget.__class__.__name__ == CheckboxInput().__class__.__name__

@register.filter
def jet_select2_lookups(field):
    if hasattr(field, 'field') and \
            (isinstance(field.field, ModelChoiceField) or isinstance(field.field, ModelMultipleChoiceField)):
        qs = field.field.queryset
        model = qs.model

        if getattr(model, 'autocomplete_search_fields', None) and getattr(field.field, 'autocomplete', True):
            choices = []
            app_label = model._meta.app_label
            model_name = model._meta.object_name

            attrs = {
                'class': 'ajax',
                'data-app-label': app_label,
                'data-model': model_name,
                'data-ajax--url': reverse('jet:model_lookup')
            }

            form = field.form
            initial_value = form.data.get(field.name) if form.data != {} else form.initial.get(field.name)

            if hasattr(field, 'field') and isinstance(field.field, ModelMultipleChoiceField):
                if initial_value:
                    initial_objects = model.objects.filter(pk__in=initial_value)
                    choices.extend(
                        [(initial_object.pk, get_model_instance_label(initial_object))
                            for initial_object in initial_objects]
                    )

                if isinstance(field.field.widget, RelatedFieldWidgetWrapper):
                    field.field.widget.widget = SelectMultiple(attrs)
                else:
                    field.field.widget = SelectMultiple(attrs)
                field.field.choices = choices
            elif hasattr(field, 'field') and isinstance(field.field, ModelChoiceField):
                if initial_value:
                    try:
                        initial_object = model.objects.get(pk=initial_value)
                        attrs['data-object-id'] = initial_value
                        choices.append((initial_object.pk, get_model_instance_label(initial_object)))
                    except model.DoesNotExist:
                        pass

                if isinstance(field.field.widget, RelatedFieldWidgetWrapper):
                    field.field.widget.widget = Select(attrs)
                else:
                    field.field.widget = Select(attrs)
                field.field.choices = choices

    return field

@register.assignment_tag(takes_context=True)
def jet_get_current_theme(context):
    if 'request' in context and 'JET_THEME' in context['request'].COOKIES:
        theme = context['request'].COOKIES['JET_THEME']
        if isinstance(settings.JET_THEMES, list) and len(settings.JET_THEMES) > 0:
            for conf_theme in settings.JET_THEMES:
                if isinstance(conf_theme, dict) and conf_theme.get('theme') == theme:
                    return theme
    return settings.JET_DEFAULT_THEME

@register.assignment_tag
def jet_get_themes():
    return settings.JET_THEMES

@register.assignment_tag
def jet_get_current_version():
    return VERSION

@register.filter
def jet_append_version(url):
    if '?' in url:
        return '%s&v=%s' % (url, VERSION)
    else:
        return '%s?v=%s' % (url, VERSION)

@register.assignment_tag
def jet_get_side_menu_compact():
    return settings.JET_SIDE_MENU_COMPACT

@register.assignment_tag
def jet_change_form_sibling_links_enabled():
    return settings.JET_CHANGE_FORM_SIBLING_LINKS

def jet_sibling_object_url(context, next):
    original = context.get('original')

    if not original:
        return

    model = type(original)
    preserved_filters_plain = context.get('preserved_filters', '')
    preserved_filters = dict(parse_qsl(preserved_filters_plain))
    admin_site = get_admin_site(context)

    if admin_site is None:
        return

    request = context.get('request')
    queryset = get_model_queryset(admin_site, model, request, preserved_filters=preserved_filters)

    if queryset is None:
        return

    sibling_object = None
    object_pks = list(queryset.values_list('pk', flat=True))

    try:
        index = object_pks.index(original.pk)
        sibling_index = index + 1 if next else index - 1
        exists = sibling_index < len(object_pks) if next else sibling_index >= 0
        sibling_object = queryset.get(pk=object_pks[sibling_index]) if exists else None
    except ValueError:
        pass

    if sibling_object is None:
        return

    url = reverse('%s:%s_%s_change' % (
        admin_site.name,
        model._meta.app_label,
        model._meta.model_name
    ), args=(sibling_object.pk,))

    if preserved_filters_plain != '':
        url += '?' + preserved_filters_plain

    return url

@register.assignment_tag(takes_context=True)
def jet_previous_object_url(context):
    return jet_sibling_object_url(context, False)

@register.assignment_tag(takes_context=True)
def jet_next_object_url(context):
    return jet_sibling_object_url(context, True)

@register.assignment_tag(takes_context=True)
def jet_popup_response_data(context):
    if context.get('popup_response_data'):
        return context['popup_response_data']

    return json.dumps({
        'action': context.get('action'),
        'value': context.get('value') or context.get('pk_value'),
        'obj': smart_text(context.get('obj')),
        'new_value': context.get('new_value')
    })

@register.simple_tag(takes_context=True)
def jet_delete_confirmation_context(context):
    if context.get('deletable_objects') is None and context.get('deleted_objects') is None:
        return ''
    return mark_safe('

')

@register.assignment_tag
def jet_static_translation_urls():
    language_codes = get_possible_language_codes()

    urls = []
    url_templates = [
        'jet/js/i18n/jquery-ui/datepicker-__LANGUAGE_CODE__.js',
        'jet/js/i18n/jquery-ui-timepicker/jquery.ui.timepicker-__LANGUAGE_CODE__.js',
        'jet/js/i18n/select2/__LANGUAGE_CODE__.js'
    ]

    static_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static')

    for tpl in url_templates:
        for language_code in language_codes:
            url = tpl.replace('__LANGUAGE_CODE__', language_code)
            path = os.path.join(static_dir, url)

            if os.path.exists(path):
                urls.append(url)
                break

    return urls


text:
require 'helper'

class TestTinymceSpellcheck < Test::Unit::TestCase
  should "probably rename this file and start testing for real" do
    flunk "hey buddy, you should probably rename this file and start testing for real"
  end
end


text:
package org.apache.hadoop.mapreduce;

import org.apache.hadoop.classification.InterfaceAudience;

@InterfaceAudience.Private
public abstract class StatusReporter {
  public abstract Counter getCounter(Enum<?> name);
  public abstract Counter getCounter(String group, String name);
  public abstract void progress();
  /**
   * Get the current progress.
   * @return a number between 0.0 and 1.0 (inclusive) indicating the attempt's
   * progress.
   */
  public abstract float getProgress();
  public abstract void setStatus(String status);
}


text:
package chimp

import (
    "log"
    "os"
    "io"
)

var (
    Stderr = os.Stdout
)

type TaskLogger struct {
    ln *log.Logger
}

func newTaskLogger(ln *log.Logger) *TaskLogger {
    tl := &TaskLogger{ln}
    tl.ln = ln
    return tl
}

func (tl *TaskLogger) Error(fmt string, v ...interface{}) {
    tl.ln.Printf("[ERROR] - " + fmt + "\n", v...)
}

func (tl *TaskLogger) Info(fmt string, v ...interface{}) {
    tl.ln.Printf("[INFO] - " + fmt + "\n", v...)
}

/**
Create a new loger which points to Stderr
*/
func NewLog(name string) *TaskLogger {
    ln := log.New(Stderr, "[" + name + "] ", log.Ldate | log.Ltime)
    return newTaskLogger(ln)
}

/**
Create a new loger which points to file
*/
func NewFileLog(name string, file io.Writer) *TaskLogger {
    ln := log.New(file, "[" + name + "] ", log.Ldate | log.Ltime)
    return newTaskLogger(ln)
}


text:
package org.jboss.resteasy.resteasy1008;

import javax.ejb.Stateful;
import javax.validation.constraints.Min;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Path("test")
@Stateful
public class SessionResourceImpl implements SessionResource
{
   private static final Logger log = LoggerFactory.getLogger(SessionResourceImpl.class);

   @GET
   @Path("resource/{param}")
   @Produces(MediaType.TEXT_PLAIN)
   public int test(@PathParam("param") int param)
   {
      log.info("entering SessionResourceImpl.test()");
      return param;
   }
}


text:
[Prefix your PR title with [WIP], if it's a 'work in progress',
or if you're looking for feedback before merging.]

A brief description of the Pull Request goes here. If you haven't yet done so,
please read the 'contributing guidelines' thoroughly.

See: https://github.com/bolt/bolt/blob/master/.github/CONTRIBUTING.md

Fixes: #1555 (please refer to an existing issue number, that this PR fixes)

Details
-------

Please list any details for the PR, that might be relevant. Some pointers:

 - Please include tests with your PR. If you do, we will love you for it.
 - Check if the change in the PR is a good fit for Bolt, or if it would be
   better off as an extension.
 - Make sure you're doing the PR to the correct branch: 'master' for 3.0, or
   'release/2.2' for Bolt 2.2.x.


text:
#include "resource.h"

// CMtnPosnCompensDlg dialog

class CMtnPosnCompensDlg : public CDialog
{
	DECLARE_DYNAMIC(CMtnPosnCompensDlg)

public:
	CMtnPosnCompensDlg(HANDLE hInHandle, CWnd* pParent = NULL);   // standard constructor
	virtual ~CMtnPosnCompensDlg();
	virtual void ShowWindow(int nCmdShow);

	void UpdateDataFromVarToUI();
	void UpdateDataFromUIToVar();
	void UpdateEditCurrSegment(unsigned int uiCurrSeg);

	void UI_UpdateEditByDetectionFlag(char cFlagDetectionSwitch);

	void UI_InitPositionForceCalibrationDlg(); // 20121129
	HANDLE m_hHandle;
	void ThreadDoSearchContactWithForceControl();
	void ThreadDoForceVerification(); // 20130103
	void ThreadDoForceCalibration();

	void ThreadDoForceVerificationByGramJig(); // 20130107

	void Thread_ForceLogVerification();  // 20130103

	CWinThread* m_pWinThreadPosnForceCali;

	void RunPosnForceCaliThread();
	void StopPosnForceCaliThread();
//	void DoThreadForceVerificationLog();

	BOOL mFlagStopPosnForceCaliThread;
	void UI_SetEnableButton(BOOL bFlagEnable);
	void ReadDoubleFromEdit(int nResId, double *pdValue);

	int UI_GetShowWindowFlag();
	void DlgTimerEvent();
	void DlgEventUpdateForceFbAdc();
	void InitForceFbAdc();
// Dialog Data
	enum { IDD = IDC_POSNCOMPN_OFFSET_LABEL};

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

	virtual BOOL OnInitDialog();

	DECLARE_MESSAGE_MAP()
public:
	afx_msg void OnBnClickedPosnCompensateStartTune();
	afx_msg void OnBnClickedPosncompenDebugFlag();
	afx_msg void OnBnClickedPosnCompensateStartVerify();
	afx_msg void OnBnClickedButtonTeachContact();
	afx_msg void OnEnChangeEditForceControlMaxSegment();
	afx_msg void OnCbnSelchangeComboForceControlEditSegment();
	afx_msg void OnEnChangeEditForceControlRampCountCurrSeg();
	afx_msg void OnEnChangeEditForceControlLevelCntCurrSeg();
	afx_msg void OnEnChangeEditForceControlLevelAmpCurrSeg();
	afx_msg void OnBnClickedButtonSearchContactWithForceControl();
	afx_msg void OnEnChangeForceControlHoldCountInitForce();
	afx_msg void OnBnClickedButtonForceCalibration();
	afx_msg void OnBnClickedButtonForceVerification();
	afx_msg void OnEnChangeEditForceCaliTotalSeg();
	afx_msg void OnEnChangeEditForceCaliGramFirstSeg();
	afx_msg void OnEnChangeEditForceCaliGramLastSeg();
	afx_msg void OnEnChangeEditForceVerifyDesiredGram();
	afx_msg void OnEnChangePosncompnUpperLimit();
	afx_msg void OnEnChangePosncompnTotalPoint();
	afx_msg void OnEnChangePosncompnLowerLimit();
	afx_msg void OnBnClickedButtonVerificationLog();
	afx_msg void OnBnClickedOkDialogPositionCompensation();
	afx_msg void OnBnClickedCheckContactTuneFlagB1w();
	afx_msg void OnCbnSelchangeComboPosnForceCompensationDlgForceControlDetectionFlag();
	afx_msg void OnEnKillfocusPosncompnUpperLimit();
	afx_msg void OnEnKillfocusPosncompnLowerLimit();
	afx_msg void OnEnKillfocusEditTeachContactStartDist();
	afx_msg void OnEnKillfocusPosncompnTotalPoint();
	afx_msg void OnEnKillfocusEditTeachContactStartVel();
	afx_msg void OnEnKillfocusEditTeachContactSearchVel();
	afx_msg void OnEnKillfocusEditTeachContactEndPosn();
	afx_msg void OnEnKillfocusEditTeachContactMaxDist();
	afx_msg void OnEnKillfocusEditTeachContactAntiBounce();
	afx_msg void OnEnKillfocusEditTeachContactTimeOut();
	afx_msg void OnEnKillfocusEditForceControlMaxSegment();
	afx_msg void OnEnKillfocusEditContactForceLoopTest();
	afx_msg void OnEnKillfocusEditForceControlRampCountCurrSeg();
	afx_msg void OnEnKillfocusEditForceControlLevelCntCurrSeg();
	afx_msg void OnEnKillfocusEditForceControlLevelAmpCurrSeg();
	afx_msg void OnEnKillfocusEditForceCaliTotalSeg();
	afx_msg void OnEnKillfocusEditForceCaliGramFirstSeg();
	afx_msg void OnEnKillfocusEditForceCaliGramLastSeg();
	afx_msg void OnEnKillfocusEditForceVerifyDesiredGram();
	afx_msg void OnCbnSelchangeComboSearchVelPosnForceCalibrationDlg();
	afx_msg void OnCbnSelchangeComboSearchTolPePosnForceCalibrationDlg();
	afx_msg void OnCbnKillfocusComboDampPosnForceCalibrationDlg();
	afx_msg void OnCbnSelchangeComboPreImpForcePositionForceCaliDlg();
	afx_msg void OnEnKillfocusEditMaxJerkMoveSrchHtPosnForceCaliDlg();
	afx_msg void OnCbnSelchangeComboLoopCountCheckForcePositionCalibrationDlg();
	afx_msg void OnBnClickedButtonCalibrateForceRatioPosnForceCalibrateDlg();
	afx_msg void OnEnSetfocusEditForceReadByGramGaugePosnForceDlg();
	afx_msg void OnEnKillfocusForceVerifyTrialsPerLoop();
	afx_msg void OnBnClickedCheckForceVerifyByGramJig();
	afx_msg void OnEnKillfocusEditForceCaliDeltaDcom();
};