text:
//
//  SKNoteTextView.m
//  Skim
//
//  Created by Christiaan Hofman on 9/14/10.

#import "SKNoteTextView.h"
#import "NSUserDefaultsController_SKExtensions.h"

static char SKNoteTextViewDefaultsObservationContext;

#define SKNoteTextFontSizeKey @"SKNoteTextFontSize"

@implementation SKNoteTextView

@synthesize usesDefaultFontSize;

- (void)dealloc {
    if (usesDefaultFontSize)
        [[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forKey:SKNoteTextFontSizeKey];
    [super dealloc];
}

- (void)setUsesDefaultFontSize:(BOOL)flag {
    if (usesDefaultFontSize != flag) {
        usesDefaultFontSize = flag;
        if (usesDefaultFontSize) {
            CGFloat fontSize = [[NSUserDefaults standardUserDefaults] floatForKey:SKNoteTextFontSizeKey];
            [self setFont:[NSFont userFontOfSize:fontSize]];
            [[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forKey:SKNoteTextFontSizeKey context:&SKNoteTextViewDefaultsObservationContext];
        } else {
            [[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forKey:SKNoteTextFontSizeKey];
        }
    }
}

- (void)changeFont:(id)sender {
    if (usesDefaultFontSize) {
        NSFont *font = [sender convertFont:[self font]];
        [[NSUserDefaults standardUserDefaults] setFloat:[font pointSize] forKey:SKNoteTextFontSizeKey];
    } else {
        [super changeFont:sender];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == &SKNoteTextViewDefaultsObservationContext) {
        NSString *key = [keyPath substringFromIndex:7];
        if ([key isEqualToString:SKNoteTextFontSizeKey] && usesDefaultFontSize) {
            CGFloat fontSize = [[NSUserDefaults standardUserDefaults] floatForKey:SKNoteTextFontSizeKey];
            [self setFont:[NSFont userFontOfSize:fontSize]];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

@end


text:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { RegistrationService } from './registration.service';

@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {

  user: any;
  errors = {
    name: [],
    email: [],
    password: [],
    password_confirmation: []
  };
  success = false;

  constructor(private service: RegistrationService, private router: Router) {
    this.user = {
      name: '',
      email: '',
      password: '',
      password_confirmation: ''
    };
  }

  doSubmit () {
    this.service.registerAccount(this.user).subscribe(
      (res) => {
        this.success = true;
        this.router.navigate(['account/confirm'])
      },
      (res) => {
        this.success = false;
        this.errors = res;
      }
    );
  }

  ngOnInit() {
  }

}

redpajama_set_name: RedPajamaGithub


text:
import io
import logging
import os
import re
import sys
from datetime import datetime
from datetime import timedelta

from django import db
from django.apps import apps
from django.conf import settings

import kolibri
from kolibri.core.deviceadmin.exceptions import IncompatibleDatabase
from kolibri.core.tasks.decorators import register_task
from kolibri.core.utils.lock import db_lock
from kolibri.utils.conf import KOLIBRI_HOME
from kolibri.utils.time_utils import local_now

# Import db instead of db.connections because we want to use an instance of
# connections that might be updated from outside.

logger = logging.getLogger(__name__)

# Use encoded text for Python 3 (doesn't work in Python 2!)
KWARGS_IO_READ = {"mode": "r", "encoding": "utf-8"}
KWARGS_IO_WRITE = {"mode": "w", "encoding": "utf-8"}

# Constant job_id for vacuum task
SCH_VACUUM_JOB_ID = "1"

# Use binary file mode for Python 2 (doesn't work in Python 3!)
if sys.version_info < (3,):
    KWARGS_IO_READ = {"mode": "rb"}
    KWARGS_IO_WRITE = {"mode": "wb"}

def default_backup_folder():
    return os.path.join(KOLIBRI_HOME, "backups")

def get_dtm_from_backup_name(fname):
    """
    Returns the date time string from our automated backup filenames
    """
    p = re.compile(r"^db\-v[^_]+_(?P<dtm>[\d\-_]+).*\.dump$")
    m = p.search(fname)
    if m:
        label = m.groups("dtm")[0]
        date = label.split("_")[0]
        time = label.split("_")[1]
        return "{date} {time}".format(date=date, time=time.replace("-", ":"))
    raise ValueError(
        "Tried to get date component of unparsed filename: {}".format(fname)
    )

def is_full_version(fname):
    """
    Tells us if a backup file name is named as if it's from the exact same
    version.

    Supposes versions do not contain underscores '_'
    """
    # Can contain suffixes denoting alpha, beta, post, dev etc.
    full_version = kolibri.__version__
    return fname.startswith("db-v{}_".format(full_version))

def dbbackup(old_version, dest_folder=None):
    """
    Sqlite3 only

    Backup database to dest_folder. Uses SQLite's built in iterdump():
    https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.iterdump

    Notice that it's important to add at least version and date to the path
    of the backup, otherwise you risk that upgrade activities carried out on
    the same date overwrite each other. It's also quite important for the user
    to know which version of Kolibri that a certain database should match.

    :param: dest_folder: Default is ~/.kolibri/backups/db-[version]-[date].dump

    :returns: Path of new backup file
    """

    if "sqlite3" not in settings.DATABASES["default"]["ENGINE"]:
        raise IncompatibleDatabase()

    if not dest_folder:
        dest_folder = default_backup_folder()

    # This file name is a convention, used to figure out the latest backup
    # that was made (by the dbrestore command)
    fname = "db-v{version}_{dtm}.dump".format(
        version=old_version, dtm=datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    )

    if not os.path.exists(dest_folder):
        os.makedirs(dest_folder)

    backup_path = os.path.join(dest_folder, fname)

    # Setting encoding=utf-8: io.open() is Python 2 compatible
    # See: https://github.com/learningequality/kolibri/issues/2875
    with io.open(backup_path, **KWARGS_IO_WRITE) as f:
        # If the connection hasn't been opened yet, then open it
        if not db.connections["default"].connection:
            db.connections["default"].connect()
        for line in db.connections["default"].connection.iterdump():
            f.write(line)

    return backup_path

def dbrestore(from_file):
    """
    Sqlite3 only

    Restores the database given a special database dump file containing SQL
    statements.
    """

    if "sqlite3" not in settings.DATABASES["default"]["ENGINE"]:
        raise IncompatibleDatabase()

    dst_file = settings.DATABASES["default"]["NAME"]

    # Close connections
    db.connections.close_all()

    # Wipe current database file
    if not db.connections["default"].is_in_memory_db():
        with open(dst_file, "w") as f:
            f.truncate()
    else:
        logger.info("In memory database, not truncating: {}".format(dst_file))

    # Setting encoding=utf-8: io.open() is Python 2 compatible
    # See: https://github.com/learningequality/kolibri/issues/2875
    with open(from_file, **KWARGS_IO_READ) as f:
        db.connections["default"].connect()
        db.connections["default"].connection.executescript(f.read())

    # Finally, it's okay to import models and open database connections.
    # We need this to avoid generating records with identical 'Instance ID'
    # and conflicting counters, in case the database we're overwriting had
    # already been synced with other devices.:
    from morango.models import DatabaseIDModel

    DatabaseIDModel.objects.create()

def search_latest(search_root, fallback_version):
    logger.info("Searching latest backup in {}...".format(search_root))

    newest = ""  # Should be a path/filename.sqlite3
    newest_dtm = ""

    # All file names have to be according to the fall back version.
    prefix = "db-v{}".format(fallback_version)

    backups = os.listdir(search_root)
    backups = filter(lambda f: f.endswith(".dump"), backups)
    backups = filter(lambda f: f.startswith(prefix), backups)

    # Everything is sorted alphanumerically, and since dates in the
    # filenames behave accordingly, we can now traverse the list
    # without having to access meta data, just use the file name.
    backups = list(backups)
    backups.sort()

    for backup in backups:
        try:
            dtm = get_dtm_from_backup_name(backup)
        except ValueError:
            continue
        # Always pick the newest version
        if is_full_version(backup) or dtm > newest_dtm:
            newest_dtm = dtm
            newest = backup

    if newest:
        return os.path.join(search_root, newest)

@register_task(job_id=SCH_VACUUM_JOB_ID)
def perform_vacuum(database=db.DEFAULT_DB_ALIAS, full=False):
    connection = db.connections[database]
    if connection.vendor == "sqlite":
        try:
            with db_lock():
                db.close_old_connections()
                db.connections.close_all()
                cursor = connection.cursor()
                cursor.execute("vacuum;")
                connection.close()
        except Exception as e:
            logger.error(e)
            new_msg = (
                "Vacuum of database {db_name} couldn't be executed. Possible reasons:\n"
                "  * There is an open transaction in the db.\n"
                "  * There are one or more active SQL statements.\n"
                "The full error: {error_msg}"
            ).format(
                db_name=db.connections[database].settings_dict["NAME"], error_msg=e
            )
            logger.error(new_msg)
        else:
            logger.info("Sqlite database Vacuum finished.")
    elif connection.vendor == "postgresql":
        if full:
            morango_models = ("morango_recordmaxcounterbuffer", "morango_buffer")
        else:
            morango_models = [
                m
                for m in apps.get_models(include_auto_created=True)
                if "morango.models" in str(m)
            ]
        cursor = connection.cursor()
        for m in morango_models:
            if full:
                cursor.execute("vacuum full analyze {};".format(m))
            else:
                cursor.execute("vacuum analyze {};".format(m._meta.db_table))
        connection.close()

def schedule_vacuum():
    current_dt = local_now()
    vacuum_time = current_dt.replace(hour=3, minute=0, second=0, microsecond=0)
    if vacuum_time < current_dt:
        # If it is past 3AM, change the day to tomorrow.
        vacuum_time = vacuum_time + timedelta(days=1)
    # Repeat indefinitely
    perform_vacuum.enqueue_at(vacuum_time, repeat=None, interval=24 * 60 * 60)


text:
  <link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet">
  <title>Hello Vue</title>

Stories

                    #
                    Plot
                    Writer
                    Upvotes
                    Actions

Here's a list of all your stories.
                <button @click="createStory()" class="btn btn-primary">Add a new one?</button>

{{ $data }}

<template id="template-story-raw">

            {{story.id}}

            <input v-if="story.editing" v-model="story.plot" class="form-control">
            </input>

                {{story.plot}}

            <input v-if="story.editing" v-model="story.writer" class="form-control">
            </input>

                {{story.writer}}

            {{story.upvotes}}

                <button @click="upvoteStory(story)" class="btn btn-primary">Upvote</button>
                <button @click="editStory(story)" class="btn btn-default">Edit</button>
                <button @click="deleteStory(story)" class="btn btn-danger">Delete</button>

                <button v-if="story.id" class="btn btn-primary" @click="updateStory(story)">Update Story
                </button>

                <button v-else class="btn btn-success" @click="storeStory(story)">Save New Story</button>

                <button @click="story.editing=false" class="btn btn-default">Cancel</button>

</template>


text:
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script.  Only    //
// add custom code in the designated areas or it will be overwritten during  //
// the next update.                                                          //
//-----------------------------------NOTICE----------------------------------//

//--BEGIN FILE HEAD CUSTOM CODE--//

//--END CUSTOM CODE--//

#include "../../include/FixLink.h"
#include "../../include/ObjectRegistry.h"
#include "../../include/NIF_IO.h"
#include "../../include/obj/NiPSSimulatorGeneralStep.h"
using namespace Niflib;

//Definition of TYPE constant
const Type NiPSSimulatorGeneralStep::TYPE("NiPSSimulatorGeneralStep", &NiPSSimulatorStep::TYPE);

NiPSSimulatorGeneralStep::NiPSSimulatorGeneralStep() : numSizeKeys((byte) 0), sizeLoopBehavior((PSLoopBehavior) 0), unknown1(0.0f), unknown2(0.0f), unknown3(0.0f), numColorKeys((byte) 0), colorLoopBehavior((PSLoopBehavior) 0), numRotationKeys((byte) 0), rotationLoopBehavior((PSLoopBehavior) 0), growTime(0.0f), shrinkTime(0.0f), growGeneration((unsigned short) 0), shrinkGeneration((unsigned short) 0)
{
	//--BEGIN CONSTRUCTOR CUSTOM CODE--//

	//--END CUSTOM CODE--//
}

NiPSSimulatorGeneralStep::~NiPSSimulatorGeneralStep()
{
	//--BEGIN DESTRUCTOR CUSTOM CODE--//

	//--END CUSTOM CODE--//
}

const Type & NiPSSimulatorGeneralStep::GetType() const
{
	return TYPE;
}

NiObject * NiPSSimulatorGeneralStep::Create()
{
	return new NiPSSimulatorGeneralStep;
}

void NiPSSimulatorGeneralStep::Read(istream& in, list<unsigned int> & link_stack, const NifInfo & info)
{
	//--BEGIN PRE-READ CUSTOM CODE--//

	//--END CUSTOM CODE--//

	NiPSSimulatorStep::Read(in, link_stack, info);
	NifStream(numSizeKeys, in, info);
	sizeKeys.resize(numSizeKeys);
	for(unsigned int i1 = 0; i1 < sizeKeys.size(); i1++)
	{
		NifStream(sizeKeys[i1], in, info, 1);
	};
	if(info.version >= 0x1E000002)
	{
		NifStream(sizeLoopBehavior, in, info);
	};
	if(info.version <= 0x14060000)
	{
		NifStream(unknown1, in, info);
		NifStream(unknown2, in, info);
		NifStream(unknown3, in, info);
	};
	if(info.version >= 0x1E000002)
	{
		NifStream(numColorKeys, in, info);
		colorKeys.resize(numColorKeys);
		for(unsigned int i2 = 0; i2 < colorKeys.size(); i2++)
		{
			NifStream(colorKeys[i2], in, info, 1);
		};
		NifStream(colorLoopBehavior, in, info);
		NifStream(numRotationKeys, in, info);
		rotationKeys.resize(numRotationKeys);
		for(unsigned int i2 = 0; i2 < rotationKeys.size(); i2++)
		{
			NifStream(rotationKeys[i2], in, info, 1);
		};
		NifStream(rotationLoopBehavior, in, info);
		NifStream(growTime, in, info);
		NifStream(shrinkTime, in, info);
		NifStream(growGeneration, in, info);
		NifStream(shrinkGeneration, in, info);
	};

	//--BEGIN POST-READ CUSTOM CODE--//

	//--END CUSTOM CODE--//
}

void NiPSSimulatorGeneralStep::Write(ostream& out, const map<NiObjectRef, unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info) const
{
	//--BEGIN PRE-WRITE CUSTOM CODE--//

	//--END CUSTOM CODE--//

	NiPSSimulatorStep::Write(out, link_map, missing_link_stack, info);
	numRotationKeys = (byte) (rotationKeys.size());
	numColorKeys = (byte) (colorKeys.size());
	numSizeKeys = (byte) (sizeKeys.size());
	NifStream(numSizeKeys, out, info);
	for(unsigned int i1 = 0; i1 < sizeKeys.size(); i1++)
	{
		NifStream(sizeKeys[i1], out, info, 1);
	};
	if(info.version >= 0x1E000002)
	{
		NifStream(sizeLoopBehavior, out, info);
	};
	if(info.version <= 0x14060000)
	{
		NifStream(unknown1, out, info);
		NifStream(unknown2, out, info);
		NifStream(unknown3, out, info);
	};
	if(info.version >= 0x1E000002)
	{
		NifStream(numColorKeys, out, info);
		for(unsigned int i2 = 0; i2 < colorKeys.size(); i2++)
		{
			NifStream(colorKeys[i2], out, info, 1);
		};
		NifStream(colorLoopBehavior, out, info);
		NifStream(numRotationKeys, out, info);
		for(unsigned int i2 = 0; i2 < rotationKeys.size(); i2++)
		{
			NifStream(rotationKeys[i2], out, info, 1);
		};
		NifStream(rotationLoopBehavior, out, info);
		NifStream(growTime, out, info);
		NifStream(shrinkTime, out, info);
		NifStream(growGeneration, out, info);
		NifStream(shrinkGeneration, out, info);
	};

	//--BEGIN POST-WRITE CUSTOM CODE--//

	//--END CUSTOM CODE--//
}

std::string NiPSSimulatorGeneralStep::asString(bool verbose) const
{
	//--BEGIN PRE-STRING CUSTOM CODE--//

	//--END CUSTOM CODE--//

	stringstream out;
	unsigned int array_output_count = 0;
	out << NiPSSimulatorStep::asString(verbose);
	numRotationKeys = (byte) (rotationKeys.size());
	numColorKeys = (byte) (colorKeys.size());
	numSizeKeys = (byte) (sizeKeys.size());
	out << "  Num Size Keys:  " << numSizeKeys << endl;
	array_output_count = 0;
	for(unsigned int i1 = 0; i1 < sizeKeys.size(); i1++)
	{
		if(!verbose && (array_output_count > MAXARRAYDUMP))
		{
			out << "<Data Truncated. Use verbose mode to see complete listing.>" << endl;
			break;
		};
		if(!verbose && (array_output_count > MAXARRAYDUMP))
		{
			break;
		};
		out << "    Size Keys[" << i1 << "]:  " << sizeKeys[i1] << endl;
		array_output_count++;
	};
	out << "  Size Loop Behavior:  " << sizeLoopBehavior << endl;
	out << "  Unknown 1:  " << unknown1 << endl;
	out << "  Unknown 2:  " << unknown2 << endl;
	out << "  Unknown 3:  " << unknown3 << endl;
	out << "  Num Color Keys:  " << numColorKeys << endl;
	array_output_count = 0;
	for(unsigned int i1 = 0; i1 < colorKeys.size(); i1++)
	{
		if(!verbose && (array_output_count > MAXARRAYDUMP))
		{
			out << "<Data Truncated. Use verbose mode to see complete listing.>" << endl;
			break;
		};
		if(!verbose && (array_output_count > MAXARRAYDUMP))
		{
			break;
		};
		out << "    Color Keys[" << i1 << "]:  " << colorKeys[i1] << endl;
		array_output_count++;
	};
	out << "  Color Loop Behavior:  " << colorLoopBehavior << endl;
	out << "  Num Rotation Keys:  " << numRotationKeys << endl;
	array_output_count = 0;
	for(unsigned int i1 = 0; i1 < rotationKeys.size(); i1++)
	{
		if(!verbose && (array_output_count > MAXARRAYDUMP))
		{
			out << "<Data Truncated. Use verbose mode to see complete listing.>" << endl;
			break;
		};
		if(!verbose && (array_output_count > MAXARRAYDUMP))
		{
			break;
		};
		out << "    Rotation Keys[" << i1 << "]:  " << rotationKeys[i1] << endl;
		array_output_count++;
	};
	out << "  Rotation Loop Behavior:  " << rotationLoopBehavior << endl;
	out << "  Grow Time:  " << growTime << endl;
	out << "  Shrink Time:  " << shrinkTime << endl;
	out << "  Grow Generation:  " << growGeneration << endl;
	out << "  Shrink Generation:  " << shrinkGeneration << endl;
	return out.str();

	//--BEGIN POST-STRING CUSTOM CODE--//

	//--END CUSTOM CODE--//
}

void NiPSSimulatorGeneralStep::FixLinks(const map<unsigned int, NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info)
{
	//--BEGIN PRE-FIXLINKS CUSTOM CODE--//

	//--END CUSTOM CODE--//

	NiPSSimulatorStep::FixLinks(objects, link_stack, missing_link_stack, info);

	//--BEGIN POST-FIXLINKS CUSTOM CODE--//

	//--END CUSTOM CODE--//
}

std::list<NiObjectRef> NiPSSimulatorGeneralStep::GetRefs() const
{
	list<Ref<NiObject> > refs;
	refs = NiPSSimulatorStep::GetRefs();
	return refs;
}

std::list<NiObject *> NiPSSimulatorGeneralStep::GetPtrs() const
{
	list<NiObject *> ptrs;
	ptrs = NiPSSimulatorStep::GetPtrs();
	return ptrs;
}

/***Begin Example Naive Implementation****

vector<Key<float > > NiPSSimulatorGeneralStep::GetSizeKeys() const {
return sizeKeys;
}

void NiPSSimulatorGeneralStep::SetSizeKeys( const vector<Key<float > >& value ) {
sizeKeys = value;
}

PSLoopBehavior NiPSSimulatorGeneralStep::GetSizeLoopBehavior() const {
return sizeLoopBehavior;
}

void NiPSSimulatorGeneralStep::SetSizeLoopBehavior( const PSLoopBehavior & value ) {
sizeLoopBehavior = value;
}

vector<Key<ByteColor4 > > NiPSSimulatorGeneralStep::GetColorKeys() const {
return colorKeys;
}

void NiPSSimulatorGeneralStep::SetColorKeys( const vector<Key<ByteColor4 > >& value ) {
colorKeys = value;
}

PSLoopBehavior NiPSSimulatorGeneralStep::GetColorLoopBehavior() const {
return colorLoopBehavior;
}

void NiPSSimulatorGeneralStep::SetColorLoopBehavior( const PSLoopBehavior & value ) {
colorLoopBehavior = value;
}

vector<Key<Quaternion > > NiPSSimulatorGeneralStep::GetRotationKeys() const {
return rotationKeys;
}

void NiPSSimulatorGeneralStep::SetRotationKeys( const vector<Key<Quaternion > >& value ) {
rotationKeys = value;
}

PSLoopBehavior NiPSSimulatorGeneralStep::GetRotationLoopBehavior() const {
return rotationLoopBehavior;
}

void NiPSSimulatorGeneralStep::SetRotationLoopBehavior( const PSLoopBehavior & value ) {
rotationLoopBehavior = value;
}

float NiPSSimulatorGeneralStep::GetGrowTime() const {
return growTime;
}

void NiPSSimulatorGeneralStep::SetGrowTime( float value ) {
growTime = value;
}

float NiPSSimulatorGeneralStep::GetShrinkTime() const {
return shrinkTime;
}

void NiPSSimulatorGeneralStep::SetShrinkTime( float value ) {
shrinkTime = value;
}

unsigned short NiPSSimulatorGeneralStep::GetGrowGeneration() const {
return growGeneration;
}

void NiPSSimulatorGeneralStep::SetGrowGeneration( unsigned short value ) {
growGeneration = value;
}

unsigned short NiPSSimulatorGeneralStep::GetShrinkGeneration() const {
return shrinkGeneration;
}

void NiPSSimulatorGeneralStep::SetShrinkGeneration( unsigned short value ) {
shrinkGeneration = value;
}

****End Example Naive Implementation***/

//--BEGIN MISC CUSTOM CODE--//

//--END CUSTOM CODE--//


text:
<tru-label label="{{label}}" field="field">
    <input data-ng-model="field.value.$"
           data-ng-disabled="!field.context.isEditing || !field.type.canEdit"
           data-ng-trim="false"
           data-std-percent="field"
           data-z-validate
           type="text"
            />
</tru-label>


text:
$(document).ready(function(){
var gui = require('nw.gui');

$("#loginWindow").click(function(){
	var newWindow = gui.Window.open(
		'http://node.la/desktop/login',{
			position: "center",
			width: 500,
			height: 400
		}
	);

	newWindow.on('close', function(){
		window.location.replace("index.html");
		newWindow.close();
	});

});

});


text:
/**
 * Module dependencies.
 */

var NullCache = module.exports = function() {};

/**
 * Set cache item with given `key` to `value`.
 *
 * @param {String} key
 * @param {Object} value
 * @api private
 */

NullCache.prototype.set = function(key, value) {};

/**
 * Get cache item with given `key`.
 *
 * @param {String} key
 * @return {Object}
 * @api private
 */

NullCache.prototype.get = function(key) {};

/**
 * Check if cache has given `key`.
 *
 * @param {String} key
 * @return {Boolean}
 * @api private
 */

NullCache.prototype.has = function(key) {
  return false;
};

/**
 * Generate key for the source `str` with `options`.
 *
 * @param {String} str
 * @param {Object} options
 * @return {String}
 * @api private
 */

NullCache.prototype.key = function(str, options) {
  return '';
};


text:
<?php

// No direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.modellist');

/**
 * This models supports retrieving a category, the articles associated with the category,
 * sibling, child and parent categories.
 */
class TZ_PortfolioModelCategory extends JModelList
{
	/**
	 * Category items data
	 *
	 * @var array
	 */
	protected $_item = null;

	protected $_articles = null;

	protected $_siblings = null;

	protected $_children = null;

	protected $_parent = null;

	/**
	 * Model context string.
	 *
	 * @var		string
	 */
	protected $_context = 'com_tz_portfolio.category';

	/**
	 * The category that applies.
	 *
	 * @access	protected
	 * @var		object
	 */
	protected $_category = null;

	/**
	 * The list of other newfeed categories.
	 *
	 * @access	protected
	 * @var		array
	 */
	protected $_categories = null;

	/**
	 * Constructor.
	 *
	 * @param	array	An optional associative array of configuration settings.
	 * @see		JController
	 * @since	1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields'])) {
			$config['filter_fields'] = array(
				'id', 'a.id',
				'title', 'a.title',
				'alias', 'a.alias',
				'checked_out', 'a.checked_out',
				'checked_out_time', 'a.checked_out_time',
				'catid', 'a.catid', 'category_title',
				'state', 'a.state',
				'access', 'a.access', 'access_level',
				'created', 'a.created',
				'created_by', 'a.created_by',
				'modified', 'a.modified',
				'ordering', 'a.ordering',
				'featured', 'a.featured',
				'language', 'a.language',
				'hits', 'a.hits',
				'publish_up', 'a.publish_up',
				'publish_down', 'a.publish_down',
				'author', 'a.author'
			);
		}

		parent::__construct($config);
	}

    function getCatImages(){
        $query  = 'SELECT * FROM #__tz_portfolio_categories'
                  .' WHERE catid='.$this -> getState('category.id');
        $db     = JFactory::getDbo();
        $db -> setQuery($query);
        if(!$db -> query()){
            $this -> setError($db -> getErrorMsg());
            return false;
        }
        if($row = $db -> loadObject()){
            return $row;
        }
        return false;
    }

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * return	void
	 * @since	1.6
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		// Initiliase variables.
		$app	= JFactory::getApplication('site');
		$pk		= JRequest::getInt('id');

		$this->setState('category.id', $pk);

		// Load the parameters. Merge Global and Menu Item params into new object
		$params = $app->getParams();
//        $params = JComponentHelper::getParams('com_content');

		$menuParams = new JRegistry;

		if ($menu = $app->getMenu()->getActive()) {
			$menuParams->loadString($menu->params);
		}

		$mergedParams = clone $menuParams;
		$mergedParams->merge($params);

		$this->setState('params', $mergedParams);
		$user		= JFactory::getUser();
				// Create a new query object.
		$db		= $this->getDbo();
		$query	= $db->getQuery(true);
		$groups	= implode(',', $user->getAuthorisedViewLevels());

		if ((!$user->authorise('core.edit.state', 'com_tz_portfolio')) &&  (!$user->authorise('core.edit', 'com_tz_portfolio'))){
			// limit to published for people who can't edit or edit.state.
			$this->setState('filter.published', 1);
			// Filter by start and end dates.
			$nullDate = $db->Quote($db->getNullDate());
			$nowDate = $db->Quote(JFactory::getDate()->toSQL());

			$query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')');
			$query->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
		}
		else {
			$this->setState('filter.published', array(0, 1, 2));
		}

		// process show_noauth parameter

		if (!$params->get('show_noauth')) {
			$this->setState('filter.access', true);
		}
		else {
			$this->setState('filter.access', false);
		}

		// Optional filter text
		$this->setState('list.filter', JRequest::getString('filter-search'));

		// filter.order
		$itemid = JRequest::getInt('id', 0) . ':' . JRequest::getInt('Itemid', 0);
		$orderCol = $app->getUserStateFromRequest('com_tz_portfolio.category.list.' . $itemid . '.filter_order', 'filter_order', '', 'string');
		if (!in_array($orderCol, $this->filter_fields)) {
			$orderCol = 'a.ordering';
		}
		$this->setState('list.ordering', $orderCol);

		$listOrder = $app->getUserStateFromRequest('com_tz_portfolio.category.list.' . $itemid . '.filter_order_Dir',
			'filter_order_Dir', '', 'cmd');
		if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', ''))) {
			$listOrder = 'ASC';
		}
		$this->setState('list.direction', $listOrder);

		$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));

		// set limit for query. If list, use parameter. If blog, add blog parameters for limit.
		if ((JRequest::getCmd('layout') == 'blog') || $params->get('layout_type') == 'blog') {
			$limit = $params->get('num_leading_articles') + $params->get('num_intro_articles') + $params->get('num_links');
			$this->setState('list.links', $params->get('num_links'));
		}
		else {
			$limit = $app->getUserStateFromRequest('com_tz_portfolio.category.list.' . $itemid . '.limit', 'limit', $params->get('display_num'));
		}

		$this->setState('list.limit', $limit);

		// set the depth of the category query based on parameter
		$showSubcategories = $params->get('show_subcategory_content', '0');

		if ($showSubcategories) {
			$this->setState('filter.max_category_levels', $params->get('show_subcategory_content', '1'));
			$this->setState('filter.subcategories', true);
		}

        //Filter by first letter of article's title
        $this -> setState('filter.char',JRequest::getString('char',null));
        $this -> setState('filter.use_filter_first_letter',$params -> get('use_filter_first_letter',1));

		$this->setState('filter.language', $app->getLanguageFilter());

		$this->setState('layout', JRequest::getCmd('layout'));

	}

	/**
	 * Get the articles in the category
	 *
	 * @return	mixed	An array of articles or false if an error occurs.
	 * @since	1.5
	 */
	function getItems()
	{
		$params = $this->getState()->get('params');

		$limit = $this->getState('list.limit');

		if ($this->_articles === null && $category = $this->getCategory()) {
            $params -> merge($category -> params);
            $this -> setState('catParams',$params);
			$model = JModelLegacy::getInstance('Articles', 'TZ_PortfolioModel', array('ignore_request' => true));
			$model->setState('params',JFactory::getApplication()->getParams());
			$model->setState('filter.category_id', $category->id);
			$model->setState('filter.published', $this->getState('filter.published'));
			$model->setState('filter.access', $this->getState('filter.access'));
			$model->setState('filter.language', $this->getState('filter.language'));
			$model->setState('list.ordering', $this->_buildContentOrderBy());
			$model->setState('list.start', $this->getState('list.start'));
			$model->setState('list.limit', $limit);
			$model->setState('list.direction', $this->getState('list.direction'));
			$model->setState('list.filter', $this->getState('list.filter'));
			// filter.subcategories indicates whether to include articles from subcategories in the list or blog
			$model->setState('filter.subcategories', $this->getState('filter.subcategories'));
			$model->setState('filter.max_category_levels', $this->setState('filter.max_category_levels'));
			$model->setState('list.links', $this->getState('list.links'));

            //Filter by first letter of article's title
            $model -> setState('filter.tz_use_filter_letter',$this -> getState('filter.use_filter_first_letter'));
            $model -> setState('filter.char',$this -> getState('filter.char'));

			if ($limit >= 0) {
				$this->_articles = $model->getItems();

				if ($this->_articles === false) {
					$this->setError($model->getError());
				}
			}
			else {
				$this->_articles=array();
			}

			$this->_pagination = $model->getPagination();
		}

		return $this -> _articles;
	}

	/**
	 * Build the orderby for the query
	 *
	 * @return	string	$orderby portion of query
	 * @since	1.5
	 */
	protected function _buildContentOrderBy()
	{
		$app		= JFactory::getApplication('site');
		$db			= $this->getDbo();
		$params		= $this->state->params;
		$itemid		= JRequest::getInt('id', 0) . ':' . JRequest::getInt('Itemid', 0);
		$orderCol	= $app->getUserStateFromRequest('com_tz_portfolio.category.list.' . $itemid . '.filter_order', 'filter_order', '', 'string');
		$orderDirn	= $app->getUserStateFromRequest('com_tz_portfolio.category.list.' . $itemid . '.filter_order_Dir', 'filter_order_Dir', '', 'cmd');
		$orderby	= ' ';

		if (!in_array($orderCol, $this->filter_fields)) {
			$orderCol = null;
		}

		if (!in_array(strtoupper($orderDirn), array('ASC', 'DESC', ''))) {
			$orderDirn = 'ASC';
		}

		if ($orderCol && $orderDirn) {
			$orderby .= $db->escape($orderCol) . ' ' . $db->escape($orderDirn) . ', ';
		}

		$articleOrderby		= $params->get('orderby_sec', 'rdate');
		$articleOrderDate	= $params->get('order_date');
		$categoryOrderby	= $params->def('orderby_pri', '');
		$secondary			= TZ_PortfolioHelperQuery::orderbySecondary($articleOrderby, $articleOrderDate) . ', ';
		$primary			= TZ_PortfolioHelperQuery::orderbyPrimary($categoryOrderby);

		$orderby .= $db->escape($primary) . ' ' . $db->escape($secondary) . ' a.created ';

		return $orderby;
	}

	public function getPagination()
	{
		if (empty($this->_pagination)) {
			return null;
		}
		return $this->_pagination;
	}

	/**
	 * Method to get category data for the current category
	 *
	 * @param	int		An optional ID
	 *
	 * @return	object
	 * @since	1.5
	 */
	public function getCategory()
	{
		if (!is_object($this->_item)) {
			if( isset( $this->state->params ) ) {
				$params = $this->state->params;
				$options = array();
				$options['countItems'] = $params->get('show_cat_num_articles', 1) || !$params->get('show_empty_categories_cat', 0);
			}
			else {
				$options['countItems'] = 0;
			}

			$categories = JCategories::getInstance('Content', $options);
			$this->_item = $categories->get($this->getState('category.id', 'root'));

			// Compute selected asset permissions.
			if (is_object($this->_item)) {
				$user	= JFactory::getUser();
				$userId	= $user->get('id');
				$asset	= 'com_tz_portfolio.category.'.$this->_item->id;

				// Check general create permission.
				if ($user->authorise('core.create', $asset)) {
					$this->_item->getParams()->set('access-create', true);
				}

				// TODO: Why aren't we lazy loading the children and siblings?
				$this->_children = $this->_item->getChildren();
				$this->_parent = false;

				if ($this->_item->getParent()) {
					$this->_parent = $this->_item->getParent();
				}

				$this->_rightsibling = $this->_item->getSibling();
				$this->_leftsibling = $this->_item->getSibling(false);
			}
			else {
				$this->_children = false;
				$this->_parent = false;
			}
		}

		return $this->_item;
	}

	/**
	 * Get the parent categorie.
	 *
	 * @param	int		An optional category id. If not supplied, the model state 'category.id' will be used.
	 *
	 * @return	mixed	An array of categories or false if an error occurs.
	 * @since	1.6
	 */
	public function getParent()
	{
		if (!is_object($this->_item)) {
			$this->getCategory();
		}

		return $this->_parent;
	}

	/**
	 * Get the left sibling (adjacent) categories.
	 *
	 * @return	mixed	An array of categories or false if an error occurs.
	 * @since	1.6
	 */
	function &getLeftSibling()
	{
		if (!is_object($this->_item)) {
			$this->getCategory();
		}

		return $this->_leftsibling;
	}

	/**
	 * Get the right sibling (adjacent) categories.
	 *
	 * @return	mixed	An array of categories or false if an error occurs.
	 * @since	1.6
	 */
	function &getRightSibling()
	{
		if (!is_object($this->_item)) {
			$this->getCategory();
		}

		return $this->_rightsibling;
	}

	/**
	 * Get the child categories.
	 *
	 * @param	int		An optional category id. If not supplied, the model state 'category.id' will be used.
	 *
	 * @return	mixed	An array of categories or false if an error occurs.
	 * @since	1.6
	 */
	function &getChildren()
	{
		if (!is_object($this->_item)) {
			$this->getCategory();
		}

		// Order subcategories
		if (sizeof($this->_children)) {
			$params = $this->getState()->get('params');
			if ($params->get('orderby_pri') == 'alpha' || $params->get('orderby_pri') == 'ralpha') {
				jimport('joomla.utilities.arrayhelper');
				JArrayHelper::sortObjects($this->_children, 'title', ($params->get('orderby_pri') == 'alpha') ? 1 : -1);
			}
		}

		return $this->_children;
	}
}


text:
import logging
from collections import defaultdict
import time
from datetime import datetime

from django.core.management.base import BaseCommand
from pip._internal.exceptions import CommandError

from corehq.apps.app_manager.models import Application
from corehq.apps.es import CaseES, FormES, UserES, AppES
from corehq.apps.locations.models import SQLLocation
from corehq.apps.users.models import CommCareUser
from corehq.form_processor.models import CommCareCase, XFormInstance
from corehq.motech.dhis2.repeaters import Dhis2EntityRepeater
from corehq.motech.openmrs.repeaters import OpenmrsRepeater
from corehq.motech.repeaters.dbaccessors import (
    get_domains_that_have_repeat_records,
    get_repeat_records_by_payload_id,
    get_repeaters_by_domain,
)
from corehq.motech.repeaters.models import FormRepeater, ShortFormRepeater, CaseRepeater, CreateCaseRepeater, \
    UpdateCaseRepeater, RepeatRecord, LocationRepeater, UserRepeater, AppStructureRepeater
from corehq.util.argparse_types import date_type

from dimagi.utils.parsing import string_to_utc_datetime

from corehq.util.metrics import metrics_counter

logger = logging.getLogger(__name__)

CASES = 'cases'
FORMS = 'forms'
LOCATIONS = 'locations'
USERS = 'users'
APPS = 'apps'
COMMAND_CHOICES = [CASES, FORMS, LOCATIONS, USERS, APPS]
EXPECTED_REPEAT_RECOUNT_COUNT = 'expected_repeat_record_count'  # Total count of expected repeat records
ACTUAL_REPEAT_RECORD_COUNT = 'actual_repeat_record_count'  # Total count of found repeat records
MISSING_REPEAT_RECORD_COUNT = 'missing_repeat_record_count'  # Total count of missing repeat records
MISSING_CREATE_CASE_RECORD_COUNT = 'missing_create_case_record_count'  # Specifically for CreateCaseRepeater
MISSING_UPDATE_CASE_RECORD_COUNT = 'missing_update_case_record_count'  # Specifically for UpdateCaseRepeater
PCT_MISSING = 'percentage_missing'  # Percentage of repeat records missing relative to expected over the date range
TIME_TO_RUN = 'time_to_run'

def find_missing_form_repeat_records(startdate, enddate, domains, should_create=False):
    """
    :param startdate: search for missing form repeat records after this date
    :param enddate: search for missing form repeat records before this date
    :param domains: list of domains to check
    :param should_create: if  True, missing repeat records that are discovered will be registered with the repeater
    :return: a dictionary containing stats about the missing repeat records and metadata
    """
    missing_forms_per_domain = {}
    for index, domain in enumerate(domains):
        t0 = time.time()
        try:
            total_missing_count, total_count = find_missing_form_repeat_records_for_domain(
                domain, startdate, enddate, should_create
            )
            t1 = time.time()
            time_to_run = t1 - t0
            if total_missing_count > 0:
                pct_missing = f'{round((total_missing_count / total_count) * 100, 2)}%'
                rounded_time = f'{round(time_to_run, 0)} seconds'
                missing_forms_per_domain[domain] = {
                    FORMS: {
                        MISSING_REPEAT_RECORD_COUNT: total_missing_count,
                        PCT_MISSING: pct_missing,
                        TIME_TO_RUN: rounded_time,
                    }
                }

                logger.info(f'{domain} complete. Found {total_missing_count}" missing repeat records in '
                            f'{rounded_time}. This accounts for {pct_missing} of all repeat records in the '
                            f'specified date range.'
                            )

            if index + 1 % 10 == 0:
                logger.info(f"{(index + 1)}/{len(domains)} domains complete.")

        except Exception as e:
            logger.error(f"Encountered error with {domain}: {e}")

    return missing_forms_per_domain

def find_missing_form_repeat_records_for_domain(domain, startdate, enddate, should_create):
    total_missing_count = total_count = 0
    form_repeaters_in_domain = get_form_repeaters_in_domain(domain)
    form_ids = [f['_id'] for f in get_form_ids_in_domain_between_dates(domain, startdate, enddate)]
    forms = XFormInstance.objects.get_forms(form_ids, domain)
    for form in forms:
        missing_count, successful_count = find_missing_form_repeat_records_for_form(
            form, domain, form_repeaters_in_domain, enddate, should_create
        )
        total_missing_count += missing_count
        total_count += missing_count + successful_count

    return total_missing_count, total_count

def find_missing_form_repeat_records_for_form(form, domain, repeaters, enddate, should_create):
    if form.is_duplicate:
        return 0, 0

    missing_count = 0
    successful_count = 0
    repeat_records = get_repeat_records_by_payload_id(domain, form.get_id)
    triggered_repeater_ids = [record.repeater_id for record in repeat_records]
    for repeater in repeaters:
        if not repeater.allowed_to_forward(form):
            continue

        if repeater.started_at.date() >= enddate:
            # don't count a repeater that was created after the window we care about
            continue

        if repeater.get_id in triggered_repeater_ids:
            successful_count += 1
        else:
            missing_count += 1
            if should_create:
                logger.info(f"Registering form {form.get_id} for repeater {repeater.get_id}")
                repeater.register(form)
            else:
                logger.info(f"Missing form {form.get_id} for repeater {repeater.get_id}")

    return missing_count, successful_count

def find_missing_case_repeat_records(startdate, enddate, domains, should_create=False):
    """
    :param startdate: search for missing case repeat records after this date
    :param enddate: search for missing case repeat records before this date
    :param domains: list of domains to check
    :param should_create: if  True, missing repeat records that are discovered will be registered with the repeater
    :return: a dictionary containing stats about the missing repeat records and metadata
    """
    missing_case_counts_per_domain = {}
    for index, domain in enumerate(domains):
        t0 = time.time()
        try:
            missing_case_counts = find_missing_case_repeat_records_for_domain(
                domain, startdate, enddate, should_create
            )
            t1 = time.time()
            time_to_run = t1 - t0

            number_of_records_missing = missing_case_counts[MISSING_REPEAT_RECORD_COUNT]
            number_of_records_expected = missing_case_counts[EXPECTED_REPEAT_RECOUNT_COUNT]
            if number_of_records_missing > 0:
                missing_case_counts_per_domain[domain] = missing_case_counts
                pct_missing = f'{round((number_of_records_missing / number_of_records_expected) * 100, 2)}%'
                rounded_time = f'{round(time_to_run, 0)} seconds'
                logger.info(f'{domain} complete. Found {number_of_records_missing}" missing case repeat records '
                            f'in {rounded_time}. This accounts for {pct_missing} of all case repeat records in '
                            f'the specified date range'
                            )
            else:
                logger.info(f"Found 0 missing case repeat records in {domain}.")
            if index + 1 % 10 == 0:
                logger.info(f"{(index + 1)}/{len(domains)} domains complete.")

        except Exception as e:
            logger.error(f"Encountered error with {domain}: {e}")

    return missing_case_counts_per_domain

def find_missing_case_repeat_records_for_domain(domain, startdate, enddate, should_create=False):

    # get all cases in domain
    case_repeaters_in_domain = get_case_repeaters_in_domain(domain)
    case_ids = [c['_id'] for c in get_case_ids_in_domain_since_date(domain, startdate)]
    cases = CommCareCase.objects.get_cases(case_ids, domain)

    missing_case_counts = defaultdict(int)
    for case in cases:
        missing_case_counts_for_case = find_missing_case_repeat_records_for_case(
            case, domain, case_repeaters_in_domain, startdate, enddate, should_create
        )

        missing_case_counts[MISSING_REPEAT_RECORD_COUNT] += \
            missing_case_counts_for_case[MISSING_REPEAT_RECORD_COUNT]
        missing_case_counts[MISSING_CREATE_CASE_RECORD_COUNT] += \
            missing_case_counts_for_case[MISSING_CREATE_CASE_RECORD_COUNT]
        missing_case_counts[MISSING_UPDATE_CASE_RECORD_COUNT] += \
            missing_case_counts_for_case[MISSING_UPDATE_CASE_RECORD_COUNT]
        missing_case_counts[ACTUAL_REPEAT_RECORD_COUNT] += \
            missing_case_counts_for_case[ACTUAL_REPEAT_RECORD_COUNT]
        missing_case_counts[EXPECTED_REPEAT_RECOUNT_COUNT] += \
            missing_case_counts_for_case[EXPECTED_REPEAT_RECOUNT_COUNT]

    return missing_case_counts

def find_missing_case_repeat_records_for_case(case, domain, repeaters, startdate, enddate, should_create=False):
    successful_count = missing_all_count = missing_create_count = missing_update_count = 0

    repeat_records = get_repeat_records_by_payload_id(domain, case.get_id)
    # grab repeat records that were registered during the date range
    records_during_daterange = [record for record in repeat_records
                                if startdate <= record.registered_on.date() <= enddate]
    fired_repeater_ids_and_counts_during_daterange = defaultdict(int)
    for record in records_during_daterange:
        fired_repeater_ids_and_counts_during_daterange[record.repeater_id] += 1

    # grab repeat records that were registered after the enddate
    records_after_daterange = [record for record in repeat_records if record.registered_on.date() >= enddate]
    fired_repeater_ids_and_counts_after_enddate = defaultdict(int)
    for record in records_after_daterange:
        fired_repeater_ids_and_counts_after_enddate[record.repeater_id] += 1

    for repeater in repeaters:
        repeaters_to_ignore = (Dhis2EntityRepeater, OpenmrsRepeater)
        if isinstance(repeater, repeaters_to_ignore):
            # not dealing with these right now because their expected payload appears to be a form?
            continue

        if repeater.started_at.date() >= enddate:
            # don't count a repeater that was created after the outage
            continue

        if fired_repeater_ids_and_counts_after_enddate.get(repeater.get_id, 0) > 0:
            # no need to trigger a repeater if it has fired since the outage ended
            continue

        expected_record_count = expected_number_of_repeat_records_fired_for_case(
            case, repeater, startdate, enddate
        )
        actual_record_count = fired_repeater_ids_and_counts_during_daterange.get(repeater.get_id, 0)

        missing_count = expected_record_count - actual_record_count
        if missing_count < 0:
            logger.error(f"ERROR: negative count\nExpected: {expected_record_count} "
                         f"Actual: {actual_record_count} Case: {case.get_id}"
                         )
            missing_count = 0

        if missing_count > 0:
            if should_create:
                if isinstance(repeater, CreateCaseRepeater) and len(case.transactions) > 1:
                    create_case_repeater_register(repeater, domain, case)
                    logger.info(f"Registering case {case.get_id} for create case repeater {repeater.get_id}")
                else:
                    logger.info(f"Registering case {case.get_id} for repeater {repeater.get_id}")
                    repeater.register(case)
            else:
                logger.info(f"Missing case {case.get_id} for repeater {repeater.get_id}")

        missing_all_count += missing_count
        if isinstance(repeater, CreateCaseRepeater):
            missing_create_count += missing_count
        elif isinstance(repeater, UpdateCaseRepeater):
            missing_update_count += missing_count

        successful_count += actual_record_count

    return {
        MISSING_REPEAT_RECORD_COUNT: missing_all_count,
        MISSING_CREATE_CASE_RECORD_COUNT: missing_create_count,
        MISSING_UPDATE_CASE_RECORD_COUNT: missing_update_count,
        ACTUAL_REPEAT_RECORD_COUNT: successful_count,
        EXPECTED_REPEAT_RECOUNT_COUNT: missing_all_count + successful_count,
    }

def expected_number_of_repeat_records_fired_for_case(case, repeater, startdate, enddate):
    """
    Based on a case's transactions, and the number of repeat records
    """
    filtered_transactions = []
    if isinstance(repeater, CreateCaseRepeater):
        # to avoid modifying CreateCaseRepeater's allowed_to_forward method
        if create_case_repeater_allowed_to_forward(repeater, case):
            filtered_transactions = case.transactions[0:1]
    elif isinstance(repeater, UpdateCaseRepeater):
        if repeater.allowed_to_forward(case):
            filtered_transactions = case.transactions[1:]
    else:
        if repeater.allowed_to_forward(case):
            filtered_transactions = case.transactions

    transactions_in_daterange = [transaction for transaction in filtered_transactions
                                 if startdate <= get_transaction_date(transaction) <= enddate]

    return len(transactions_in_daterange)

def find_missing_location_repeat_records(startdate, enddate, domains, should_create):
    stats_per_domain = {}
    for index, domain in enumerate(domains):
        t0 = time.time()
        total_missing_count = 0
        location_repeaters_in_domain = get_location_repeaters_in_domain(domain)

        locations = get_locations_modified_since_startdate(domain, startdate)
        for location in locations:
            missing_count = find_missing_repeat_records_in_domain(
                domain, location_repeaters_in_domain, location, enddate, should_create
            )
            total_missing_count += missing_count

        t1 = time.time()
        time_to_run = t1 - t0
        if total_missing_count > 0:
            rounded_time = f'{round(time_to_run, 0)} seconds'
            stats_per_domain[domain] = {
                FORMS: {
                    MISSING_REPEAT_RECORD_COUNT: total_missing_count,
                    TIME_TO_RUN: rounded_time,
                }
            }

            logger.info(f'{domain} complete. Found {total_missing_count}" missing repeat records in '
                        f'{rounded_time}. Due to limitations with locations, we only looked for missing repeat '
                        f'records for newly created locations, not recently modified.'
                        )

        if index + 1 % 5 == 0:
            logger.info(f"{(index+1)}/{len(domains)} domains complete.")

    return stats_per_domain

def find_missing_user_repeat_records(startdate, enddate, domains, should_create):
    stats_per_domain = {}
    for index, domain in enumerate(domains):
        t0 = time.time()
        total_missing_count = 0
        location_repeaters_in_domain = get_location_repeaters_in_domain(domain)

        user_dicts = get_users_created_since_startdate(domain, startdate)
        users = [CommCareUser.wrap(user_dict) for user_dict in user_dicts]
        for user in users:
            missing_count = find_missing_repeat_records_in_domain(
                domain, location_repeaters_in_domain, user, enddate, should_create
            )
            total_missing_count += missing_count

        t1 = time.time()
        time_to_run = t1 - t0
        if total_missing_count > 0:
            rounded_time = f'{round(time_to_run, 0)} seconds'
            stats_per_domain[domain] = {
                FORMS: {
                    MISSING_REPEAT_RECORD_COUNT: total_missing_count,
                    TIME_TO_RUN: rounded_time,
                }
            }

            logger.info(f'{domain} complete. Found {total_missing_count}" missing repeat records in '
                        f'{rounded_time}. Due to limitations with users, we only looked for missing repeat '
                        f'records for newly created users, not recently modified.'
                        )

        if index + 1 % 5 == 0:
            logger.info(f"{(index+1)}/{len(domains)} domains complete.")

    return stats_per_domain

def find_missing_app_repeat_records(startdate, enddate, domains, should_create):
    stats_per_domain = {}
    for index, domain in enumerate(domains):
        t0 = time.time()
        total_missing_count = 0
        app_repeaters_in_domain = get_app_repeaters_in_domain(domain)

        app_dicts = get_apps_updated_between_dates(domain, startdate, enddate)
        apps = [Application.wrap(app_dict) for app_dict in app_dicts]
        for app in apps:
            missing_count = find_missing_repeat_records_in_domain(
                domain, app_repeaters_in_domain, app, enddate, should_create
            )
            total_missing_count += missing_count

        t1 = time.time()
        time_to_run = t1 - t0
        if total_missing_count > 0:
            rounded_time = f'{round(time_to_run, 0)} seconds'
            stats_per_domain[domain] = {
                FORMS: {
                    MISSING_REPEAT_RECORD_COUNT: total_missing_count,
                    TIME_TO_RUN: rounded_time,
                }
            }

            logger.info(f'{domain} complete. Found {total_missing_count}" missing repeat records in '
                        f'{rounded_time}. We only looked for missing repeat records for apps last modified during '
                        f'the specified date range.'
                        )

        if index + 1 % 5 == 0:
            logger.info(f"{(index+1)}/{len(domains)} domains complete.")

    return stats_per_domain

def find_missing_repeat_records_in_domain(domain, repeaters, payload, enddate, should_create):
    """
    Generic method to obtain repeat records (used for Locations, Users)
    NOTE: Assumes the payload passed in was modified since the startdate
    """
    missing_count = 0
    repeat_records = get_repeat_records_by_payload_id(domain, payload.get_id)
    records_since_last_modified_date = [record for record in repeat_records
                                        if record.registered_on.date() >= payload.last_modified.date()]
    fired_repeater_ids_and_counts = defaultdict(int)
    for record in records_since_last_modified_date:
        fired_repeater_ids_and_counts[record.repeater_id] += 1

    for repeater in repeaters:
        if repeater.started_at.date() >= enddate:
            # don't count a repeater that was created after the outage
            continue

        if fired_repeater_ids_and_counts.get(repeater.get_id, 0) > 0:
            # no need to trigger a repeater if it has fired since startdate
            continue

        # if we've made it this far, the repeater should have fired
        missing_count += 1
        if should_create:
            logger.info(f"Registering {type(payload)} {payload.get_id} for repeater {repeater.get_id}")
            repeater.register(payload)
        else:
            logger.info(f"Missing {type(payload)} {payload.get_id} for repeater {repeater.get_id}")

    return missing_count

def get_form_ids_in_domain_between_dates(domain, startdate, enddate):
    return FormES(for_export=True).domain(domain)\
        .date_range('server_modified_on', gte=startdate, lte=enddate).source(['_id']).run().hits

def get_case_ids_in_domain_since_date(domain, startdate):
    """
    Can only search for cases modified since a date
    """
    return CaseES(for_export=True).domain(domain).server_modified_range(gte=startdate)\
        .source(['_id']).run().hits

def get_locations_modified_since_startdate(domain, startdate):
    return SQLLocation.objects.filter(domain=domain, last_modified__gte=startdate)

def get_users_created_since_startdate(domain, startdate):
    """
    Had to use created_on because last_modified did not seem to work
    """
    return UserES(for_export=True).mobile_users().domain(domain)\
        .date_range('created_on', gte=startdate).run().hits

def get_apps_updated_between_dates(domain, startdate, enddate):
    return AppES(for_export=True).domain(domain)\
        .date_range('last_modified', gte=startdate, lte=enddate).run().hits

def get_transaction_date(transaction):
    return string_to_utc_datetime(transaction.server_date).date()

def get_form_repeaters_in_domain(domain):
    form_repeater_classes = (FormRepeater, ShortFormRepeater, OpenmrsRepeater, Dhis2EntityRepeater)
    return get_repeaters_for_type_in_domain(domain, form_repeater_classes)

def get_case_repeaters_in_domain(domain):
    return get_repeaters_for_type_in_domain(domain, (CaseRepeater, ))

def get_location_repeaters_in_domain(domain):
    return get_repeaters_for_type_in_domain(domain, (LocationRepeater, ))

def get_app_repeaters_in_domain(domain):
    return get_repeaters_for_type_in_domain(domain, (AppStructureRepeater, ))

def get_user_repeaters_in_domain(domain):
    return get_repeaters_for_type_in_domain(domain, (UserRepeater, ))

def get_repeaters_for_type_in_domain(domain, repeater_types):
    """
    :param domain: domain to search in
    :param repeater_types: a tuple of repeater class types
    """
    repeaters = get_repeaters_by_domain(domain)
    if repeater_types:
        return [repeater for repeater in repeaters if isinstance(repeater, repeater_types)]
    return repeaters

def create_case_repeater_allowed_to_forward(repeater, case):
    """
    Use this instead of CreateCaseRepeater.allowed_to_forward to get around len(case.transactions) > 1 check
    """
    return repeater._allowed_case_type(case) and repeater._allowed_user(case)

def create_case_repeater_register(repeater, domain, payload):
    """
    Only useful in a very specific edge case for CreateCaseRepeater
    If a CreateCaseRepeater has a missing repeat record, but the case now contains update transactions
    This can be used to properly trigger the missing repeat record.
    """
    if not isinstance(repeater, CreateCaseRepeater):
        logger.error(f"Error - cannot call create_case_repeater_register on repeater type f{type(repeater)}")
        return

    if not create_case_repeater_allowed_to_forward(repeater, payload):
        return

    now = datetime.utcnow()
    repeat_record = RepeatRecord(
        repeater_id=repeater.get_id,
        repeater_type=repeater.doc_type,
        domain=domain,
        registered_on=now,
        next_check=now,
        payload_id=payload.get_id
    )
    metrics_counter('commcare.repeaters.new_record', tags={
        'domain': domain,
        'doc_type': repeater.doc_type
    })
    repeat_record.save()
    repeat_record.attempt_forward_now()
    return repeat_record

class Command(BaseCommand):
    help = """
    Find case/form submissions/updates that do not have a corresponding repeat record and create a repeat record
    """

    def add_arguments(self, parser):
        parser.add_argument('command', choices=COMMAND_CHOICES)
        parser.add_argument('-s', '--startdate', type=date_type, help='Format YYYY-MM-DD')
        parser.add_argument('-e', '--enddate', type=date_type, help='Format YYYY-MM-DD')
        parser.add_argument('-d', '--domain', default=None, type=str, help='Run on a specific domain')
        parser.add_argument('-w', '--startswith', default=None, type=str, help='Domains that start with substring')
        parser.add_argument('-c', '--create', action='store_true', help='Create missing repeat records')
        parser.add_argument('--verbose', action="store_true")

    def handle(self, command, startdate, enddate, domain, startswith, create, **options):
        if not startdate:
            raise CommandError("Must specify a startdate in the format YYYY-MM-DD")

        if not enddate:
            enddate = datetime.utcnow().date()

        if domain and startswith:
            raise CommandError("Cannot specify both domain and startswith")
        elif domain:
            domains_to_inspect = [domain]
        elif startswith:
            all_domains = get_domains_that_have_repeat_records()
            domains_to_inspect = [d for d in all_domains if d.startswith(startswith)]
        else:
            domains_to_inspect = get_domains_that_have_repeat_records()

        logger.setLevel(logging.INFO if options["verbose"] else logging.WARNING)
        if command == CASES:
            stats = find_missing_case_repeat_records(startdate, enddate, domains_to_inspect, create)
        elif command == FORMS:
            stats = find_missing_form_repeat_records(startdate, enddate, domains_to_inspect, create)
        elif command == LOCATIONS:
            stats = find_missing_location_repeat_records(startdate, enddate, domains_to_inspect, create)
        elif command == USERS:
            stats = find_missing_user_repeat_records(startdate, enddate, domains_to_inspect, create)
        elif command == APPS:
            stats = find_missing_app_repeat_records(startdate, enddate, domains_to_inspect, create)
        else:
            raise CommandError(f"The '{command}' command is not support at this time.")
        if stats:
            logger.info(f"Here's what is missing:\n{stats}")
        else:
            logger.info("Did not find any missing repeat records.")


text:
package org.olat.presentation.framework.dispatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.olat.lms.admin.AdminModule;
import org.olat.lms.commons.mediaresource.ServletUtil;

/**
 * This dispatcher acts as proxy to receive the message.
 *
 * Initial Date: 13.06.2006 <br>
 *
 * @author patrickb
 * @author christian guretzki
 */
public class AdminModuleDispatcher implements Dispatcher {

    private final static String PARAMETER_CMD = "cmd";
    private final static String PARAMETER_MSG = "msg";
    private final static String PARAMETER_MAX_MESSAGE = "maxsessions";
    private final static String PARAMETER_NBR_SESSIONS = "nbrsessions";
    private final static String PARAMETER_SESSIONTIMEOUT = "sec";

    private final static String CMD_SET_MAINTENANCE_MESSAGE = "setmaintenancemessage";
    private final static String CMD_SET_LOGIN_BLOCKED = "setloginblocked";
    private final static String CMD_SET_LOGIN_NOT_BLOCKED = "setloginnotblocked";
    private final static String CMD_SET_MAX_SESSIONS = "setmaxsessions";
    private final static String CMD_INVALIDATE_ALL_SESSIONS = "invalidateallsessions";
    private final static String CMD_INVALIDATE_OLDEST_SESSIONS = "invalidateoldestsessions";
    private final static String CMD_SET_SESSIONTIMEOUT = "sessiontimeout";

    /**
	 */

    protected AdminModuleDispatcher() {
    }

    @Override
    public void execute(final HttpServletRequest request, final HttpServletResponse response, final String uriPrefix) {
        final String cmd = request.getParameter(PARAMETER_CMD);
        if (cmd.equalsIgnoreCase(CMD_SET_MAINTENANCE_MESSAGE)) {
            handleSetMaintenanceMessage(request, response);
        } else {
            if (AdminModule.checkSessionAdminToken(request, response)) {
                handleSessionsCommand(request, response, cmd);
            } else {
                DispatcherAction.sendForbidden(request.getPathInfo(), response);
            }
        }
    }

    /**
     * Handle session-administration commands (setLoginBlocked, setLoginNotBlocked, setMaxSession, invalidateAllSessions, ïnvalidateOldestSessions).
     */
    private void handleSessionsCommand(final HttpServletRequest request, final HttpServletResponse response, final String cmd) {
        if (cmd.equalsIgnoreCase(CMD_SET_LOGIN_BLOCKED)) {
            AdminModule.setLoginBlocked(true);
            ServletUtil.serveStringResource(request, response, "Ok, login blocked");
        } else if (cmd.equalsIgnoreCase(CMD_SET_LOGIN_NOT_BLOCKED)) {
            AdminModule.setLoginBlocked(false);
            ServletUtil.serveStringResource(request, response, "Ok, login no more blocked");
        } else if (cmd.equalsIgnoreCase(CMD_SET_MAX_SESSIONS)) {
            handleSetMaxSessions(request, response);
        } else if (cmd.equalsIgnoreCase(CMD_INVALIDATE_ALL_SESSIONS)) {
            AdminModule.invalidateAllSessions();
            ServletUtil.serveStringResource(request, response, "Ok, Invalidated all sessions");
        } else if (cmd.equalsIgnoreCase(CMD_INVALIDATE_OLDEST_SESSIONS)) {
            handleInvidateOldestSessions(request, response);
        } else if (cmd.equalsIgnoreCase(CMD_SET_SESSIONTIMEOUT)) {
            handleSetSessiontimeout(request, response);
        } else {
            ServletUtil.serveStringResource(request, response, "NOT OK, unknown command=" + cmd);
        }
    }

    /**
     * Handle setMaxSessions command, extract parameter maxsessions form request and call method on AdminModule.
     *
     * @param request
     * @param response
     */
    private void handleSetMaxSessions(final HttpServletRequest request, final HttpServletResponse response) {
        final String maxSessionsString = request.getParameter(PARAMETER_MAX_MESSAGE);
        if (maxSessionsString == null || maxSessionsString.equals("")) {
            ServletUtil.serveStringResource(request, response, "NOT_OK, missing parameter " + PARAMETER_MAX_MESSAGE);
        } else {
            try {
                final int maxSessions = Integer.parseInt(maxSessionsString);
                AdminModule.setMaxSessions(maxSessions);
                ServletUtil.serveStringResource(request, response, "Ok, max-session=" + maxSessions);
            } catch (final NumberFormatException nbrException) {
                ServletUtil.serveStringResource(request, response, "NOT_OK, parameter " + PARAMETER_MAX_MESSAGE + " must be a number");
            }
        }
    }

    private void handleSetSessiontimeout(final HttpServletRequest request, final HttpServletResponse response) {
        final String paramStr = request.getParameter(PARAMETER_SESSIONTIMEOUT);
        if (paramStr == null || paramStr.equals("")) {
            ServletUtil.serveStringResource(request, response, "NOT_OK, missing parameter " + PARAMETER_SESSIONTIMEOUT);
        } else {
            try {
                final int sessionTimeout = Integer.parseInt(paramStr);
                AdminModule.setSessionTimeout(sessionTimeout);
                ServletUtil.serveStringResource(request, response, "Ok, sessiontimeout=" + sessionTimeout);
            } catch (final NumberFormatException nbrException) {
                ServletUtil.serveStringResource(request, response, "NOT_OK, parameter " + PARAMETER_SESSIONTIMEOUT + " must be a number");
            }
        }
    }

    /**
     * Handle invalidateOldestSessions command, extract parameter nbrsessions form request and call method on AdminModule.
     *
     * @param request
     * @param response
     */
    private void handleInvidateOldestSessions(final HttpServletRequest request, final HttpServletResponse response) {
        final String nbrSessionsString = request.getParameter(PARAMETER_NBR_SESSIONS);
        if (nbrSessionsString == null || nbrSessionsString.equals("")) {
            ServletUtil.serveStringResource(request, response, "NOT_OK, missing parameter " + PARAMETER_NBR_SESSIONS);
        } else {
            try {
                final int nbrSessions = Integer.parseInt(nbrSessionsString);
                AdminModule.invalidateOldestSessions(nbrSessions);
                ServletUtil.serveStringResource(request, response, "Ok, Invalidated oldest sessions, nbrSessions=" + nbrSessions);
            } catch (final NumberFormatException nbrException) {
                ServletUtil.serveStringResource(request, response, "NOT_OK, parameter " + PARAMETER_NBR_SESSIONS + " must be a number");
            }
        }
    }

    /**
     * Handle setMaintenanceMessage command, extract parameter msg form request and call method on AdminModule.
     *
     * @param request
     * @param response
     */
    private void handleSetMaintenanceMessage(final HttpServletRequest request, final HttpServletResponse response) {
        if (AdminModule.checkMaintenanceMessageToken(request, response)) {
            final String message = request.getParameter(PARAMETER_MSG);
            AdminModule.setMaintenanceMessage(message);
            ServletUtil.serveStringResource(request, response, "Ok, new maintenanceMessage is::" + message);
        } else {
            DispatcherAction.sendForbidden(request.getPathInfo(), response);
        }
    }

}


text:
HRESULT ReadStream(ISequentialInStream *stream, void *data, UInt32 size, UInt32 *processedSize);
HRESULT WriteStream(ISequentialOutStream *stream, const void *data, UInt32 size, UInt32 *processedSize);

#endif


text:
package com.adaptris.core;

import static org.apache.commons.lang.StringUtils.defaultIfEmpty;
import static org.apache.commons.lang.StringUtils.isBlank;

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

import com.adaptris.annotation.AdvancedConfig;
import com.adaptris.annotation.InputFieldDefault;
import com.adaptris.core.util.ExceptionHelper;
import com.adaptris.util.GuidGenerator;

/**
 *

 * Implementation of default / common behaviour for Services.
 * Includes basic implementation of MessageEventGenerator which
 * returns the fully qualified name of the class.
 *

 */
public abstract class ServiceImp implements Service {
  // protected transient Logger log = LoggerFactory.getLogger(this.getClass().getName());

  protected transient Logger log = LoggerFactory.getLogger(this.getClass().getName());

  private transient ComponentState serviceState;
  private transient boolean prepared = false;

  @AdvancedConfig
  private String lookupName;
  private String uniqueId;
  private transient boolean isBranching; // defaults to false
  @AdvancedConfig
  @InputFieldDefault(value = "false")
  private Boolean continueOnFail;
  @AdvancedConfig
  @InputFieldDefault(value = "false")
  private Boolean isTrackingEndpoint;
  @AdvancedConfig
  @InputFieldDefault(value = "false")
  @Deprecated
  private Boolean isConfirmation;

  /**
   *

   * Creates a new instance. Default unique ID is autogenerated using {@link GuidGenerator#getUUID()}.
   *

   */
  public ServiceImp() {
    setUniqueId(new GuidGenerator().getUUID());
    changeState(ClosedState.getInstance());
  }

  public final void init() throws CoreException {
    if (!prepared)
      prepare();
    initService();
  }

  protected abstract void initService() throws CoreException;

  public final void close() {
    closeService();
    prepared = false;
  }

  protected abstract void closeService();

  @Override
  public void stop() {
    // over-ride if required
  }

  @Override
  public void start() throws CoreException {
    // over-ride if required
  }

  @Override
  public String createName() {
    return this.getClass().getName();
  }

  @Override
  public String createQualifier() {
    return defaultIfEmpty(getUniqueId(), "");
  }

  @Override
  public String toString() {
    StringBuffer result = new StringBuffer();
    result.append("[");
    result.append(this.getClass().getName());
    if (!isBlank(getUniqueId())) {
      result.append("] unique ID [");
      result.append(getUniqueId());
    }
    result.append("] continue on fail [");
    result.append(getContinueOnFail());
    result.append("]");

    return result.toString();
  }

  @Override
  public String getUniqueId() {
    return uniqueId;
  }

  @Override
  public void setUniqueId(String s) {
    if (s == null) {
      throw new IllegalArgumentException("null param");
    }
    uniqueId = s;
  }

  @Override
  public boolean isBranching() {
    return isBranching;
  }

  @Override
  public boolean continueOnFailure() {
    if (getContinueOnFail() != null) {
      return getContinueOnFail().booleanValue();
    }
    return false;
  }

  /**
   * @return whether or not this service is configured to continue on failure.
   * @see #continueOnFailure()
   */
  public Boolean getContinueOnFail() {
    return continueOnFail;
  }

  /**
   * whether or not this service is configured to continue on failure.
   *
   * @param b true/false, default if not specified is false.
   */
  public void setContinueOnFail(Boolean b) {
    continueOnFail = b;
  }

  public Boolean getIsTrackingEndpoint() {
    return isTrackingEndpoint;
  }

  /**
   * whether or not this service is is a tracking endpoint.
   *
   * @param b true/false, default if not specified is false.
   */
  public void setIsTrackingEndpoint(Boolean b) {
    isTrackingEndpoint = b;
  }

  /**
   *
   * @deprecated since 3.6.2 No-one has ever produced a confirmation service. This will be removed.
   */
  @Deprecated
  public Boolean getIsConfirmation() {
    return isConfirmation;
  }

  /**
   * whether or not this service is configured a confirmation.
   *
   * @param b true/false, default if not specified is false.
   * @deprecated since 3.6.2 No-one has ever produced a confirmation service. This will be removed.
   *
   */
  @Deprecated
  public void setIsConfirmation(Boolean b) {
    isConfirmation = b;
  }

  @Override
  public boolean isTrackingEndpoint() {
    if (isTrackingEndpoint != null) {
      return isTrackingEndpoint.booleanValue();
    }
    return false;
  }

  @Override
  public boolean isConfirmation() {
    if (isConfirmation != null) {
      return isConfirmation.booleanValue();
    }
    return false;
  }

  /**
   * @deprecated use {@link ExceptionHelper#wrapServiceException(Throwable)} or
   *             {@link ExceptionHelper#rethrowServiceException(Throwable)} instead.
   */
  @Deprecated
  protected static void rethrowServiceException(Throwable e) throws ServiceException {
    throw ExceptionHelper.wrapServiceException(e);
  }

  /**
   *

   * Updates the state for the component ComponentState.
   *

   */
  public void changeState(ComponentState newState) {
    serviceState = newState;
  }

  /**
   *

   * Returns the last record ComponentState.
   *

   * @return the current ComponentState
   */
  public ComponentState retrieveComponentState() {
    return serviceState;
  }

  /**
   *

   * Request this component is init'd.
   *

   * @throws CoreException wrapping any underlying Exceptions
   */
  public void requestInit() throws CoreException {
    serviceState.requestInit(this);
  }

  /**
   *

   * Request this component is started.
   *

   * @throws CoreException wrapping any underlying Exceptions
   */
  public void requestStart() throws CoreException {
    serviceState.requestStart(this);
  }

  /**
   *

   * Request this component is stopped.
   *

   */
  public void requestStop() {
    serviceState.requestStop(this);
  }

  /**
   *

   * Request this component is closed.
   *

   */
  public void requestClose() {
    serviceState.requestClose(this);
  }

  public String getLookupName() {
    return lookupName;
  }

  /**
   * Specify the lookup name (if required) when adding this service as a shared component.
   *

   * If you don't know what to fill in here, leave it blank, and the adapter will use the unique-id instead.
   *

   *
   * @param lookupName the lookup name.
   */
  public void setLookupName(String lookupName) {
    this.lookupName = lookupName;
  }

}


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

namespace Amazon.S3.Model
{
    /// <summary>Grant
    /// </summary>
    public class S3Grant
    {

        private S3Grantee grantee;
        private S3Permission permission;

        /// <summary>
        /// The grantee details.
        /// </summary>
        public S3Grantee Grantee
        {
            get { return this.grantee; }
            set { this.grantee = value; }
        }

        // Check to see if Grantee property is set
        internal bool IsSetGrantee()
        {
            return this.grantee != null;
        }

        /// <summary>
        /// Specifies the permission given to the grantee.
        ///
        /// </summary>
        public S3Permission Permission
        {
            get { return this.permission; }
            set { this.permission = value; }
        }

        // Check to see if Permission property is set
        internal bool IsSetPermission()
        {
            return this.permission != null;
        }
    }
}


text:
namespace Dike.Web.Configuration
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;

    /// <summary>
    /// Represents the Web module configuration.
    /// </summary>
    /// <seealso cref="Dike.Core.Configuration.DictionaryBasedConfig" />
    /// <seealso cref="Dike.Web.Configuration.IWebConfiguration" />
    internal class WebConfiguration
        : Core.Configuration.DictionaryBasedConfig, IWebConfiguration
    {
        #region Fields

        private static readonly Lazy<WebConfiguration> _instance = new Lazy<WebConfiguration>(() => new WebConfiguration());

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Prevents a default instance of the <see cref="WebConfiguration"/> class from being created.
        /// </summary>
        private WebConfiguration()
        {
            IsValidationEnabledForControllers = true;
            IsAuditingEnabled = true;
            SetNoCacheForAjaxResponses = true;
        }

        #endregion Constructors

        #region Properties

        /// <summary>
        /// Gets the singleton instance.
        /// </summary>
        /// <value>The singleton instance.</value>
        public static WebConfiguration Instance
            => _instance.Value;

        /// <summary>
        /// Gets the anti forgery security configuration.
        /// </summary>
        /// <value>The anti forgery security configuration.</value>
        public Runtime.Security.AntiForgery.IAntiForgeryConfiguration AntiForgery
            => GetOrCreateItem(nameof(AntiForgery), () => new Runtime.Security.AntiForgery.AntiForgeryConfiguration());

        /// <summary>
        /// Gets the API proxy scripting configuration.
        /// </summary>
        /// <value>The API proxy scripting configuration.</value>
        public Api.ProxyScripting.IApiProxyScriptingConfiguration ApiProxyScripting
            => GetOrCreateItem(nameof(ApiProxyScripting), () => new Api.ProxyScripting.ApiProxyScriptingConfiguration());

        /// <summary>
        /// Gets the controller assembly settings.
        /// </summary>
        /// <value>The controller assembly settings.</value>
        public ControllerAssemblySettingCollection ControllerAssemblySettings
            => GetOrCreateItem(nameof(ControllerAssemblySettings), () => new ControllerAssemblySettingCollection());

        /// <summary>
        /// Gets the default client cache.
        /// </summary>
        /// <value>The default client cache.</value>
        public Mvc.Results.Caching.IClientCache DefaultClientCache
            => GetOrCreateItem(nameof(DefaultClientCache), () => new Mvc.Results.Caching.NoClientCache(false));

        /// <summary>
        /// Gets the default unit of work attribute.
        /// </summary>
        /// <value>The default unit of work attribute.</value>
        public Core.Domain.UnitOfWork.UnitOfWorkAttribute DefaultUnitOfWorkAttribute
            => GetOrCreateItem(nameof(DefaultUnitOfWorkAttribute), () => new Core.Domain.UnitOfWork.UnitOfWorkAttribute());

        /// <summary>
        /// Gets the default wrap result attribute.
        /// </summary>
        /// <value>The default wrap result attribute.</value>
        public Core.Web.Models.WrapResultAttribute DefaultWrapResultAttribute
            => GetOrCreateItem(nameof(DefaultWrapResultAttribute), () => new Core.Web.Models.WrapResultAttribute());

        /// <summary>
        /// Gets the embedded resources configuration.
        /// </summary>
        /// <value>The embedded resources.</value>
        public IWebEmbeddedResourcesConfiguration EmbeddedResources
            => GetOrCreateItem(nameof(EmbeddedResources), () => new WebEmbeddedResourcesConfiguration());

        /// <summary>
        /// Gets the form body binding ignored types.
        /// </summary>
        /// <value>The form body binding ignored types.</value>
        public List<Type> FormBodyBindingIgnoredTypes
            => GetOrCreateItem(nameof(FormBodyBindingIgnoredTypes), () => new List<Type>());

        /// <summary>
        /// Gets or sets a value indicating whether auditing for the MVC controllers is enabled.
        /// </summary>
        /// <value><c>true</c> if auditing for the MVC controllers is auditing enabled; otherwise, <c>false</c>.</value>
        public bool IsAuditingEnabled
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether the validation for MVC controllers is enabled.
        /// </summary>
        /// <value><c>true</c> if the validation for MVC controllers is enabled; otherwise, <c>false</c>.</value>
        public bool IsValidationEnabledForControllers
        {
            get;
            set;
        }

        /// <summary>
        /// Gets the multi tenancy configuration.
        /// </summary>
        /// <value>The multi tenancy configuration.</value>
        public MultiTenancy.IWebMultiTenancyConfiguration MultiTenancy
            => GetOrCreateItem(nameof(MultiTenancy), () => new MultiTenancy.WebMultiTenancyConfiguration());

        /// <summary>
        /// Gets or sets a value indicating whether to send all exceptions directly to the clients.
        /// </summary>
        /// <value><c>true</c> to send all exceptions directly to the clients; otherwise, <c>false</c>.</value>
        /// <remarks>The default value is <c>false</c>.</remarks>
        public bool SendAllExceptionsToClients
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether to set no cache for AJAX responses.
        /// </summary>
        /// <value><c>true</c> to set no cache for AJAX responses; otherwise, <c>false</c>.</value>
        public bool SetNoCacheForAjaxResponses
        {
            get;
            set;
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Creates the controllers for application services.
        /// </summary>
        /// <param name="assembly">The assembly.</param>
        /// <param name="moduleName">Name of the module.</param>
        /// <param name="useConventionalHttpVerbs">Set to <c>true</c> use conventional HTTP verbs.</param>
        /// <returns>A reference to the <see cref="ControllerAssemblySettingBuilder" />.</returns>
        public ControllerAssemblySettingBuilder CreateControllersForAppServices(
            Assembly assembly,
            string moduleName = ControllerAssemblySetting.DefaultServiceModuleName,
            bool useConventionalHttpVerbs = true)
        {
            ControllerAssemblySetting setting = new ControllerAssemblySetting(moduleName, assembly, useConventionalHttpVerbs);
            ControllerAssemblySettings.Add(setting);
            return new ControllerAssemblySettingBuilder(setting);
        }

        #endregion Methods
    }
}


text:
package crypto

type SecretI interface {
	Algorithm() string
	Equal(any interface{}) bool
	String() string
}


text:
@(
  queryString: helpers.QueryString,
  list: PagedRecords[(
    Item,
    Option[ItemName],
    Option[ItemDescription],
    Option[Site],
    Option[ItemPriceHistory],
    Map[ItemNumericMetadataType, ItemNumericMetadata],
    Option[Map[SiteItemNumericMetadataType, SiteItemNumericMetadata]],
    Map[ItemTextMetadataType, ItemTextMetadata]
  )],
  itemPriceStrategy: ItemPriceStrategy
)(
  implicit flash: play.api.mvc.Flash,
  request: MessagesRequest[AnyContent],
  login: LoginSession,
  shoppingCartItemRepo: ShoppingCartItemRepo,
  db: play.api.db.Database
)

@main(Messages("createNewRecommendationByAdminTitle"), Some(login), contentCssClass = "adminContents") {
} {

@Messages("createNewRecommendationByAdminTitle")

@Messages("createNewRecommendationByAdminDescription")

  @flash.get("message").map { message =>

      @message

  }

  @flash.get("errorMessage").map { message =>

      @message

  }

  @helper.form(action=routes.RecommendationByAdmin.selectItem(queryString.table.toList)) {
    <input id="searchBox" type="search" name="q" placeholder="@Messages("search.placeholder")" value="@queryString.toString">
    <input id="searchSubmit" type="submit" value="@Messages("search.button.title")">
  }

      @defining(Some(login)) { implicit loginSession =>

          @orderMark(
            "id",
            routes.RecommendationByAdmin.selectItem(queryString.toList, _: Int, _: Int, _: String),
            "item_name.item_id", list
          )

          @orderMark(
            Messages("itemName"),
            routes.RecommendationByAdmin.selectItem(queryString.toList, _: Int, _: Int, _: String),
            "item_name.item_name", list
          )

          @orderMark(
            Messages("site"),
            routes.RecommendationByAdmin.selectItem(queryString.toList, _: Int, _: Int, _: String),
            "site.site_name", list
          )

          @orderMark(
            Messages("unitPrice"),
            routes.RecommendationByAdmin.selectItem(queryString.toList, _: Int, _: Int, _: String),
            "item_price_history." + itemPriceStrategy.columnName, list
          )

      }

    @list.records.map { e =>

      @e._1.id

        <form class="addRecommendationByAdminForm" method="POST"
              action="@helper.CSRF(routes.RecommendationByAdmin.addRecommendation(e._4.get.id.get, e._1.id.get.id))">
          <input type="submit" value="Add">
        </form>
        @e._2.map(_.name).getOrElse("-")

      @e._4.map(_.name).getOrElse("-")
      @e._5.map {p => @amount(itemPriceStrategy.price(ItemPriceStrategyInput(p)))}.getOrElse("-")

    }

  @defining(Some(login)) { implicit loginSession =>
    @pagingPanel(
      list,
      routes.RecommendationByAdmin.selectItem(queryString.toList, _: Int, _: Int, _: String),
      10, 25, 50
    )
  }

      @Messages("backTo", Messages("recommendationByAdminTitle"))

    @admin.backToAdminTop()

}


text:
package com.beanframework;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.system.ApplicationPidFileWriter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan({"com.beanframework"})
public class WebadminApplication {

	public static void main(String[] args) {
		SpringApplication springApplication = new SpringApplication(WebadminApplication.class);
		springApplication.addListeners(new ApplicationPidFileWriter());
		springApplication.run(args);
	}
}


text:
<?php

namespace Snide\Bundle\TravinizerBundle\Helper;

/**
 * Class PoserHelper
 *
 * @author Pascal DENIS <pascal.denis@businessdecision.com>
 */
class PoserHelper
{
    /**
     * Poser host
     *
     * @var string
     */
    protected $host = 'https://poser.pugx.org';

    /**
     * Get stable version badge Url
     *
     * @param string $slug Packagist slug
     * @return string
     */
    public function getStableVersionBadgeUrl($slug)
    {
        return sprintf('%s/%s/v/stable.png', $this->host, $slug);
    }

    /**
     * Get unstable version badge Url
     *
     * @param string $slug Packagist slug
     * @return string
     */
    public function getUnstableVersionBadgeUrl($slug)
    {
        return sprintf('%s/%s/v/unstable.png', $this->host, $slug);
    }

    /**
     * Get total downloads badge Url
     *
     * @param string $slug Packagist slug
     * @return string
     */
    public function getTotalDownloadBadgeUrl($slug)
    {
        return sprintf('%s/%s/downloads.png', $this->host, $slug);

    }

    /**
     * Get monthly downloads badge Url
     *
     * @param string $slug Packagist slug
     * @return string
     */
    public function getMonthlyDownloadBadgeUrl($slug)
    {
        return sprintf('%s/%s/d/monthly.png', $this->host, $slug);
    }

    /**
     * Get daily downloads badge Url
     *
     * @param string $slug Packagist slug
     * @return string
     */
    public function getDailyDownloadBadgeUrl($slug)
    {
        return sprintf('%s/%s/d/daily.png', $this->host, $slug);
    }

    /**
     * Get license badge Url
     *
     * @param string $slug Packagist slug
     * @return string
     */
    public function getLicenseBadgeUrl($slug)
    {
        return sprintf('%s/%s/license.png', $this->host, $slug);
    }
}


text:
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;

namespace Shopping.DemoApp.iOS.Thanhvien.QLMG
{
    [Register ("TVQLMGViewController")]
    partial class TVQLMGViewController
    {
        [Outlet]
        [GeneratedCode ("iOS Designer", "1.0")]
        UIKit.UITableView TVQLMGTableView { get; set; }

        void ReleaseDesignerOutlets ()
        {
            if (TVQLMGTableView != null) {
                TVQLMGTableView.Dispose ();
                TVQLMGTableView = null;
            }

        }
    }
}


text:
@interface FORMPopoverFieldCell : FORMBaseFieldCell

@property (nonatomic, strong) FORMFieldValueLabel *fieldValueLabel;
@property (nonatomic, strong) UIPopoverController *popoverController;
@property (nonatomic, strong) UIImageView *iconImageView;

- (instancetype)initWithFrame:(CGRect)frame contentViewController:(UIViewController *)controller
               andContentSize:(CGSize)contentSize;

- (void)updateContentViewController:(UIViewController *)contentViewController withField:(FORMField *)field;

@end


text:
<query id="updateMemberEmailAddress" action="update">
    <tables>
        <table name="member" />
    </tables>
    <columns>
        <column name="email_address" var="email_address" notnull="notnull" />
        <column name="email_id" var="email_id" notnull="notnull" />
        <column name="email_host" var="email_host" notnull="notnull" />
    </columns>
    <conditions>
        <condition operation="equal" column="member_srl" var="member_srl" notnull="notnull" filter="number" />
    </conditions>
</query>


text:
import hashlib
import json
import random

from six.moves.urllib import parse
from swiftclient import utils as swiftclient_utils
import yaml

from heat_integrationtests.common import test
from heat_integrationtests.functional import functional_base

class AwsStackTest(functional_base.FunctionalTestsBase):
    test_template = '''
HeatTemplateFormatVersion: '2012-12-12'
Resources:
  the_nested:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: the.yaml
      Parameters:
        KeyName: foo
Outputs:
  output_foo:
    Value: {"Fn::GetAtt": [the_nested, Outputs.Foo]}
'''

    nested_template = '''
HeatTemplateFormatVersion: '2012-12-12'
Parameters:
  KeyName:
    Type: String
Outputs:
  Foo:
    Value: bar
'''

    update_template = '''
HeatTemplateFormatVersion: '2012-12-12'
Parameters:
  KeyName:
    Type: String
Outputs:
  Foo:
    Value: foo
'''

    nested_with_res_template = '''
HeatTemplateFormatVersion: '2012-12-12'
Parameters:
  KeyName:
    Type: String
Resources:
  NestedResource:
    Type: OS::Heat::RandomString
Outputs:
  Foo:
    Value: {"Fn::GetAtt": [NestedResource, value]}
'''

    def setUp(self):
        super(AwsStackTest, self).setUp()
        self.object_container_name = test.rand_name()
        self.project_id = self.identity_client.project_id
        self.swift_key = hashlib.sha224(
            str(random.getrandbits(256))).hexdigest()[:32]
        key_header = 'x-container-meta-temp-url-key'
        self.object_client.put_container(self.object_container_name,
                                         {key_header: self.swift_key})
        self.addCleanup(self.object_client.delete_container,
                        self.object_container_name)

    def publish_template(self, contents, cleanup=True):
        oc = self.object_client

        # post the object
        oc.put_object(self.object_container_name, 'template.yaml', contents)
        if cleanup:
            self.addCleanup(oc.delete_object,
                            self.object_container_name,
                            'template.yaml')
        path = '/v1/AUTH_%s/%s/%s' % (self.project_id,
                                      self.object_container_name,
                                      'template.yaml')
        timeout = self.conf.build_timeout * 10
        tempurl = swiftclient_utils.generate_temp_url(path, timeout,
                                                      self.swift_key, 'GET')
        sw_url = parse.urlparse(oc.url)
        return '%s://%s%s' % (sw_url.scheme, sw_url.netloc, tempurl)

    def test_nested_stack_create(self):
        url = self.publish_template(self.nested_template)
        self.template = self.test_template.replace('the.yaml', url)
        stack_identifier = self.stack_create(template=self.template)
        stack = self.client.stacks.get(stack_identifier)
        self.assert_resource_is_a_stack(stack_identifier, 'the_nested')
        self.assertEqual('bar', self._stack_output(stack, 'output_foo'))

    def test_nested_stack_create_with_timeout(self):
        url = self.publish_template(self.nested_template)
        self.template = self.test_template.replace('the.yaml', url)
        timeout_template = yaml.safe_load(self.template)
        props = timeout_template['Resources']['the_nested']['Properties']
        props['TimeoutInMinutes'] = '50'

        stack_identifier = self.stack_create(
            template=timeout_template)
        stack = self.client.stacks.get(stack_identifier)
        self.assert_resource_is_a_stack(stack_identifier, 'the_nested')
        self.assertEqual('bar', self._stack_output(stack, 'output_foo'))

    def test_nested_stack_adopt_ok(self):
        url = self.publish_template(self.nested_with_res_template)
        self.template = self.test_template.replace('the.yaml', url)
        adopt_data = {
            "resources": {
                "the_nested": {
                    "resource_id": "test-res-id",
                    "resources": {
                        "NestedResource": {
                            "type": "OS::Heat::RandomString",
                            "resource_id": "test-nested-res-id",
                            "resource_data": {"value": "goopie"}
                        }
                    }
                }
            },
            "environment": {"parameters": {}},
            "template": yaml.safe_load(self.template)
        }

        stack_identifier = self.stack_adopt(adopt_data=json.dumps(adopt_data))

        self.assert_resource_is_a_stack(stack_identifier, 'the_nested')
        stack = self.client.stacks.get(stack_identifier)
        self.assertEqual('goopie', self._stack_output(stack, 'output_foo'))

    def test_nested_stack_adopt_fail(self):
        url = self.publish_template(self.nested_with_res_template)
        self.template = self.test_template.replace('the.yaml', url)
        adopt_data = {
            "resources": {
                "the_nested": {
                    "resource_id": "test-res-id",
                    "resources": {
                    }
                }
            },
            "environment": {"parameters": {}},
            "template": yaml.safe_load(self.template)
        }

        stack_identifier = self.stack_adopt(adopt_data=json.dumps(adopt_data),
                                            wait_for_status='ADOPT_FAILED')
        rsrc = self.client.resources.get(stack_identifier, 'the_nested')
        self.assertEqual('ADOPT_FAILED', rsrc.resource_status)

    def test_nested_stack_update(self):
        url = self.publish_template(self.nested_template)
        self.template = self.test_template.replace('the.yaml', url)
        stack_identifier = self.stack_create(template=self.template)
        original_nested_id = self.assert_resource_is_a_stack(
            stack_identifier, 'the_nested')
        stack = self.client.stacks.get(stack_identifier)
        self.assertEqual('bar', self._stack_output(stack, 'output_foo'))

        new_template = yaml.safe_load(self.template)
        props = new_template['Resources']['the_nested']['Properties']
        props['TemplateURL'] = self.publish_template(self.update_template,
                                                     cleanup=False)

        self.update_stack(stack_identifier, new_template)

        # Expect the physical resource name staying the same after update,
        # so that the nested was actually updated instead of replaced.
        new_nested_id = self.assert_resource_is_a_stack(
            stack_identifier, 'the_nested')
        self.assertEqual(original_nested_id, new_nested_id)
        updt_stack = self.client.stacks.get(stack_identifier)
        self.assertEqual('foo', self._stack_output(updt_stack, 'output_foo'))

    def test_nested_stack_suspend_resume(self):
        url = self.publish_template(self.nested_template)
        self.template = self.test_template.replace('the.yaml', url)
        stack_identifier = self.stack_create(template=self.template)
        self.stack_suspend(stack_identifier)
        self.stack_resume(stack_identifier)


text:
import json
from datetime import datetime
json_data_file_path = './data/events.json'

events = None

with open(json_data_file_path, 'r') as f:
    events = f.read()

if events:
    events_json = json.loads(events, encoding="utf-8")
    event_list = events_json['events']

    classified_events = dict()

    for e in event_list:
        st = datetime.strptime(e['start'], "%Y-%m-%d %H:%M:%S")
        key = st.strftime('%Y-%m')
        if key not in classified_events:
            classified_events[key] = dict()
            classified_events[key]['events'] = list()
        classified_events[key]['events'].append(e)

    for k, v in classified_events.items():
        write_file_path = './data/events-' + k + '.json'
        with open(write_file_path, 'w') as f:
            f.write(json.dumps(v, ensure_ascii=False, indent=4))