text:
#include "SDL_config.h"

/* Allow access to a raw mixing buffer */

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mmsystem.h>

#include "SDL_timer.h"
#include "SDL_audio.h"
#include "../SDL_audio_c.h"
#include "SDL_dibaudio.h"
#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
#include "win_ce_semaphore.h"
#endif

/* Audio driver functions */
static int DIB_OpenAudio(_THIS, SDL_AudioSpec *spec);
static void DIB_ThreadInit(_THIS);
static void DIB_WaitAudio(_THIS);
static Uint8 *DIB_GetAudioBuf(_THIS);
static void DIB_PlayAudio(_THIS);
static void DIB_WaitDone(_THIS);
static void DIB_CloseAudio(_THIS);

int volatile dibaudio_thread_debug = 0;
int volatile dibaudio_cb_debug     = 0;
int volatile dibaudio_main_debug   = 0;

/* Audio driver bootstrap functions */

static int Audio_Available(void)
{
	return(1);
}

static void Audio_DeleteDevice(SDL_AudioDevice *device)
{
	SDL_free(device->hidden);
	SDL_free(device);
}

static SDL_AudioDevice *Audio_CreateDevice(int devindex)
{
	SDL_AudioDevice *this;

	/* Initialize all variables that we clean on shutdown */
	this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
	if ( this ) {
		SDL_memset(this, 0, (sizeof *this));
		this->hidden = (struct SDL_PrivateAudioData *)
				SDL_malloc((sizeof *this->hidden));
	}
	if ( (this == NULL) || (this->hidden == NULL) ) {
		SDL_OutOfMemory();
		if ( this ) {
			SDL_free(this);
		}
		return(0);
	}
	SDL_memset(this->hidden, 0, (sizeof *this->hidden));

	/* Set the function pointers */
	this->OpenAudio = DIB_OpenAudio;
	this->ThreadInit = DIB_ThreadInit;
	this->WaitAudio = DIB_WaitAudio;
	this->PlayAudio = DIB_PlayAudio;
	this->GetAudioBuf = DIB_GetAudioBuf;
	this->WaitDone = DIB_WaitDone;
	this->CloseAudio = DIB_CloseAudio;

	this->free = Audio_DeleteDevice;

	return this;
}

AudioBootStrap WAVEOUT_bootstrap = {
	"waveout", "Win95/98/NT/2000 WaveOut",
	Audio_Available, Audio_CreateDevice
};

/* The Win32 callback for filling the WAVE device */
static void CALLBACK FillSound(HWAVEOUT hwo, UINT uMsg, DWORD_PTR dwInstance,
						DWORD dwParam1, DWORD dwParam2)
{
	SDL_AudioDevice *this = (SDL_AudioDevice *)dwInstance;

	/* Only service "buffer done playing" messages */
	if ( uMsg != WOM_DONE )
		return;

	/* Signal that we are done playing a buffer */
	dibaudio_cb_debug = 1;
	EnterCriticalSection(&audio_cs);
	dibaudio_cb_debug = 2;
	SetEvent(audio_event);
	dibaudio_cb_debug = 3;
	LeaveCriticalSection(&audio_cs);
	dibaudio_cb_debug = 4;
}

static void SetMMerror(char *function, MMRESULT code)
{
	size_t len;
	char errbuf[MAXERRORLENGTH];
#ifdef _WIN32_WCE
	wchar_t werrbuf[MAXERRORLENGTH];
#endif

	SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: ", function);
	len = SDL_strlen(errbuf);

#ifdef _WIN32_WCE
	/* UNICODE version */
	waveOutGetErrorText(code, werrbuf, MAXERRORLENGTH-len);
	WideCharToMultiByte(CP_ACP,0,werrbuf,-1,errbuf+len,MAXERRORLENGTH-len,NULL,NULL);
#else
	waveOutGetErrorText(code, errbuf+len, (UINT)(MAXERRORLENGTH-len));
#endif

	SDL_SetError("%s",errbuf);
}

/* Set high priority for the audio thread */
static void DIB_ThreadInit(_THIS)
{
	SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
}

void DIB_WaitAudio(_THIS)
{
	/* Wait for an audio chunk to finish */
	dibaudio_thread_debug = 1;
	WaitForSingleObject(audio_event, INFINITE);
	dibaudio_thread_debug = 2;
	ResetEvent(audio_event);
	dibaudio_thread_debug = 3;
}

Uint8 *DIB_GetAudioBuf(_THIS)
{
        Uint8 *retval;

    dibaudio_thread_debug = 4;
    EnterCriticalSection(&audio_cs);
    dibaudio_thread_debug = 5;
	retval = (Uint8 *)(wavebuf[next_buffer].lpData);
	return retval;
}

void DIB_PlayAudio(_THIS)
{
	/* Queue it up */
	dibaudio_thread_debug = 6;
	waveOutWrite(sound, &wavebuf[next_buffer], sizeof(wavebuf[0]));
	dibaudio_thread_debug = 7;
	next_buffer = (next_buffer+1)%NUM_BUFFERS;
	LeaveCriticalSection(&audio_cs);
	dibaudio_thread_debug = 8;
}

void DIB_WaitDone(_THIS)
{
	int i, left, tries = 5;

	dibaudio_thread_debug = 9;

	/* give some time for the wave output to send the last buffer,
	   but don't hang if one was cancelled
	  */
	do {
		left = NUM_BUFFERS;
		for ( i=0; i<NUM_BUFFERS; ++i ) {
			if ( wavebuf[i].dwFlags & WHDR_DONE ) {
				--left;
			}
		}
		if ( left == 0 )
			break;

		SDL_Delay(100);
	} while ( --tries > 0 );

	dibaudio_thread_debug = 10;
}

void DIB_CloseAudio(_THIS)
{
	int i;

	/* Close up audio */
	if (audio_event != INVALID_HANDLE_VALUE ) {
#if defined(_WIN32_WCE) && (_WIN32_WCE < 300)
		CloseSynchHandle(audio_event);
#else
		CloseHandle(audio_event);
#endif
	}
	if ( sound ) {
		waveOutReset(sound);
	}

	/* Clean up mixing buffers */
	for ( i=0; i<NUM_BUFFERS; ++i ) {
		if ( wavebuf[i].dwUser != 0xFFFF ) {
			waveOutUnprepareHeader(sound, &wavebuf[i],
						sizeof(wavebuf[i]));
			wavebuf[i].dwUser = 0xFFFF;
		}
	}
	/* Free raw mixing buffer */
	if ( mixbuf != NULL ) {
		SDL_free(mixbuf);
		mixbuf = NULL;
	}

	if ( sound )
		waveOutClose(sound);
}

int DIB_OpenAudio(_THIS, SDL_AudioSpec *spec)
{
	MMRESULT result;
	int i;
	WAVEFORMATEX waveformat;

	/* Initialize the wavebuf structures for closing */
	sound = NULL;
	InitializeCriticalSection(&audio_cs);
	audio_event = INVALID_HANDLE_VALUE;
	for ( i = 0; i < NUM_BUFFERS; ++i )
		wavebuf[i].dwUser = 0xFFFF;
	mixbuf = NULL;

	/* Set basic WAVE format parameters */
	SDL_memset(&waveformat, 0, sizeof(waveformat));
	waveformat.wFormatTag = WAVE_FORMAT_PCM;

	/* Determine the audio parameters from the AudioSpec */
	switch ( spec->format & 0xFF ) {
		case 8:
			/* Unsigned 8 bit audio data */
			spec->format = AUDIO_U8;
			waveformat.wBitsPerSample = 8;
			break;
		case 16:
			/* Signed 16 bit audio data */
			spec->format = AUDIO_S16;
			waveformat.wBitsPerSample = 16;
			break;
		default:
			SDL_SetError("Unsupported audio format");
			return(-1);
	}
	waveformat.nChannels = spec->channels;
	waveformat.nSamplesPerSec = spec->freq;
	waveformat.nBlockAlign =
		waveformat.nChannels * (waveformat.wBitsPerSample/8);
	waveformat.nAvgBytesPerSec =
		waveformat.nSamplesPerSec * waveformat.nBlockAlign;

	/* Check the buffer size -- minimum of 1/4 second (word aligned) */
	if ( spec->samples < (spec->freq/4) )
		spec->samples = ((spec->freq/4)+3)&~3;

	/* Update the fragment size as size in bytes */
	SDL_CalculateAudioSpec(spec);

	/* Open the audio device */
	result = waveOutOpen(&sound, WAVE_MAPPER, &waveformat,
			(DWORD_PTR)FillSound, (DWORD_PTR)this, CALLBACK_FUNCTION);
	if ( result != MMSYSERR_NOERROR ) {
		SetMMerror("waveOutOpen()", result);
		return(-1);
	}

#ifdef SOUND_DEBUG
	/* Check the sound device we retrieved */
	{
		WAVEOUTCAPS caps;

		result = waveOutGetDevCaps((UINT)sound, &caps, sizeof(caps));
		if ( result != MMSYSERR_NOERROR ) {
			SetMMerror("waveOutGetDevCaps()", result);
			return(-1);
		}
		printf("Audio device: %s\n", caps.szPname);
	}
#endif

	/* Create the audio buffer semaphore */
	audio_event = CreateEvent( NULL, TRUE, FALSE, NULL );
	if (audio_event == NULL) {
		SDL_SetError("Couldn't create semaphore");
		return(-1);
	}

	/* Create the sound buffers */
	mixbuf = (Uint8 *)SDL_malloc(NUM_BUFFERS*spec->size);
	if ( mixbuf == NULL ) {
		SDL_SetError("Out of memory");
		return(-1);
	}
	for ( i = 0; i < NUM_BUFFERS; ++i ) {
		SDL_memset(&wavebuf[i], 0, sizeof(wavebuf[i]));
		wavebuf[i].lpData = (LPSTR) &mixbuf[i*spec->size];
		wavebuf[i].dwBufferLength = spec->size;
		wavebuf[i].dwFlags = WHDR_DONE;
		result = waveOutPrepareHeader(sound, &wavebuf[i],
							sizeof(wavebuf[i]));
		if ( result != MMSYSERR_NOERROR ) {
			SetMMerror("waveOutPrepareHeader()", result);
			return(-1);
		}
	}

	/* Ready to go! */
	next_buffer = 0;
	return(0);
}


text:
var _ = require('lodash');
var utils = require('../utils');
var HtmlParserProxy = require('./htmlparser');
var HttpStatus = require('http-status-codes');
var ReliableGet = require('reliable-get');
var url = require('url');
var extractSlots = require('../extract-slots');
var Core = require('parxer/lib/core');

module.exports = function backendProxyMiddleware(config, eventHandler, optionsTransformer) {

  var reliableGet = new ReliableGet(config),
    htmlParserMiddleware = HtmlParserProxy.getMiddleware(config, reliableGet, eventHandler, optionsTransformer);

  reliableGet.on('log', eventHandler.logger);
  reliableGet.on('stat', eventHandler.stats);

  return function (req, res) {
    htmlParserMiddleware(req, res, function () {

      req.tracer = req.headers['x-tracer'] || 'no-tracer';

      var DEFAULT_LOW_TIMEOUT = 5000,
        referer = req.headers.referer || 'direct',
        userAgent = req.headers['user-agent'] || 'unknown',
        remoteAddress = req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress,
        remoteIp = req.headers['x-forwarded-for'] || remoteAddress,
        backend = req.backend,
        targetUrl = backend.target + (backend.dontPassUrl ? '' : req.url),
        targetHost = url.parse(backend.target).hostname,
        host = backend.host || targetHost,
        accept = backend.accept || 'text/html',
        device = req.templateVars['device:type'],
        backendHeaders = {
          'x-forwarded-host': req.headers.host || 'no-forwarded-host',
          'x-forwarded-for': req.headers['x-forwarded-for'] || remoteAddress,
          host: host,
          accept: accept,
          'x-tracer': req.tracer,
          'user-agent': userAgent,
          'x-device': device,
          'x-site-country': req.headers['x-site-country'],
          'x-site-language': req.headers['x-site-language'],
          'x-site-locales': req.headers['x-site-locales'],
          'x-geoip-country-code': req.headers['x-geoip-country-code'],
          'x-csrf-token': req.headers['x-csrf-token']
        },
        targetCacheKey = backend.cacheKey,
        targetCacheTTL = utils.timeToMillis(backend.ttl || '30s'),
        targetTags = backend.tags,
        explicitNoCache = backend.noCache || req.explicitNoCache,
        options;

      if (config.cdn && config.cdn.url) { backendHeaders['x-cdn-url'] = config.cdn.url; }

      if (req.cookies && req.headers.cookie) {
        var whitelist = config.cookies && config.cookies.whitelist;
        backendHeaders.cookie = whitelist ? utils.filterCookies(whitelist, req.cookies) : req.headers.cookie;
      }

      if (req.headers['accept-language']) {
        backendHeaders['accept-language'] = req.headers['accept-language'];
      }

      if (backend.headers) {
        backend.headers.forEach(function (header) {
          backendHeaders[header] = req.headers[header] || '';
        });
      }

      eventHandler.logger('debug', 'GET ' + req.url, {
        tracer: req.tracer,
        referer: referer,
        remoteIp: remoteIp,
        userAgent: userAgent
      });

      options = {
        url: targetUrl,
        cacheKey: targetCacheKey,
        cacheTTL: targetCacheTTL,
        tags: targetTags,
        explicitNoCache: explicitNoCache,
        timeout: utils.timeToMillis(backend.timeout || DEFAULT_LOW_TIMEOUT),
        headers: backendHeaders,
        tracer: req.tracer,
        type: 'backend',
        statsdKey: 'backend',
        statsdTags: ['application:' + utils.getServiceNameFromUrl(targetUrl)],
        eventHandler: eventHandler
      };

      var logError = function (err, message) {
        var logLevel = err.statusCode === 404 ? 'warn' : 'error';
        eventHandler.logger(logLevel, message, {
          tracer: req.tracer
        });
      }

      var showResponseContentOnError = function(statusCode) {
        var codes = config.renderContentOnErrorCode || [];
        return codes.includes(statusCode);
      }

      var handleError = function (err) {
        if (!res.headersSent) {
          res.writeHead(err.statusCode || HttpStatus.INTERNAL_SERVER_ERROR);
          res.end(err.message);
        }
        logError(err, 'Backend FAILED but to respond: ' + err.message);
      };

      var handleErrorDecorator = function (func) {
        return function (err, response) {
          if (!err) {
            return func(null, response); // no errors!
          }

          // If we are allowing the backend to respond with content, then do so
          if (showResponseContentOnError(err.statusCode)) {
            return func(null, response);
          }

          // Check to see if we have any statusCode handlers defined
          if (err.statusCode && config.statusCodeHandlers && config.statusCodeHandlers[err.statusCode]) {
            var handlerDefn = config.statusCodeHandlers[err.statusCode];
            var handlerFn = config.functions && config.functions[handlerDefn.fn];
            if (handlerFn) {
              return handlerFn(req, res, req.templateVars, handlerDefn.data, options, err, res.parse);
            }
          }

          if (req.backend.quietFailure && response && response.stale) {
            logError(err, 'Backend FAILED but serving STALE content from key ' + targetCacheKey + ' : ' + err.message);
            func(null, response);
          } else {
            handleError(err, response);
          }
        };
      };

      var setAdditionalHeaders = function () {
        var headersToAdd = _.keys(backend.addResponseHeaders);
        headersToAdd.forEach(function (header) {
          var headerValue = Core.render(backend.addResponseHeaders[header], req.templateVars);
          if (headerValue) { res.setHeader(header, headerValue); }
        });
      }

      var passThroughHeaders = function (backendHeaders) {
        var headersToAllow = backend.passThroughHeaders || [];
        headersToAllow.forEach(function (header) {
          var headerValue = backendHeaders[header];
          if (headerValue) { res.setHeader(header, headerValue); }
        });
      }

      optionsTransformer(req, options, function (err, transformedOptions) {
        if (err) { return handleError(err); }

        if (config.enableExtension && req.method === 'POST' && req.is('text/compoxure')) {
          res.parse(req.body);
          return;
        }

        var logEventsPage = utils.isDebugEnabled(req) && utils.attachEventLogger(transformedOptions);
        transformedOptions.explicitNoCache = utils.isNoCacheEnabled(req);
        reliableGet.get(transformedOptions, handleErrorDecorator(function (err, response) {
          var layoutUrl;
          var newTemplateVars = utils.formatTemplateVariables(response.headers);
          req.templateVars = _.assign(req.templateVars, newTemplateVars);
          if (response.headers['set-cookie']) {
            res.setHeader('set-cookie', response.headers['set-cookie']);
          }
          setAdditionalHeaders();
          passThroughHeaders(response.headers);
          /* server timing: main page */
          if(utils.isDebugEnabled(req)) {
            utils.appendServerTimings(res, 'page', utils.getServerTimingName('page', response), response.realTiming);
            res.debugInfo = utils.delimitContent('', response, transformedOptions, logEventsPage, 'page');
          }

          if ('cx-layout' in response.headers) {
            layoutUrl = Core.render(response.headers['cx-layout'], req.templateVars);
            req.templateVars.layout = layoutUrl;

            // Make an extract function to make it easier to switch the code based on allowing slots.
            var extract = function extract(data) {
              // extract slots from original html
              extractSlots(data, function (err, slots) {
                req.templateVars.slots =  slots;

                var layoutConfig = utils.getBackendConfig(config, layoutUrl);
                var cacheKey = layoutConfig && layoutConfig.cacheKey ?
                  Core.render(layoutConfig.cacheKey, req.templateVars) :
                  'layout:'+ layoutUrl;

                var cacheTTL = layoutConfig && layoutConfig.cacheTTL ?
                  layoutConfig.cacheTTL :
                  60000 * 5; // 5 mins

                var layoutOptions = {
                  url: layoutUrl,
                  cacheKey: cacheKey,
                  cacheTTL: cacheTTL,
                  statsdKey: 'layout',
                  statsdTags: ['application:' + utils.getServiceNameFromUrl(layoutUrl)],
                  headers: {
                    'user-agent': transformedOptions.headers['user-agent'],
                    'x-device': transformedOptions.headers['x-device'],
                    'x-site-country': transformedOptions.headers['x-site-country'],
                    'x-site-language': transformedOptions.headers['x-site-language'],
                    cookie: transformedOptions.headers.cookie
                  },
                  explicitNoCache: utils.isNoCacheEnabled(req)
                };
                var logEventsLayout = utils.isDebugEnabled(req) && utils.attachEventLogger(layoutOptions);
                // get the layout
                reliableGet.get(layoutOptions, handleErrorDecorator(function (err, response) {
                  /* server timing: layout */
                  if(utils.isDebugEnabled(req)) {
                    utils.appendServerTimings(res, 'layout', utils.getServerTimingName('layout', response), response.realTiming);
                    res.debugInfo += utils.delimitContent('', response, layoutOptions, logEventsLayout, 'layout');
                  }
                  res.parse(response.content, response.statusCode);
                }));
              });
            };

            // If we are allowed to define slots in the content then we need to parse the content here before looking for slots.
            if ('cx-allow-slot-use' in response.headers) {
              res.parseOnly(response.content, function(err, data) {
                // No error handling here as the callback doesn't get called on errors.
                extract(data);
              });
            } else {
              extract(response.content);
            }

          } else {
            res.parse(response.content, response.statusCode);
          }
        }));
      });

    });

  }
}

redpajama_set_name: RedPajamaGithub


text:
package guru.nidi.codeassert.dependency;

import guru.nidi.codeassert.model.UsingElement;

public class AmbiguousRuleException extends RuntimeException {
    private final DependencyRule rule;
    private final UsingElement<?> from;
    private final UsingElement<?> to;

    AmbiguousRuleException(DependencyRule rule, UsingElement<?> from, UsingElement<?> to) {
        this.rule = rule;
        this.from = from;
        this.to = to;
    }

    public DependencyRule getRule() {
        return rule;
    }

    public UsingElement<?> getFrom() {
        return from;
    }

    public UsingElement<?> getTo() {
        return to;
    }

    @Override
    public String getMessage() {
        return rule + " is ambiguous for dependency " + from + " -> " + to;
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Ivan
 * Date: 26.11.2016
 * Time: 17:40
 */

namespace Consumer;

use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

class Module implements ConfigProviderInterface
{
    public function getConfig() {
        return include __DIR__ . '/../config/module.config.php';
    }

    public function getServiceConfig()
    {
        return [
            'factories' => [
                Model\ConsumerTable::class => function($container) {
                    $tableGateway = $container->get(Model\ConsumerTableGateway::class);
                    return new Model\ConsumerTable($tableGateway);
                },
                Model\ConsumerTableGateway::class => function ($container) {
                    $dbAdapter = $container->get(AdapterInterface::class);
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Model\Consumer());
                    return new TableGateway('consumer', $dbAdapter, null, $resultSetPrototype);
                },
            ],
        ];
    }

    public function getControllerConfig()
    {
        return [
            'factories' => [
                Controller\ConsumerController::class => function($container) {
                    return new Controller\ConsumerController(
                        $container->get(Model\ConsumerTable::class)
                    );
                },
            ],
        ];
    }
}


text:
using FlintSharp.Behaviours;
using FlintSharp.Activities;
using FlintSharp.Counters;
using FlintSharp.Easing;
using FlintSharp.Emitters;
using FlintSharp.EnergyEasing;
using FlintSharp.Initializers;
using FlintSharp.Particles;
using FlintSharp.Zones;

namespace FlintSharp.Behaviours
{
    /// <summary>
    /// The TweenPosition action adjusts the particle's position between two
    /// locations as it ages. This action
    /// should be used in conjunction with the Age action.
    /// </summary>
    public class TweenPosition : Behaviour
    {
        private double m_diffX;
        private double m_endX;
        private double m_diffY;
        private double m_endY;

        public TweenPosition()
            : this(0, 0, 1, 1)
        {
        }

        /// <summary>
        /// The constructor creates a TweenPosition action for use by
        /// an emitter. To add a TweenPosition to all particles created by an emitter, use the
        /// emitter's addAction method.
        ///
        /// @see org.flintparticles.emitters.Emitter#addAction()
        /// </summary>
        /// <param name="startX">The x value for the particle at the
        /// start of its life.</param>
        /// <param name="startY">The y value for the particle at the
        /// start of its life.</param>
        /// <param name="endX">The x value of the particle at the end of its
        /// life.</param>
        /// <param name="endY">The y value of the particle at the end of its
        /// life.</param>
        public TweenPosition(double startX, double startY, double endX, double endY)
        {
            m_diffX = startX - endX;
            m_endX = endX;
            m_diffY = startY - endY;
            m_endY = endY;
        }

        /// <summary>
        /// The x position for the particle at the start of its life.
        /// </summary>
        public double StartX
        {
            get { return m_endX + m_diffX; }
            set { m_diffX = value - m_endX; }
        }

        /// <summary>
        /// The X value for the particle at the end of its life.
        /// </summary>
        public double EndX
        {
            get { return m_endX; }
            set { m_diffX = m_endX + m_diffX - value; m_endX = value; }
        }

        /// <summary>
        /// The y position for the particle at the start of its life.
        /// </summary>
        public double StartY
        {
            get { return m_endY + m_diffY; }
            set { m_diffY = value - m_endY; }
        }

        /// <summary>
        /// The y value for the particle at the end of its life.
        /// </summary>
        public double EndY
        {
            get { return m_endY; }
            set { m_diffY = m_endY + m_diffY - value; m_endY = value; }
        }

        /// <summary>
        /// The update method is used by the emitter to apply the action
        /// to every particle. It is called within the emitter's update
        /// loop and need not be called by the user.
        /// </summary>
        /// <param name="emitter">The Emitter that created the particle.</param>
        /// <param name="particle">The particle to be updated.</param>
        /// <param name="elapsedTime">The duration of the frame - used for time based updates.</param>
        public override void Update(Emitter emitter, Particle particle, double elapsedTime)
        {
            if (particle == null)
            {
                return;
            }

            particle.X = m_endX + m_diffX * particle.Energy;
            particle.Y = m_endY + m_diffY * particle.Energy;
        }
    }
}


text:
var batched = require("../index")

var asyncThing = {
    _state: {
        1: 1
        , 2: 2
        , 3: 3
    }
    , getAll: function (callback) {
        var state = this._state
        process.nextTick(function () {
            callback(null, state)
        })
    }
    , get: function (id, callback) {
        var state = this._state
        process.nextTick(function () {
            callback(null, state[id])
        })
    }
    , set: function (id, value, callback) {
        var state = this._state
        process.nextTick(function () {
            state[id] = value
            callback(null)
        })
    }
    , del: function (id, callback) {
        var state = this._state
        process.nextTick(function () {
            delete state[id]
            callback(null)
        })
    }
}

batched(asyncThing)
    .set("foo", "bar")
    .set("hello", "world")
    .del("1")
    .del("2")
    .get("3", function (err, result) {
        console.log("result", result)
    })
    .getAll(function (err, results) {
        console.log("results!", results)
    })
    .on("error", function () {
        // no errors!
    })
    .once("finish", function () {
        console.log("finished")
    })

console.log("go chain go!")


text:
#ifndef ROPUFU_SETTLERS_ONLINE_BUILDING_ATTRIBUTE_HPP_INCLUDED
#define ROPUFU_SETTLERS_ONLINE_BUILDING_ATTRIBUTE_HPP_INCLUDED

#include <ropufu/enum_array.hpp>

#include <cstddef>     // std::size_t
#include <string>      // std::string, std::to_string
#include <type_traits> // std::underlying_type_t

namespace ropufu::settlers_online
{
    /** @brief Enumerates some of the building attributes.
     *  @remark Used internally as an indexer for \c enum_array, so don't go too high or negative.
     **/
    enum struct building_attribute : char
    {
        none = 0,
        cannot_be_moved = 1,
        cannot_be_buffed = 2,
        cannot_be_demolished = 3,
        placed_on_deposit = 4,
        storehouse = 5
    }; // struct building_attribute
} // namespace ropufu::settlers_online

namespace std
{
    std::string to_string(ropufu::settlers_online::building_attribute x) noexcept
    {
        using argument_type = ropufu::settlers_online::building_attribute;
        switch (x)
        {
            case argument_type::none: return "none";
            case argument_type::cannot_be_moved: return "cannot be moved";
            case argument_type::cannot_be_buffed: return "cannot be buffed";
            case argument_type::cannot_be_demolished: return "cannot be demolished";
            case argument_type::placed_on_deposit: return "placed on deposit";
            case argument_type::storehouse: return "storehouse";
            default: return "unknown <building_attribute> " + std::to_string(static_cast<std::size_t>(x));
        } // switch (...)
    } // to_string(...)
} // namespace std

namespace ropufu::aftermath::detail
{
    /** Mark \c building_attribute as suitable for \c enum_array storage. */
    template <>
    struct enum_array_keys<ropufu::settlers_online::building_attribute>
    {
        using underlying_type = std::underlying_type_t<ropufu::settlers_online::building_attribute>;
        static constexpr underlying_type first_index = 0;
        static constexpr underlying_type past_the_last_index = 6;
    }; // struct enum_array_keys<...>

    template <>
    struct enum_parser<ropufu::settlers_online::building_attribute>
    {
        using enum_type = ropufu::settlers_online::building_attribute;

        static std::string to_string(const enum_type& from) noexcept { return std::to_string(from); }

        static bool try_parse(const std::string& from, enum_type& to) noexcept
        {
            if (from == "none") { to = enum_type::none; return true; }
            if (from == "cannot be moved") { to = enum_type::cannot_be_moved; return true; }
            if (from == "cannot be buffed") { to = enum_type::cannot_be_buffed; return true; }
            if (from == "cannot be demolished") { to = enum_type::cannot_be_demolished; return true; }
            if (from == "placed on deposit") { to = enum_type::placed_on_deposit; return true; }
            if (from == "storehouse") { to = enum_type::storehouse; return true; }
            return false;
        } // try_parse(...)
    }; // struct enum_parser<...>
} // namespace ropufu::aftermath::detail

#endif // ROPUFU_SETTLERS_ONLINE_BUILDING_ATTRIBUTE_HPP_INCLUDED


text:
Login

Accounts are reset on server restart from dummydata.js. Default account is test@test.com / test

    <form class="form" name="form" ng-submit="login(form)" novalidate>

        Email

        <input type="text" name="email" class="form-control" ng-model="user.email">

        Password

        <input type="password" name="password" class="form-control" ng-model="user.password">

           Please enter your email and password.

{{ errors.other }}

      <button type="submit" class="btn btn-lg btn-primary"> Sign in </button>
    </form>

    Not registered? Create an account.


text:
ShellWindow* ShellWindow::Create(Profile* profile,
                                 const Extension* extension,
                                 const GURL& url) {
  ExtensionProcessManager* manager = profile->GetExtensionProcessManager();
  DCHECK(manager);
  if (!manager)
    return NULL;

  ExtensionHost* host = manager->CreateShellHost(extension, url);
  // CHECK host so that non-GTK platform compilers don't complain about unused
  // variables.
  // TODO(mihaip): remove when ShellWindow has been implemented everywhere.
  CHECK(host);

#if defined(TOOLKIT_GTK) || defined(TOOLKIT_VIEWS)
  // This object will delete itself when the window is closed.
  // TODO(mihaip): remove the #if block when ShellWindow has been implemented
  // everywhere.
  return ShellWindow::CreateShellWindow(host);
#endif

  return NULL;
}

void ShellWindow::Observe(int type,
                          const content::NotificationSource& source,
                          const content::NotificationDetails& details) {
  switch (type) {
    case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:
      if (content::Details<ExtensionHost>(host_.get()) == details)
        Close();
      break;
    case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
      const Extension* unloaded_extension =
          content::Details<UnloadedExtensionInfo>(details)->extension;
      // We compare extension IDs and not Extension pointers since ExtensionHost
      // nulls out its Extension pointer when it gets this notification.
      if (host_->extension_id() == unloaded_extension->id())
        Close();
      break;
    }
    case content::NOTIFICATION_APP_TERMINATING:
      Close();
      break;
    default:
      NOTREACHED() << "Received unexpected notification";
  }
}

void ShellWindow::RenderViewCreated(RenderViewHost* render_view_host) {
  DisableNPAPIPlugins();
}

ShellWindow::ShellWindow(ExtensionHost* host)
    : host_(host) {
  // Close the window in response to window.close() and the like.
  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
                 content::Source<Profile>(host->profile()));
  // Also close if the window if the extension has been unloaded (parallels
  // NOTIFICATION_EXTENSION_UNLOADED closing the app's tabs in TabStripModel).
  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED,
                 content::Source<Profile>(host->profile()));
  // Close when the browser is exiting.
  // TODO(mihaip): we probably don't want this in the long run (when platform
  // apps are no longer tied to the browser process).
  registrar_.Add(this, content::NOTIFICATION_APP_TERMINATING,
                 content::NotificationService::AllSources());
  content::WebContentsObserver::Observe(web_contents());
}

ShellWindow::~ShellWindow() {
  ClearDisabledNPAPIPlugins();
}

void ShellWindow::DisableNPAPIPlugins() {
  int render_process_id = host_->render_process_host()->GetID();
  int render_view_id = host_->render_view_host()->routing_id();
  ChromePluginServiceFilter* filter =
      ChromePluginServiceFilter::GetInstance();
  filter->DisableNPAPIForRenderView(render_process_id,
                                    render_view_id);
}

void ShellWindow::ClearDisabledNPAPIPlugins() {
  int render_process_id = host_->render_process_host()->GetID();
  int render_view_id = host_->render_view_host()->routing_id();
  ChromePluginServiceFilter* filter =
      ChromePluginServiceFilter::GetInstance();
  filter->ClearDisabledNPAPIForRenderView(render_process_id,
                                          render_view_id);
}


text:
> Account JSON API backed by PouchDB

[![Build Status](https://api.travis-ci.org/hoodiehq/hoodie-account-server.svg?branch=master)](https://travis-ci.org/hoodiehq/hoodie-account-server)
[![Coverage Status](https://coveralls.io/repos/hoodiehq/hoodie-account-server/badge.svg?branch=master)](https://coveralls.io/github/hoodiehq/hoodie-account-server?branch=master)
[![Dependency Status](https://david-dm.org/hoodiehq/hoodie-account-server.svg)](https://david-dm.org/hoodiehq/hoodie-account-server)
[![devDependency Status](https://david-dm.org/hoodiehq/hoodie-account-server/dev-status.svg)](https://david-dm.org/hoodiehq/hoodie-account-server#info=devDependencies)

`hoodie-account-server` is a [Hapi](http://hapijs.com/) plugin that implements
the [Account JSON API](http://docs.accountjsonapi.apiary.io) routes and exposes
a corresponding API at `server.plugins.account.api.*`, persisting user accounts
using [PouchDB](https://pouchdb.com).

## Example

```js
var Hapi = require('hapi')
var PouchDB = require('PouchDB')
var hapiAccount = require('@hoodie/account-server')

var options = {
  PouchDB: PouchDB,
  admins: {
    admin: '-pbkdf2-a2ca9d3ee921c26d2e9d61e03a0801b11b8725c6,1081b31861bd1e91611341da16c11c16a12c13718d1f712e,10'
  },
  secret: 'secret123'
})

server.register({register: hapiAccount, options: options}, function (error) {})
server.connection({ port: 8000 })
server.start(function () {
  console.log('Server running at %s', server.info.uri)
})
```

## More

- [Plugin & Options](plugin/README.md)
- [Routes](routes/README.md)
- [How it works](how-it-works.md)
- [Testing](tests/README.md)

## Contributing

Have a look at the Hoodie project's [contribution guidelines](https://github.com/hoodiehq/hoodie/blob/master/CONTRIBUTING.md).
If you want to hang out you can join our [Hoodie Community Chat](http://hood.ie/chat/).

## License

[Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0)


text:
//
//  BLTransitionAnimator.h
//  翻页效果
//
//  Created by 冰泪 on 2017/6/19.
//  Copyright © 2017年 冰泪. All rights reserved.
//

#ifndef BLTransitionAnimator_h
#define BLTransitionAnimator_h

//#import "BLPresentTransitionAnimator.h"//模态转场
//#import "BLPushTransitionAnimator.h"  //push转场
#import "UINavigationController+BLPushTrasition.h"
#import "UIViewController+BLPresentTrasition.h"
#import "BLTabBarTransitionAnimator.h"  //tabbar转场

#import "BLTransitionInteraction.h" //手势处理

#import "BLTrasitionAnimatorConfig.h"

#endif /* BLTransitionAnimator_h */


text:
using System;
using System.Linq;
using JabbR.Models;
using JabbR.Services;

namespace JabbR.Commands
{
    [Command("note", "Note_CommandInfo", "note", "user")]
    public class NoteCommand : UserCommand
    {
        public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args)
        {
            // We need to determine if we're either
            // 1. Setting a new Note.
            // 2. Clearing the existing Note.
            // If we have no optional text, then we need to clear it. Otherwise, we're storing it.
            bool isNoteBeingCleared = args.Length == 0;
            callingUser.Note = isNoteBeingCleared ? null : String.Join(" ", args).Trim();

            ChatService.ValidateNote(callingUser.Note);

            context.NotificationService.ChangeNote(callingUser);

            context.Repository.CommitChanges();
        }
    }
}


text:
Reports any inner classes which may safely be made
static. An inner class may be static if it doesn't reference
its enclosing class instance. A static inner class uses slightly less memory.


text:
#include "Weapon/CGameProjectile.hpp"
#include "World/CGameLight.hpp"
#include "CStateManager.hpp"
#include "TCastTo.hpp"
#include "World/CPlayer.hpp"
#include "World/CHUDBillboardEffect.hpp"
#include "World/CWallCrawlerSwarm.hpp"
#include "World/CScriptDoor.hpp"
#include "Collision/CInternalRayCastStructure.hpp"
#include "MP1/World/CPuddleToadGamma.hpp"
#include "World/CScriptPlatform.hpp"
#include "Collision/CCollisionActor.hpp"

namespace urde {
CGameProjectile::CGameProjectile(bool active, const TToken<CWeaponDescription>& wDesc, std::string_view name,
                                 EWeaponType wType, const zeus::CTransform& xf, EMaterialTypes excludeMat,
                                 const CDamageInfo& dInfo, TUniqueId uid, TAreaId aid, TUniqueId owner,
                                 TUniqueId homingTarget, EProjectileAttrib attribs, bool underwater,
                                 const zeus::CVector3f& scale,
                                 const std::optional<TLockedToken<CGenDescription>>& visorParticle,
                                 u16 visorSfx, bool sendCollideMsg)
: CWeapon(uid, aid, active, owner, wType, name, xf,
          CMaterialFilter::MakeIncludeExclude(
              {EMaterialTypes::Solid, EMaterialTypes::NonSolidDamageable},
              {EMaterialTypes::Projectile, EMaterialTypes::ProjectilePassthrough, excludeMat}),
          CMaterialList(), dInfo, attribs | GetBeamAttribType(wType), CModelData::CModelDataNull())
, x158_visorParticle(visorParticle)
, x168_visorSfx(visorSfx)
, x170_projectile(wDesc, xf.origin, xf.basis, scale,
                  (attribs & EProjectileAttrib::ParticleOPTS) == EProjectileAttrib::ParticleOPTS)
, x298_previousPos(xf.origin)
, x2a4_projExtent((xe8_projectileAttribs & EProjectileAttrib::BigProjectile) == EProjectileAttrib::BigProjectile ? 0.25f
                                                                                : 0.1f)
, x2c0_homingTargetId(homingTarget)
, x2cc_wpscId(wDesc.GetObjectTag()->id) {
  x2e4_24_active = true;
  x2e4_25_startedUnderwater = underwater;
  x2e4_26_waterUpdate = underwater;
  x2e4_27_inWater = underwater;
  x2e4_28_sendProjectileCollideMsg = sendCollideMsg;
}

void CGameProjectile::Accept(urde::IVisitor& visitor) { visitor.Visit(this); }

void CGameProjectile::ResolveCollisionWithActor(const CRayCastResult& res, CActor& act, CStateManager& mgr) {
  zeus::CVector3f revDir = -x34_transform.basis[1].normalized();
  if (TCastToPtr<CPlayer>(act)) {
    if (x158_visorParticle && mgr.GetPlayer().GetCameraState() == CPlayer::EPlayerCameraState::FirstPerson) {
      if (zeus::radToDeg(std::acos(
              mgr.GetCameraManager()->GetCurrentCameraTransform(mgr).basis[1].normalized().dot(revDir))) <= 45.f) {
        /* Hit us head on! Draw Billboard! */
        std::optional<TToken<CGenDescription>> bb = {*x158_visorParticle};
        CHUDBillboardEffect* effect = new CHUDBillboardEffect(
            bb, {}, mgr.AllocateUniqueId(), true, "VisorAcid", CHUDBillboardEffect::GetNearClipDistance(mgr),
            CHUDBillboardEffect::GetScaleForPOV(mgr), zeus::skWhite, zeus::skOne3f,
            zeus::skZero3f);
        mgr.AddObject(effect);
        CSfxManager::SfxStart(x168_visorSfx, 1.f, 0.f, false, 0x7f, false, kInvalidAreaId);
        if (x2e4_28_sendProjectileCollideMsg)
          mgr.SendScriptMsg(&mgr.GetPlayer(), GetUniqueId(), EScriptObjectMessage::ProjectileCollide);
      }
    }
  }
}

void CGameProjectile::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId /*uid*/, CStateManager& mgr) {
  if (msg == EScriptObjectMessage::AddSplashInhabitant) {
    if (!x2e4_27_inWater) {
      x2e4_27_inWater = true;
      x2e4_26_waterUpdate = true;
    }
  } else if (msg == EScriptObjectMessage::UpdateSplashInhabitant) {
    if (!x2e4_26_waterUpdate)
      x2e4_26_waterUpdate = true;
  } else if (msg == EScriptObjectMessage::RemoveSplashInhabitant) {
    if (x2e4_26_waterUpdate) {
      x2e4_26_waterUpdate = false;
      x2e4_27_inWater = false;
    }
  } else if (msg == EScriptObjectMessage::Deleted)
    DeleteProjectileLight(mgr);
}

EProjectileAttrib CGameProjectile::GetBeamAttribType(EWeaponType wType) {
  if (wType == EWeaponType::Ice)
    return EProjectileAttrib::Ice;
  else if (wType == EWeaponType::Wave)
    return EProjectileAttrib::Wave;
  else if (wType == EWeaponType::Plasma)
    return EProjectileAttrib::Plasma;
  else if (wType == EWeaponType::Phazon)
    return EProjectileAttrib::Phazon;

  return EProjectileAttrib::None;
}

void CGameProjectile::DeleteProjectileLight(CStateManager& mgr) {
  if (x2c8_projectileLight != kInvalidUniqueId) {
    mgr.FreeScriptObject(x2c8_projectileLight);
    x2c8_projectileLight = kInvalidUniqueId;
  }
}

void CGameProjectile::CreateProjectileLight(std::string_view name, const CLight& light, CStateManager& mgr) {
  DeleteProjectileLight(mgr);
  x2c8_projectileLight = mgr.AllocateUniqueId();
  mgr.AddObject(new CGameLight(x2c8_projectileLight, GetAreaId(), GetActive(), name, GetTransform(), GetUniqueId(),
                               light, u32(x2cc_wpscId.Value()), 0, 0.f));
}

void CGameProjectile::Chase(float dt, CStateManager& mgr) {
  if (!x170_projectile.IsProjectileActive() || x2c0_homingTargetId == kInvalidUniqueId)
    return;

  if (TCastToConstPtr<CActor> act = mgr.GetObjectById(x2c0_homingTargetId)) {
    if (!act->GetMaterialList().HasMaterial(EMaterialTypes::Target) &&
        !act->GetMaterialList().HasMaterial(EMaterialTypes::Player)) {
      x2c0_homingTargetId = kInvalidUniqueId;
    } else {
      zeus::CVector3f homingPos = act->GetHomingPosition(mgr, 0.f);

      TCastToConstPtr<CWallCrawlerSwarm> swarm = act.GetPtr();
      if (swarm) {
        int lockOnId = swarm->GetCurrentLockOnId();
        if (swarm->GetLockOnLocationValid(lockOnId)) {
          homingPos = swarm->GetLockOnLocation(lockOnId);
        } else {
          x2c0_homingTargetId = kInvalidUniqueId;
          return;
        }
      }

      zeus::CVector3f projToPos = homingPos - x170_projectile.GetTranslation();
      if (x2e0_minHomingDist > 0.f && projToPos.magnitude() < x2e0_minHomingDist) {
        x2c0_homingTargetId = kInvalidUniqueId;
        return;
      }

      if (!swarm && !TCastToConstPtr<CPhysicsActor>(act.GetPtr()))
        if (auto tb = act->GetTouchBounds())
          projToPos.z() += (tb->max.z() - tb->min.z()) * 0.5f;

      zeus::CQuaternion qDelta =
          zeus::CQuaternion::shortestRotationArc(x170_projectile.GetTransform().basis[1], projToPos);

      float wThres = qDelta.w() * qDelta.w() * 2.f - 1.f;
      if (wThres > 0.99f)
        return;

      float turnRate;
      if (x2e4_26_waterUpdate)
        turnRate = x170_projectile.GetMaxTurnRate() * 0.5f;
      else
        turnRate = x170_projectile.GetMaxTurnRate();

      float maxTurnDelta = zeus::degToRad(turnRate * dt);
      float turnDelta = std::acos(wThres);
      if (maxTurnDelta < turnDelta) {
        /* Clamp quat to max delta */
        qDelta =
            zeus::CQuaternion(std::cos(maxTurnDelta * 0.5f),
                              (std::sin(maxTurnDelta * 0.5f) / std::sin(turnDelta * 0.5f)) * qDelta.getImaginary());
      }

      zeus::CTransform xf = qDelta.toTransform() * x170_projectile.GetTransform();
      xf.orthonormalize();
      x170_projectile.SetWorldSpaceOrientation(xf);
    }
  }
}

void CGameProjectile::UpdateHoming(float dt, CStateManager& mgr) {
  if (!x2e4_24_active || x2c0_homingTargetId == kInvalidUniqueId || x2a8_homingDt <= 0.f)
    return;

  x2b0_targetHomingTime += dt;

  while (x2b0_targetHomingTime >= x2b8_curHomingTime) {
    Chase(x2a8_homingDt, mgr);
    x2b8_curHomingTime += x2a8_homingDt;
  }
}

void CGameProjectile::UpdateProjectileMovement(float dt, CStateManager& mgr) {
  float useDt = dt;
  if (x2e4_26_waterUpdate)
    useDt = 37.5f * dt * dt;

  x298_previousPos = x34_transform.origin;
  x170_projectile.Update(useDt);
  SetTransform(x170_projectile.GetTransform());
  SetTranslation(x170_projectile.GetTranslation());
  UpdateHoming(dt, mgr);
}

CRayCastResult CGameProjectile::DoCollisionCheck(TUniqueId& idOut, CStateManager& mgr) {
  CRayCastResult res;
  if (x2e4_24_active) {
    zeus::CVector3f posDelta = x34_transform.origin - x298_previousPos;
    rstl::reserved_vector<TUniqueId, 1024> nearList;
    mgr.BuildNearList(nearList, GetProjectileBounds(),
                      CMaterialFilter::MakeExclude(EMaterialTypes::ProjectilePassthrough), this);

    res = RayCollisionCheckWithWorld(idOut, x298_previousPos, x34_transform.origin, posDelta.magnitude(), nearList, mgr);
  }
  return res;
}

void CGameProjectile::ApplyDamageToActors(CStateManager& mgr, const CDamageInfo& dInfo) {
  if (x2c6_pendingDamagee != kInvalidUniqueId) {
    if (TCastToPtr<CActor> act = mgr.ObjectById(x2c6_pendingDamagee)) {
      mgr.ApplyDamage(GetUniqueId(), act->GetUniqueId(), xec_ownerId, dInfo, xf8_filter, x34_transform.basis[1]);
      if ((xe8_projectileAttribs & EProjectileAttrib::PlayerUnFreeze) == EProjectileAttrib::PlayerUnFreeze &&
          mgr.GetPlayer().GetUniqueId() == act->GetUniqueId() && mgr.GetPlayer().GetFrozenState())
        mgr.GetPlayer().UnFreeze(mgr);
    }
    x2c6_pendingDamagee = kInvalidUniqueId;
  }

  for (CProjectileTouchResult& res : x2d0_touchResults) {
    if (TCastToConstPtr<CActor> act = mgr.GetObjectById(res.GetActorId())) {
      mgr.ApplyDamage(GetUniqueId(), act->GetUniqueId(), xec_ownerId, dInfo, xf8_filter, x34_transform.basis[1]);
      if ((xe8_projectileAttribs & EProjectileAttrib::PlayerUnFreeze) == EProjectileAttrib::PlayerUnFreeze &&
          mgr.GetPlayer().GetUniqueId() == act->GetUniqueId() && mgr.GetPlayer().GetFrozenState())
        mgr.GetPlayer().UnFreeze(mgr);
    }
  }

  x2d0_touchResults.clear();
}

void CGameProjectile::FluidFXThink(EFluidState state, CScriptWater& water, CStateManager& mgr) {
  if (x170_projectile.GetWeaponDescription()->xa6_SWTR)
    CWeapon::FluidFXThink(state, water, mgr);
}

CRayCastResult CGameProjectile::RayCollisionCheckWithWorld(TUniqueId& idOut, const zeus::CVector3f& start,
                                                           const zeus::CVector3f& end, float mag,
                                                           const rstl::reserved_vector<TUniqueId, 1024>& nearList,
                                                           CStateManager& mgr) {
  x2d0_touchResults.clear();
  idOut = kInvalidUniqueId;
  x2c6_pendingDamagee = kInvalidUniqueId;
  CRayCastResult res;
  zeus::CVector3f delta = end - start;
  if (!delta.canBeNormalized())
    return res;

  float bestMag = mag;
  zeus::CVector3f dir = delta.normalized();
  CRayCastResult res2 = mgr.RayStaticIntersection(start, dir, mag, xf8_filter);
  if (res2.IsValid()) {
    bestMag = res2.GetT();
    res = res2;
  }

  for (TUniqueId id : nearList) {
    if (CActor* ent = static_cast<CActor*>(mgr.ObjectById(id))) {
      CProjectileTouchResult tRes = CanCollideWith(*ent, mgr);
      if (tRes.GetActorId() == kInvalidUniqueId)
        continue;
      if (tRes.HasRayCastResult()) {
        if (tRes.GetRayCastResult().GetT() < bestMag) {
          ent->Touch(*this, mgr);
          bestMag = tRes.GetRayCastResult().GetT();
          res = tRes.GetRayCastResult();
          x2c6_pendingDamagee = idOut = tRes.GetActorId();
        }
      } else {
        auto tb = ent->GetTouchBounds();
        CGameProjectile* projObj = nullptr;
        if (TCastToPtr<CScriptDoor> door = ent) {
          tb = door->GetProjectileBounds();
        } else if (TCastToPtr<CGameProjectile> proj = ent) {
          tb.emplace(proj->GetProjectileBounds());
          projObj = proj.GetPtr();
        }
        if (!tb)
          continue;

        CCollidableAABox prim(*tb, ent->GetMaterialList());
        CRayCastResult res3 =
            prim.CastRayInternal(CInternalRayCastStructure(start, dir, mag, {}, CMaterialFilter::skPassEverything));
        if (res3.IsValid()) {
          if (res3.GetT() < bestMag) {
            bestMag = res3.GetT();
            res = res3;
            x2c6_pendingDamagee = idOut = tRes.GetActorId();
          }
        } else if (tb->pointInside(start) || (projObj && projObj->GetProjectileBounds().intersects(*tb))) {
          x2c6_pendingDamagee = idOut = ent->GetUniqueId();
          zeus::CUnitVector3f norm(-dir);
          res = CRayCastResult(0.f, start, {norm, norm.dot(start)}, ent->GetMaterialList());
          break;
        }
      }
    }
  }

  if (x2e4_27_inWater && idOut == kInvalidUniqueId)
    x2e4_27_inWater = false;

  return res;
}

CProjectileTouchResult CGameProjectile::CanCollideWith(CActor& act, CStateManager& mgr) const {
  if (act.GetDamageVulnerability()->GetVulnerability(x12c_curDamageInfo.GetWeaponMode(), false) ==
      EVulnerability::PassThrough) {
    return {kInvalidUniqueId, {}};
  } else {
    if (TCastToPtr<CScriptTrigger>(act)) {
      return CanCollideWithTrigger(act, mgr);
    } else if (TCastToPtr<CScriptPlatform>(act) || TCastToPtr<CCollisionActor>(act) ||
               CPatterned::CastTo<MP1::CPuddleToadGamma>(&act)) {
      return CanCollideWithComplexCollision(act, mgr);
    } else {
      return CanCollideWithGameObject(act, mgr);
    }
  }
}

CProjectileTouchResult CGameProjectile::CanCollideWithComplexCollision(CActor& act, CStateManager& mgr) const {
  CPhysicsActor* useAct = nullptr;
  if (TCastToPtr<CScriptPlatform> plat = act) {
    if (plat->HasComplexCollision())
      useAct = plat.GetPtr();
  } else if (MP1::CPuddleToadGamma* toad = CPatterned::CastTo<MP1::CPuddleToadGamma>(&act)) {
    useAct = toad;
  } else if (TCastToPtr<CCollisionActor> cact = act) {
    if (cact->GetOwnerId() == xec_ownerId)
      return {kInvalidUniqueId, {}};
    useAct = cact.GetPtr();
  }

  if (useAct) {
    const CCollisionPrimitive* prim = useAct->GetCollisionPrimitive();
    zeus::CTransform xf = useAct->GetPrimitiveTransform();
    zeus::CVector3f deltaPos = GetTranslation() - x298_previousPos;
    if (deltaPos.canBeNormalized()) {
      zeus::CVector3f dir = deltaPos.normalized();
      float mag = deltaPos.magnitude();
      CRayCastResult res = prim->CastRayInternal(
          {x298_previousPos, dir, mag, xf,
           CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Solid}, {EMaterialTypes::ProjectilePassthrough})});
      if (!res.IsValid()) {
        if (prim->GetPrimType() == FOURCC('SPHR')) {
          mag *= 2.f;
          CRayCastResult res2 = prim->CastRayInternal(
              {x298_previousPos - dir * mag, dir, deltaPos.magnitude(), xf,
               CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Solid}, {EMaterialTypes::ProjectilePassthrough})});
          if (res2.IsValid())
            return {act.GetUniqueId(), {res2}};
        } else if (TCastToPtr<CCollisionActor> cAct = act) {
          float rad = cAct->GetSphereRadius();
          if ((x298_previousPos - GetTranslation()).magSquared() < rad * rad) {
            zeus::CVector3f point = x298_previousPos - dir * rad * 1.125f;
            zeus::CUnitVector3f revDir(-dir);
            return {act.GetUniqueId(), {{0.f, point, {revDir, point.dot(revDir)}, act.GetMaterialList()}}};
          }
        }
        return {kInvalidUniqueId, {}};
      } else {
        return {act.GetUniqueId(), {res}};
      }
    } else {
      return {kInvalidUniqueId, {}};
    }
  } else {
    return {act.GetUniqueId(), {}};
  }
}

CProjectileTouchResult CGameProjectile::CanCollideWithGameObject(CActor& act, CStateManager& mgr) const {
  TCastToPtr<CGameProjectile> proj = act;
  if (!proj) {
    if (!act.GetMaterialList().HasMaterial(EMaterialTypes::Solid) && !act.HealthInfo(mgr)) {
      return {kInvalidUniqueId, {}};
    } else if (act.GetUniqueId() == xec_ownerId) {
      return {kInvalidUniqueId, {}};
    } else if (act.GetUniqueId() == x2c2_lastResolvedObj) {
      return {kInvalidUniqueId, {}};
    } else if (xf8_filter.GetExcludeList().Intersection(act.GetMaterialList())) {
      return {kInvalidUniqueId, {}};
    } else if (TCastToPtr<CAi> ai = act) {
      if (!ai->CanBeShot(mgr, int(xe8_projectileAttribs)))
        return {kInvalidUniqueId, {}};
    }
  } else if ((xe8_projectileAttribs & EProjectileAttrib::PartialCharge) == EProjectileAttrib::PartialCharge ||
             (proj->xe8_projectileAttribs & EProjectileAttrib::PartialCharge) == EProjectileAttrib::PartialCharge) {
    return {act.GetUniqueId(), {}};
  } else if ((xe8_projectileAttribs & EProjectileAttrib::PartialCharge) != EProjectileAttrib::PartialCharge &&
             (proj->xe8_projectileAttribs & EProjectileAttrib::PartialCharge) != EProjectileAttrib::PartialCharge) {
    return {kInvalidUniqueId, {}};
  }
  return {act.GetUniqueId(), {}};
}

CProjectileTouchResult CGameProjectile::CanCollideWithTrigger(CActor& act, CStateManager& mgr) const {
  bool isWater = TCastToPtr<CScriptWater>(act).operator bool();
  if (isWater) {
    bool enteredWater = false;
    if (isWater && !x2e4_25_startedUnderwater) {
      if (!x170_projectile.GetWeaponDescription()->xa4_EWTR)
        enteredWater = true;
    }
    /* This case is logically unreachable */
    bool leftWater = false;
    if (!isWater && x2e4_25_startedUnderwater) {
      if (!x170_projectile.GetWeaponDescription()->xa5_LWTR)
        leftWater = true;
    }
    return {(enteredWater || leftWater) ? act.GetUniqueId() : kInvalidUniqueId, {}};
  }
  return {kInvalidUniqueId, {}};
}

zeus::CAABox CGameProjectile::GetProjectileBounds() const {
  return {{std::min(x298_previousPos.x(), GetTranslation().x()) - x2a4_projExtent,
           std::min(x298_previousPos.y(), GetTranslation().y()) - x2a4_projExtent,
           std::min(x298_previousPos.z(), GetTranslation().z()) - x2a4_projExtent},
          {std::max(x298_previousPos.x(), GetTranslation().x()) + x2a4_projExtent,
           std::max(x298_previousPos.y(), GetTranslation().y()) + x2a4_projExtent,
           std::max(x298_previousPos.z(), GetTranslation().z()) + x2a4_projExtent}};
}

std::optional<zeus::CAABox> CGameProjectile::GetTouchBounds() const {
  if (x2e4_24_active)
    return {GetProjectileBounds()};
  return {};
}

} // namespace urde


text:
package com.rometools.rome.feed.synd.impl;

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

import org.jdom2.Element;

import com.rometools.rome.feed.WireFeed;
import com.rometools.rome.feed.atom.Content;
import com.rometools.rome.feed.atom.Entry;
import com.rometools.rome.feed.atom.Feed;
import com.rometools.rome.feed.atom.Link;
import com.rometools.rome.feed.atom.Person;
import com.rometools.rome.feed.module.impl.ModuleUtils;
import com.rometools.rome.feed.synd.Converter;
import com.rometools.rome.feed.synd.SyndContent;
import com.rometools.rome.feed.synd.SyndContentImpl;
import com.rometools.rome.feed.synd.SyndEnclosure;
import com.rometools.rome.feed.synd.SyndEnclosureImpl;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndEntryImpl;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.feed.synd.SyndImage;
import com.rometools.rome.feed.synd.SyndImageImpl;
import com.rometools.rome.feed.synd.SyndLink;
import com.rometools.rome.feed.synd.SyndLinkImpl;
import com.rometools.rome.feed.synd.SyndPerson;
import com.rometools.rome.feed.synd.SyndPersonImpl;
import com.rometools.utils.Alternatives;
import com.rometools.utils.Lists;
import com.rometools.utils.Strings;

/**
 */
public class ConverterForAtom03 implements Converter {

    private final String type;

    public ConverterForAtom03() {
        this("atom_0.3");
    }

    protected ConverterForAtom03(final String type) {
        this.type = type;
    }

    @Override
    public String getType() {
        return type;
    }

    @Override
    public void copyInto(final WireFeed feed, final SyndFeed syndFeed) {

        final Feed aFeed = (Feed) feed;

        syndFeed.setModules(ModuleUtils.cloneModules(aFeed.getModules()));

        final List<Element> foreignMarkup = feed.getForeignMarkup();
        if (Lists.isNotEmpty(foreignMarkup)) {
            syndFeed.setForeignMarkup(foreignMarkup);
        }

        syndFeed.setEncoding(aFeed.getEncoding());
        syndFeed.setStyleSheet(aFeed.getStyleSheet());

        final String logo = aFeed.getLogo();
        final String icon = aFeed.getIcon();

        if (logo != null) {
            final SyndImage image = new SyndImageImpl();
            image.setUrl(logo);
            syndFeed.setImage(image);
        } else if (icon != null) {
            final SyndImage image = new SyndImageImpl();
            image.setUrl(icon);
            syndFeed.setImage(image);
        }

        syndFeed.setUri(aFeed.getId());

        syndFeed.setTitle(aFeed.getTitle());

        // use first alternate links as THE link
        final List<Link> alternateLinks = aFeed.getAlternateLinks();
        if (Lists.isNotEmpty(alternateLinks)) {
            final Link link = alternateLinks.get(0);
            syndFeed.setLink(link.getHrefResolved());
        }
        // lump alternate and other links together
        final List<SyndLink> syndLinks = new ArrayList<SyndLink>();
        if (Lists.isNotEmpty(alternateLinks)) {
            syndLinks.addAll(createSyndLinks(alternateLinks));
        }
        final List<Link> otherLinks = aFeed.getOtherLinks();
        if (Lists.isNotEmpty(otherLinks)) {
            syndLinks.addAll(createSyndLinks(otherLinks));
        }
        syndFeed.setLinks(syndLinks);

        final Content tagline = aFeed.getTagline();
        if (tagline != null) {
            syndFeed.setDescription(tagline.getValue());
        }

        final List<Entry> aEntries = aFeed.getEntries();
        if (Lists.isNotEmpty(aEntries)) {
            syndFeed.setEntries(createSyndEntries(aEntries, syndFeed.isPreservingWireFeed()));
        }

        // Core Atom language/author/copyright/modified elements have precedence
        // over DC equivalent info.

        final String language = aFeed.getLanguage();
        if (language != null) {
            syndFeed.setLanguage(language);
        }

        final List<SyndPerson> authors = aFeed.getAuthors();
        if (Lists.isNotEmpty(authors)) {
            syndFeed.setAuthors(createSyndPersons(authors));
        }

        final String copyright = aFeed.getCopyright();
        if (copyright != null) {
            syndFeed.setCopyright(copyright);
        }

        final Date date = aFeed.getModified();
        if (date != null) {
            syndFeed.setPublishedDate(date);
        }

    }

    protected List<SyndLink> createSyndLinks(final List<Link> atomLinks) {
        final ArrayList<SyndLink> syndLinks = new ArrayList<SyndLink>();
        for (final Link atomLink : atomLinks) {
            final Link link = atomLink;
            if (!link.getRel().equals("enclosure")) {
                final SyndLink syndLink = createSyndLink(link);
                syndLinks.add(syndLink);
            }
        }
        return syndLinks;
    }

    public SyndLink createSyndLink(final Link link) {
        final SyndLink syndLink = new SyndLinkImpl();
        syndLink.setRel(link.getRel());
        syndLink.setType(link.getType());
        syndLink.setHref(link.getHrefResolved());
        syndLink.setTitle(link.getTitle());
        return syndLink;
    }

    protected List<SyndEntry> createSyndEntries(final List<Entry> atomEntries, final boolean preserveWireItems) {
        final List<SyndEntry> syndEntries = new ArrayList<SyndEntry>();
        for (final Entry atomEntry : atomEntries) {
            syndEntries.add(createSyndEntry(atomEntry, preserveWireItems));
        }
        return syndEntries;
    }

    protected SyndEntry createSyndEntry(final Entry entry, final boolean preserveWireItem) {

        final SyndEntryImpl syndEntry = new SyndEntryImpl();

        if (preserveWireItem) {
            syndEntry.setWireEntry(entry);
        }

        syndEntry.setModules(ModuleUtils.cloneModules(entry.getModules()));

        final List<Element> foreignMarkup = entry.getForeignMarkup();
        if (Lists.isNotEmpty(foreignMarkup)) {
            syndEntry.setForeignMarkup(foreignMarkup);
        }

        syndEntry.setTitle(entry.getTitle());

        // if there is exactly one alternate link, use that as THE link
        final List<Link> alternateLinks = entry.getAlternateLinks();
        if (Lists.sizeIs(alternateLinks, 1)) {
            final Link theLink = alternateLinks.get(0);
            syndEntry.setLink(theLink.getHrefResolved());
        }

        // Create synd enclosures from enclosure links
        final List<SyndEnclosure> syndEnclosures = new ArrayList<SyndEnclosure>();
        final List<Link> otherLinks = entry.getOtherLinks();
        if (Lists.isNotEmpty(otherLinks)) {
            for (final Link otherLink : otherLinks) {
                final Link thisLink = otherLink;
                if ("enclosure".equals(thisLink.getRel())) {
                    syndEnclosures.add(createSyndEnclosure(entry, thisLink));
                }
            }
        }
        syndEntry.setEnclosures(syndEnclosures);

        // lump alternate and other links together
        final List<SyndLink> syndLinks = new ArrayList<SyndLink>();

        if (Lists.isNotEmpty(alternateLinks)) {
            syndLinks.addAll(createSyndLinks(alternateLinks));
        }

        if (Lists.isNotEmpty(otherLinks)) {
            syndLinks.addAll(createSyndLinks(otherLinks));
        }

        syndEntry.setLinks(syndLinks);

        final String id = entry.getId();
        if (id != null) {
            syndEntry.setUri(id);
        } else {
            final String link = syndEntry.getLink();
            syndEntry.setUri(link);
        }

        Content summary = entry.getSummary();
        if (summary == null) {
            final List<Content> contents = entry.getContents();
            if (Lists.isNotEmpty(contents)) {
                summary = contents.get(0);
            }
        } else {
            final SyndContent sContent = new SyndContentImpl();
            sContent.setType(summary.getType());
            sContent.setValue(summary.getValue());
            syndEntry.setDescription(sContent);
        }

        final List<Content> contents = entry.getContents();
        if (Lists.isNotEmpty(contents)) {
            final List<SyndContent> sContents = new ArrayList<SyndContent>();
            for (final Content content : contents) {
                final SyndContent sContent = new SyndContentImpl();
                sContent.setType(content.getType());
                sContent.setValue(content.getValue());
                sContent.setMode(content.getMode());
                sContents.add(sContent);

            }
            syndEntry.setContents(sContents);
        }

        final List<SyndPerson> authors = entry.getAuthors();
        if (Lists.isNotEmpty(authors)) {
            syndEntry.setAuthors(createSyndPersons(authors));
            final SyndPerson firstPerson = syndEntry.getAuthors().get(0);
            syndEntry.setAuthor(firstPerson.getName());
        }

        Date date = entry.getModified();
        if (date == null) {
            date = Alternatives.firstNotNull(entry.getIssued(), entry.getCreated());
        }

        if (date != null) {
            syndEntry.setPublishedDate(date);
        }

        return syndEntry;
    }

    public SyndEnclosure createSyndEnclosure(final Entry entry, final Link link) {
        final SyndEnclosure syndEncl = new SyndEnclosureImpl();
        syndEncl.setUrl(link.getHrefResolved());
        syndEncl.setType(link.getType());
        syndEncl.setLength(link.getLength());
        return syndEncl;
    }

    @Override
    public WireFeed createRealFeed(final SyndFeed syndFeed) {
        final Feed aFeed = new Feed(getType());
        aFeed.setModules(ModuleUtils.cloneModules(syndFeed.getModules()));

        aFeed.setEncoding(syndFeed.getEncoding());
        aFeed.setStyleSheet(syndFeed.getStyleSheet());

        aFeed.setId(syndFeed.getUri());

        final SyndContent sTitle = syndFeed.getTitleEx();
        if (sTitle != null) {

            final Content title = new Content();
            final String type = sTitle.getType();
            if (type != null) {
                title.setType(type);
            }

            final String mode = sTitle.getMode();
            if (mode != null) {
                title.setMode(mode);
            }

            title.setValue(sTitle.getValue());
            aFeed.setTitleEx(title);
        }

        // separate SyndEntry's links collection into alternate and other links
        final List<Link> alternateLinks = new ArrayList<Link>();
        final List<Link> otherLinks = new ArrayList<Link>();

        final List<SyndLink> slinks = syndFeed.getLinks();
        if (slinks != null) {
            for (final SyndLink syndLink2 : slinks) {
                final SyndLink syndLink = syndLink2;
                final Link link = createAtomLink(syndLink);
                final String rel = link.getRel();
                if (Strings.isBlank(rel) || "alternate".equals(rel)) {
                    alternateLinks.add(link);
                } else {
                    otherLinks.add(link);
                }
            }
        }
        // no alternate link? then use THE link if there is one
        final String sLink = syndFeed.getLink();
        if (alternateLinks.isEmpty() && sLink != null) {
            final Link link = new Link();
            link.setRel("alternate");
            link.setHref(sLink);
            alternateLinks.add(link);
        }

        if (!alternateLinks.isEmpty()) {
            aFeed.setAlternateLinks(alternateLinks);
        }
        if (!otherLinks.isEmpty()) {
            aFeed.setOtherLinks(otherLinks);
        }

        final String sDesc = syndFeed.getDescription();
        if (sDesc != null) {
            final Content tagline = new Content();
            tagline.setValue(sDesc);
            aFeed.setTagline(tagline);
        }

        aFeed.setLanguage(syndFeed.getLanguage());

        final List<SyndPerson> authors = syndFeed.getAuthors();
        if (Lists.isNotEmpty(authors)) {
            aFeed.setAuthors(createAtomPersons(authors));
        }

        aFeed.setCopyright(syndFeed.getCopyright());

        aFeed.setModified(syndFeed.getPublishedDate());

        final List<SyndEntry> sEntries = syndFeed.getEntries();
        if (sEntries != null) {
            aFeed.setEntries(createAtomEntries(sEntries));
        }

        return aFeed;
    }

    protected static List<SyndPerson> createAtomPersons(final List<SyndPerson> sPersons) {
        final List<SyndPerson> persons = new ArrayList<SyndPerson>();
        for (final SyndPerson syndPerson : sPersons) {
            final SyndPerson sPerson = syndPerson;
            final Person person = new Person();
            person.setName(sPerson.getName());
            person.setUri(sPerson.getUri());
            person.setEmail(sPerson.getEmail());
            person.setModules(sPerson.getModules());
            persons.add(person);
        }
        return persons;
    }

    protected static List<SyndPerson> createSyndPersons(final List<SyndPerson> aPersons) {
        final List<SyndPerson> persons = new ArrayList<SyndPerson>();
        for (final SyndPerson person2 : aPersons) {
            final SyndPerson person = new SyndPersonImpl();
            person.setName(person2.getName());
            person.setUri(person2.getUri());
            person.setEmail(person2.getEmail());
            person.setModules(person2.getModules());
            persons.add(person);
        }
        return persons;
    }

    protected List<Entry> createAtomEntries(final List<SyndEntry> syndEntries) {
        final List<Entry> atomEntries = new ArrayList<Entry>();
        for (final SyndEntry syndEntry : syndEntries) {
            atomEntries.add(createAtomEntry(syndEntry));
        }
        return atomEntries;
    }

    protected Entry createAtomEntry(final SyndEntry sEntry) {
        final Entry aEntry = new Entry();
        aEntry.setModules(ModuleUtils.cloneModules(sEntry.getModules()));

        aEntry.setId(sEntry.getUri());

        final SyndContent sTitle = sEntry.getTitleEx();
        if (sTitle != null) {
            final Content title = new Content();
            final String type = sTitle.getType();
            if (type != null) {
                title.setType(type);
            }

            final String mode = sTitle.getMode();
            if (mode != null) {
                title.setMode(mode);
            }

            title.setValue(sTitle.getValue());
            aEntry.setTitleEx(title);
        }

        // separate SyndEntry's links collection into alternate and other links
        final List<Link> alternateLinks = new ArrayList<Link>();
        final List<Link> otherLinks = new ArrayList<Link>();
        final List<SyndLink> syndLinks = sEntry.getLinks();

        if (syndLinks != null) {
            for (final SyndLink syndLink : syndLinks) {
                final Link link = createAtomLink(syndLink);
                final String rel = link.getRel();
                if (Strings.isBlank(rel) || "alternate".equals(rel)) {
                    alternateLinks.add(link);
                } else {
                    otherLinks.add(link);
                }
            }
        }
        // no alternate link? then use THE link if there is one
        final String sLink = sEntry.getLink();
        if (alternateLinks.isEmpty() && sLink != null) {
            final Link link = new Link();
            link.setRel("alternate");
            link.setHref(sLink);
            alternateLinks.add(link);
        }

        final List<SyndEnclosure> sEnclosures = sEntry.getEnclosures();
        if (sEnclosures != null) {
            for (final SyndEnclosure syndEnclosure : sEnclosures) {
                final Link link = createAtomEnclosure(syndEnclosure);
                otherLinks.add(link);
            }
        }

        if (!alternateLinks.isEmpty()) {
            aEntry.setAlternateLinks(alternateLinks);
        }
        if (!otherLinks.isEmpty()) {
            aEntry.setOtherLinks(otherLinks);
        }

        final SyndContent sContent = sEntry.getDescription();
        if (sContent != null) {
            final Content content = new Content();
            content.setType(sContent.getType());
            content.setValue(sContent.getValue());
            content.setMode(Content.ESCAPED);
            aEntry.setSummary(content);
        }

        final List<SyndContent> contents = sEntry.getContents();
        if (!contents.isEmpty()) {
            final List<Content> aContents = new ArrayList<Content>();
            for (final SyndContent syndContent : contents) {
                final Content content = new Content();
                content.setType(syndContent.getType());
                content.setValue(syndContent.getValue());
                content.setMode(syndContent.getMode());
                aContents.add(content);
            }
            aEntry.setContents(aContents);
        }

        final List<SyndPerson> sAuthors = sEntry.getAuthors();
        final String author = sEntry.getAuthor();
        if (Lists.isNotEmpty(sAuthors)) {
            aEntry.setAuthors(createAtomPersons(sAuthors));
        } else if (author != null) {
            final Person person = new Person();
            person.setName(author);
            final List<SyndPerson> authors = new ArrayList<SyndPerson>();
            authors.add(person);
            aEntry.setAuthors(authors);
        }

        aEntry.setModified(sEntry.getPublishedDate());
        aEntry.setIssued(sEntry.getPublishedDate());

        return aEntry;
    }

    public Link createAtomLink(final SyndLink syndLink) {
        final Link link = new Link();
        link.setRel(syndLink.getRel());
        link.setType(syndLink.getType());
        link.setHref(syndLink.getHref());
        link.setTitle(syndLink.getTitle());
        return link;
    }

    public Link createAtomEnclosure(final SyndEnclosure syndEnclosure) {
        final Link link = new Link();
        link.setRel("enclosure");
        link.setType(syndEnclosure.getType());
        link.setHref(syndEnclosure.getUrl());
        link.setLength(syndEnclosure.getLength());
        return link;
    }

}


text:
"use strict";

var jsx = require('jsx-runtime');
var hasOwn = Object.prototype.hasOwnProperty;

var emptyTags = require('empty-tags').reduce(function(map, tag) {
  map[tag] = true;
  return map;
}, Object.create(null));

var SVG_NS = 'http://www.w3.org/2000/svg';
var HTML_NS = 'http://www.w3.org/1999/xhtml';

var renderer = jsx.register('DOM', {
  before: function(element) {
    this.scope.namespaces = [];
    return element;
  },
  tags: {
    '*': {
      enter: function(tag, props) {
        var namespaces = this.scope.namespaces;

        if (tag === 'svg') {
          namespaces.unshift(SVG_NS);
        } else if (tag === 'foreignObject') {
          namespaces.unshift(HTML_NS);
        }

        var element;

        if (namespaces.length) {
          element = document.createElementNS(namespaces[0], tag);
        } else {
          element = document.createElement(tag);
        }

        applyProps(element, props);

        return element;
      },
      leave: function(parent, tag) {
        if (
          tag === 'svg' && this.scope.namespaces[0] === SVG_NS ||
          tag === 'foreignObject' && this.scope.namespaces[0] === HTML_NS
        ) {
          this.scope.namespaces.shift();
        }

        return parent;
      },
      child: function(child, parent) {
        if (child instanceof Element) {
          // do nothing
        } else {
          child = document.createTextNode(child + '');
        }

        parent.appendChild(child);
        return parent;
      },
      children: function(children, parent, tag) {
        if (typeof emptyTags[tag.toLowerCase()] !== 'undefined') {
          throw new Error('Tag <' + tag + ' /> cannot have children');
        }

        return children;
      }
    }
  }
});

module.exports = renderer;

function applyStyle(element, style) {
  if (typeof style === 'string') {
    element.setAttribute('style', style);
    return;
  }

  var elementStyle = element.style;

  for (var key in style) {
    if (!hasOwn.call(style, key)) continue;

    elementStyle[key] = style[key];
  }
}

function applyProps(element, props) {
  for (var key in props) {
    if (!hasOwn.call(props, key)) continue;

    var val = props[key];

    switch (key) {
      case 'style': applyStyle(element, val); break;
      case 'class': element.className = val; break;
      case 'for': element.cssFor = val; break;

      case 'innerHTML':
      case 'outerHTML':
      case 'textContent':
      case 'innerText':
      case 'text':
        console.warn('Direct manipulation of tags content is not allowed');
        break;
      default: {
        if (key.indexOf('-') !== -1) {
          element.setAttribute(key, val);
        } else {
          element[key] = val;
        }
      }
    }
  }
}


text:
/* mqueue.h: POSIX 1003.1b Message Queues */

#ifndef _MQUEUE_H_
#define	_MQUEUE_H_

#include <sys/_posix.h>

#ifdef _P1003_1B_INCLUDE_MAYBES
#include <sys/types.h>
#include <fcntl.h>
#include <time.h>
#include <signal.h>
#else
struct sigevent;
#endif

typedef	int		mqd_t;	/* message queue descriptors */

struct mq_attr {
	long	mq_flags;	/* message queue flags */
	long	mq_maxmsg;	/* maximum number of messages */
	long	mq_msgsize;	/* maximum message size */
	long	mq_curmsgs;	/* number of messages currently queued */
};

#ifndef _KERNEL

#include <sys/cdefs.h>

__BEGIN_DECLS
int	 mq_close(mqd_t);
int	 mq_getattr(mqd_t, struct mq_attr *);
int	 mq_notify(mqd_t, const struct sigevent *);
mqd_t	 mq_open(const char *, int oflag, ...);
ssize_t	 mq_receive(mqd_t, char *, size_t, unsigned int *);
int	 mq_send(mqd_t, const char *, size_t, unsigned int);
int	 mq_setattr(mqd_t, const struct mq_attr *, struct mq_attr *);
int	 mq_unlink(const char *);
__END_DECLS

#endif

#endif /* !_MQUEUE_H_ */


text:
Nautilus is named after that

# Rhythmbox

## Preferences

Preferences and plugins can be found under the edit menu.

## Lyrics. WTF is this artist saying? Cat in the catbox.

I haven't investigated as to why yet but the songlyrics plugin is broken. My guess is it uses a web api
that lacks lyrics. It also is pretty much useless as it has no sidebar.

You can improve your lyrics experience by installing [lLyrics](https://github.com/dmo60/lLyrics)

Add the ppa fossfreedom. Fossfreedom is a ppa (Public Project Awesome, just kidding. Real definition here).
It's a ppa with Rhythmbox plugins.

```sh
sudo add-apt-repository ppa:fossfreedom/rhythmbox-plugins
sudo apt-get update
```

Then install

```sh
sudo apt-get install rhythmbox-plugin-llyrics
```

Go enable the plugin. Click the lLyrics icon. You'll now have a sidebar for lyrics.

# Unity

If you approach Unity like a dock you're going to hate it. It's a terrible dock, it's meant to keyboard
driven not mouse driven. Unfortunately this is massive failure on Canonical's part in the delight department.

## Dealing with crashes

### WTF is happening

(screenshot example) insane overlay thingy

# Bugs

If you have certain themes or applications installed you may expreince the following.

```sh
Gtk-WARNING **: Unable to locate theme engine in module_path: "pixmap",
```

This can be fixed by installing `gtk2-engines-pixbuf`

Run

```sh
sudo apt-get install gtk2-engines-pixbuf
```

## Disks/Udisks

Clicking format will often just delay for a bit until and error dialog arrives. No fix. Just be aware.
Tread carefully and carry backups.

### Errors

```
Error synchronizing after initial wipe: Timed out waiting for object (udisks-error-quark, 0)
```

A known bug and unfortunately unfixed. https://bugs.launchpad.net/ubuntu/+source/udisks/+bug/1059872.
There are two solutions. 1. Format via terminal or 2. Install Gparted

Delight:
	If your disk uses gpt you will need to use Gparted not the terminal. This is likely to have occurred
	if you clicked around in Disks trying to make things work.

	Run:

	```sh
	sudo fdisk -l
	```

	If you get back
	```
		WARNING: GPT (GUID Partition Table) detected on '/dev/sdg1'! The util fdisk doesn't support GPT. Use GNU Parted.
	```

	Then you need to use gparted

#### Terminal

Formatting USB from the terminal requires using mkfs. I'll let them do the describing.

```
The mkfs (i.e., make filesystem) command is used to create a filesystem (i.e., a system for organizing a hierarchy of directories, subdirectories and files) on a formatted storage device or media, usually a partition on a hard disk drive (HDD).
```

Let's see what we have got by running the command.

```sh
mkfs
``

We will get back the following.

```sh
Usage: mkfs [options] [-t type fs-options] device [size]

Options:
 -t, --type=TYPE  file system type, when undefined ext2 is used
     fs-options   parameters to real file system builder
     device       path to a device
     size         number of blocks on the device
 -V, --verbose    explain what is done
                  defining -V more than once will cause a dry-run
 -V, --version    output version information and exit
                  -V as version must be only option
 -h, --help       display this help and exit

For more information see mkfs(8).
```

The filetypes that are allowed are;

- ext3.
	A journaled file system that is commonly used by the Linux kernel. Use this if you intend to only
	use the stick on Linux systems.
- minix.
	Minix file system. No reason to use, unless you are one of those weirdos installing strange
	OSes for the fun of it. Don't worry, I love you anyway, but you are so god damn weird.
- msdos
	What the name says.
- vfat
	This is where things get a little convoluted. VFAT is technically an extension of FAT16 and FAT32 is
	the next iteration. But mkfs seems to treat VFAT as FAT32.
- xfs.
	A high performance file system originally developed for IRIX.

Delight:
	Types are mount to mkfs 'sub commands', e.g `mkfs.vfat` for FAT. We will use these for ease of use.

You need to figure out the /dev address of the usb stick.

You can run `df` if your disk is mounted. If it's not then head over to Disks Utility.
In my case it's `/sdg`

Very Delightful:
	If your USB has multiple partitions then you need to delete them first. First enter into a sudo session

  ``sh
  sudo su
  ```

  1. Then we need to delete all the partitions on the drive.
    - `fdisk -l` will give you the drive letter
    - `fdisk /dev/driveletterhere` will open fdisk to the drive
    - `d` deletes a partition
    - `1` selects the 1st partition

    fdisk should automatically select the next partition so you just keep hitting d until all the partitions are gone. In any case repeat commands as necessary until all the partitions are gone.

	2. Finally we need to a create primary partition.
    - `n` makes a new partition
    - `p` makes the partition primary
    - `1` makes the partition the first one

    Accept the defaults and then type `w` to write the changes

We have to unmount a disk before formatting.

```sh
sudo umount /dev/driveletter
```

Then to format we do

```sh
mkfs.vfat -F 32 -n MediaUSB /dev/driveletter
```

### Cp

To copy files you can use a wildcard

```sh
cp filesfolder/* newfilesfolder/*
```

Now you may be wondering, "can cp take regular expressions?". The answer is no. But it does take
globs which are almost as powerful. If you use ruby or php chances are you have been exposed to them
at one time or another. To get details just type:

```sh
man glob
```

So how does this work? A basic example is the following:

```sh
cp cats*.jar /destination/directory
```

### Glob all the things

Did you know your shell has regex practically built in? It's in the form of globs. If you use ruby or php chances are you have been exposed to them at one time or another. Probably doing something file  Dir.glob('*.rb'). Or using
rakes Filesets. It works the same, sorta regex without all the capturing stuff. Basically globs don't
make a try at being a turing complete bastard, and just KISS it.

So what are globs useful for? Being build into the shell opens up a massive range of possibilities.
Here are a few:

Use it with ls:

```
ls *.gif  # List gifs
ls ?.gif  # List gifs with 1 char names (e.g 1.gif, a.gif)
```

Use it to remove things:

```sh
rm [A-Z]*.rar # Removes rar files
```

Use it to copy things:

```sh
cp *.jar /destination/directory # Copy all the jar files
```

You can enable more power with extended globbing:

For bash this is:

```sh
shopt -s extglob
```

For zsh this is:

```sh
setopt kshglob
```

I'll let the man tell you what this does:

```sh
?(pattern-list)   Matches zero or one occurrence of the given patterns
*(pattern-list)   Matches zero or more occurrences of the given patterns
+(pattern-list)   Matches one or more occurrences of the given patterns
@(pattern-list)   Matches one of the given patterns
!(pattern-list)   Matches anything except one of the given patterns
```

We can use this to combine globs:

```sh
ls *+(.jpg|.md) # List jpg and md files
```

What else can this puppy do? Anything you set it do. The limit is your imagination. Maybe you
use it as a simple replacement for regex in grep or maybe you use it to build a House of Gold(fish).

#### Gparted

Install using apt

The best design is intuitive, intuition comes from experience. Know the experiences of your users.

```sh
sudo apt-get install gparted
```

We need to run as root so do:

```sh
sudo gparted
```

Find your USB drive and select it via the dropdown

[Image Here]

Delight:
	You may get a warning along the lines of:

	```sh
		/dev/sdg contains GPT signatures, indicating that it has a GPT table.
		However, it does not have a valid fake msdos partition table, as it should. Perhaps it was corrupted
		-- possibly by a program that doesn't understand GPT partition tables.
		Or perhaps you deleted the GPT table, and are now using an msdos partition table.
		Is this a GPT partition table?
  ```

  If you care about the data on the disk then you need to use gdisk and try to repair the broken partition table. But if not then just click no and continue with the process. You will overwrite the old partition table.

Delight:
	If you have no table. Do Device->Create Partition Table first

Choose Partition->New

[Image Here]

Select fat32 (this will be readable on most places; Linux, Windows and Mac). Make sure to give it a
label you lazy human. One day when you aren't starting at four mounted volumes labeled Untitled you'll thank me. If the latter happens you'll learn a valuable lesson about listening to advice you find in ebooks
you got off the internet written by strangers.

[Image Here]

Click the checkmark icon

It will pend the changes. Be patient. Seriously, be patient, you need patience.

##

### Read Only Error

The first thing you need to do is determine whether or not it's Nautilus or the actual USB stick.

Do `sudo nautilus`. If you can copy files then you need to do some googling. It might be well known bug
in 12.10.

The quick fix is:

```sh
sudo add-apt-repository ppa:webupd8team/experiments
sudo apt-get update
sudo apt-get dist-upgrade
nautilus -q
```

It will install a patche nautilus with various fixes.

To remove just do:

```sh
sudo apt-get install ppa-purge
sudo ppa-purge ppa:webupd8team/experiments
```

If you still cant copy files then it's likely a patrition issue, a filesystem check will usually resolve this.

To check a partition do the following:

1. Open GParted

```sh
sudo gparted
```

2. Select it in the drop down

[Image here]

3. Right Click partition select Check

[Image Here]

## Terminal

Type `exit` to quit a `su` session.

# Flareget

Just don't. It's too buggy. Install uget instead.

do the following

```sh
sudo add-apt-repository ppa:plushuang-tw/uget-stable
sudo apt-get update
sudo apt-get install uget aria2
```

# Uget

## Scheduler

If the scheduler is enabled you must click `Force Start` to start a download.

## Settings

It wont remember some of your settings like location and number of connections per server;
so make sure to set them everytime.

## Packages

### Check what packages you have installed

Use the following

```sh
dpkg --get-selections
```

To search just pipe the result to grep:

```sh
dpkg --get-selections | grep packagename
```

For example:

```sh
dpkg --get-selections | grep awk
```

TODO:

How the fuck does dpkg --list and less command work together?

You get back:

```sh
mawk						install
```

### Removing Packages

Use the following:

```sh
sudo apt-get remove packagename
```

For example remove vlc:
```sh
sudo apt-get remove vlc
```

What if you want to remove the config files to?

```sh
sudo apt-get --purge remove vlc
```

Delight:
	Remove takes multiple packages, e.g:

	```sh
	sudo apt-get remove vlc zsh
	```

## Get info on a package

~~~ sh
apt-cache show packagename
~~~

Example:

~~~ sh
apt-cache show gummi
~~~

If you get long output you can pipe into less

~~~ sh
apt-cache show  texlive-latex-extra | less
~~~

Scroll to scroll. Hit `q` to quit.

## Terminal

Change permissions.

Use numbers.

```sh
chmod 644 filename
```

Get your group
```sh
groups <username>
```

Defaults to your username so you can just use:

```sh
groups
```

Change ownership:

```
sudo chown username:usergroup somefile
```

List file permissions:

```sh
ls -l
```

What the fuck does that `-l` do? Th answer lies in the man:

```sh
-l     use a long listing format
```

Pipe long terminal things to less:

If you get a lot of output from a command you can pipe it less and then page through it. For example:

~~~ sh
apt-cache show  texlive-latex-extra | less
~~~

Scroll to scroll. Hit `q` to quit.

## Man tips for your man (or woman)

Lets say you have a loved one and they have questions about cat. It's the middle of the night
and you really don't have time for that google shit. You want answers now. He is keeping you
up and god damnit cant a man research tech stuff on his own? Do they have to be so helpless when
it comes to technology. So you pull up man and you're like "What do you want to know honey?" and
he is like "If you don't want to help thats fine I'll just google tomorrow" and you're like "Come on. Just
spit it out so we can go to bed." and he is like "what does" `cat -u` "do?"

So you go to pull up `man cat` but you're like you know what I bet I can search through this.

The first thing you try is:

```sh
man cat | grep -u
```

But you get back:

```sh
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
```

And now you want to take your man and shove him out the window. But you push on.
What if you pass it as a string:

```sh
man cat | grep '-u'
```

Same thing. Maybe you can escape this fucker? So you try:

```sh
man cat | grep \-u
```

But no cigar. Now you have really had it so you decide to man up and man your grep for info:

```sh
man grep
```

After some scrolling you discover that you can pass a real regex to grep via `-e` so you do the following:

```sh
man cat | grep -e '-u'
```

And get back:

```sh
-u     (ignored)
```

Finally you can go to bed. You turn over to your man and he IS SLEEPING. You consider waking him up
and teaching him lesson about tech questions in the middle of night. But you realize he cant help himself,
you smile at his adorkable ignorance and curiosity and drift off to sleep.

Delight:
	You can scroll through man pages (actually anything paged by less). Use your mousewheel man.

## Firefox

Need to drag and drop an image to Nautilus? Hold Crtl and drag. Drag without holding crtl and you'll
save a link.

## Desktop

Ever see a strang lttl box appear in the right rand bototm corner? It looks like this

IMAGE HERE

It's Nautlius' search function. You can filter your desktop icons with it. Once you have any app
open it will go away and you will have to focus on the desktop to get it back. (Shorcut for cfocusing on desktop here)


text:
<?php

/* MrRestBundle:Vie:article.html.twig */
class __TwigTemplate_fc16e14e38341d6901fa426a1880c676 extends Twig_Template
{
    protected $parent;

    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->blocks = array(
            'javascripts' => array($this, 'block_javascripts'),
            'content' => array($this, 'block_content'),
        );
    }

    public function getParent(array $context)
    {
        if (null === $this->parent) {
            $this->parent = $this->env->loadTemplate("LiipHelloBundle::vie.html.twig");
        }

        return $this->parent;
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $context = array_merge($this->env->getGlobals(), $context);

        $this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_javascripts($context, array $blocks = array())
    {
        // line 4
        echo "
    ";
        // line 5
        echo $this->renderParentBlock("javascripts", $context, $blocks);
        echo "

";
    }

    // line 53
    public function block_content($context, array $blocks = array())
    {
        // line 54
        echo "

env, $this->getAttribute($this->getContext($context, 'article'), "fullpath", array(), "any", false), "html");
        echo "\">

";
        // line 58
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, 'article'), "title", array(), "any", false), "html");
        echo "

                ";
        // line 60
        echo $this->getAttribute($this->getContext($context, 'article'), "body", array(), "any", false);
        echo "

";
    }

    public function getTemplateName()
    {
        return "MrRestBundle:Vie:article.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }
}


text:
module ProjectHeaderSelection {
  export interface IProjectHeaderSelectionScope extends ng.IScope {
    vm: ProjectHeaderSelectionCtrl; //DashboardSelectionCtrl;
  }

  export class ProjectHeaderSelectionCtrl {
    public scope: any;
    public project: csComp.Services.SolutionProject;

    // $inject annotation.
    // It provides $injector with information about dependencies to be injected into constructor
    // it is better to have it close to the constructor, because the parameters must match in count and type.
    // See http://docs.angularjs.org/guide/di
    public static $inject = [
      '$scope',
      'layerService',
      'dashboardService',
      'mapService',
      'messageBusService'
    ];

    // dependencies are injected via AngularJS $injector
    // controller's name is registered in Application.ts and specified from ng-controller attribute in index.html
    constructor(
      private $scope: any,
      public $layerService: csComp.Services.LayerService,
      public $dashboardService: csComp.Services.DashboardService,
      private $mapService: csComp.Services.MapService,
      public $messageBusService: csComp.Services.MessageBusService
      ) {
        $scope.vm = this;
    }
  }
}


text:
. ./path.sh || exit 1;

langdir=$1

arpa_lm=db/cantab-TEDLIUM/cantab-TEDLIUM-pruned.lm3.gz
[ ! -f $arpa_lm ] && echo No such file $arpa_lm && exit 1;

outlangdir=${langdir}_test

rm -rf $outlangdir
cp -r $langdir $outlangdir

gunzip -c "$arpa_lm" | \
   grep -v '<s> <s>' | \
   grep -v '</s> <s>' | \
   grep -v '</s> </s>' | \
   arpa2fst - | fstprint | \
   utils/remove_oovs.pl /dev/null | \
   utils/eps2disambig.pl | utils/s2eps.pl | fstcompile --isymbols=$outlangdir/words.txt \
     --osymbols=$outlangdir/words.txt  --keep_isymbols=false --keep_osymbols=false | \
    fstrmepsilon | fstarcsort --sort_type=ilabel > $outlangdir/G.fst

# Compose the final decoding graph. The composition of L.fst and G.fst is determinized and
# minimized.
fsttablecompose $outlangdir/L.fst $outlangdir/G.fst | fstdeterminizestar --use-log=true | \
  fstminimizeencoded | fstarcsort --sort_type=ilabel > $outlangdir/LG.fst || exit 1;
fsttablecompose $outlangdir/T.fst $outlangdir/LG.fst > $outlangdir/TLG.fst || exit 1;
rm -rf $outlangdir/LG.fst

echo "Composing decoding graph TLG.fst succeeded"


text:
<?php

namespace Drupal\Core\Entity;

/**
 * Provides a trait for managing an object's dependencies.
 */
trait DependencyTrait {

  /**
   * The object's dependencies.
   *
   * @var array
   */
  protected $dependencies = [];

  /**
   * Adds a dependency.
   *
   * @param string $type
   *   Type of dependency being added: 'module', 'theme', 'config', 'content'.
   * @param string $name
   *   If $type is 'module' or 'theme', the name of the module or theme. If
   *   $type is 'config' or 'content', the result of
   *   EntityInterface::getConfigDependencyName().
   *
   * @see \Drupal\Core\Entity\EntityInterface::getConfigDependencyName()
   *
   * @return $this
   */
  protected function addDependency($type, $name) {
    if (empty($this->dependencies[$type])) {
      $this->dependencies[$type] = [$name];
      if (count($this->dependencies) > 1) {
        // Ensure a consistent order of type keys.
        ksort($this->dependencies);
      }
    }
    elseif (!in_array($name, $this->dependencies[$type])) {
      $this->dependencies[$type][] = $name;
      // Ensure a consistent order of dependency names.
      sort($this->dependencies[$type], SORT_FLAG_CASE);
    }
    return $this;
  }

  /**
   * Adds multiple dependencies.
   *
   * @param array $dependencies
   *   An array of dependencies keyed by the type of dependency. One example:
   *   @code
   *   array(
   *     'module' => array(
   *       'node',
   *       'field',
   *       'image',
   *     ),
   *   );
   *   @endcode
   *
   * @see \Drupal\Core\Entity\DependencyTrait::addDependency
   */
  protected function addDependencies(array $dependencies) {
    foreach ($dependencies as $dependency_type => $list) {
      foreach ($list as $name) {
        $this->addDependency($dependency_type, $name);
      }
    }
  }

}


text:
'use strict';

var webpack = require('webpack');
var _ = require('lodash');

module.exports = _.merge(
    require('./scalajs.webpack.config'),
    require('./webpack.config.shared'),
    {
        plugins: [
            // new webpack.optimize.UglifyJsPlugin({
            //     compress: {
            //         warnings: false,
            //         screw_ie8: true,
            //         conditionals: true,
            //         unused: true,
            //         comparisons: true,
            //         sequences: true,
            //         dead_code: true,
            //         evaluate: true,
            //         if_return: true,
            //         join_vars: true
            //     },
            //     output: {
            //         comments: false
            //     }
            // }),
            new webpack.HashedModuleIdsPlugin(),
            new webpack.DefinePlugin({
                'process.env.NODE_ENV': JSON.stringify('production')
            })
        ]
    });


text:
Clustering coefficients
=======================

.. automodule:: zen.algorithms.clustering


text:
import os
import os.path

from dbManager import DbManager

home = os.path.expanduser('~')

if '.musicplayer' not in os.listdir(home):
    os.mkdir(os.path.join(home, '.musicplayer'))

dbPath = os.path.join(home, '.musicplayer', 'userData.db')

createTableString = """
CREATE TABLE IF NOT EXISTS playhistory(
    id INTEGER PRIMARY KEY autoincrement,
    name TEXT,
    author TEXT,
    playTimes INTEGER default 1
)"""

# 粗略设计
# 所有平台的id号都归为一类,
# 但推荐时使用的网易云系统。
class UserDbManager(DbManager):

    def __init__(self, database=dbPath, *args):
        super().__init__(database, *args)
        self.initDb()

    def initDb(self):
        self.createTable(createTableString)

    def getSongByPlayTimes(self, maxes=5) -> list:
        """
            返回前5个播放次数最多的歌曲信息。
        """
        fetchedData = self.cursor.execute("""SELECT id FROM playhistory
            ORDER BY playTimes DESC
            LIMIT {}""".format(maxes))

        # TODO
        # 错误过滤
        return [i[0] for i in fetchedData]

    def addPlayTimesById(self, songId, name='Test', author='Test'):
        """
            给songId所标示的数据playTimes + 1
        """
        try:
            insertData = self.cursor.execute("""INSERT INTO playhistory
                (id, name, author) VALUES
                ({0}, '{1}', '{2}')
                """.format(songId, name, author))
        except:
            # 暂时不知道sqlite中如何进行
            # 无此数据时创建,有此数据时将某个值在其基础上增加或减少。
            # 目前的思路是在初始化时进行一次查询,然后将数据次数都保存在内存中进行增减,
            # 这样可以减少数据库操作。
            # 但数据量较小,不是主要考虑目标。

            updateData = self.cursor.execute("""UPDATE playhistory
                SET playTimes = playTimes + 1
                WHERE id = {}
                """.format(songId))

        self.db.commit()

if __name__ == '__main__':

    userDb = UserDbManager()

    # userDb.addPlayTimesById(7, '5', '6')
    userDb.cursor.execute("""SELECT * from playhistory""")
    print(userDb.cursor.fetchall())
    for i in userDb.cursor.fetchall():
        print(i)

    # print(userDb.getSongByPlayTimes())


text: "use strict";import"../../Stock/Indicators/OBV/OBVIndicator.js";