text:
void foo(int) __attribute__((xray_log_args(1)));
struct __attribute__((xray_log_args(1))) a { int x; }; // expected-warning {{'xray_log_args' attribute only applies to functions and Objective-C methods}}

void fop() __attribute__((xray_log_args(1))); // expected-error {{'xray_log_args' attribute parameter 1 is out of bounds}}

void foq() __attribute__((xray_log_args(-1))); // expected-error {{'xray_log_args' attribute parameter 1 is out of bounds}}

void fos() __attribute__((xray_log_args(0))); // expected-error {{'xray_log_args' attribute parameter 1 is out of bounds}}


text:
require 'libxml'
LibXML::XML.indent_tree_output = true

module Spreadsheet
  class LibxmlXmlBuilder
    def initialize
      @document = LibXML::XML::Document.new
      @node = nil
    end

    def tag!(name, attrs={}, content=nil)
      node = LibXML::XML::Node.new(name.to_s)
      node << content.to_s if content
      attrs.each { |k, v| LibXML::XML::Attr.new(node, k.to_s, v.to_s) }
      if @document.root
        @node << node
      else
        @node = node
        @document.root = node
      end
      if block_given?
        node, @node = @node, node
        yield
        @node = node
      end
    end

    def import!(builder)
      @node << @document.import(builder.root)
    end

    def to_s
      @document.to_s
    end

  protected

    def root
      @document.root
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
import collections
from ascetic.databases.base import Database
from ascetic.utils import cached_property

@Database.register('postgresql')
class PostgreSQLDatabase(Database):

    @cached_property
    def psycopg2(self):
        import psycopg2
        psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
        psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
        return psycopg2

    def connection_factory(self, **kwargs):
        return self.psycopg2.connect(**kwargs)

    def last_insert_id(self, cursor):
        cursor.execute("SELECT lastval()")
        return cursor.fetchone()[0]

    def read_pk(self, db_table):
        # https://wiki.postgresql.org/wiki/Retrieve_primary_key_columns
        cursor = self.execute("""
        SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type
        FROM   pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid
               AND a.attnum = ANY(i.indkey)
        WHERE  i.indrelid = %s::regclass
               AND i.indisprimary
        ORDER BY a.attnum;
        """, [db_table])
        return tuple(i[0] for i in cursor.fetchall())

    def describe_table(self, db_table):
        cursor = self.execute("""
            SELECT column_name, ordinal_position, data_type, is_nullable, column_default, character_maximum_length
            FROM   information_schema.columns
            WHERE  table_name = %s
            ORDER BY ordinal_position;
        """, [db_table])
        schema = collections.OrderedDict()
        for row in cursor.fetchall():
            col = {
                'column': row[0],
                'position': row[1],
                'data_type': row[2],
                'null': row[3].upper() == 'YES',
                # 'default': row[4],
                'max_length': row[5],
            }
            schema[col['column']] = col
        return schema

    def set_autocommit(self, autocommit):
        # The server-side autocommit setting was removed and reimplemented in client applications and languages.
        # Server-side autocommit was causing too many problems with languages and applications that wanted
        # to control their own autocommit behavior, so autocommit was removed from the server and added to individual
        # client APIs as appropriate.
        # https://www.postgresql.org/docs/7.4/static/release-7-4.html
        # self.execute("SET AUTOCOMMIT = {}".format('ON' if autocommit else 'OFF'))
        self.connection.set_session(autocommit=autocommit)
        super(PostgreSQLDatabase, self).set_autocommit(autocommit)


text:
Html5hivRails simply provides the [html5him.js and html5shim-printshim.js](https://github.com/aFarkas/html5shiv) libraries in a rails engine form.

## Rails 3.2 and up

For Rails 3.1 and greater, the files will be added to the asset pipeline and available for you to use.  You have the option of `html5shiv.js` and `html5shiv-printshiv.js`, depending on if you need to support printing.

### Installation

Just add this to your Gemfile:

    gem 'html5shiv-rails'

and run

    bundle install

### Usage

Since you probably only want to include this when serving IE, place it in a conditional comment in the `<head>` section in your layout:

    <!--[if lt IE 9]>
      <%= javascript_include_tag 'html5shiv-printshiv' %>
    <![endif]-->


text:
<?php

/**
 * IConnectionTableOptionStatement interface file.
 *
 * @author Anastaszor
 */
interface IConnectionTableOptionStatement extends ITableOptionStatement
{

	/**
	 *
	 * @return string
	 */
	public function getConnectionString();

}


text:
<?xml version="1.0" encoding="utf-16"?>

<CompatibleDialogText xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Title>LMP <-> KSP kompatibilitet</Title>
  <Text>Denne version af LMP er ikke kompatibel med din nuværende KSP -version.</Text>
  <Accept>Godkend</Accept>
</CompatibleDialogText>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Gnomonia rhoina Feltgen

### Remarks
null


text:
namespace shape
{
    public class Triangle:Shape,ISurface
    {
        public Triangle(double width, double height):base(width, height)
        {
        }

        public override double CalculateSurface()
        {
            double surface = this.Width * this.Height / 2;
            return surface;
        }
        public override string ToString()
        {
            return string.Format("Triangle");
        }
    }
}


text:
Semantic HTML
=============

### Problem 1. Refactoring
*	Refactor (edit) the [homework-refactoring.html](https://github.com/TelerikAcademy/HTML/blob/master/Topics/05.%20Semantic-HTML/homework/homework-refactoring.html) web page and make it HTML semantic.

### Problem 2. Student System
*	Create a web page using semantic HTML by the design.
*	Use some kind of approach to support old (non-HTML5-compatible) Web browsers like IE8.

![picture1](https://cloud.githubusercontent.com/assets/3619393/7179645/ba6f880e-e442-11e4-9f54-235e88cb686a.png)

_Note: Do not try to make the same styles. Implement just the content with its semantics._

### Problem 3. LinkedIn
*	Create a web page using semantic HTML by the design.

![picture2](https://cloud.githubusercontent.com/assets/3619393/7179271/ac996bf4-e43e-11e4-981f-d0914a8ca92d.png)

_Note: Do not try to make the same styles. Implement just the content with its semantics._


text:
package com.bstek.bdf3.dbconsole.model;

import java.util.List;
import java.util.Map;

public class DataGridWrapper {
	private List<ColumnInfo> columnNames;
	private int pageSize;

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	private int totalCount;

	public List<ColumnInfo> getColumnNames() {
		return columnNames;
	}

	public void setColumnNames(List<ColumnInfo> columnNames) {
		this.columnNames = columnNames;
	}

	private List<Map<String, Object>> tableData;

	public List<Map<String, Object>> getTableData() {
		return tableData;
	}

	public void setTableData(List<Map<String, Object>> tableData) {
		this.tableData = tableData;
	}

}


text:
package com.alliander.osgp.domain.core.valueobjects;

public enum EventType {
    DIAG_EVENTS_GENERAL(0), HARDWARE_FAILURE_RELAY(1), LIGHT_FAILURE_DALI_COMMUNICATION(2), LIGHT_FAILURE_BALLAST(3), LIGHT_EVENTS_LIGHT_ON(
            4), LIGHT_EVENTS_LIGHT_OFF(5), MONITOR_EVENTS_LONG_BUFFER_FULL(6), FIRMWARE_EVENTS_ACTIVATING(7), FIRMWARE_EVENTS_DOWNLOAD_NOTFOUND(
            8), FIRMWARE_EVENTS_DOWNLOAD_FAILED(9), LIGHT_FAILURE_TARIFF_SWITCH_ATTEMPT(10), TARIFF_EVENTS_TARIFF_ON(11), TARIFF_EVENTS_TARIFF_OFF(
            12), MONITOR_FAILURE_P1_COMMUNICATION(13), COMM_EVENTS_ALTERNATIVE_CHANNEL(14), COMM_EVENTS_RECOVERED_CHANNEL(
            15), SECURITY_EVENTS_OUT_OF_SEQUENCE(16), MONITOR_SHORT_DETECTED(17), MONITOR_SHORT_RESOLVED(18), MONITOR_DOOR_OPENED(
            19), MONITOR_DOOR_CLOSED(20);

    private int value;

    EventType(final int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}


text:
@class DVTDocumentLocation, DVTSourceCodeSymbolKind, NSString;

@interface IDESourceCodeAdjustNodeTypesResult : NSObject
{
    DVTDocumentLocation *_location;
    NSString *_symbolName;
    DVTSourceCodeSymbolKind *_symbolKind;
    BOOL _isInProject;
}

@property(readonly) BOOL isInProject; // @synthesize isInProject=_isInProject;
@property(readonly) DVTSourceCodeSymbolKind *symbolKind; // @synthesize symbolKind=_symbolKind;
@property(readonly) NSString *symbolName; // @synthesize symbolName=_symbolName;
@property(readonly) DVTDocumentLocation *location; // @synthesize location=_location;
- (void).cxx_destruct;
- (id)initWithLocation:(id)arg1 symbolName:(id)arg2 symbolKind:(id)arg3 isInProject:(BOOL)arg4;

@end


text:
package org.apache.ignite.internal.processors.cache.database.evict;

import java.util.concurrent.ThreadLocalRandom;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.configuration.MemoryConfiguration;
import org.apache.ignite.configuration.MemoryPolicyConfiguration;
import org.apache.ignite.internal.pagemem.PageIdUtils;
import org.apache.ignite.internal.pagemem.PageMemory;
import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.util.GridUnsafe;
import org.apache.ignite.internal.util.typedef.internal.LT;
import org.apache.ignite.internal.util.typedef.internal.U;

/**
 *
 */
public class Random2LruPageEvictionTracker extends PageAbstractEvictionTracker {
    /** Evict attempts limit. */
    private static final int EVICT_ATTEMPTS_LIMIT = 30;

    /** LRU Sample size. */
    private static final int SAMPLE_SIZE = 5;

    /** Maximum sample search spin count */
    private static final int SAMPLE_SPIN_LIMIT = SAMPLE_SIZE * 1000;

    /** Logger. */
    private final IgniteLogger log;

    /** Tracking array ptr. */
    private long trackingArrPtr;

    /**
     * @param pageMem Page memory.
     * @param plcCfg Policy config.
     * @param sharedCtx Shared context.
     */
    public Random2LruPageEvictionTracker(
        PageMemory pageMem,
        MemoryPolicyConfiguration plcCfg,
        GridCacheSharedContext<?, ?> sharedCtx
    ) {
        super(pageMem, plcCfg, sharedCtx);

        MemoryConfiguration memCfg = sharedCtx.kernalContext().config().getMemoryConfiguration();

        assert plcCfg.getSize() / memCfg.getPageSize() < Integer.MAX_VALUE;

        log = sharedCtx.logger(getClass());
    }

    /** {@inheritDoc} */
    @Override public void start() throws IgniteException {
        trackingArrPtr = GridUnsafe.allocateMemory(trackingSize * 8);

        GridUnsafe.setMemory(trackingArrPtr, trackingSize * 8, (byte)0);
    }

    /** {@inheritDoc} */
    @Override public void stop() throws IgniteException {
        GridUnsafe.freeMemory(trackingArrPtr);
    }

    /** {@inheritDoc} */
    @Override public void touchPage(long pageId) throws IgniteCheckedException {
        int pageIdx = PageIdUtils.pageIndex(pageId);

        long latestTs = compactTimestamp(U.currentTimeMillis());

        assert latestTs >= 0 && latestTs < Integer.MAX_VALUE;

        boolean success;

        do {
            int trackingIdx = trackingIdx(pageIdx);

            int firstTs = GridUnsafe.getIntVolatile(null, trackingArrPtr + trackingIdx * 8);

            int secondTs = GridUnsafe.getIntVolatile(null, trackingArrPtr + trackingIdx * 8 + 4);

            if (firstTs <= secondTs)
                success = GridUnsafe.compareAndSwapInt(null, trackingArrPtr + trackingIdx * 8, firstTs, (int)latestTs);
            else {
                success = GridUnsafe.compareAndSwapInt(
                    null, trackingArrPtr + trackingIdx * 8 + 4, secondTs, (int)latestTs);
            }
        } while (!success);
    }

    /** {@inheritDoc} */
    @Override public void evictDataPage() throws IgniteCheckedException {
        ThreadLocalRandom rnd = ThreadLocalRandom.current();

        int evictAttemptsCnt = 0;

        while (evictAttemptsCnt < EVICT_ATTEMPTS_LIMIT) {
            int lruTrackingIdx = -1;

            int lruCompactTs = Integer.MAX_VALUE;

            int dataPagesCnt = 0;

            int sampleSpinCnt = 0;

            while (dataPagesCnt < SAMPLE_SIZE) {
                int trackingIdx = rnd.nextInt(trackingSize);

                int firstTs = GridUnsafe.getIntVolatile(null, trackingArrPtr + trackingIdx * 8);

                int secondTs = GridUnsafe.getIntVolatile(null, trackingArrPtr + trackingIdx * 8 + 4);

                int minTs = Math.min(firstTs, secondTs);

                int maxTs = Math.max(firstTs, secondTs);

                if (maxTs != 0) {
                    // We chose data page with at least one touch.
                    if (minTs < lruCompactTs) {
                        lruTrackingIdx = trackingIdx;

                        lruCompactTs = minTs;
                    }

                    dataPagesCnt++;
                }

                sampleSpinCnt++;

                if (sampleSpinCnt > SAMPLE_SPIN_LIMIT) {
                    LT.warn(log, "Too many attempts to choose data page: " + SAMPLE_SPIN_LIMIT);

                    return;
                }
            }

            if (evictDataPage(pageIdx(lruTrackingIdx)))
                return;

            evictAttemptsCnt++;
        }

        LT.warn(log, "Too many failed attempts to evict page: " + EVICT_ATTEMPTS_LIMIT);
    }

    /** {@inheritDoc} */
    @Override protected boolean checkTouch(long pageId) {
        int trackingIdx = trackingIdx(PageIdUtils.pageIndex(pageId));

        int firstTs = GridUnsafe.getIntVolatile(null, trackingArrPtr + trackingIdx * 8);

        return firstTs != 0;
    }

    /** {@inheritDoc} */
    @Override public void forgetPage(long pageId) {
        int pageIdx = PageIdUtils.pageIndex(pageId);

        int trackingIdx = trackingIdx(pageIdx);

        GridUnsafe.putLongVolatile(null, trackingArrPtr + trackingIdx * 8, 0L);
    }
}


text:
<?php

namespace CodesWholesale\Util;

class Magic
{

    /** @var array Hash of methods available to the class (provides fast isset() lookups) */
    private $methods;

    public function __construct()
    {
        $this->methods = array_flip(get_class_methods(get_class($this)));
    }

    /**
     * Magic "get" method
     *
     * @param string $property Property name
     * @return mixed|null Property value if it exists, null if not
     */
    public function __get($property)
    {

        $method = 'get' . ucfirst($property);
        if (isset($this->methods[$method])) {
            return $this->{$method}();
        }

        return null;
    }

    /**
     * Magic "set" method
     *
     * @param string $property Property name
     * @param mixed $value Property value
     */
    public function __set($property, $value)
    {
        $method = 'set' . ucfirst($property);
        if (isset($this->methods[$method])) {
            $this->{$method}($value);
        }
    }
}


text:
# IMPORTANT: Before releasing this package, copy/paste the next 2 lines into PowerShell to remove all comments from this file:
#   $f='c:\path\to\thisFile.ps1'
#   gc $f | ? {$_ -notmatch "^\s*#"} | % {$_ -replace '(^.*?)\s*?[^``]#.*','$1'} | Out-File $f+".~" -en utf8; mv -fo $f+".~" $f

$ErrorActionPreference = 'Stop';

$packageArgs = @{
  packageName   = $env:ChocolateyPackageName
  softwareName  = 'usacloud*'
  zipFileName   = 'usacloud_windows-386.zip'
  zipFileName64 = 'usacloud_windows-amd64.zip'
}

$uninstalled = $false

# Only necessary if you did not unpack to package directory - see https://chocolatey.org/docs/helpers-uninstall-chocolatey-zip-package
$os = Get-WmiObject -Class Win32_OperatingSystem;
if ($os.OSarchitecture.Contains("64")) {
  Uninstall-ChocolateyZipPackage -PackageName $packageArgs['packageName'] -ZipFileName $packageArgs['zipFileName']
} else {
  Uninstall-ChocolateyZipPackage -PackageName $packageArgs['packageName'] -ZipFileName $packageArgs['zipFileName64']
}


text:
package edu.pdx.cs410J.whitlock.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import edu.pdx.cs410J.whitlock.client.Generation;
import edu.pdx.cs410J.whitlock.client.GenerationService;

import java.util.Random;

/**
 * The server-side implementation of the division service
 */
public class GenerationServiceImpl extends RemoteServiceServlet implements GenerationService
{

  private GameOfLife game;

  @Override
  public Generation createNewGameOfLife(int numberOfRows, int numberOfColumns) {
    game = new GameOfLife(numberOfRows, numberOfColumns);
    populateGameWithRandomCells(game);
    return game.getCurrentGeneration();
  }

  @Override
  public Generation getNextGeneration() {
    this.game.computeNextGeneration();
    return game.getCurrentGeneration();
  }

  private void populateGameWithRandomCells(GameOfLife game) {
    Random random = new Random();
    for (int row = 0; row < game.getRowCount(); row++) {
      StringBuilder rowString = new StringBuilder();
      for (int column = 0; column < game.getColumnCount(); column++) {
        rowString.append(getRandomCellState(random));
      }
      game.addRow(rowString.toString());
    }

  }

  private char getRandomCellState(Random random) {
    boolean isAlive = random.nextBoolean();
    return isAlive ? '*' : '.';
  }

  @Override
  protected void doUnexpectedFailure(Throwable unhandled) {
    unhandled.printStackTrace(System.err);
    super.doUnexpectedFailure(unhandled);
  }

}


text:
package ch.ninecode.sc

/**
 * Errors encountered in processing.
 *
 * @param fatal   if true processing should stop, otherwise it can proceed
 * @param invalid if true the results are invalid, otherwise the results are valid
 * @param message the error message
 */
case class ScError
(
    fatal: Boolean,
    invalid: Boolean,
    message: String)
{
    override def toString: String = (if (fatal) "FATAL: " else
        if (invalid) "INVALID: " else "") + message
}

object ScError
{
    @SuppressWarnings(Array("org.wartremover.warts.Null"))
    def combine_errors (list1: List[ScError], list2: List[ScError], max: Int): List[ScError] =
    {
        if (null == list1)
            list2
        else
            if (null == list2)
                list1
            else // both not null
            {
                // eliminate duplicates
                val l0 = list2.filter(!list1.contains(_))
                // prefer the fatal ones
                val l1 = (list1.filter(_.fatal) ++ l0.filter(_.fatal)).take(max)
                // also prefer invalid ones
                val l2 = (l1 ++ list1.filter(x => !x.fatal && x.invalid) ++ l0.filter(x => !x.fatal && x.invalid)).take(max)
                // add existing non-fatal & non-invalid messages
                val l3 = (l2 ++ list1.filter(x => !x.fatal && !x.invalid)).take(max)
                // add any new non-fatal & non-invalid messages that fit
                val l4 = (l3 ++ l0.filter(x => !x.fatal && !x.invalid)).take(max)
                if (0 == l4.length) null else l4
            }
    }
}


text:
from __future__ import annotations
import os
import shutil
import time
import gc
import threading
from typing import Optional
from utils.utilfuncs import safeprint

def DummyAsyncFileWrite(fn, writestr, access='a'):
	safeprint('Called  HB file write before init {} {} {}'.format(fn, writestr, access))

AsyncFileWrite = DummyAsyncFileWrite  # set from log support to avoid circular imports
DevPrint = None

# import topper

WatchGC = False  # set True to see garbage collection info
Buffers = {}
HBdir = ''
GCBuf: Optional[HistoryBuffer] = None
bufdumpseq = 0
HBNet = None

def SetupHistoryBuffers(dirnm, maxlogs):
	global HBdir, GCBuf
	r = [k for k in os.listdir('.') if '.HistoryBuffer' in k]
	if ".HistoryBuffer." + str(maxlogs) in r:
		shutil.rmtree(".HistoryBuffer." + str(maxlogs))
	for i in range(maxlogs - 1, 0, -1):
		if ".HistoryBuffer." + str(i) in r:
			os.rename('.HistoryBuffer.' + str(i), ".HistoryBuffer." + str(i + 1))
	# noinspection PyBroadException
	try:
		os.rename('.HistoryBuffer', '.HistoryBuffer.1')
	except:
		pass
	os.mkdir('.HistoryBuffer')
	HBdir = dirnm + '/.HistoryBuffer/'
	if WatchGC:
		gc.callbacks.append(NoteGCs)
		GCBuf = HistoryBuffer(50, 'GC')

def NoteGCs(phase, info):
	if GCBuf is not None:
		GCBuf.Entry('GC Call' + phase + repr(info))

def DumpAll(idline, entrytime):
	global bufdumpseq
	if HBdir == '':  # logs not yet set up
		safeprint(time.strftime('%m-%d-%y %H:%M:%S') + ' Suppressing History Buffer Dump for {}'.format(idline))
		return
	fn = HBdir + str(bufdumpseq) + '-' + entrytime
	try:
		#topper.mvtops(str(bufdumpseq) + '-' + entrytime)
		bufdumpseq += 1
		t = {}
		curfirst = {}
		curtime = {}
		initial = {}
		now = time.time()
		more = True
		for nm, HB in Buffers.items():
			t[nm] = HB.content()
			try:
				curfirst[nm] = next(t[nm])
				curtime[nm] = curfirst[nm][1]
			except StopIteration:
				if nm in curfirst: del curfirst[nm]
				if nm in curtime:  del curtime[nm]
			initial[nm] = '*'
		if curfirst == {} or curtime == {}:
			more = False

		prevtime = 0
		AsyncFileWrite(fn, '{} ({}): '.format(entrytime, now) + idline + '\n', 'w')
		while more:
			nextup = min(curtime, key=curtime.get)
			if curtime[nextup] > prevtime:
				prevtime = curtime[nextup]
			else:
				AsyncFileWrite(fn, 'seq error:' + str(prevtime) + ' ' + str(curtime[nextup]) + '\n')
				prevtime = 0
			if now - curfirst[nextup][1] < 300:  # limit history dump to 5 minutes worth
				AsyncFileWrite(fn,
							   '{:1s}{:10s}:({:3d}) {:.5f}: [{}] {}\n'.format(initial[nextup], nextup,
																			  curfirst[nextup][0],
																			  now - curfirst[nextup][1],
																			  curfirst[nextup][3],
																			  curfirst[nextup][2]))
				initial[nextup] = ' '
			try:
				curfirst[nextup] = next(t[nextup])
				curtime[nextup] = curfirst[nextup][1]
			except StopIteration:
				del curfirst[nextup]
				del curtime[nextup]
			if curfirst == {} or curtime == {}: more = False
	except Exception as E:
		AsyncFileWrite(fn, 'Error dumping buffer for: ' + entrytime + ': ' + idline + '\n')
		AsyncFileWrite(fn, 'Exception was: ' + repr(E) + '\n')

class EntryItem(object):
	def __init__(self):
		self.timeofentry = 0
		self.entry = ""
		self.thread = ""

class HistoryBuffer(object):
	def __init__(self, size, name):
		self.buf = []
		for i in range(size):
			self.buf.append(EntryItem())
		self.current = 0
		self.size = size
		self.name = name
		Buffers[name] = self

	def Entry(self, entry):
		self.buf[self.current].entry = entry
		self.buf[self.current].timeofentry = time.time()
		self.buf[self.current].thread = threading.current_thread().name
		self.current = (self.current + 1) % self.size

	def content(self):
		# freeze for dump and reset empty
		# this is subject to races from other threads doing entry reports
		# sequence must be create new buf offline, replace current buf with it so always one or other valid list
		# then change current back to 0
		# at worst this loses a few events that record between grabbing current and replacing with new one
		tempbuf = []
		for i in range(self.size):
			tempbuf.append(EntryItem())
		cur = self.buf
		curind = self.current
		self.buf = tempbuf
		self.current = 0
		#DevPrint('Enter HB content for: {} index {}'.format(self.name, curind))
		for i in range(self.size):
			j = (i + curind) % self.size
			if cur[j].timeofentry != 0:
				# DevPrint('Item from {}: {}/{}/{}/{}'.format(self.name, i, j, cur[j].timeofentry, cur[j].entry))
				yield j, cur[j].timeofentry, cur[j].entry, cur[j].thread
	#DevPrint('Content exit: {}/{}'.format(self.name, j))


text:
		 Change your Password:

			<form action="?update_pass" name="update_pass" autocomplete="off" method="post">
				Password: <input type="password" name="password">

		     		Repeated: <input type="password" name="password_repeat">

		     		<input type="submit" name="submit">
			</form>

<?php
if(isset($_GET['update_pass'])) {
	// GET passwords
	$password = $_POST['password'];
	$repeated = $_POST['password_repeat'];

// check if they match
if($password == $repeated) {
// What we need.
$username = htmlspecialchars($_SESSION['username']);
$userid = htmlspecialchars($_SESSION['userid']);

// Password hashing options
$options = [
'cost' => 12,
];

// Hash the password
$password_hashed = password_hash($password, PASSWORD_BCRYPT, $options);

// prepare the statement
	$stmt = $mysqli->prepare("UPDATE users SET password=? WHERE user_id=? AND username=?");

// Bind shit to it
	$stmt->bind_param("sis", $password_hashed, $userid, $username);

// Execute the statement
	$stmt->execute();

	echo "";

} else {
	echo "";
}
}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping default-access="field">
	<class name="net.chrisrichardson.foodToGo.domain.MenuItem"
		lazy="true" table="FTGO_MENU_ITEM">

		<id name="id" column="MENU_ITEM_ID" type="int"
			unsaved-value="-1">
			<generator class="native">
				<param name="sequence">FTGO_UNIQUE_ID_SEQUENCE</param>
			</generator>
		</id>

		<version name="version" column="VERSION" />
		<property name="name" column="NAME" />
		<property name="price" column="PRICE" />
	</class>

</hibernate-mapping>


text:
<?php

namespace M6Web\Bundle\XRequestUidBundle\Guzzle;

use GuzzleHttp\ClientInterface;
use M6Web\Bundle\XRequestUidBundle\UniqId\UniqIdInterface;
use GuzzleHttp\Client;
use Psr\Http\Message\RequestInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Class GuzzleProxy
 * proxy for guzzle, adding the X-Request-Uid
 * The proxy extends the guzzle client to pass all interfaces
 *
 */
class GuzzleProxy implements ClientInterface
{

    /**
     * @var Client
     */
    protected $guzzleClient;

    protected $allowedMethods = [
        'get',
        'head',
        'put',
        'post',
        'patch',
        'delete',
        'getAsync',
        'headAsync',
        'putAsync',
        'postAsync',
        'patchAsync',
        'deleteAsync',
    ];

    /**
     * @var RequestStack
     */
    protected $requestStack;

    /**
     * @var UniqIdInterface
     */
    protected $uniqId;

    /**
     * @var string
     */
    protected $headerName;

    /**
     * @var string
     */
    protected $headerParentName;

    /**
     * @param Client          $guzzleClient
     * @param RequestStack    $requestStack
     * @param UniqIdInterface $uniqId
     * @param string          $headerName
     * @param string          $headerParentName
     */
    public function __construct(Client $guzzleClient, RequestStack $requestStack, UniqIdInterface $uniqId, $headerName, $headerParentName)
    {
        $this->guzzleClient     = $guzzleClient;
        $this->requestStack     = $requestStack;
        $this->uniqId           = $uniqId;
        $this->headerName       = $headerName;
        $this->headerParentName = $headerParentName;
    }

    /**
     * 12 methods used with guzzle
     *
     * @param string $method
     * @param array  $args
     *
     * @method ResponseInterface get($uri, array $options = [])
     * @method ResponseInterface head($uri, array $options = [])
     * @method ResponseInterface put($uri, array $options = [])
     * @method ResponseInterface post($uri, array $options = [])
     * @method ResponseInterface patch($uri, array $options = [])
     * @method ResponseInterface delete($uri, array $options = [])
     * @method Promise\PromiseInterface getAsync($uri, array $options = [])
     * @method Promise\PromiseInterface headAsync($uri, array $options = [])
     * @method Promise\PromiseInterface putAsync($uri, array $options = [])
     * @method Promise\PromiseInterface postAsync($uri, array $options = [])
     * @method Promise\PromiseInterface patchAsync($uri, array $options = [])
     * @method Promise\PromiseInterface deleteAsync($uri, array $options = [])
     *
     *
     * @return mixed
     */
    public function __call($method, $args)
    {
        $options = array_merge_recursive($args[1] ?? [], $this->getOptions($method));
        $args[1] = $options;

        // forward the call to the client
        return call_user_func_array([$this->guzzleClient, $method], $args);
    }

    /**
     * @param string $method
     * @param string $uri
     * @param array  $options
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function request($method, $uri = '', array $options = [])
    {
        $options = array_merge_recursive($options, $this->getOptions($method));

        return $this->guzzleClient->request($method, $uri, $options);
    }

    /**
     * @param string $method
     * @param string $uri
     * @param array  $options
     *
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function requestAsync($method, $uri = '', array $options = [])
    {
        $options = array_merge_recursive($options, $this->getOptions($method));

        return $this->guzzleClient->requestAsync($method, $uri, $options);
    }

    /**
     * @param RequestInterface $request
     * @param array            $options
     *
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function sendAsync(RequestInterface $request, array $options = [])
    {
        $options = array_merge_recursive($options, $this->getOptions($request->getMethod()));

        return $this->guzzleClient->sendAsync($request, $options);
    }

    /**
     * @param RequestInterface $request
     * @param array            $options
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface
     */
    public function send(RequestInterface $request, array $options = [])
    {
        $options = array_merge_recursive($options, $this->getOptions($request->getMethod()));

        return $this->guzzleClient->send($request, $options);
    }

    /**
     * @param Client $guzzle
     *
     * @return $this
     */
    public function setClient(Client $guzzle)
    {
        $this->guzzleClient = $guzzle;

        return $this;
    }

    /**
     * @param null $option
     *
     * @return array|mixed|null
     */
    public function getConfig($option = null)
    {
        return $this->guzzleClient->getConfig($option);
    }

    /**
     * @param string $method
     *
     * @return array
     */
    protected function getOptions(string $method): array
    {
        if (in_array(strtolower($method), $this->allowedMethods)) {
            // add headers to guzzle client
            $request =  $this->requestStack->getCurrentRequest();
            if ($request) {
                return [
                    'headers' => [
                        // generate a new uniqid for the request
                        $this->headerName => $this->uniqId->uniqId(),
                        // switch the id to the parent
                        $this->headerParentName => $request->attributes->get($this->headerParentName)
                    ]
                ];
            }
        }

        return [];
    }
}


text:
#ifndef FAULTINJECTOR_WARNINGS_MOCK_H
#define FAULTINJECTOR_WARNINGS_MOCK_H

/*
 * Dummy implementation of src/backend/utils/misc/faultinjector_warnings.h
 */

#endif  // FAULTINJECTOR_WARNINGS_MOCK_H


text:
let PIXI = require('pixi.js');

let CONSTS = require('../consts');
let textures = require('../textures');

class GameObject {
    constructor({stage, x, y} = {}, textureName) {
        if (!stage) {
            throw new Error('stage required');
        }

        this.createSprite(textureName, stage, x, y);

        this.hasAppearedOnScreen = false;
    }

    collidesWith(gameObject) {
        let hitbox = this.getHitboxCoordinates();
        let gameObjectHitbox = gameObject.getHitboxCoordinates();
        if (hitbox.x2 >= gameObjectHitbox.x1) {
            if (hitbox.x1 <= gameObjectHitbox.x2) {
                if (hitbox.y2 >= gameObjectHitbox.y1) {
                    if (hitbox.y1 <= gameObjectHitbox.y2) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    createSprite(textureName, stage, x=0, y=0) {
        this.sprite = new PIXI.Sprite(textures[textureName]);
        this.sprite.anchor.x = 0.5;
        this.sprite.anchor.y = 0.5;
        this.sprite.x = x;
        this.sprite.y = y;
        this.stage = stage;
        this.stage.addChild(this.sprite);
    }

    getHitboxCoordinates() {
        return {
            x1: this.x + this.hitbox.x[0],
            x2: this.x + this.hitbox.x[1],
            y1: this.y + this.hitbox.y[0],
            y2: this.y + this.hitbox.y[1],
        };
    }

    isOffScreen() {
        return this.x < 0 - CONSTS.GAME.SCREEN.PADDING
            || this.x > CONSTS.GAME.SCREEN.WIDTH + CONSTS.GAME.SCREEN.PADDING
            || this.y < 0  - CONSTS.GAME.SCREEN.PADDING
            || this.y > CONSTS.GAME.SCREEN.HEIGHT + CONSTS.GAME.SCREEN.PADDING;
    }

    isOnScreen() {
        return this.x > 0
            && this.x < CONSTS.GAME.SCREEN.WIDTH
            && this.y > 0
            && this.y < CONSTS.GAME.SCREEN.HEIGHT;
    }

    move() {
        if (!this.hasAppearedOnScreen && this.isOnScreen()) {
            this.hasAppearedOnScreen = true;
        }
    }

    remove() {
        this.stage.removeChild(this.sprite);
        if (this.collection) {
            this.collection.remove(this);
        }
    }

    removeIfDead() {
        if (this.isOffScreen() && this.hasAppearedOnScreen) {
            this.remove();
        }
    }

    get alpha() {
        return this.sprite.alpha;
    }

    set alpha(alpha) {
        return this.sprite.alpha = alpha;
    }

    get rotation() {
        return this.sprite.rotation;
    }

    set rotation(rotation) {
        return this.sprite.rotation = rotation;
    }

    get x() {
        return this.sprite.x;
    }

    set x(x) {
        return this.sprite.x = x;
    }

    get y() {
        return this.sprite.y;
    }

    set y(y) {
        return this.sprite.y = y;
    }
}
module.exports = GameObject;


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from hypothesis import given
import hypothesis.strategies as st
from multiprocessing import Process, Queue

import numpy as np
import os
import pickle
import tempfile
import shutil

from caffe2.python import core, workspace, dyndep
import caffe2.python.hypothesis_test_util as hu
from gloo.python import IoError

dyndep.InitOpsLibrary("@/caffe2/caffe2/distributed:file_store_handler_ops")
dyndep.InitOpsLibrary("@/caffe2/caffe2/distributed:redis_store_handler_ops")
dyndep.InitOpsLibrary("@/caffe2/caffe2/distributed:store_ops")
dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/gloo:gloo_ops")
dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/gloo:gloo_ops_gpu")

op_engine = 'GLOO'

class TemporaryDirectory:
    def __enter__(self):
        self.tmpdir = tempfile.mkdtemp()
        return self.tmpdir

    def __exit__(self, type, value, traceback):
        shutil.rmtree(self.tmpdir)

class TestCase(hu.HypothesisTestCase):
    test_counter = 0
    sync_counter = 0

    def run_test_locally(self, fn, device_option=None, **kwargs):
        # Queue for assertion errors on subprocesses
        queue = Queue()

        # Capture any exception thrown by the subprocess
        def run_fn(*args, **kwargs):
            try:
                with core.DeviceScope(device_option):
                    fn(*args, **kwargs)
                    workspace.ResetWorkspace()
                    queue.put(True)
            except Exception as ex:
                queue.put(ex)

        # Start N processes in the background
        procs = []
        for i in range(kwargs['comm_size']):
            kwargs['comm_rank'] = i
            proc = Process(
                target=run_fn,
                kwargs=kwargs)
            proc.start()
            procs.append(proc)

        # Test complete, join background processes
        while len(procs) > 0:
            proc = procs.pop(0)
            while proc.is_alive():
                proc.join(10)

            # Raise exception if we find any. Otherwise each worker
            # should put a True into the queue
            # Note that the following is executed ALSO after
            # the last process was joined, so if ANY exception
            # was raised, it will be re-raised here.
            self.assertFalse(queue.empty(), "Job failed without a result")
            o = queue.get()
            if isinstance(o, Exception):
                raise o
            else:
                self.assertTrue(o)

    def run_test_distributed(self, fn, device_option=None, **kwargs):
        comm_rank = os.getenv('COMM_RANK')
        self.assertIsNotNone(comm_rank)
        comm_size = os.getenv('COMM_SIZE')
        self.assertIsNotNone(comm_size)
        kwargs['comm_rank'] = int(comm_rank)
        kwargs['comm_size'] = int(comm_size)
        with core.DeviceScope(device_option):
            fn(**kwargs)
            workspace.ResetWorkspace()

    def create_common_world(self, comm_rank, comm_size, tmpdir=None, existing_cw=None):
        store_handler = "store_handler"

        # If REDIS_HOST is set, use RedisStoreHandler for rendezvous.
        if existing_cw is None:
            redis_host = os.getenv("REDIS_HOST")
            redis_port = int(os.getenv("REDIS_PORT", 6379))
            if redis_host is not None:
                workspace.RunOperatorOnce(
                    core.CreateOperator(
                        "RedisStoreHandlerCreate",
                        [],
                        [store_handler],
                        prefix=str(TestCase.test_counter) + "/",
                        host=redis_host,
                        port=redis_port))
            else:
                workspace.RunOperatorOnce(
                    core.CreateOperator(
                        "FileStoreHandlerCreate",
                        [],
                        [store_handler],
                        path=tmpdir))
            common_world = "common_world"
        else:
            common_world = str(existing_cw) + ".forked"

        inputs = [store_handler]
        if existing_cw is not None:
            inputs.append(existing_cw)
        workspace.RunOperatorOnce(
            core.CreateOperator(
                "CreateCommonWorld",
                inputs,
                [common_world],
                size=comm_size,
                rank=comm_rank,
                sync=True,
                engine=op_engine))
        return (store_handler, common_world)

    def synchronize(self, store_handler, value, comm_rank=None):
        TestCase.sync_counter += 1
        blob = "sync_{}".format(TestCase.sync_counter)
        if comm_rank == 0:
            workspace.FeedBlob(blob, pickle.dumps(value))
            workspace.RunOperatorOnce(
                core.CreateOperator(
                    "StoreSet",
                    [store_handler, blob],
                    []))
        else:
            workspace.RunOperatorOnce(
                core.CreateOperator(
                    "StoreGet",
                    [store_handler],
                    [blob]))
        return pickle.loads(workspace.FetchBlob(blob))

    def _test_broadcast(self,
                        comm_rank=None,
                        comm_size=None,
                        blob_size=None,
                        num_blobs=None,
                        tmpdir=None,
                        use_float16=False,
                        ):
        store_handler, common_world = self.create_common_world(
            comm_rank=comm_rank,
            comm_size=comm_size,
            tmpdir=tmpdir)

        blob_size = self.synchronize(
            store_handler,
            blob_size,
            comm_rank=comm_rank)

        num_blobs = self.synchronize(
            store_handler,
            num_blobs,
            comm_rank=comm_rank)

        for i in range(comm_size):
            blobs = []
            for j in range(num_blobs):
                blob = "blob_{}".format(j)
                offset = (comm_rank * num_blobs) + j
                value = np.full(blob_size, offset,
                                np.float16 if use_float16 else np.float32)
                workspace.FeedBlob(blob, value)
                blobs.append(blob)

            net = core.Net("broadcast")
            net.Broadcast(
                [common_world] + blobs,
                blobs,
                root=i,
                engine=op_engine)

            workspace.CreateNet(net)
            workspace.RunNet(net.Name())

            for j in range(num_blobs):
                np.testing.assert_array_equal(
                    workspace.FetchBlob(blobs[j]),
                    i * num_blobs)

            # Run the net a few more times to check the operator
            # works not just the first time it's called
            for _tmp in range(4):
                workspace.RunNet(net.Name())

    @given(comm_size=st.integers(min_value=2, max_value=8),
           blob_size=st.integers(min_value=1e3, max_value=1e6),
           num_blobs=st.integers(min_value=1, max_value=4),
           device_option=st.sampled_from([hu.cpu_do]),
           use_float16=st.booleans())
    def test_broadcast(self, comm_size, blob_size, num_blobs, device_option,
                       use_float16):
        TestCase.test_counter += 1
        if os.getenv('COMM_RANK') is not None:
            self.run_test_distributed(
                self._test_broadcast,
                blob_size=blob_size,
                num_blobs=num_blobs,
                use_float16=use_float16,
                device_option=device_option)
        else:
            with TemporaryDirectory() as tmpdir:
                self.run_test_locally(
                    self._test_broadcast,
                    comm_size=comm_size,
                    blob_size=blob_size,
                    num_blobs=num_blobs,
                    device_option=device_option,
                    tmpdir=tmpdir,
                    use_float16=use_float16)

    def _test_allreduce(self,
                        comm_rank=None,
                        comm_size=None,
                        blob_size=None,
                        num_blobs=None,
                        tmpdir=None,
                        use_float16=False
                        ):
        store_handler, common_world = self.create_common_world(
            comm_rank=comm_rank,
            comm_size=comm_size,
            tmpdir=tmpdir)

        blob_size = self.synchronize(
            store_handler,
            blob_size,
            comm_rank=comm_rank)

        num_blobs = self.synchronize(
            store_handler,
            num_blobs,
            comm_rank=comm_rank)

        blobs = []
        for i in range(num_blobs):
            blob = "blob_{}".format(i)
            value = np.full(blob_size, (comm_rank * num_blobs) + i,
                            np.float16 if use_float16 else np.float32)
            workspace.FeedBlob(blob, value)
            blobs.append(blob)

        net = core.Net("allreduce")
        net.Allreduce(
            [common_world] + blobs,
            blobs,
            engine=op_engine)

        workspace.CreateNet(net)
        workspace.RunNet(net.Name())

        for i in range(num_blobs):
            np.testing.assert_array_equal(
                workspace.FetchBlob(blobs[i]),
                (num_blobs * comm_size) * (num_blobs * comm_size - 1) / 2)

        # Run the net a few more times to check the operator
        # works not just the first time it's called
        for _tmp in range(4):
            workspace.RunNet(net.Name())

    def _test_allreduce_multicw(self,
                                comm_rank=None,
                                comm_size=None,
                                tmpdir=None
                                ):
        _store_handler, common_world = self.create_common_world(
            comm_rank=comm_rank,
            comm_size=comm_size,
            tmpdir=tmpdir)

        _, common_world2 = self.create_common_world(
            comm_rank=comm_rank,
            comm_size=comm_size,
            tmpdir=tmpdir,
            existing_cw=common_world)

        blob_size = 1e4
        num_blobs = 4

        for cw in [common_world, common_world2]:
            blobs = []
            for i in range(num_blobs):
                blob = "blob_{}".format(i)
                value = np.full(blob_size, (comm_rank * num_blobs) + i, np.float32)
                workspace.FeedBlob(blob, value)
                blobs.append(blob)

            net = core.Net("allreduce_multicw")
            net.Allreduce(
                [cw] + blobs,
                blobs,
                engine=op_engine)

            workspace.RunNetOnce(net)
            for i in range(num_blobs):
                np.testing.assert_array_equal(
                    workspace.FetchBlob(blobs[i]),
                    (num_blobs * comm_size) * (num_blobs * comm_size - 1) / 2)

    @given(comm_size=st.integers(min_value=2, max_value=8),
           blob_size=st.integers(min_value=1e3, max_value=1e6),
           num_blobs=st.integers(min_value=1, max_value=4),
           device_option=st.sampled_from([hu.cpu_do]),
           use_float16=st.booleans())
    def test_allreduce(self, comm_size, blob_size, num_blobs, device_option,
                       use_float16):
        TestCase.test_counter += 1
        if os.getenv('COMM_RANK') is not None:
            self.run_test_distributed(
                self._test_allreduce,
                blob_size=blob_size,
                num_blobs=num_blobs,
                use_float16=use_float16,
                device_option=device_option)
        else:
            with TemporaryDirectory() as tmpdir:
                self.run_test_locally(
                    self._test_allreduce,
                    comm_size=comm_size,
                    blob_size=blob_size,
                    num_blobs=num_blobs,
                    device_option=device_option,
                    tmpdir=tmpdir,
                    use_float16=use_float16)

    def _test_reduce_scatter(self,
                             comm_rank=None,
                             comm_size=None,
                             blob_size=None,
                             num_blobs=None,
                             tmpdir=None,
                             use_float16=False
                             ):
        store_handler, common_world = self.create_common_world(
            comm_rank=comm_rank,
            comm_size=comm_size,
            tmpdir=tmpdir)

        blob_size = self.synchronize(
            store_handler,
            blob_size,
            comm_rank=comm_rank)

        num_blobs = self.synchronize(
            store_handler,
            num_blobs,
            comm_rank=comm_rank)

        blobs = []
        for i in range(num_blobs):
            blob = "blob_{}".format(i)
            value = np.full(blob_size, (comm_rank * num_blobs) + i,
                            np.float16 if use_float16 else np.float32)
            workspace.FeedBlob(blob, value)
            blobs.append(blob)

        # Specify distribution among ranks i.e. number of elements
        # scattered/distributed to each process.
        recv_counts = np.zeros(comm_size, dtype=np.int32)
        remaining = blob_size
        chunk_size = (blob_size + comm_size - 1) / comm_size
        for i in range(comm_size):
            recv_counts[i] = min(chunk_size, remaining)
            remaining = remaining - chunk_size if remaining > chunk_size else 0
        recv_counts_blob = "recvCounts"
        workspace.FeedBlob(recv_counts_blob, recv_counts)
        blobs.append(recv_counts_blob)

        net = core.Net("reduce_scatter")
        net.ReduceScatter(
            [common_world] + blobs,
            blobs,
            engine=op_engine)

        workspace.CreateNet(net)
        workspace.RunNet(net.Name())

        for i in range(num_blobs):
            np.testing.assert_array_equal(
                np.resize(workspace.FetchBlob(blobs[i]), recv_counts[comm_rank]),
                (num_blobs * comm_size) * (num_blobs * comm_size - 1) / 2)

        # Run the net a few more times to check the operator
        # works not just the first time it's called
        for _tmp in range(4):
            workspace.RunNet(net.Name())

    @given(comm_size=st.integers(min_value=2, max_value=8),
           blob_size=st.integers(min_value=1e3, max_value=1e6),
           num_blobs=st.integers(min_value=1, max_value=4),
           device_option=st.sampled_from([hu.cpu_do]),
           use_float16=st.booleans())
    def test_reduce_scatter(self, comm_size, blob_size, num_blobs,
                            device_option, use_float16):
        TestCase.test_counter += 1
        if os.getenv('COMM_RANK') is not None:
            self.run_test_distributed(
                self._test_reduce_scatter,
                blob_size=blob_size,
                num_blobs=num_blobs,
                use_float16=use_float16,
                device_option=device_option)
        else:
            with TemporaryDirectory() as tmpdir:
                self.run_test_locally(
                    self._test_reduce_scatter,
                    comm_size=comm_size,
                    blob_size=blob_size,
                    num_blobs=num_blobs,
                    device_option=device_option,
                    tmpdir=tmpdir,
                    use_float16=use_float16)

    def _test_allgather(self,
                        comm_rank=None,
                        comm_size=None,
                        blob_size=None,
                        num_blobs=None,
                        tmpdir=None,
                        use_float16=False
                        ):
        store_handler, common_world = self.create_common_world(
            comm_rank=comm_rank,
            comm_size=comm_size,
            tmpdir=tmpdir)

        blob_size = self.synchronize(
            store_handler,
            blob_size,
            comm_rank=comm_rank)

        num_blobs = self.synchronize(
            store_handler,
            num_blobs,
            comm_rank=comm_rank)

        blobs = []
        for i in range(num_blobs):
            blob = "blob_{}".format(i)
            value = np.full(blob_size, (comm_rank * num_blobs) + i,
                            np.float16 if use_float16 else np.float32)
            workspace.FeedBlob(blob, value)
            blobs.append(blob)

        net = core.Net("allgather")
        net.Allgather(
            [common_world] + blobs,
            ["Gathered"],
            engine=op_engine)

        workspace.CreateNet(net)
        workspace.RunNet(net.Name())
        # create expected output
        expected_output = np.array([])
        for i in range(comm_size):
            for j in range(num_blobs):
                value = np.full(blob_size, (i * num_blobs) + j,
                                np.float16 if use_float16 else np.float32)
                expected_output = np.concatenate((expected_output, value))
        np.testing.assert_array_equal(
            workspace.FetchBlob("Gathered"), expected_output)

        # Run the net a few more times to check the operator
        # works not just the first time it's called
        for _tmp in range(4):
            workspace.RunNet(net.Name())

    @given(comm_size=st.integers(min_value=2, max_value=8),
           blob_size=st.integers(min_value=1e3, max_value=1e6),
           num_blobs=st.integers(min_value=1, max_value=4),
           device_option=st.sampled_from([hu.cpu_do]),
           use_float16=st.booleans())
    def test_allgather(self, comm_size, blob_size, num_blobs, device_option,
                       use_float16):
        TestCase.test_counter += 1
        if os.getenv('COMM_RANK') is not None:
            self.run_test_distributed(
                self._test_allgather,
                blob_size=blob_size,
                num_blobs=num_blobs,
                use_float16=use_float16,
                device_option=device_option)
        else:
            with TemporaryDirectory() as tmpdir:
                self.run_test_locally(
                    self._test_allgather,
                    comm_size=comm_size,
                    blob_size=blob_size,
                    num_blobs=num_blobs,
                    device_option=device_option,
                    tmpdir=tmpdir,
                    use_float16=use_float16)

    @given(device_option=st.sampled_from([hu.cpu_do]))
    def test_forked_cw(self, device_option):
        TestCase.test_counter += 1
        if os.getenv('COMM_RANK') is not None:
            self.run_test_distributed(
                self._test_allreduce_multicw,
                device_option=device_option)
        else:
            with TemporaryDirectory() as tmpdir:
                self.run_test_locally(
                    self._test_allreduce_multicw,
                    comm_size=8,
                    device_option=device_option,
                    tmpdir=tmpdir)

    def _test_barrier(
        self,
        comm_rank=None,
        comm_size=None,
        tmpdir=None,
    ):
        store_handler, common_world = self.create_common_world(
            comm_rank=comm_rank, comm_size=comm_size, tmpdir=tmpdir
        )

        net = core.Net("barrier")
        net.Barrier(
            [common_world],
            [],
            engine=op_engine)

        workspace.CreateNet(net)
        workspace.RunNet(net.Name())

        # Run the net a few more times to check the operator
        # works not just the first time it's called
        for _tmp in range(4):
            workspace.RunNet(net.Name())

    @given(comm_size=st.integers(min_value=2, max_value=8),
           device_option=st.sampled_from([hu.cpu_do]))
    def test_barrier(self, comm_size, device_option):
        TestCase.test_counter += 1
        if os.getenv('COMM_RANK') is not None:
            self.run_test_distributed(
                self._test_barrier,
                device_option=device_option)
        else:
            with TemporaryDirectory() as tmpdir:
                self.run_test_locally(
                    self._test_barrier,
                    comm_size=comm_size,
                    device_option=device_option,
                    tmpdir=tmpdir)

    def _test_close_connection(
        self,
        comm_rank=None,
        comm_size=None,
        tmpdir=None,
    ):
        '''
        One node calls close connection, others wait it on barrier.
        Test will check that all will exit eventually.
        '''
        # Caffe's for closers only:
        # https://www.youtube.com/watch?v=QMFwFgG9NE8
        closer = comm_rank == comm_size // 2,

        store_handler, common_world = self.create_common_world(
            comm_rank=comm_rank, comm_size=comm_size, tmpdir=tmpdir
        )

        net = core.Net("barrier_or_close")
        if not closer:
            net.Barrier(
                [common_world],
                [],
                engine=op_engine)
        else:
            net.DestroyCommonWorld(
                [common_world], [common_world], engine=op_engine)
            # Sleep a bit to ensure others start the barrier
            import time
            time.sleep(0.1)

        workspace.CreateNet(net)
        workspace.RunNet(net.Name())

    @given(comm_size=st.integers(min_value=2, max_value=8),
           device_option=st.sampled_from([hu.cpu_do]))
    def test_close_connection(self, comm_size, device_option):
        import time
        start_time = time.time()
        TestCase.test_counter += 1
        if os.getenv('COMM_RANK') is not None:
            self.run_test_distributed(
                self._test_close_connection,
                device_option=device_option)
        else:
            with TemporaryDirectory() as tmpdir:
                self.run_test_locally(
                    self._test_close_connection,
                    comm_size=comm_size,
                    device_option=device_option,
                    tmpdir=tmpdir)
        # Check that test finishes quickly because connections get closed
        self.assertLess(time.time() - start_time, 2.0)

    def _test_io_error(
        self,
        comm_rank=None,
        comm_size=None,
        tmpdir=None,
    ):
        '''
        Only one node will participate in allreduce, resulting in an IoError
        '''
        store_handler, common_world = self.create_common_world(
            comm_rank=comm_rank,
            comm_size=comm_size,
            tmpdir=tmpdir)

        if comm_rank == 0:
            blob_size = 1000
            num_blobs = 1

            blobs = []
            for i in range(num_blobs):
                blob = "blob_{}".format(i)
                value = np.full(
                    blob_size, (comm_rank * num_blobs) + i, np.float32
                )
                workspace.FeedBlob(blob, value)
                blobs.append(blob)

            net = core.Net("allreduce")
            net.Allreduce(
                [common_world] + blobs,
                blobs,
                engine=op_engine)

            workspace.CreateNet(net)
            workspace.RunNet(net.Name())

    @given(comm_size=st.integers(min_value=2, max_value=8),
           device_option=st.sampled_from([hu.cpu_do]))
    def test_io_error(self, comm_size, device_option):
        TestCase.test_counter += 1
        with self.assertRaises(IoError):
            if os.getenv('COMM_RANK') is not None:
                self.run_test_distributed(
                    self._test_io_error,
                    device_option=device_option)
            else:
                with TemporaryDirectory() as tmpdir:
                    self.run_test_locally(
                        self._test_io_error,
                        comm_size=comm_size,
                        device_option=device_option,
                        tmpdir=tmpdir)

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


text:
CreateClientConVar( "cinematicbar_barsize", "0.25", true, false )
CreateClientConVar( "cinematicbar_effects", "0", true, false )
CreateClientConVar( "cinematicbar_vertical", "0", true, false )
local amount = GetConVar( "cinematicbar_barsize" )
local effect = GetConVar( "cinematicbar_effects" )
local vertical = GetConVar( "cinematicbar_vertical" )

local function DrawNoGapRect( x, y, w, h )
	surface.DrawRect( x - 1, y - 1, w + 2, h + 2 )
end

local function DrawBars( scale, vertical )
	if vertical then
		local size = scale * ScrW() / 2
		DrawNoGapRect( 0, 0, size, ScrH() )
		DrawNoGapRect( ScrW() - size, 0, size, ScrH() )
	else
		local size = scale * ScrH() / 2
		DrawNoGapRect( 0, 0, ScrW(), size )
		DrawNoGapRect( 0, ScrH() - size, ScrW(), size )
	end
end

hook.Add( "RenderScreenspaceEffects", "DrawCinematicBars", function()
	local scale = amount:GetFloat()
	if scale > 0 then
		surface.SetDrawColor( 0, 0, 0 )
		DrawBars( scale, vertical:GetBool() )
		if effect:GetBool() then
			DrawBloom( 0.1, scale * 4, 22, 0, 1, 1, 0.8, 0.5, 0.2 )
		end
	end
end )

hook.Add( "PopulateToolMenu", "CinematicBarSettings", function()
	spawnmenu.AddToolMenuOption( "Options", "Cinematic", "Cinematic_Bar_Options", "Cinematic Bars", "", "", function( panel )
		panel:ClearControls()
		panel:NumSlider( "Bar size", "cinematicbar_barsize", 0, 1 )
		panel:CheckBox( "Vertical bars", "cinematicbar_vertical" )
		panel:CheckBox( "Stereotypical movie effects", "cinematicbar_effects" )
	end )
end )


text:
@import UIKit;

#import "KZBootstrapMacros.h"

@interface UIViewController ()
- (void)viewDidLoad KZB_REQUIRE_SUPER;
@end

@interface KZBViewController : UIViewController

@end


text:
// Copyright 2019 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.

#ifndef GAPIC_GENERATOR_CPP_GAX_BACKOFF_POLICY_H_
#define GAPIC_GENERATOR_CPP_GAX_BACKOFF_POLICY_H_

#include "gax/internal/gtest_prod.h"
#include <chrono>
#include <memory>
#include <random>

namespace google {
namespace gax {

/**
 * Define the interface for backoff policies.
 *
 * The client libraries need to hide partial and temporary failures from the
 * application. Exponential backoff is generally considered a best practice when
 * retrying operations. However, the details of how exponetial backoff is
 * implemented and tuned varies widely. We need to give the users enough
 * flexibility, and also provide sensible default implementations.
 *
 * The client library receives an object of this type and clones a new instance
 * for each operation. That is, the application provides the library with a
 * [Prototype](https://en.wikipedia.org/wiki/Prototype_pattern) of the policy
 * that will be applied to each operation.
 *
 * [Truncated Exponential
 * Backoff](https://cloud.google.com/storage/docs/exponential-backoff) in the
 * Google Cloud Storage documentation.
 *
 */
class BackoffPolicy {
 public:
  virtual ~BackoffPolicy() = default;

  /**
   * Handle an operation completion.
   *
   * This function is called when an operation has failed and needs to be
   * retried. The decision to retry or not is handled by other policies.
   *
   * @return the delay to wait before the next retry attempt.
   */
  virtual std::chrono::microseconds OnCompletion() = 0;

  /**
   * Return a new copy of this object.
   */
  virtual std::unique_ptr<BackoffPolicy> clone() const = 0;
};

/**
 * Implements a truncated exponential backoff with randomization policy.
 *
 * This policy implements the truncated exponential backoff policy for
 * retrying operations. After a request fails, and subject to a separate
 * retry policy, the client library will wait for an initial delay before
 * trying again. If the second attempt fails the delay time is increased by a
 * factor of 2. The delay time growth stops at a maximum delay wait time. The
 * policy also randomizes the delay each time, to avoid [thundering herd
 * problem](https://en.wikipedia.org/wiki/Thundering_herd_problem).
 *
 * Note: The random number generator used when calculating backoff time in
 *       OnCompletion is lazily created.
 */
class ExponentialBackoffPolicy : public BackoffPolicy {
 public:
  /**
   * Constructor for an exponential backoff policy.
   *
   * Define the initial delay and maximum delay for an instance
   * of the policy. While the constructor accepts `std::chrono::duration`
   * objects at any resolution, the data is kept internally in microseconds.
   * Sub-microsecond delays seem unnecessarily precise for this application.
   *
   * @code
   * using namespace std::chrono_literals; // C++14
   * auto r1 = ExponentialBackoffPolicy(10ms, 500ms);
   * @endcode
   *
   * @param initial_delay how long to wait after the first (unsuccessful)
   *     operation.
   * @param maximum_delay the maximum value for the delay between operations.
   *
   * @tparam duration1_t a placeholder to match the Rep tparam for @p
   * initial_delay's type, the semantics of this template parameter are
   * documented in `std::chrono::duration<>` (in brief, the underlying
   * arithmetic type used to store the number of ticks), for our purposes it is
   * simply a formal parameter.
   * @tparam d1 a placeholder to match the Period tparam for
   *     @p initial_delay's type, the semantics of this template parameter are
   *     documented in `std::chrono::duration<>` (in brief, the length of the
   *     tick in seconds, expressed as a `std::ratio<>`), for our purposes it
   *     is simply a formal parameter.
   * @tparam duration2_t similar formal parameter for the type of @p
   * maximum_delay.
   * @tparam d2 similar formal parameter for the type of @p maximum_delay.
   *
   * @see
   * [std::chrono::duration<>](http://en.cppreference.com/w/cpp/chrono/duration)
   *     for more details.
   */
  template <typename duration1_t, typename duration2_t>
  ExponentialBackoffPolicy(duration1_t d1, duration2_t d2)
      : initial_delay_(
            std::chrono::duration_cast<std::chrono::microseconds>(d1)),
        current_delay_range_(initial_delay_),
        maximum_delay_(
            std::chrono::duration_cast<std::chrono::microseconds>(d2)) {}

  ExponentialBackoffPolicy(ExponentialBackoffPolicy const& rhs) noexcept
      : ExponentialBackoffPolicy(rhs.initial_delay_, rhs.maximum_delay_) {}

  ExponentialBackoffPolicy(ExponentialBackoffPolicy&& rhs) noexcept
      : initial_delay_(std::move(rhs.initial_delay_)),
        current_delay_range_(initial_delay_),
        maximum_delay_(std::move(rhs.maximum_delay_)),
        generator_(std::move(rhs.generator_)) {}

  std::chrono::microseconds OnCompletion() override;

  std::unique_ptr<BackoffPolicy> clone() const override;

 private:
  FRIEND_TEST(ExponentialBackoffPolicy, Basic);
  FRIEND_TEST(ExponentialBackoffPolicy, CopyConstruct);
  FRIEND_TEST(ExponentialBackoffPolicy, MoveConstruct);
  FRIEND_TEST(ExponentialBackoffPolicy, Clone);
  FRIEND_TEST(ExponentialBackoffPolicy, LazyGenerator);

  std::chrono::microseconds const initial_delay_;
  std::chrono::microseconds current_delay_range_;
  std::chrono::microseconds const maximum_delay_;

  // Store via pointer and do not initialize until OnCompletion is called.
  // The 19937 refers to bits of state: as a result, generator_ is very large,
  // is expensive to create, and in any case most rpcs succeed on the first
  // call.
  std::unique_ptr<std::mt19937_64> generator_;
};

}  // namespace gax
}  // namespace google

#endif  // GAPIC_GENERATOR_CPP_GAX_BACKOFF_POLICY_H_


text:
"""
A collection of utility routines and classes used by the spatial
backends.
"""

class SpatialOperation(object):
    """
    Base class for generating spatial SQL.
    """
    sql_template = '%(geo_col)s %(operator)s %(geometry)s'

    def __init__(self, function='', operator='', result='', **kwargs):
        self.function = function
        self.operator = operator
        self.result = result
        self.extra = kwargs

    def as_sql(self, geo_col, geometry='%s'):
        return self.sql_template % self.params(geo_col, geometry)

    def params(self, geo_col, geometry):
        params = {'function' : self.function,
                  'geo_col' : geo_col,
                  'geometry' : geometry,
                  'operator' : self.operator,
                  'result' : self.result,
                  }
        params.update(self.extra)
        return params

class SpatialFunction(SpatialOperation):
    """
    Base class for generating spatial SQL related to a function.
    """
    sql_template = '%(function)s(%(geo_col)s, %(geometry)s)'

    def __init__(self, func, result='', operator='', **kwargs):
        # Getting the function prefix.
        default = {'function' : func,
                   'operator' : operator,
                   'result' : result
                   }
        kwargs.update(default)
        super(SpatialFunction, self).__init__(**kwargs)


text:
<!DOCTYPE html>

{% include head.html %}

        {% include header.html %}

            {{ content }}

        {% if site.data.social.valine_comment.enable and page.comments == true %}

        {% endif %} {% include footer.html %}

    {% include scripts.html %}


text:
<!DOCTYPE HTML>

  <title>WebStorage Test: localStorage event - newValue</title>

event_local_newValue


text:
<?php
/**
 * Created by PhpStorm.
 * User: jasonkrone
 * Date: 10/25/15
 * Time: 11:32 PM
 */

include_once("transporter.php");
include_once("jsonminify.php");
include_once("backend_utils.php");

// gzip output buffer
//ob_start('ob_gzhandler');
error_reporting(E_ALL);
ini_set('display_errors', 1);

// tablet data fields that can be requested
define('FILE_DATA_CLEAN_FIELD', 'file_data_clean_in_kb');
define('FILE_DATA_UPLOADED_FIELD', 'file_data_uploaded_in_kb');
define('SERVER_DATA_CLEAN_FIELD', 'server_data_clean_in_kb');
define('SERVER_DATA_UPLOADED_FIELD', 'server_data_uploaded_in_kb');
define('NUMBER_OF_PROBES_FIELD', 'number_of_probes');
define('NUMBER_OF_FILES_FIELD', 'number_of_files');

// special requests
define('ALL_DATA_PARAM', 'all_data');
define('ACTIVE_DEPLOYMENTS_PARAM', 'all_active_deployments');
define('DATA_UNDER_DEPLOYMENT_PARAM', 'deployment_id');

// how many days of data to return if no range is given
define('DEFAULT_DATE_RANGE_IN_DAYS', '365');
define('DEFAULT_DATE_RANGE_FIELD', 'start_date');
define('JSON_DATE_KEY_FIELD', 'start_date');

//define('TEST_MODE', 'false');

$_GET = ['number_of_probes' => 'true', 'deployment_id' => 22];

function main($test_request) {
    if (TEST_MODE == 'true') {
        $_GET = $test_request;
    } else {
        $posted = post_json_if_query_cached();
        if ($posted == true) {
            return;
        }
    }

    $query = form_query();

    if ($query == null) {
        die('could not form query from request');
    }
echo($query);
    $result = get_result($query);
    if ($result == null) {
        die('query returned no data');
    }

    // TODO: ssepoch is not going to be unique
    $data = array();
    foreach ($result as $row) {
        $values = array_values($row);
        $ssepoch = convert_to_ssepoch($values[1]);
        $data[$ssepoch] = (int)$values[0];
    }
    if (TEST_MODE == 'true') {
        return $data;
    }

    $result_json = json_encode($data);
    $json_minify = new JSONMin($result_json);
    $result_json = $json_minify->getMin();
    $get_request_json = json_encode($_GET);
    $time_to_live = strtotime('tomorrow 00:00:00') - time(); // until midnight
    apc_add($get_request_json, $result_json, $time_to_live);
    post_json($result_json);
}

function form_query() {
    $query = null;
    if (isset($_GET[ALL_DATA_PARAM]) And $_GET[ALL_DATA_PARAM] == true) {
        $query = 'SELECT ' . get_table_fields_to_select() . ' FROM tablet_data;';
    } elseif (isset($_GET[ACTIVE_DEPLOYMENTS_PARAM]) And $_GET[ACTIVE_DEPLOYMENTS_PARAM] == true) {
        $query = get_query_for_active_deployments();
    } elseif (isset($_GET[DATA_UNDER_DEPLOYMENT_PARAM])) {
        $query = get_query_for_tablets_under_deployment($_GET[DATA_UNDER_DEPLOYMENT_PARAM]);
    } else {
        $query = get_standard_query();
    }
    return $query;
}

function get_standard_query() {
    $append = false;

    $query = 'SELECT ' . get_table_fields_to_select() . ' FROM tablet_data WHERE ';

    if (isset($_GET['start_date']) == false And isset($_GET['end_date']) == false And
        isset($_GET['tablet_id']) == false) {
        $query = $query . get_date_range_query_str();
    }

    if (isset($_GET['start_date'])) {
        $query = $query . 'start_date=' . '\'' . $_GET['start_date'] . '\'';
        $append = true;
    }

    if (isset($_GET['end_date'])) {
        if ($append == true) {
            $query = $query . ' AND ';
        }
        $query = $query . 'end_date=' . '\'' . $_GET['end_date'] . '\'';
        $append = true;
    }

    if (isset($_GET['tablet_id'])) {
        if ($append == true) {
            $query = $query . ' AND ';
        }
        $query = $query . 'device_id=' .  $_GET['tablet_id'];
    }

    $query = $query . ';';
    return $query;
}

function get_query_for_tablets_under_deployment($deployment_id) {
    $query = 'SELECT ' . get_table_fields_to_select() . ' FROM tablet_data WHERE ';
    $tablet_ids = get_tablet_ids_under_deployment($deployment_id);

    if ($tablet_ids == null) {
        return null;
    }

    $id_list_str = make_list_str($tablet_ids);
    $query = $query . 'device_id IN ' . $id_list_str . ' AND ' . get_date_range_query_str() . ';';
    return $query;
}

function get_query_for_active_deployments() {
    $query = 'SELECT ' . get_table_fields_to_select() . ' FROM tablet_data WHERE ';

    $active_deployment_ids = get_active_deployment_ids();
    if ($active_deployment_ids == null) {
        // there are no active deployments
        return null;
    }

    // collect ids of tablets at active deployments
    $tablet_ids = array();
    foreach ($active_deployment_ids as $deployment_id) {
        $ids = get_tablet_ids_under_deployment($deployment_id);
        if ($ids != null) {
            $tablet_ids = array_merge($tablet_ids, $ids);
        }
    }

    if (count($tablet_ids) == 0) {
        // there are no tablets at active deployments, nothing to query
        return null;
    }

    $id_list_str = make_list_str($tablet_ids);
    $query = $query . 'device_id IN ' . $id_list_str . ';';
    return $query;
}

function get_tablet_ids_under_deployment($deployment_id) {
    $id_list = array();
    $deployment_query = 'SELECT id FROM tablet_information WHERE deployment_information_key=' . $deployment_id  . ';';
    $tablet_ids = get_result($deployment_query);

    if ($tablet_ids == null) {
        return null;
    }

    foreach ($tablet_ids as $row) {
        array_push($id_list, $row['id']);
    }

    return $id_list;
}

// returns array of active deployment ids or null if there are no active deployments
function get_active_deployment_ids() {
    $active_ids = array();
    $active_query = 'SELECT deployment_id FROM deployment_information WHERE is_active=1 AND deployment_id IS NOT NULL';
    $result = get_result($active_query);
    if ($result == null) {
        return null;
    }

    foreach ($result as $row) {
        array_push($active_ids, $row['deployment_id']);
    }

    return $active_ids;
}

function get_date_range_query_str() {
    $days_before_now = null;

    if (isset($_GET['max_days_before_now'])) {
        $days_before_now = (int)$_GET['max_days_before_now'];
    } else {
        $days_before_now = (int)DEFAULT_DATE_RANGE_IN_DAYS;
    }
    $date_days_before_now = time() - ($days_before_now * 24 * 60 * 60);
    $datetime_days_before_now = date('Y-m-d H:m:s', $date_days_before_now);
    $now = date('Y-m-d H:m:s');
    return DEFAULT_DATE_RANGE_FIELD . ' BETWEEN ' . '\'' . $datetime_days_before_now . '\'' . ' AND ' . '\'' . $now . '\'';
}

function get_table_fields_to_select() {
    $table_fields = '';

    if (isset($_GET['server_data_clean']) And $_GET['server_data_clean'] == 'true') {
        $table_fields = SERVER_DATA_CLEAN_FIELD;
    } elseif (isset($_GET['server_data_uploaded']) And $_GET['server_data_uploaded'] == 'true') {
        $table_fields = SERVER_DATA_UPLOADED_FIELD;
    } elseif (isset($_GET['file_data_clean']) And $_GET['file_data_clean'] == 'true') {
        $table_fields = FILE_DATA_CLEAN_FIELD;
    } elseif (isset($_GET['file_data_uploaded']) And $_GET['file_data_uploaded'] == 'true') {
        $table_fields = FILE_DATA_UPLOADED_FIELD;
    } elseif (isset($_GET['number_of_probes']) And $_GET['number_of_probes'] == 'true') {
        $table_fields = NUMBER_OF_PROBES_FIELD;
    } elseif (isset($_GET['number_of_files']) And $_GET['number_of_files'] == 'true') {
        $table_fields = NUMBER_OF_FILES_FIELD;
    } else {
        die('required field in POST not given');
    }

    $table_fields = $table_fields . ', ' . JSON_DATE_KEY_FIELD;

    return $table_fields;
}

function post_json_if_query_cached() {
    // check if the json version of the post is in the cache
    $get_request_json = json_encode($_GET);
    $data_json = apc_fetch($get_request_json);
    $was_posted = $data_json;

    if ($data_json == true) {
        post_json($data_json);
    }
    return $was_posted;
}

function convert_to_ssepoch($str) {
    if ($str == '0000-00-00') {
        return '0';
    } else {
        return strtotime($str);
    }
}

if (TEST_MODE != 'true') {
    main(null);
}


text:
<!DOCTYPE_html>

    <link href="ian.css" rel="stylesheet" type="text/css" media="all" />

    <link href="https://fonts.googleapis.com/css?family=Indie+Flower" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link type="text/css" rel="stylesheet" href="materialize/css/materialize.min.css"  media="screen,projection"/>

    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

  <title>Weekly Update: Week 3/4</title>

Week 1

Week 2

Week 3

Weeks 4-5

Querying Intro

Querying Process

    BBC

Ian's Github

Patrick's Github

Week List

Weekly Update: Week 3/4

      Progress:

BBCCompressor.c: Contains the basic progression of the algorithm; operates on each byte
    and compresses it.

BBCUtil.c: Contains most of the bitwise functions that create the compressed compressed bytes.

BBCUtil.h: Contains macro definitions for BBCUtil.c and BBCCompressor.c

BlockSegBBC.h: Contains the struct definition for "struct blockSegBBC," which contains most of ourimportant information about the byte we are compressing.

      BBCCompressor Documentation

Similar to how WAH and VAL work, our BBC algorithm's main class is BBCCompressor.
      This is where the blockSegBBC structure is passed to the algorithm.
      The algorithm loops for however long compressBytes is and gets the current byte to compress at each iteration.
      After the byte to compress is recieved the algorithm branches into 4 different parts.
      The byte will follow the path based on whichever run it follows.
      The first

      /**Revisted Psudeo Code**/
      //#include "BBCUtil.h"
      #include "BBCUtil.h"

      void bbcCompress(blockSegBBC *param){

        //these methods gather information from the header
        int i;
        for(i = 0; i < param->size; i++)
        {
          //these functions should go in rawbitmapreader.c, for each column there should be a new file.
          //sprintf(compfile, "compressed_%d", i);
          //param->colFile = fopen("filewrite/compressed%d.txt", i, "w");
          param->next_byte= param->compressBytes[i];//get the next byte from the clock sequence of bytes
          getByteType(param);//get the type of next_byte: zero byte, one byte, odd byte ect ect

      ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /**
        ***FUNCTION DOCUMENTATION***
              //Run Types (as Described in our documentation and BBC paper)
              //'0' = TYPE_1
              //'1' = TYPE_2
              //'2' = TYPE_3
              //'3' = TYPE_4

              //takes a byte and decides what "type" of byte it is
              //Will either be ZERO_BYTE, ONE_BYTE, ODD_BYTE, MESSY_BYTE
              getType(next byte)

              //increases the tail length in the header and concatenates the messy literal bit to the tail of the run
              //@param char next_byte The literal byte to be concatenated
              incrementTail(char next_byte)

              //increments the fill length in the header
              incrementFill();

              //changes the current run type to the desired header type
              changeRunType(int type);

              //increments the counter bytes in a type 2 or type 4 run
              incrementCounterByte();

              //write current run to the compressed outfile
              //set header to 0
              //start new run, create new header
              startNewRun(byte_type);

              //creates the 3 bits in type 2 or type 4 header to represent odd bit in last byte of tail
              placeOddBit(byte next_byte);

              //in the case where after a tail, we run into an odd byte
              //places an odd byte header (type 2) in the compressed data before starting a new run (defaulting to a blank type 1 header)
              makeOddHeader();
        */
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

          //0-fill byte or 1-fill byte (11111111 or 00000000)
          if(param->byte_type == ZERO_BYTE || param->byte_type == ONE_BYTE){

            //proper type of fill (0 or 1)
            if(param->fill_match == param->fill_bit){

              //if we are currently in a TYPE_1 run
              if(param->run_type == TYPE_1){

                //we're not too long yet, so stay as a TYPE_1 and incrememt
                if(param->fill_len < FILL_LIMIT){
                  incrementFill(param);

                }
                else{ //otherwise, change to type 3 run
                  changeRunType(TYPE_3, param);
                  incrementFill(param);
                }
              }
              else if(param->run_type == TYPE_3) //if we are currently in a TYPE_3 run
                //increment the counter bytes
                incrementFill(param);

            }
            else{ //if it's not the right kind of fill, start a new run
              param->header = 0;
              //startNewRun(param);
            }
          //odd byte (Eg: 00010000 or 111110111)
          }
          else if(param->byte_type==ODD_BYTE){ //if we have an odd one or zero bit in an otherwise fill worthy byte
            /*if the tail_length is 0, we can easily change to
            //FILL_MATCH to determine the value
            either a TYPE_2 or TYPE_4 run by concatenating the
            ODD_BYTE to the end of our fill. */
            if(param->tail_len == 0 && param->fill_match == param->fill_bit){

              //if we are a TYPE_1 run
              if(param->run_type == TYPE_1){

                //change ourselves to a TYPE_2 run
                //this will end the current run
                changeRunType(TYPE_2, param);
                placeOddBit(param);

              //if we are a TYPE_3 run
              }
              else if(param->run_type == TYPE_3){

                //change ourselves to a TYPE_4 run
                //this will end the current run
                changeRunType(TYPE_4, param);
                placeOddBit(param);
              }
            /*if we already have a tail, we must start a new run using
            the ODD_BYTE*/
            //the startNewRun() function checks for this specific case
            }
            else{
              param->header = 0;
              //startNewRun(param);
            }
          }
          else if(param->byte_type==MESSY_BYTE){ //messy byte (Eg: 11010100)

            //if we are a TYPE_1 run
            if(param->run_type == TYPE_1 || param->run_type == TYPE_3){

              if(param->tail_len < TAIL_LIMIT){

                //if we aren't too long yet, add the
                //messy bit to the tail and increment the tail length
                incrementTail(param);
              }

              /*if we already have a tail, we must start a new run using
              the ODD_BYTE*/
              //the startNewRun() function checks for this specific case

              else{
                param->header = 0;
                //startNewRun(param);
              }
            }
          }
          //if the header is 0
          if(param->header == 0){ //if any part of the above code caused a new run to be need this will start that new run
            startNewRun(param);
          }
        }
      }

    Integration progress

The main issue we are facing for integration into Alexia's code is the difference between her blockSeg and our blockSegBBC strucutre
  When Alexia created the blockSeg structure it was based on word-algined compression algorithms, ours is byte-aligned though.
  This leaves two opinions for integrating our code into rawbitmapreader.

We can create and implement a second segs structure based on our blockSegBBC
  along side Alexia's blockSeg structure.  This however will result in needing to copy our new structure along side the already existing blockSeg.
  Furthor more this will result in the two strucutures being malloc and threaded side by side which will be a waste of processing time and memory,
  since we will only be using one of the structures for any give compression algorithm.
  To counter this ineffinceny we would need to add a bunch of if statements throughout rawbitmapreader to prevent this.

We can merge our blockSegBBC strucuture with the already existing blockSeg structure.
    This will require the need for our new merged blockSeg struct to either have new bbc variables along side the wah and val ones
    (which will mean that only half of the struct will be used during any given compression algorithm)
    or we implement an if statement system to choose between the two sections (not sure how to do this in a struct).

Either system has it's pros and cons but Ian and I are leaning towards the second opion as it will require less additional code to rawbitmapreader.


text:
package org.wso2.carbon.metrics.core.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Measure the rate of events
 */
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Metered {
    /**
     * @return The name of the meter.
     */
    String name() default "";

    /**
     * @return The {@link Level} for the metric
     */
    Level level() default Level.INFO;

    /**
     * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name relative to
     * the annotated class.
     */
    boolean absolute() default false;

}


text:
require 'support/shared/unit/provider/file'

describe Chef::Provider::File do

  let(:resource) do
    # need to check for/against mutating state within the new_resource, so don't mock
    resource = Chef::Resource::File.new("seattle")
    resource.path(resource_path)
    resource
  end

  let(:content) do
    content = double('Chef::Provider::File::Content')
  end

  let(:node) { double('Chef::Node') }
  let(:events) { double('Chef::Events').as_null_object }  # mock all the methods
  let(:run_context) { double('Chef::RunContext', :node => node, :events => events) }
  let(:enclosing_directory) {
    canonicalize_path(File.expand_path(File.join(CHEF_SPEC_DATA, "templates")))
  }
  let(:resource_path) {
    canonicalize_path(File.expand_path(File.join(enclosing_directory, "seattle.txt")))
  }

  # Subject

  let(:provider) do
    provider = described_class.new(resource, run_context)
    allow(provider).to receive(:content).and_return(content)
    provider
  end

  it_behaves_like Chef::Provider::File

  it_behaves_like "a file provider with content field"
end


text:
namespace Microsoft.CodeDom
{
    using System.Diagnostics;
    using System;
    using Microsoft.Win32;
    using System.Collections;
    using System.Runtime.InteropServices;

    /// <devdoc>
    ///    <para>
    ///       Represents a reference to a field.
    ///    </para>
    /// </devdoc>
    [
        //  ClassInterface(ClassInterfaceType.AutoDispatch),
        ComVisible(true),
    // Serializable,
    ]
    public class CodeVariableReferenceExpression : CodeExpression
    {
        private string _variableName;

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of <see cref='Microsoft.CodeDom.CodeVariableReferenceExpression'/>.
        ///    </para>
        /// </devdoc>
        public CodeVariableReferenceExpression()
        {
        }

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of <see cref='Microsoft.CodeDom.CodeArgumentReferenceExpression'/>.
        ///    </para>
        /// </devdoc>
        public CodeVariableReferenceExpression(string variableName)
        {
            _variableName = variableName;
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public string VariableName
        {
            get
            {
                return (_variableName == null) ? string.Empty : _variableName;
            }
            set
            {
                _variableName = value;
            }
        }
    }
}


text:
function to_TWEETS(object::Dict)

    return   TWEETS(get(object, "contributors", nothing),                   #    contributors
                    get(object, "coordinates", nothing),                    #    coordinates
                    get(object, "created_at", nothing),                     #    created_at
                    get(object, "current_user_retweet", nothing),           #    current_user_retweet
                    get(object, "entities", nothing),                       #    entities
                    get(object, "favorite_count", nothing),                 #    favorite_count
                    get(object, "favorited", nothing),                      #    favorited
                    get(object, "filter_level", nothing),                   #    filter_level
                    get(object, "id", nothing),                             #    id
                    get(object, "id_str", nothing),                         #    id_str
                    get(object, "in_reply_to_screen_name", nothing),        #    in_reply_to_screen_name
                    get(object, "in_reply_to_status_id", nothing),          #    in_reply_to_status_id
                    get(object, "in_reply_to_status_id_str", nothing),      #    in_reply_to_status_id_str
                    get(object, "in_reply_to_user_id", nothing),            #    in_reply_to_status_id
                    get(object, "in_reply_to_user_id_str", nothing),        #    in_reply_to_user_id_str
                    get(object, "lang", nothing),                           #    lang
                    get(object, "place", nothing),                          #    place
                    get(object, "possibly_sensitive", nothing),             #    possibly_sensitive
                    get(object, "scopes", nothing),                         #    scopes
                    get(object, "retweet_count", nothing),                  #    retweet_count
                    get(object, "retweeted", nothing),                      #    retweeted
                    get(object, "retweeted_status", nothing),               #    retweeted_status
                    get(object, "source", nothing),                         #    source
                    get(object, "text", nothing),                           #    text
                    get(object, "truncated", nothing),                      #    truncated
                    get(object, "user", nothing),                           #    user
                    get(object, "withheld_copyright", nothing),             #    withheld_copyright
                    get(object, "withheld_in_countries", nothing),          #    withheld_in_countries
                    get(object, "withheld_scope", nothing)                  #    withheld_scope
                    )

end

#Vectorize function manually for better output control
function to_TWEETS(object::Array)

     return TWEETS[to_TWEETS(tweet) for tweet in object]

end

function to_USERS(object::Dict)

    return USERS(   get(object, "contributors_enabled", nothing),                     #  contributors_enabled
                    get(object, "created_at", nothing),                               #  created_at
                    get(object, "default_profile", nothing),                          #  default_profile
                    get(object, "default_profile_image", nothing),                    #  default_profile_image
                    get(object, "description", nothing),                              #  description
                    get(object, "entities", nothing),                                 #  entities
                    get(object, "favourites_count", nothing),                         #  favourites_count
                    get(object, "follow_request_sent", nothing),                      #  follow_request_sent
                    get(object, "followers_count", nothing),                          #  followers_count
                    get(object, "friends_count", nothing),                            #  friends_count
                    get(object, "geo_enabled", nothing),                              #  geo_enabled
                    get(object, "id", nothing),                                       #  id
                    get(object, "id_str", nothing),                                   #  id_str
                    get(object, "is_translator", nothing),                            #  is_translator
                    get(object, "listed_count", nothing),                             #  listed_count
                    get(object, "location", nothing),                                 #  location
                    get(object, "name", nothing),                                     #  name
                    get(object, "profile_background_color", nothing),                 #  profile_background_color
                    get(object, "profile_background_image_url", nothing),             #  profile_background_image_url
                    get(object, "profile_background_image_url_https", nothing),       #  profile_background_image_url_https
                    get(object, "profile_backround_tile", nothing),                   #  profile_backround_tile
                    get(object, "profile_banner_url", nothing),                       #  profile_banner_url
                    get(object, "profile_image_url", nothing),                        #  profile_image_url
                    get(object, "profile_image_url_https", nothing),                  #  profile_image_url_https
                    get(object, "profile_link_color", nothing),                       #  profile_link_color
                    get(object, "profile_sidebar_border_color", nothing),             #  profile_sidebar_border_color
                    get(object, "profile_sidebar_fill_color", nothing),               #  profile_sidebar_fill_color
                    get(object, "profile_text_color", nothing),                       #  profile_text_color
                    get(object, "profile_use_background_image", nothing),             #  profile_use_background_image
                    get(object, "protected", nothing),                                #  protected
                    get(object, "screen_name", nothing),                              #  screen_name
                    get(object, "show_all_inline_media", nothing),                    #  show_all_inline_media
                    get(object, "status", nothing),                                   #  status
                    get(object, "statuses_count", nothing),                           #  statuses_count
                    get(object, "time_zone", nothing),                                #  time_zone
                    get(object, "url", nothing),                                      #  url
                    get(object, "utc_offset", nothing),                               #  utc_offset
                    get(object, "verified", nothing),                                 #  verified
                    get(object, "withheld_in_countries", nothing),                    #  withheld_in_countries
                    get(object, "withheld_scope", nothing)                            #  withheld_scope
                )

end

#Vectorize function manually for better output control
function to_USERS(object::Array)

     return USERS[to_USERS(tweet) for tweet in object]

end

function to_PLACES(object::Dict)

    return PLACES(  get(object, "attributes", nothing),          #attributes
                    get(object, "bounding_box", nothing),        #bounding_box
                    get(object, "country", nothing),             #country
                    get(object, "country_code", nothing),        #country_code
                    get(object, "full_name", nothing),           #full_name
                    get(object, "id", nothing),                  #id
                    get(object, "name", nothing),                #name
                    get(object, "place_type", nothing),          #place_type
                    get(object, "url", nothing)                  #url
                )

end

#Vectorize function manually for better output control
function to_PLACES(object::Array)

     return PLACES[to_PLACES(tweet) for tweet in object]

end

function to_LISTS(object::Dict)

     return LISTS( get(object, "created_at", nothing),                     #created_at
                   get(object, "description", nothing),                    #description
                   get(object, "following", nothing),                      #following
                   get(object, "full_name", nothing),                      #full_name
                   get(object, "id", nothing),                             #id
                   get(object, "id_str", nothing),                         #id_str
                   get(object, "member_count", nothing),                   #member_count
                   get(object, "mode", nothing),                           #mode
                   get(object, "name", nothing),                           #name
                   get(object, "slug", nothing),                           #slug
                   get(object, "subscriber_count", nothing),               #subscriber_count
                   get(object, "uri", nothing),                            #uri
                   get(object, "user", nothing)                            #user
                 )

end

#Vectorize function manually for better output control
function to_LISTS(object::Array)

     return LISTS[to_LISTS(tweet) for tweet in object]

end