text:
using System;
using System.Collections.Generic;
using System.Linq;
using EcsRx.Collections.Database;
using EcsRx.Components.Lookups;
using EcsRx.Extensions;
using EcsRx.Groups;
using EcsRx.Groups.Observable;
using EcsRx.Lookups;

namespace EcsRx.Collections
{
    public class ObservableGroupManager : IObservableGroupManager
    {
        public ObservableGroupLookup _observableGroups { get; }

        public IReadOnlyList<IObservableGroup> ObservableGroups => _observableGroups;

        public IEntityDatabase EntityDatabase { get; }
        public IObservableGroupFactory ObservableGroupFactory { get; }
        public IComponentTypeLookup ComponentTypeLookup { get; }

        public ObservableGroupManager(IObservableGroupFactory observableGroupFactory, IEntityDatabase entityDatabase, IComponentTypeLookup componentTypeLookup)
        {
            ObservableGroupFactory = observableGroupFactory;
            EntityDatabase = entityDatabase;
            ComponentTypeLookup = componentTypeLookup;

            _observableGroups = new ObservableGroupLookup();
        }

        public IEnumerable<IObservableGroup> GetApplicableGroups(int[] componentTypeIds)
        {
            for (var i = _observableGroups.Count - 1; i >= 0; i--)
            {
                if (_observableGroups[i].Token.LookupGroup.Matches(componentTypeIds))
                { yield return _observableGroups[i]; }
            }
        }

        public IObservableGroup GetObservableGroup(IGroup group, params int[] collectionIds)
        {
            var lookupGroup = ComponentTypeLookup.GetLookupGroupFor(group);

            var observableGroupToken = new ObservableGroupToken(lookupGroup, collectionIds);
            if (_observableGroups.Contains(observableGroupToken))
            { return _observableGroups[observableGroupToken]; }

            var entityMatches = EntityDatabase.GetEntitiesFor(lookupGroup, collectionIds);
            var configuration = new ObservableGroupConfiguration
            {
                ObservableGroupToken = observableGroupToken,
                InitialEntities = entityMatches
            };

            if (collectionIds != null && collectionIds.Length > 0)
            { configuration.NotifyingCollections = EntityDatabase.Collections.Where(x => collectionIds.Contains(x.Id)); }
            else
            { configuration.NotifyingCollections = new []{EntityDatabase}; }

            var observableGroup = ObservableGroupFactory.Create(configuration);
            _observableGroups.Add(observableGroup);

            return _observableGroups[observableGroupToken];
        }

        public void Dispose()
        {
            foreach (var observableGroup in _observableGroups)
            { (observableGroup as IDisposable)?.Dispose(); }

            EntityDatabase.Dispose();
        }
    }
}


text:
package org.vaadin.maps.ui.handler;

import org.vaadin.maps.ui.LayerLayout;

/**
 * @author Kamil Morong
 */
public interface RequiresLayerLayout {

    void setLayout(LayerLayout layout);

}

redpajama_set_name: RedPajamaGithub


text:
import logging
from datetime import timedelta, datetime
from typing import Optional, List

from django.conf import settings
from django.contrib.auth.models import User
from django.template.loader import get_template
from django.utils import timezone
from django.utils.translation import gettext as _
from elasticsearch_dsl import Q
from html2text import html2text

from mainapp.functions.mail import send_mail
from mainapp.functions.search import MainappSearch, parse_hit
from mainapp.functions.search_notification_tools import search_result_for_notification
from mainapp.models import UserAlert

logger = logging.getLogger(__name__)

class NotifyUsers:
    fallback_timeframe = timedelta(days=14)

    def __init__(
        self, override_since: Optional[datetime] = None, simulate: bool = False
    ):
        self.override_since = override_since
        self.simulate = simulate

    def perform_search(self, alert: UserAlert) -> List[dict]:
        if self.override_since is not None:
            since = self.override_since
        elif alert.last_match is not None:
            since = alert.last_match
        else:
            since = timezone.now() - self.fallback_timeframe

        search = MainappSearch(
            alert.get_search_params(),
            extra_filter=[Q("range", modified={"gte": since.isoformat()})],
        )
        executed = search.execute()
        return [parse_hit(hit) for hit in executed.hits]

    def notify_user(self, user: User) -> bool:
        context = {
            "base_url": settings.ABSOLUTE_URI_BASE,
            "site_name": settings.TEMPLATE_META["logo_name"],
            "alerts": [],
            "email": user.email,
        }

        for alert in user.useralert_set.all():
            notify_objects = self.perform_search(alert)
            for obj in notify_objects:
                search_result_for_notification(obj)

            if len(notify_objects) > 0:
                results = []
                for obj in notify_objects:
                    results.append(search_result_for_notification(obj))
                context["alerts"].append({"title": str(alert), "results": results})

        logger.debug("User %s: %i results\n" % (user.email, len(context["alerts"])))

        if len(context["alerts"]) == 0:
            return False

        message_html = get_template("email/user-alert.html").render(context)
        message_html = message_html.replace("", "").replace(
            "", ""
        )
        message_text = html2text(message_html)

        if self.simulate:
            logging.info(message_text)
        else:
            # TODO: When this is called by cron it shouldn't write to stdout
            logger.info("Sending notification to: %s" % user.email)
            send_mail(
                user.email,
                settings.PRODUCT_NAME + ": " + _("New search results"),
                message_text,
                message_html,
                user.profile,
            )

        if not self.override_since:
            for alert in user.useralert_set.all():
                alert.last_match = timezone.now()
                alert.save()

        return True

    def notify_all(self):
        alerts_send = 0
        users = User.objects.filter(is_active=True).all()
        for user in users:
            alert_send = self.notify_user(user)
            if alert_send:
                alerts_send += 1
        logger.info(f"Sent notifications to {alerts_send} users")


text:
#
# This file is a Makefile for HOSTIP.  If it has the name "Makefile.in"
# then it is a template for a Makefile;  to generate the actual Makefile,
# run "./configure", which is a configuration script generated by the
# "autoconf" program (constructs like "@foo@" will get replaced in the
# actual Makefile.
#

PACKAGE = js9
VERSION = 1-e
DISTNAME = ${PACKAGE}-${VERSION}
DDISTNAME = ${PACKAGE}-data

DISTDIR	= ../export
FTPDIR	= ../ftp

#----------------------------------------------------------------
# Things you can change to personalize the Makefile for your own
# site (you can make these changes in either Makefile.in or
# Makefile, but changes to Makefile will get lost if you re-run
# the configuration script).
#----------------------------------------------------------------

# Default top-level directories in which to install architecture-
# specific files (exec_prefix) and machine-independent files such
# as scripts (prefix).  The values specified here may be overridden
# at configure-time with the --exec-prefix and --prefix options
# to the "configure" script.

prefix =		/soft/saord
exec_prefix =		${prefix}

# The following definition can be set to non-null for special systems
# like AFS with replication.  It allows the pathnames used for installation
# to be different than those used for actually reference files at
# run-time.  INSTALL_ROOT is prepended to $prefix and $exec_prefix
# when installing files.
INSTALL_ROOT =

# Directory in which to install the .a or .so binary for the TPOS library:
LIB_INSTALL_DIR =	$(INSTALL_ROOT)$(exec_prefix)/lib

# Directory in which to install the program wish:
BIN_INSTALL_DIR =	$(INSTALL_ROOT)$(exec_prefix)/bin

# Directory in which to install the include file tpos.h:
INCLUDE_INSTALL_DIR =	$(INSTALL_ROOT)$(prefix)/include

# Top-level directory for manual entries:
MAN_INSTALL_DIR =	$(INSTALL_ROOT)$(prefix)/man

# Directory in which to install manual entry for TPOS programs:
MAN1_INSTALL_DIR =	$(MAN_INSTALL_DIR)/man1

# Directory in which to install manual entries for TPOS's C library
# procedures:
MAN3_INSTALL_DIR =	$(MAN_INSTALL_DIR)/man3

# extra Libs required to link (e.g. socket libraries)
LIBS =            	-L /soft/saord/lib -lfuntools -Wl,-R /proj/rd/linux64/lib -L /proj/rd/linux64/lib -lpng  -ldl -lm

INCS =			-I/soft/saord/include -I/proj/rd/linux64/include

# To change the compiler switches, for example to change from -O
# to -g, change the following line:
CFLAGS = 		-g -W -Wall -Wno-implicit-int

# To add ld switches, change the following line:
LDFLAGS =		-g

# Some versions of make, like SGI's, use the following variable to
# determine which shell to use for executing commands:
SHELL =			/bin/sh

# There are just too many different versions of "install" around;
# better to use the install-sh script that comes with the distribution,
# which is slower but guaranteed to work.

INSTALL = 		./install-sh -c
INSTALL_PROGRAM =	${INSTALL}
INSTALL_DATA =		${INSTALL} -m 644

#----------------------------------------------------------------
# The information below is modified by the configure script when
# Makefile is generated from Makefile.in.  You shouldn't normally
# modify any of this stuff by hand.
#----------------------------------------------------------------

AC_FLAGS =		-DHAVE_CONFIG_H
RANLIB =		ranlib

#----------------------------------------------------------------
# The information below should be usable as is.  The configure
# script won't modify it and you shouldn't need to modify it
# either.
#----------------------------------------------------------------
RM =		rm -f

CP =		cp -p

CC =		gcc

CC_SWITCHES =	${CFLAGS} -I. ${AC_FLAGS} ${INCS}

DEPEND_SWITCHES = ${CFLAGS} -I. ${AC_FLAGS}

# type of backend server (or none)
HELPER =	get
USEHELPER =	yes

# where the web files go on your site
WEBDIR =   	/home/mred/public_html/htdocs/js9
CGIDIR =   	/home/mred/public_html/cgi-bin/js9
CGIURL =   	./cgi-bin/js9
CGIXPATH =   	/soft/saord/bin
# this is for SAO install only ... I think!
SAODIR =

WEBDIRS	=	plugins params js css images

BEDIRS =	node_modules analysis-plugins analysis-wrappers

WEBFILES =	js9.js js9.min.js js9-$(VERSION).js js9-$(VERSION).min.js \
		js9support.js js9support.min.js js9support.css js9plugins.js \
		js9support.txt js9.css fitsy.js fitsy.min.js \
		js9Msg.js js9Helper.js js9Prefs-default.json \
		js9Prefs.json favicon.ico index.html

SAOFILES =	index.html

CSSFILES =	css/jquery.contextMenu.css css/dhtmlwindow.css

JSFILES =	js/jquery.min.js js/jquery.contextMenu.min.js js/jquery.flot.min.js js/jquery.flot.errorbars.min.js js/jquery.flot.selection.min.js js/flot-zoom.min.js js/sprintf.min.js js/dhtmlwindow.min.js js/dhtmlwindow_blurb.js js/fabric.min.js js/pako_inflate.min.js js/astroem.js

PLUGINFILES =	plugins/archive/archive.js \
		plugins/fitsy/binning.js \
		plugins/imexam/imexam.js \
		plugins/imexam/encircled.js \
		plugins/imexam/pixtable.js \
		plugins/imexam/radproj.js \
		plugins/imexam/reghist.js \
		plugins/imexam/regstat.js \
		plugins/imexam/xyproj.js \
		plugins/imexam/3dplot.js

PREFFILES =	js9Prefs.json

CGIFILES =	js9Helper.cgi

WEBHELP	=	help

WEBDATA	=	fits png kes75

SRCS =		tpos.c js9helper.c

PROGS =		tpos js9helper

TESTPROGS =	pngdisp

INCLUDES =	js9helper.h

SCRIPTS =	funhist2flot funcnts2flot fits2png

SCRIPTS2 =	js9

ARCFILES =	js9-$(VERSION).js js9-$(VERSION).min.js js9Msg.js \
		js9.css js9Helper.js js9Prefs-default.json \
		js9basics.html js9panzoom.html js9analysis.html js9multi.html \
		js9create.html js9preload.html js9bitpix.html \
		js9onchange.html js9rgb.html js9cat.html js9plugins.html index.html \
		js9Helper-default.cgi fitsy.js

MFILES =	Makefile Makefile.in conf.h conf.h.in config.guess config.sub \
		configure configure.ac install-sh js9helper.pc.in js9.in \
		saoconfig saoprefs.sed nnode mkhelper mkjs9 js9Helper-default.cgi

all:		progs-$(USEHELPER) helper

progs-yes:	$(PROGS)

progs-no:

testall:	$(TESTPROGS)

All:		all testall

tpos:		tpos.o
		$(CC) $(LDFLAGS) tpos.o -o tpos $(LIBS)

js9helper:	js9helper.o
		$(CC) $(LDFLAGS) js9helper.o -o js9helper $(LIBS)

pngdisp:	pngdisp.o
		$(CC) $(LDFLAGS) pngdisp.o -o pngdisp $(LIBS)

links:		FORCE
		@(rm -f js9.js js9.min.js; \
		  ln -s js9-$(VERSION).js js9.js; \
		  ln -s js9-$(VERSION).min.js js9.min.js;)

prefs:		FORCE
		@(echo "copying default preferences to js9Prefs.json"; \
		  cp -p js9Prefs-default.json js9Prefs.json;)

saoprefs:	FORCE
		@(echo "editing js9Prefs for SAO installations ..."; \
		sed -f saoprefs.sed < js9Prefs.json > js9Prefs-sao.json)

helper:		FORCE
		@(./mkhelper "$(HELPER)" \
		  "$(CGIDIR)" "$(CGIURL)" "$(CGIXPATH)"; \
		  if [ x"$(USEHELPER)" = x"yes" ]; then \
		    ./mkjs9 "$(WEBDIR)"; \
		  fi;)

nohelper:	FORCE
		@(./mkhelper none; \
		  ./mkjs9 "$(WEBDIR)")

nodejshelper:	FORCE
		@(./mkhelper nodejs; \
		  ./mkjs9 "$(WEBDIR)")

cgihelper:	FORCE prefs
		@(./mkhelper get "$(CGIDIR)" "$(CGIURL)" "$(CGIXPATH)"; \
		  ./mkjs9 "$(WEBDIR)")

js9:		FORCE
		@(if [ x"$(USEHELPER)" = x"yes" ]; then \
		    ./mkjs9 "$(WEBDIR)"; \
		  fi;)

minify:		FORCE
		@minify js9-$(VERSION).js

js9support:	FORCE
		@(echo "remaking js9support ..."; minify fitsy.js; \
		  echo "css files in js9support.css: " > js9support.txt; \
		  echo $(CSSFILES) >>  js9support.txt; \
		  cat $(CSSFILES)  >  js9support.css;  \
		  echo "js files in js9support.js: " >> js9support.txt; \
		  echo $(JSFILES)  >> js9support.txt; \
		  cat $(JSFILES)   >  js9support.min.js; \
		  X=`echo "$(JSFILES)" | sed 's/\.min//g'`; \
		  cat $$X  > js9support.js; \
		  echo "plugin files in js9plugins.js: " >> js9support.txt; \
		  echo $(PLUGINFILES)  >> js9support.txt; \
		  cat $(PLUGINFILES)   >  js9plugins.js;)

remin:		FORCE
		@(echo "remaking js9.min.js ..."; touch js9-$(VERSION).js; minify js9-$(VERSION).js)

refresh:	js9support remin

jslint:		FORCE
		@(jslint js9.js; jslint fitsy.js)

archive:	FORCE
		@jsarchive $(ARCFILES) $(SCRIPTS) $(SRCS)

tar:		FORCE
		($(RM) config.cache; \
		cd ..; \
		tar cf - $(DISTNAME) | gzip -9 -c > $(DISTNAME).tar.gz)

install:	install-binaries install-scripts install-web

install-binaries: FORCE
	@(if [ x$(USEHELPER) = xyes ]; then \
	  echo "Installing programs ..."; \
	  for i in $(LIB_INSTALL_DIR) $(INCLUDE_INSTALL_DIR) $(BIN_INSTALL_DIR) ; \
	    do \
	    if [ ! -d $$i ] ; then \
		echo "making directory $$i"; \
		mkdir -p $$i; \
		chmod 755 $$i; \
		else true; \
		fi; \
	    done; \
	  for i in $(PROGS) ; \
	    do \
		if [ -f $$i.exe ] ; then \
		    echo "installing $$i.exe" ; \
		    $(INSTALL_PROGRAM) $$i.exe $(BIN_INSTALL_DIR)/$$i.exe ; \
		elif [ -f $$i ] ; then \
		    echo "installing $$i" ; \
		    $(INSTALL_PROGRAM) $$i $(BIN_INSTALL_DIR)/$$i ; \
		fi; \
	    done; \
	  else \
	    echo "nothing to install for 'binaries' (no helper configured)"; \
	  fi;)

install-scripts: $(SCRIPTS) $(SCRIPTS2)
	@(if [ x$(USEHELPER) = xyes ]; then \
	  echo "Installing scripts ..."; \
	  for i in $(BIN_INSTALL_DIR) ; \
	    do \
	    if [ ! -d $$i ] ; then \
		echo "making directory $$i"; \
		mkdir -p $$i; \
		chmod 755 $$i; \
		else true; \
		fi; \
	    done; \
	 for i in $(SCRIPTS) $(SCRIPTS2) ; \
	    do \
		if [ -f $$i ] ; then \
		    echo "installing $$i" ; \
		    $(INSTALL_PROGRAM) $$i $(BIN_INSTALL_DIR)/$$i ; \
		fi; \
	    done; \
	  else \
	    echo "nothing to install for 'scripts' (no helper configured)"; \
	  fi;)

install-web:		install-webdirs install-webfiles

install-webdirs:	FORCE
	@(echo "Installing web directories ..."; \
	 for i in $(WEBDIRS) $(WEBHELP); do \
	    if [ x$(WEBDIR) != x ]; then \
		mkdir -p $(WEBDIR); \
		if [ -d $$i ] ; then \
		    echo "installing web dir: $$i" ; \
		    tar cf - $$i | (cd $(WEBDIR); tar xf -); \
		fi; \
	    fi; \
         done; \
	 if [ x$(USEHELPER) = xyes ]; then \
	   echo "Installing backend helper dirs ..."; \
	   for i in $(BEDIRS); do \
		if [ -d $$i ] ; then \
		    echo "installing backend dir: $$i" ; \
		    tar cf - $$i | (cd $(WEBDIR); tar xf -); \
		fi; \
           done; \
	 fi;)

install-webfiles:	FORCE
	@(echo "Installing web files ..."; \
	if [ x$(WEBDIR) != x ]; then \
		mkdir -p $(WEBDIR); \
		if [ -f $(WEBDIR)/js9Prefs.json ] ; then \
		    echo "moving aside old js9Prefs.json" ; \
		    mv $(WEBDIR)/js9Prefs.json{,-old}; \
	        fi; \
	fi; \
	for i in $(PREFFILES) $(WEBFILES) js9*.html ; do\
	    if [ x$(WEBDIR) != x ]; then \
		if [ -d $$i ] ; then \
		    echo "installing web directory: $$i" ; \
		elif [ -f $$i ] ; then \
		    echo "installing web file: $$i" ; \
		fi; \
		tar cf - $$i | (cd $(WEBDIR); tar xf -); \
	    fi; \
        done; \
	if [ -d "$(CGIDIR)" ]; then \
	    for i in $(CGIFILES) ; do\
	        if [ -f $$i ]; then \
		    if [ -d $$i ] ; then \
		        echo "installing cgi directory: $$i" ; \
	  	    elif [ -f $$i ] ; then \
		        echo "installing cgi file: $$i" ; \
		    fi; \
		    tar cf - $$i | (cd $(CGIDIR); tar xf -); \
	        else \
		    echo "skipping cgi install: $$i"; \
	        fi; \
	    done; \
	else \
	    echo "nothing to install in cgi (no helper configured)"; \
	fi;)

install-webdata:	FORCE
	@(for i in $(WEBDATA) ; do\
	    if [ x$(WEBDIR) != x ]; then \
	        mkdir -p $(WEBDIR); \
		if [ -d $$i ] ; then \
		    echo "installing $$i" ; \
		    tar cf - $$i | (cd $(WEBDIR); tar xf -); \
		fi; \
	    fi; \
         done;)

install-sao:	saoprefs
		@(if [ -d "$(SAODIR)" ]; then \
		    for i in $(SAOFILES) ; \
		    do \
			if [ -f $$i ] ; then \
			    echo "installing file: $$i" ; \
		            $(CP) $$i $(SAODIR)/.; \
			fi; \
		    done; \
		  fi; \
		  $(CP) js9Prefs-sao.json $(WEBDIR)/js9Prefs.json;)

release:	refresh js9support links prefs
		(mkdir -p $(DISTDIR)/$(DISTNAME); \
		tar cf - $(WEBFILES) $(WEBDIRS) $(WEBHELP) js9*.html \
			 $(SRCS) $(INCLUDES) \
			 $(SCRIPTS) $(MFILES) | \
		(cd $(DISTDIR)/$(DISTNAME); tar xf -); \
		cd $(DISTDIR) ; \
		tar cf - $(DISTNAME) | gzip -c > $(DISTNAME).tar.gz; \
		rm -rf $(DISTNAME))

release-data:	FORCE
		tar cf - $(WEBDATA) | gzip -c > $(DISTDIR)/$(DDISTNAME).tar.gz;

spell:		FORCE
		@(for f in $(WEBHELP)/*.html; do \
			echo "spellcheck $$f ..."; \
			aspell -c $$f; \
		  done)

clean:		FORCE
		$(RM) *.a *.so *.dylib *.o *.exe core errs *pure* .nfs* \
			foo* *~ \#* TAGS *.E a.out errors \
			$(PROGS) $(CGIFILES) $(TESTPROGS) \
			gmon.out *.pg *.bak  *js9Prefs.json-orig \
			config.info config.log ltest \
			js/*~ params/*~ \
			doc/*~ notes/*~ test/*~ help/*~ help/*.bak \
			analysis-wrappers/*~ analysis-plugins/*~ \
			plugins/*~ plugins/*/*~ \
			astroem/*~ astroem/*.o
		$(RM) -rf autom4te.cache a.out.dSYM

distclean:	clean
		$(RM) Makefile config.status config.cache config.log \
		$(PREFFILES)

maintainer-clean:: clean
		$(RM) config.status config.cache config.log \
		$(PREFFILES)

Makefile:	Makefile.in
		$(SHELL) config.status

make:		Makefile.in
		$(SHELL) config.status

depend:		FORCE
		makedepend -- $(DEPEND_SWITCHES) -- $(SRCS)

tpos.o:		tpos.c $(INCL)
		$(CC) -c $(CC_SWITCHES) tpos.c

js9helper.o:	js9helper.c $(INCL)
		$(CC) -c $(CC_SWITCHES) js9helper.c

pngdisp.o:	pngdisp.c $(INCL)
		$(CC) -c $(CC_SWITCHES) pngdisp.c

configure:	configure.ac
		autoconf

errcheck:	FORCE
		@-egrep 'error|warning' foo | egrep -v "^lex.*but not used"

FORCE:

# DO NOT DELETE THIS LINE -- make depend depends on it.


text:
package com.payneteasy.superfly.demo.web.security;

import com.payneteasy.superfly.demo.web.utils.SecurityUtils;
import org.apache.wicket.Component;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.request.component.IRequestableComponent;
import org.springframework.security.access.annotation.Secured;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.StringTokenizer;

public class SpringSecurityAuthorizationStrategy implements IAuthorizationStrategy {

    private static final String DEV_FILE_PATH = "src/main/resources/components-security.properties";
    private static final String PROD_FILE_PATH = "components-security.properties";

    /**
     * Used only in production mode (i.e. when properties are loaded from the classpath).
     */
    private Properties cachedProperties = null;

    public <T extends IRequestableComponent> boolean isInstantiationAuthorized(Class<T> componentClass) {
        return true;
    }

    public boolean isActionAuthorized(Component component, Action action) {
        boolean ret ;
        String path = component.getPage().getClass().getSimpleName()+"."+component.getId()+"."+action.getName();
        String superPath = component.getPage().getClass().getSuperclass().getSimpleName()+"."+component.getId()+"."+action.getName();

        Properties securityProperties = loadSecurityProperties();
        if(isInSecurityPath(path, securityProperties)) {
            ret = isComponentAllowed(path, securityProperties);
        } else if(isInSecurityPath(superPath, securityProperties)) {
            ret = isComponentAllowed(superPath, securityProperties);
        } else if (component.getClass().isAnnotationPresent(Secured.class)) {
            ret = SecurityUtils.isComponentVisible(component.getClass());
        } else if (component instanceof BookmarkablePageLink<?>) {
            BookmarkablePageLink<?> link = (BookmarkablePageLink<?>) component;
            ret = SecurityUtils.isComponentVisible(link.getPageClass());
        } else {
            ret = true;
        }
        return ret;
    }

    private boolean isComponentAllowed(String aPath, Properties aProps) {
        String line = aProps.getProperty(aPath);
        StringTokenizer st = new StringTokenizer(line, "; , \t");
        while(st.hasMoreTokens()) {
            if(SecurityUtils.isUserInRole(st.nextToken())) {
                return true;
            }
        }
        return false ;
    }

    private boolean isInSecurityPath(String aPath, Properties aProps) {
        return aProps.containsKey(aPath);
    }

    private Properties loadSecurityProperties() {
        Properties prop = new Properties();
        String file = DEV_FILE_PATH;
        boolean devMode = new File(file).exists();
        InputStream in = null;
        try {
            if (devMode) {
                in = new FileInputStream(file);
            } else {
                if (cachedProperties != null) {
                    return cachedProperties;
                }
                ClassLoader cl = Thread.currentThread().getContextClassLoader();
                if (cl == null) {
                    cl = getClass().getClassLoader();
                }
                in = cl.getResourceAsStream(PROD_FILE_PATH);
            }
            prop.load(in);
            if (!devMode) {
                cachedProperties = prop;
            }
            return prop;
        } catch (IOException e) {
            throw new IllegalStateException("Error reading from file " +file+": "+e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                throw new IllegalStateException("Error closing file " +file+": "+e.getMessage(), e);
            }
        }
    }
}


text:
/* global describe it */
var assert = require('assert')
var genlib = require( '../dist/index.js' )

var gen = genlib.gen
var abs = genlib.abs
var round = genlib.round
var ceil = genlib.ceil
var sign = genlib.sign
var floor = genlib.floor

describe( 'monops', ()=> {
  it( 'should generate the absolute value of -.5 as .5', ()=> {
    let answer = .5,
        graph = abs( -.5 ),
        out = gen.createCallback( graph ),
        result = out()

    assert.equal( result, answer )
  })

  it( 'should round .75 to 1', ()=> {
    let answer = 1,
        graph = round( .75 ),
        out = gen.createCallback( graph ),
        result = out()

    assert.equal( result, answer )
  })

  it( 'should floor .75 to 0', ()=> {
    let answer = 0,
        graph = floor( .75 ),
        out = gen.createCallback( graph ),
        result = out()

    assert.equal( result, answer )
  })

  it( 'should ceil .25 to 1', ()=> {
    let answer = 1,
        graph = ceil( .25 ),
        out = gen.createCallback( graph ),
        result = out()

    assert.equal( result, answer )
  })

  it( 'should return -1 for sign(-1000)', ()=> {
    let answer = -1,
        graph = sign( -1000 ),
        out = gen.createCallback( graph ),
        result = out()

    assert.equal( result, answer )
  })
  it( 'should return 1 for sign(1000)', ()=> {
    let answer = 1,
        graph = sign( 1000 ),
        out = gen.createCallback( graph ),
        result = out()

    assert.equal( result, answer )
  })
})


text:
extern string SPR_ERROR;

int    SPR_init();
void   SPR_destroy();

int    SPR_load(string location);
int    SPR_reload();

int    SPR_run(string section, string option_expr);
string SPR_getText(string section, string option_expr);

string SPR_getOptionMatched(string section, string option_expr);
int    SPR_getOptions(string section, string options[]);
int    SPR_getLastCalled(string section, string option);


text:
import React from "react";
import Week from "../src/week";
import WeekNumber from "../src/week_number";
import Day from "../src/day";
import { shallow } from "enzyme";
import sinon from "sinon";
import * as utils from "../src/date_utils";

describe("Week", () => {
  it("should have the week CSS class", () => {
    const week = shallow(<Week day={utils.newDate()} />);
    expect(week.hasClass("react-datepicker__week")).to.equal(true);
  });

  it("should render the days of the week", () => {
    const weekStart = utils.getStartOfWeek(utils.newDate("2015-12-20"));
    const week = shallow(<Week day={weekStart} />);

    const days = week.find(Day);
    expect(days.length).to.equal(7);
    days.forEach((day, offset) => {
      const expectedDay = utils.addDays(weekStart, offset);
      assert(utils.isSameDay(day.prop("day"), expectedDay));
    });

    const weekNumber = week.find(WeekNumber);
    expect(weekNumber.length).to.equal(0);
  });

  it("should render the week number", () => {
    const weekStart = utils.getStartOfWeek(utils.newDate("2015-12-20"));
    const week = shallow(<Week showWeekNumber day={weekStart} />);

    const days = week.find(Day);
    expect(days.length).to.equal(7);
    days.forEach((day, offset) => {
      const expectedDay = utils.addDays(weekStart, offset);
      assert(utils.isSameDay(day.prop("day"), expectedDay));
    });

    const weekNumber = week.find(WeekNumber);
    expect(weekNumber.length).to.equal(1);
  });

  it("should call the provided onDayClick function", () => {
    let dayClicked = null;

    function onDayClick(day) {
      dayClicked = day;
    }

    const weekStart = utils.newDate("2015-12-20");
    const week = shallow(<Week day={weekStart} onDayClick={onDayClick} />);
    const day = week.find(Day).at(0);
    day.simulate("click");
    assert(utils.isSameDay(day.prop("day"), dayClicked));
  });

  it("should call the provided onWeekSelect function and pass the first day of the week", () => {
    let firstDayReceived = null;

    function onWeekClick(newFirstWeekDay) {
      firstDayReceived = newFirstWeekDay;
    }

    const weekStart = utils.newDate("2015-12-20");
    const setOpenSpy = sinon.spy();
    const week = shallow(
      <Week
        day={weekStart}
        showWeekNumber
        onWeekSelect={onWeekClick}
        setOpen={setOpenSpy}
      />
    );
    const weekNumberElement = week.find(WeekNumber);
    weekNumberElement.simulate("click");
    expect(utils.isEqual(firstDayReceived, weekStart)).to.be.true;
  });

  it("should call the provided onWeekSelect function and call the setopen function", () => {
    const weekStart = utils.newDate("2015-12-20");
    const setOpenSpy = sinon.spy();

    const week = shallow(
      <Week
        day={weekStart}
        showWeekNumber
        shouldCloseOnSelect
        onWeekSelect={() => {}}
        setOpen={setOpenSpy}
      />
    );

    const weekNumberElement = week.find(WeekNumber);
    weekNumberElement.simulate("click");
    sinon.assert.calledOnce(setOpenSpy);
  });

  it("should call the provided onWeekSelect function and not call the setopen function when 'shouldCloseOnSelect' is false", () => {
    const weekStart = utils.newDate("2015-12-20");
    const setOpenSpy = sinon.spy();

    const week = shallow(
      <Week
        day={weekStart}
        showWeekNumber
        shouldCloseOnSelect={false}
        onWeekSelect={() => {}}
        setOpen={setOpenSpy}
      />
    );

    const weekNumberElement = week.find(WeekNumber);
    weekNumberElement.simulate("click");
    sinon.assert.notCalled(setOpenSpy);
  });

  it("should call the provided onWeekSelect function and pass the week number", () => {
    let weekNumberReceived = null;

    function onWeekClick(unused, newWeekNumber) {
      weekNumberReceived = newWeekNumber;
    }

    const weekStart = utils.newDate("2015-12-20");
    const realWeekNumber = utils.getWeek(weekStart);
    const week = shallow(
      <Week
        day={weekStart}
        showWeekNumber
        shouldCloseOnSelect={false}
        onWeekSelect={onWeekClick}
      />
    );
    const weekNumberElement = week.find(WeekNumber);
    weekNumberElement.simulate("click");
    expect(weekNumberReceived).to.equal(realWeekNumber);
  });

  it("should set the week number with the provided formatWeekNumber function", () => {
    let firstDayReceived = null;

    function weekNumberFormatter(newFirstWeekDay) {
      firstDayReceived = newFirstWeekDay;
      return 9;
    }

    const weekStart = utils.newDate("2015-12-20");
    const week = shallow(
      <Week
        day={weekStart}
        showWeekNumber
        formatWeekNumber={weekNumberFormatter}
      />
    );
    const weekNumberElement = week.find(WeekNumber);

    expect(utils.isEqual(firstDayReceived, weekStart)).to.be.true;
    expect(weekNumberElement.prop("weekNumber")).to.equal(9);
  });

  it("should call the provided onDayMouseEnter function", () => {
    let dayMouseEntered = null;

    function onDayMouseEnter(day) {
      dayMouseEntered = day;
    }

    const weekStart = utils.newDate();
    const week = shallow(
      <Week day={weekStart} onDayMouseEnter={onDayMouseEnter} />
    );
    const day = week.find(Day).first();
    day.simulate("mouseenter");
    assert(utils.isSameDay(day.prop("day"), dayMouseEntered));
  });
});


text:
var myVideo = document.getElementById("BTV");

var playButton = document.getElementById("PlayButton");
playButton.onclick = play;

myVideo.onclick = pause;

var image = document.getElementById("NewsBTV");

myVideo.onended = function () {
    playButton.style.visibility = 'visible';
    myVideo.style.visibility = 'hidden';
}

function play() {
    myVideo.play();
    myVideo.style.visibility = 'visible';
    playButton.style.visibility = 'hidden'
}

function pause() {
    myVideo.pause();
    playButton.style.visibility = 'visible';
}


text:
package main

import (
	"encoding/json"
	//"fmt"
	log "github.com/Sirupsen/logrus"
	"github.com/gorilla/mux"

	//"io"
	//"io/ioutil"
	"net/http"
)

const ( //TODO: Move this out, get it from config
	HOST = "teenyurl.co/"
)

type UrlData struct {
	LongUrl  string `json:"longUrl"`
	ShortUrl string `json:"shortUrl"`
}

func AppRedirectHandler(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, "http://teenyurl/app" , 301)
}

//TODO: url checking needs to be tighter
func ShortenHandler(w http.ResponseWriter, r *http.Request) {
	longUrl := r.FormValue("url")
	//check url , create key, throw err if url is bad
	shortKey, err := GetKey(longUrl)
	if err != nil {
		log.Error("error in url")
	}

	//TODO: Get it from conf
	shortUrl := HOST + shortKey.Id

	json.NewEncoder(w).Encode(shortUrl)

}

func LengthenHandler(w http.ResponseWriter, r *http.Request) {
	ShortUrl := r.FormValue("url")

	id := string(ShortUrl[len(ShortUrl)-6:])
	Url, err := GetlongUrl(id)
	if err != nil {
		log.Error("Error in url")
	}
	shortUrl := "http://" + Url.LongUrl
	json.NewEncoder(w).Encode(shortUrl)

}

func RedirectHandler(w http.ResponseWriter, r *http.Request) {

	short := mux.Vars(r)["short"]
	longUrl, err := GetlongUrl(short)
	if err != nil {
		//TODO: http.Redirect(w, r, notfound, http.StatusMovedPermanently)
		log.Error("Cannot redirect")
	}

	http.Redirect(w, r, longUrl.LongUrl, http.StatusMovedPermanently)

}


text:
.. automodule:: insights.parsers.crio_conf
   :members:
   :show-inheritance:


text:
from .prescons import main

main()


text:
<?php

namespace Kendo\Dataviz\UI;

class MapMarkerTooltipAnimationOpen extends \Kendo\SerializableObject {
//>> Properties

    /**
    * Effect to be used for opening of the Tooltip.
    * @param string $value
    * @return \Kendo\Dataviz\UI\MapMarkerTooltipAnimationOpen
    */
    public function effects($value) {
        return $this->setProperty('effects', $value);
    }

    /**
    * Defines the animation duration.
    * @param float $value
    * @return \Kendo\Dataviz\UI\MapMarkerTooltipAnimationOpen
    */
    public function duration($value) {
        return $this->setProperty('duration', $value);
    }

//<< Properties
}

?>


text:
define(function () {
    'use strict';
    return {
        init: function (appId) {
            var grid = appId + "_grid";
            var gridPanel = appId + "_gridPanel";
            var strVar = "
";
            strVar += "
<\/div>";
            strVar += "<\/div>";
            return strVar;
        }
    }
});


text:
package br.com.siscob.util;

import br.com.siscob.model.Usuario;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Classe utilit�ria para desenvolvimento JSF
 */
public class FacesUtil {

    public static String getRequestParameter(String name) {
        return (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(name);
    }

    public static void exibirMensagemSucesso(String titulo, String mensagem) {
        exibirMensagem(FacesMessage.SEVERITY_INFO, titulo, mensagem);
    }

    public static void exibirMensagemAlerta(String titulo, String mensagem) {
        exibirMensagem(FacesMessage.SEVERITY_WARN, titulo, mensagem);
    }

    public static void exibirMensagemErro(String titulo, String mensagem) {
        exibirMensagem(FacesMessage.SEVERITY_ERROR, titulo, mensagem);
    }

    private static void exibirMensagem(FacesMessage.Severity severity, String titulo, String mensagem) {
        FacesMessage facesMessage = new FacesMessage(severity, titulo, mensagem);
        FacesContext.getCurrentInstance().addMessage(null, facesMessage);
    }

    public static ExternalContext getExternalContext() {
        return FacesContext.getCurrentInstance().getExternalContext();
    }

    @SuppressWarnings("rawtypes")
    public static Map getSessionMap() {
        return FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
    }

    public static ServletContext getServletContext() {
        return (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
    }

    public static HttpServletRequest getServletRequest() {
        return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    }

    public static HttpServletResponse getServletResponse() {
        return (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    }

    public static Usuario obterUsuarioSessao(){
        return (Usuario) FacesUtil.getServletRequest().
                                    getSession().getAttribute("usuario");
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using OpenLiveWriter.Api;
using OpenLiveWriter.CoreServices;

namespace OpenLiveWriter.Extensibility.BlogClient
{

    public class BlogPost : ICloneable, IPostInfo
    {
        public string Id
        {
            get { return _id; }
            set { _id = value; }
        }
        private string _id = String.Empty;

        public bool IsNew
        {
            get { return Id == String.Empty; }
        }

        public void ResetPostForNewBlog(IBlogClientOptions options)
        {
            Id = String.Empty;
            DatePublished = DateTime.MinValue;

            // if the current blog doesn't support pages then force
            // the post to not be a page
            if (!options.SupportsPages)
                IsPage = false;

            // author and parent are tied to blog, reset them as well
            Author = PostIdAndNameField.Empty;
            PageParent = PostIdAndNameField.Empty;

            ETag = string.Empty;
            AtomRemotePost = null;

            // categories are tied to blog, reset them
            Categories = null;
            NewCategories = null;

            // ping urls are tied to blog, reset them so they are sent again for a new blog
            UncommitPingUrls();
        }

        public bool IsPage
        {
            get { return _isPage; }
            set
            {
                _isPage = value;

                if (!_isPage)
                {
                    PageParent = PostIdAndNameField.Empty;
                    PageOrder = String.Empty;
                }
            }
        }
        private bool _isPage = false;

        public string Title
        {
            get { return XmlCharacterHelper.RemoveInvalidXmlChars(_title); }
            set { _title = XmlCharacterHelper.RemoveInvalidXmlChars(value); }
        }
        private string _title = String.Empty;

        public string Contents
        {
            get
            {
                string contents;
                if (ExtendedContents.Length > 0)
                    contents = String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", MainContents, ExtendedEntryBreak, ExtendedContents);
                else
                    contents = MainContents;

                if (contents != null)
                    contents = XmlCharacterHelper.RemoveInvalidXmlChars(contents);

                return contents;
            }
            set { SetContents(XmlCharacterHelper.RemoveInvalidXmlChars(value)); }
        }

        public string MainContents
        {
            get { return _mainContents; }
        }
        private string _mainContents = String.Empty;

        public string ExtendedContents
        {
            get { return _extendedContents; }
        }
        private string _extendedContents = String.Empty;

        public string Permalink
        {
            get { return _permaLink; }
            set
            {
                // normalize to String.Empty
                if (value != null)
                    _permaLink = value;
                else
                    _permaLink = String.Empty;
            }
        }
        private string _permaLink = String.Empty;

        public BlogPostCategory[] Categories
        {
            get { return _categories; }
            set
            {
                if (value != null)
                    _categories = value;
                else
                    _categories = new BlogPostCategory[] { };
            }
        }
        private BlogPostCategory[] _categories = new BlogPostCategory[] { };

        ICategoryInfo[] IPostInfo.Categories
        {
            get
            {
                List<PostCategoryInfo> categories = new List<PostCategoryInfo>();
                foreach (BlogPostCategory cat in Categories)
                    categories.Add(new PostCategoryInfo(cat.Id, cat.Name, false));
                foreach (BlogPostCategory cat in NewCategories)
                    categories.Add(new PostCategoryInfo(cat.Id, cat.Name, true));
                return categories.ToArray();
            }
        }

        private class PostCategoryInfo : ICategoryInfo
        {
            private readonly string id;
            private readonly string name;
            private readonly bool isNew;

            public PostCategoryInfo(string id, string name, bool isNew)
            {
                this.id = id;
                this.name = name;
                this.isNew = isNew;
            }

            public string Id
            {
                get { return id; }
            }

            public string Name
            {
                get { return name; }
            }

            public bool IsNew
            {
                get { return isNew; }
            }
        }

        public BlogPostCategory[] NewCategories
        {
            get { return _newCategories; }
            set
            {
                if (value != null)
                    _newCategories = value;
                else
                    _newCategories = new BlogPostCategory[] { };
            }
        }
        private BlogPostCategory[] _newCategories = new BlogPostCategory[] { };

        public void CommitNewCategory(BlogPostCategory newCategory)
        {
            // revised category list
            ArrayList categories = new ArrayList(Categories);
            categories.Add(newCategory);
            Categories = categories.ToArray(typeof(BlogPostCategory)) as BlogPostCategory[];

            // revised new category list
            ArrayList newCategories = new ArrayList();
            foreach (BlogPostCategory category in NewCategories)
                if (!category.Name.Equals(newCategory.Name))
                    newCategories.Add(category);
            NewCategories = newCategories.ToArray(typeof(BlogPostCategory)) as BlogPostCategory[];
        }

        public DateTime DatePublished
        {
            get { return _datePublished; }
            set { _datePublished = value; }
        }
        private DateTime _datePublished = DateTime.MinValue;

        public DateTime DatePublishedOverride
        {
            get { return _datePublishedOverride; }
            set { _datePublishedOverride = value; }
        }
        private DateTime _datePublishedOverride = DateTime.MinValue;

        public bool HasDatePublishedOverride
        {
            get { return DatePublishedOverride != DateTime.MinValue; }
        }

        public BlogCommentPolicy CommentPolicy
        {
            get { return _commentPolicy; }
            set { _commentPolicy = value; }
        }
        private BlogCommentPolicy _commentPolicy = BlogCommentPolicy.Unspecified;

        public BlogTrackbackPolicy TrackbackPolicy
        {
            get { return _trackbackPolicy; }
            set { _trackbackPolicy = value; }
        }
        private BlogTrackbackPolicy _trackbackPolicy = BlogTrackbackPolicy.Unspecified;

        public string Keywords
        {
            get { return XmlCharacterHelper.RemoveInvalidXmlChars(_keywords); }
            set { XmlCharacterHelper.RemoveInvalidXmlChars(_keywords = value); }
        }
        private string _keywords = String.Empty;

        public string Excerpt
        {
            get { return XmlCharacterHelper.RemoveInvalidXmlChars(_excerpt); }
            set { _excerpt = XmlCharacterHelper.RemoveInvalidXmlChars(value); }
        }
        private string _excerpt = String.Empty;

        public string[] PingUrlsPending
        {
            get { return _pingUrlsPending.Clone() as string[]; }
            set { _pingUrlsPending = value.Clone() as string[]; }
        }
        private string[] _pingUrlsPending = new string[0];

        public string[] PingUrlsSent
        {
            get { return _pingUrlsSent.Clone() as string[]; }
            set { _pingUrlsSent = value.Clone() as string[]; }
        }
        private string[] _pingUrlsSent = new string[0];

        public void CommitPingUrls()
        {
            PingUrlsSent = ArrayHelper.Union(PingUrlsSent, PingUrlsPending);
            PingUrlsPending = new string[0];
        }

        public void UncommitPingUrls()
        {
            PingUrlsPending = ArrayHelper.Union(PingUrlsSent, PingUrlsPending);
            PingUrlsSent = new string[0];
        }

        public string Slug
        {
            get { return _slug; }
            set { _slug = value; }
        }
        private string _slug = String.Empty;

        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }
        private string _password = String.Empty;

        public PostIdAndNameField Author
        {
            get { return _author; }
            set { _author = value; }
        }
        private PostIdAndNameField _author = PostIdAndNameField.Empty;

        public PostIdAndNameField PageParent
        {
            get { return _parentPageParent; }
            set { _parentPageParent = value; }
        }
        private PostIdAndNameField _parentPageParent = PostIdAndNameField.Empty;

        public string PageOrder
        {
            get { return _pageOrder; }
            set { _pageOrder = value; }
        }
        private string _pageOrder = String.Empty;

        ///
        /// True if the post is a temporary style detection post.
        ///
        public bool IsTemporary
        {
            get { return _temp; }
            set { _temp = value; }
        }
        private bool _temp = false;

        public string ContentsVersionSignature
        {
            get
            {
                if (_publishedPostHash == null)
                    _publishedPostHash = MD5Hash(Contents);
                return _publishedPostHash;
            }
            set { _publishedPostHash = value; }
        }
        private string _publishedPostHash = null;

        public string ETag
        {
            get { return _etag; }
            set { _etag = value; }
        }
        private string _etag = String.Empty;

        public XmlDocument AtomRemotePost
        {
            get
            {
                if (_atomRemotePost != null)
                    return (XmlDocument)_atomRemotePost.Clone();
                else
                    return null;
            }
            set
            {
                if (value == null)
                    _atomRemotePost = null;
                else
                    _atomRemotePost = (XmlDocument)value.Clone();
            }
        }
        private XmlDocument _atomRemotePost = null;

        ///
        /// Sets the main and extended contents of the post.
        ///
        /// <param name="mainContents"></param>
        /// <param name="extendedContents"></param>
        public void SetContents(string mainContents, string extendedContents)
        {
            _mainContents = mainContents;
            _extendedContents = extendedContents;
        }

        ///
        /// Sets the contents of the post.
        /// (if the content contains the , it will automatically be split into
        /// the main and extended contents).
        ///
        /// <param name="contents"></param>
        private void SetContents(string contents)
        {
            Match match = ExtendedEntryBreakRegex.Match(contents);
            if (match.Success)
            {
                _mainContents = contents.Substring(0, match.Index);
                _extendedContents = contents.Substring(match.Index + match.Length);
            }
            else
            {
                _mainContents = contents;
                _extendedContents = String.Empty;
            }
        }

        public static readonly string ClearBreak = "
"; // float clearing break
        public static readonly string HorizontalLine = "
"; // horizontal rule
        public static readonly string PlainTextHorizontalLine = "--------------------------------------------------------------------------------"; // 80 dashes
        public static readonly string ExtendedEntryBreak = "";  //the more text comment
        public static readonly string ExtendedEntryBreakMoreText = "more"; //the value of the more text comment
        private static Regex ExtendedEntryBreakRegex = new Regex(""); //regex for detecting the more text comment

        public object Clone()
        {
            BlogPost newPost = new BlogPost();
            newPost.CopyFrom(this);
            return newPost;
        }

        public void CopyFrom(BlogPost sourcePost)
        {
            Id = sourcePost.Id;
            IsPage = sourcePost.IsPage;
            Title = sourcePost.Title;
            Contents = sourcePost.Contents;
            Permalink = sourcePost.Permalink;
            Categories = sourcePost.Categories;
            NewCategories = sourcePost.NewCategories;
            DatePublished = sourcePost.DatePublished;
            DatePublishedOverride = sourcePost.DatePublishedOverride;
            CommentPolicy = sourcePost.CommentPolicy;
            TrackbackPolicy = sourcePost.TrackbackPolicy;
            Keywords = sourcePost.Keywords;
            Excerpt = sourcePost.Excerpt;
            PingUrlsPending = sourcePost.PingUrlsPending;
            PingUrlsSent = sourcePost.PingUrlsSent;
            PageParent = sourcePost.PageParent.Clone() as PostIdAndNameField;
            PageOrder = sourcePost.PageOrder;
            Slug = sourcePost.Slug;
            Password = sourcePost.Password;
            Author = sourcePost.Author.Clone() as PostIdAndNameField;

            IsTemporary = sourcePost.IsTemporary;
            ContentsVersionSignature = sourcePost.ContentsVersionSignature;
            ETag = sourcePost.ETag;
            AtomRemotePost = sourcePost.AtomRemotePost != null
                ? (XmlDocument)sourcePost.AtomRemotePost.Clone()
                : null;
        }

        public static string CalculateContentsSignature(BlogPost post)
        {
            if (post.Contents == null)
                return null;
            try
            {
                return MD5Hash(post.Contents);
            }
            catch (Exception e)
            {
                Debug.Fail("Error creating contents version signature", e.ToString());
                return null;
            }
        }

        private static string MD5Hash(string str)
        {
            byte[] bytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(str));
            StringBuilder sb = new StringBuilder(bytes.Length * 2);
            foreach (byte b in bytes)
                sb.AppendFormat("{0:x2}", b);
            return sb.ToString();
        }
    }

    public enum BlogCommentPolicy
    {
        Unspecified,
        None,
        Open,
        Closed
    }

    public enum BlogTrackbackPolicy
    {
        Unspecified,
        Allow,
        Deny
    }

    public class PostIdAndNameField : ICloneable
    {
        public static PostIdAndNameField Empty
        {
            get
            {
                return _empty;
            }
        }
        private static readonly PostIdAndNameField _empty = new PostIdAndNameField();

        public PostIdAndNameField()
            : this(String.Empty)
        {
        }

        public PostIdAndNameField(string emptyFieldText)
            : this(String.Empty, String.Empty)
        {
            _emptyFieldText = emptyFieldText;
        }

        public PostIdAndNameField(string id, string name)
        {
            _id = id;
            if (name != String.Empty)
                _name = name;
            else
                _name = _id;
        }

        public bool IsEmpty
        {
            get { return Id == String.Empty; }
        }

        public string Id
        {
            get
            {
                return _id;
            }
        }

        public string Name
        {
            get
            {
                return _name;
            }
        }

        public override bool Equals(object obj)
        {
            return obj is PostIdAndNameField
                && ((PostIdAndNameField)obj).Id.Equals(Id);
        }

        public override int GetHashCode()
        {
            return Id.GetHashCode();
        }

        public override string ToString()
        {
            if (_id != String.Empty)
            {
                return Name;
            }
            else
            {
                return _emptyFieldText;
            }
        }

        public virtual object Clone()
        {
            return new PostIdAndNameField(_id, _name);
        }

        private string _id = String.Empty;
        private string _name = String.Empty;
        private string _emptyFieldText = String.Empty;
    }
}


text:
import {FETCH_USER_WORKING_HOURS_PREFERENCES_ACTION_PREFIX} from "../constants";
import {fetchWorkingHoursPreferencesReducer} from "./fetchWorkingHoursPreferences";

describe('fetchWorkingHoursPreferencesReducer', () => {
    const sampleState = {
        fetching: false,
        error: null,
        preferences: {}
    }

    it('should set fetching flag to true and reset error on request', () => {
        // given
        const action = {
            type: `${FETCH_USER_WORKING_HOURS_PREFERENCES_ACTION_PREFIX}_request`
        }

        const state = {
            ...sampleState,
            error: "Some error message"
        }

        // when
        const expectedState = {
            ...sampleState,
            fetching: true,
            error: null
        }

        const newState = fetchWorkingHoursPreferencesReducer(state, action)

        // then
        return expect(newState).toEqual(expectedState)
    })

    it('should set fetching flag to false and add preferences on success', () => {
        // given
        const samplePreferences = {
            1: {
                "userId": 1,
                "dayPreferences": {
                    "1": {
                        "nonWorking": false,
                        "startTime": "10:00",
                        "endTime": "12:00"
                    },
                    "2": {
                        "nonWorking": false,
                        "startTime": "10:00",
                        "endTime": "12:00"
                    },
                    "3": {
                        "nonWorking": false,
                        "startTime": "10:00",
                        "endTime": "12:00"
                    },
                    "4": {
                        "nonWorking": false,
                        "startTime": "10:00",
                        "endTime": "12:00"
                    },
                    "5": {
                        "nonWorking": false,
                        "startTime": "08:00",
                        "endTime": "18:00"
                    }
                }
            },
            2: {
                "userId": 2,
                "dayPreferences": {
                    "1": {
                        "nonWorking": false,
                        "startTime": "10:00",
                        "endTime": "12:00"
                    },
                    "2": {
                        "nonWorking": false,
                        "startTime": "10:00",
                        "endTime": "12:00"
                    },
                    "3": {
                        "nonWorking": true,
                        "startTime": "10:00",
                        "endTime": "12:00"
                    },
                    "4": {
                        "nonWorking": true,
                        "startTime": "10:00",
                        "endTime": "12:00"
                    },
                    "5": {
                        "nonWorking": true,
                        "startTime": "08:00",
                        "endTime": "18:00"
                    }
                }
            }
        }

        const action = {
            type: `${FETCH_USER_WORKING_HOURS_PREFERENCES_ACTION_PREFIX}_success`,
            response: samplePreferences
        }

        const state = {
            ...sampleState,
            fetching: true
        }

        // when
        const expectedState = {
            ...sampleState,
            fetching: false,
            preferences: samplePreferences
        }

        const newState = fetchWorkingHoursPreferencesReducer(state, action)

        // then
        return expect(newState).toEqual(expectedState)
    })

    it('should set fetching flag to false and set an error message on failure', () => {
        // given
        const action = {
            type: `${FETCH_USER_WORKING_HOURS_PREFERENCES_ACTION_PREFIX}_failure`,
            error: "Some error message"
        }

        const state = {
            ...sampleState,
            fetching: true
        }

        // when
        const expectedState = {
            ...sampleState,
            fetching: false,
            error: "Some error message"
        }

        const newState = fetchWorkingHoursPreferencesReducer(state, action)

        // then
        return expect(newState).toEqual(expectedState)
    })
})


text: <img class="full-image" src="/images/css-style-guide.png">


text:
<?php

namespace Notadd\Foundation\Image\Gd\Commands;

use Notadd\Foundation\Image\Commands\AbstractCommand;

/**
 * Class BlurCommand.
 */
class BlurCommand extends AbstractCommand
{
    /**
     * @param \Notadd\Foundation\Image\Image $image
     *
     * @return bool
     */
    public function execute($image)
    {
        $amount = $this->argument(0)->between(0, 100)->value(1);
        for ($i = 0; $i < intval($amount); ++$i) {
            imagefilter($image->getCore(), IMG_FILTER_GAUSSIAN_BLUR);
        }

        return true;
    }
}


text:
using System;

namespace ServiceStack.Logging
{
    /// <summary>
    /// Logging API for this library. You can inject your own implementation otherwise
    /// will use the DebugLogFactory to write to System.Diagnostics.Debug
    /// </summary>
    public class LogManager
    {
        private static ILogFactory logFactory;

        /// <summary>
        /// Gets or sets the log factory.
        /// Use this to override the factory that is used to create loggers
        /// </summary>
        public static ILogFactory LogFactory
        {
            get
            {
                if (logFactory == null)
                {
                    return new DebugLogFactory();
                }
                return logFactory;
            }
            set { logFactory = value; }
        }

        /// <summary>
        /// Gets the logger.
        /// </summary>
        public static ILog GetLogger(Type type)
        {
            return LogFactory.GetLogger(type);
        }

        /// <summary>
        /// Gets the logger.
        /// </summary>
        public static ILog GetLogger(string typeName)
        {
            return LogFactory.GetLogger(typeName);
        }
    }
}


text:
import django.contrib.postgres.fields
from django.db import migrations, models
import djmoney.models.fields

class Migration(migrations.Migration):

    dependencies = [
        ('records', '0002_auto_20181204_1826'),
    ]

    operations = [
        migrations.AddField(
            model_name='record',
            name='comment',
            field=models.TextField(blank=True, null=True),
        ),
        migrations.AlterField(
            model_name='record',
            name='amount',
            field=djmoney.models.fields.MoneyField(decimal_places=2, default_currency='CAD', max_digits=15),
        ),
        migrations.AlterField(
            model_name='record',
            name='tags',
            field=django.contrib.postgres.fields.ArrayField(base_field=models.TextField(max_length=20), blank=True, default=list, size=None),
        ),
    ]


text:
function handles = setTagListSession(handles,hObject)

brainReg = handles.H.CurrentRegion;
if handles.H.At == 2
    brainReg = brainReg + length(handles.H.txtCort);
end
handles.sessionTags{brainReg,handles.H.dataset}{1} = handles.tags;
handles.sessionTags{brainReg,handles.H.dataset}{2} = handles.corMat;

handles.H.dataset = get(hObject,'Value');
handles.tags = handles.sessionTags{brainReg,handles.H.dataset}{1};


text:
module FileDaemon

  # Public: Extend the including class with before/after_fork hooks.
  #
  # base - The including class.
  #
  # Returns nothing.
  def self.included(base)
    base.extend(ClassMethods)
  end

  # :nodoc:
  module ClassMethods

    # Public: Store the list of currently open file descriptors so that they
    # may be reopened when a new process is spawned.
    #
    # Returns nothing.
    def before_fork
      @files_to_reopen ||= ObjectSpace.each_object(File).reject(&:closed?)
    end

    # Public: Reopen all file descriptors that have been stored through the
    # before_fork hook.
    #
    # Returns nothing.
    def after_fork
      @files_to_reopen.each do |file|
        begin
          file.reopen file.path, "a+"
          file.sync = true
        rescue ::IOError # rubocop:disable HandleExceptions
        end
      end
    end

  end

end


text:
#include "gutil_macros.h"
#include <QtCore/QString>
#include <QtTest/QtTest>

// Convenient namespace declaration
NAMESPACE_GUTIL1( DummyTest )

class TestClass
{
public:

    // You can adjust the private variables themselves by using the _p_ prefix
    TestClass() : _p_MyReadOnlyInt(10) {}

    // Convenient property declarations
    PROPERTY( MyInt, int );
    PROPERTY( MyString, QString );

    READONLY_PROPERTY( MyReadOnlyInt, int );

    // Or you can declare the accessors, and define the function bodies like below:
    PROPERTY_ACCESSORS( IsMeInsane, bool );

    READONLY_PROPERTY_ACCESSORS( Sexy, bool );
};

bool TestClass::GetIsMeInsane() const
{
    return true;
}

void TestClass::SetIsMeInsane(const bool &value)
{
    // You can't change this
}

bool TestClass::GetSexy() const
{
    return true;
}

END_NAMESPACE_GUTIL1

class GUtil_MacrosTest : public QObject
{
    Q_OBJECT

public:
    GUtil_MacrosTest();

private Q_SLOTS:
    void test_macros();
};

USING_NAMESPACE_GUTIL1( DummyTest );
//using namespace GUtil::DummyTest;

GUtil_MacrosTest::GUtil_MacrosTest()
{
}

void GUtil_MacrosTest::test_macros()
{
    TestClass tc;
    tc.SetMyInt(5);
    QVERIFY(tc.GetMyInt() == 5);

    tc.SetMyString("Hello!");
    QVERIFY(tc.GetMyString() != "Hi");
    QVERIFY(tc.GetMyString() == "Hello!");

    // Readonly Property
    QVERIFY(tc.GetMyReadOnlyInt() == 10);

    // Custom getters and setters:
    QVERIFY(tc.GetIsMeInsane());

    // Our setter does nothing
    tc.SetIsMeInsane(false);
    QVERIFY(tc.GetIsMeInsane());

    // A custom readonly property
    QVERIFY(tc.GetSexy());
}

QTEST_APPLESS_MAIN(GUtil_MacrosTest);

#include "tst_gutil_macrostest.moc"


text:
<?php
namespace Everyman\Neo4j;

class Client_TransactionTest extends \PHPUnit_Framework_TestCase
{
	protected $transport = null;
	protected $client = null;
	protected $endpoint = 'http://foo:1234/db/data';

	public function setUp()
	{
		$this->transport = $this->getMock('Everyman\Neo4j\Transport');
		$this->transport->expects($this->any())
			->method('getEndpoint')
			->will($this->returnValue($this->endpoint));

		$this->client = $this->getMock('Everyman\Neo4j\Client', array('hasCapability'), array($this->transport));
		$this->client->expects($this->any())
			->method('hasCapability')
			->will($this->returnValue(true));
	}

	public function testBeginTransaction_ReturnsNewTransactionWithNoId()
	{
		$result = $this->client->beginTransaction();
		self::assertInstanceOf('\Everyman\Neo4j\Transaction', $result);
		self::assertNull($result->getId());
	}

	public function testAddStatements_NewTransaction_ReturnsResultSetAndSetsTransactionId()
	{
		$queryTemplateA = "This is the query template";
		$queryParamsA = array('foo' => 'bar', 'baz' => 123);
		$queryA = new Cypher\Query($this->client, $queryTemplateA, $queryParamsA);

		$queryTemplateB = "This is the query template B";
		$queryParamsB = array('foo' => 'barB', 'bazB' => 456);
		$queryB = new Cypher\Query($this->client, $queryTemplateB, $queryParamsB);

		$transaction = new Transaction($this->client);

		$expectedRequest = array(
			'statements' => array(
				array(
					'statement'  => $queryTemplateA,
					'parameters' => (object)$queryParamsA,
					'resultDataContents' => array('rest'),
				),
				array(
					'statement'  => $queryTemplateB,
					'parameters' => (object)$queryParamsB,
					'resultDataContents' => array('rest'),
				),
			),
		);

		$expectedResponse = array(
			"commit" => $this->endpoint . '/transaction/987/commit',
			"transaction" => array("expires" => "Wed, 16 Oct 2013 23:07:12 +0000"),
			"errors" => array(),
			"results" => array(
				// Result of queryA
				array(
					'columns' => array('name','age'),
					'data' => array(
						array("rest" => array('Bob', 12)),
						array("rest" => array('Lotta', 0)),
						array("rest" => array('Brenda', 14)),
					)
				),
				// Result of queryB
				array(
					'columns' => array('count','somenode'),
					'data' => array(
						array("rest" => array(
							5,
							array(
								"self" => $this->endpoint.'/node/34',
								"data" => array("baz" => "qux"),
							)
						)),
						array("rest" => array(
							2,
							array(
								"self" => $this->endpoint.'/node/21',
								"data" => array("lorem" => "ipsum"),
							)
						)),
					)
				),
			),
		);

		$this->transport->expects($this->once())
			->method('post')
			->with('/transaction', $expectedRequest)
			->will($this->returnValue(array("code" => 201, "data" => $expectedResponse)));

		$result = $this->client->addStatementsToTransaction($transaction, array($queryA, $queryB));
		self::assertInternalType('array', $result);
		self::assertEquals(2, count($result));

		$resultA = $result[0];
		self::assertInstanceOf('\Everyman\Neo4j\Query\ResultSet', $resultA);
		self::assertEquals(3, count($resultA));
		self::assertEquals('Bob', $resultA[0]['name']);
		self::assertEquals(12, $resultA[0]['age']);

		$resultB = $result[1];
		self::assertInstanceOf('\Everyman\Neo4j\Query\ResultSet', $resultB);
		self::assertEquals(2, count($resultB));
		self::assertEquals(2, $resultB[1]['count']);
		self::assertInstanceOf('\Everyman\Neo4j\Node', $resultB[1]['somenode']);
		self::assertEquals(21, $resultB[1]['somenode']->getId());
		self::assertEquals('ipsum', $resultB[1]['somenode']->getProperty('lorem'));

		self::assertEquals(987, $transaction->getId());
		self::assertFalse($transaction->isClosed());
		self::assertFalse($transaction->isError());
	}

	public function testAddStatements_NoParams_ParamsSentAsEmptyObject()
	{
		$queryTemplateA = "This is the query template";
		$queryA = new Cypher\Query($this->client, $queryTemplateA);

		$transaction = new Transaction($this->client);

		$expectedRequest = array(
			'statements' => array(
				array(
					'statement'  => $queryTemplateA,
					'parameters' => (object)array(),
					'resultDataContents' => array('rest'),
				),
			),
		);

		$expectedResponse = array(
			"commit" => $this->endpoint . '/transaction/987/commit',
			"transaction" => array("expires" => "Wed, 16 Oct 2013 23:07:12 +0000"),
			"errors" => array(),
			"results" => array(
				// Result of queryA
				array(
					'columns' => array('name'),
					'data' => array(
						array("rest" => array('Brenda')),
					)
				),
			),
		);

		$this->transport->expects($this->once())
			->method('post')
			->with('/transaction', $expectedRequest)
			->will($this->returnValue(array("code" => 201, "data" => $expectedResponse)));

		$result = $this->client->addStatementsToTransaction($transaction, array($queryA));
		self::assertInternalType('array', $result);
		self::assertEquals(1, count($result));
	}

	public function testAddStatements_ExistingTransactionId_ReturnsResultSet()
	{
		$queryA = new Cypher\Query($this->client, 'foobar');

		$transaction = new Transaction($this->client);
		$transaction->setId(321);

		$expectedResponse = array(
			"commit" => $this->endpoint . '/transaction/321/commit',
			"transaction" => array("expires" => "Wed, 16 Oct 2013 23:07:12 +0000"),
			"errors" => array(),
			"results" => array(),
		);

		$this->transport->expects($this->once())
			->method('post')
			->with('/transaction/'.$transaction->getId())
			->will($this->returnValue(array("code" => 200, "data" => $expectedResponse)));

		$this->client->addStatementsToTransaction($transaction, array($queryA));
		self::assertFalse($transaction->isClosed());
		self::assertFalse($transaction->isError());
	}

	public function testAddStatements_TransactionFailed_ThrowsException()
	{
		$queryA = new Cypher\Query($this->client, 'foobar');
		$transaction = new Transaction($this->client);

		$expectedResponse = array(
			"commit" => $this->endpoint . '/transaction/321/commit',
			"transaction" => array("expires" => "Wed, 16 Oct 2013 23:07:12 +0000"),
			"errors" => array(),
			"results" => array(),
		);

		$this->transport->expects($this->once())
			->method('post')
			->with('/transaction')
			->will($this->returnValue(array("code" => 400)));

		$this->setExpectedException('\Everyman\Neo4j\Exception');
		$this->client->addStatementsToTransaction($transaction, array($queryA));
	}

	public function testAddStatements_ErrorsGiven_ThrowsException()
	{
		$queryA = new Cypher\Query($this->client, 'foobar');
		$transaction = new Transaction($this->client);

		$expectedResponse = array(
			"commit" => $this->endpoint . '/transaction/321/commit',
			"transaction" => array("expires" => "Wed, 16 Oct 2013 23:07:12 +0000"),
			"errors" => array("foo bar error"),
			"results" => array(),
		);

		$this->transport->expects($this->once())
			->method('post')
			->with('/transaction')
			->will($this->returnValue(array("code" => 200, "data" => $expectedResponse)));

		$this->setExpectedException('\Everyman\Neo4j\Exception');
		$this->client->addStatementsToTransaction($transaction, array($queryA));
	}

	public function testAddStatements_NewTransactionWithCommit_ReturnsResulSet()
	{
		$queryA = new Cypher\Query($this->client, 'foobar');
		$transaction = new Transaction($this->client);
		$commit = true;

		$expectedResponse = array(
			"errors" => array(),
			"results" => array(),
		);

		$this->transport->expects($this->once())
			->method('post')
			->with('/transaction/commit')
			->will($this->returnValue(array("code" => 200, "data" => $expectedResponse)));

		$this->client->addStatementsToTransaction($transaction, array($queryA), $commit);
	}

	public function testAddStatements_ExistingTransactionWithCommit_ReturnsResulSet()
	{
		$queryA = new Cypher\Query($this->client, 'foobar');
		$transaction = new Transaction($this->client);
		$transaction->setId(321);
		$commit = true;

		$expectedResponse = array(
			"commit" => $this->endpoint . '/transaction/321/commit',
			"transaction" => array("expires" => "Wed, 16 Oct 2013 23:07:12 +0000"),
			"errors" => array(),
			"results" => array(),
		);

		$this->transport->expects($this->once())
			->method('post')
			->with('/transaction/'.$transaction->getId().'/commit')
			->will($this->returnValue(array("code" => 200, "data" => $expectedResponse)));

		$this->client->addStatementsToTransaction($transaction, array($queryA), $commit);
	}

	public function testAddStatements_KeepAlive_HasTransactionId_SendsToTransportWithoutStatements()
	{
		$transaction = new Transaction($this->client);
		$transaction->setId(321);

		$expectedRequest = array(
			'statements' => array(),
		);

		$expectedResponse = array(
			"commit" => $this->endpoint . '/transaction/321/commit',
			"transaction" => array("expires" => "Wed, 16 Oct 2013 23:07:12 +0000"),
			"errors" => array(),
			"results" => array(),
		);

		$this->transport->expects($this->once())
			->method('post')
			->with('/transaction/'.$transaction->getId(), $expectedRequest)
			->will($this->returnValue(array("code" => 200, "data" => $expectedResponse)));

		$this->client->addStatementsToTransaction($transaction, array());
	}

	public function testAddStatements_KeepAlive_NoTransactionId_ThrowsException()
	{
		$transaction = new Transaction($this->client);

		$this->transport->expects($this->never())
			->method('post');

		$this->setExpectedException('\Everyman\Neo4j\Exception');
		$this->client->addStatementsToTransaction($transaction, array());
	}

	public function testAddStatements_NoTransactionCapability_ThrowsException()
	{
		$this->client = $this->getMock('Everyman\Neo4j\Client', array('hasCapability'), array($this->transport));
		$this->client->expects($this->any())
			->method('hasCapability')
			->will($this->returnValue(false));

		$queryA = new Cypher\Query($this->client, 'foobar');
		$transaction = new Transaction($this->client);

		$this->transport->expects($this->never())
			->method('post');

		$this->setExpectedException('\Everyman\Neo4j\Exception');
		$this->client->addStatementsToTransaction($transaction, array($queryA));
	}

	public function testRollback_HasTransactionId_SendsDelete()
	{
		$transaction = new Transaction($this->client);
		$transaction->setId(321);

		$this->transport->expects($this->once())
			->method('delete')
			->with('/transaction/'.$transaction->getId())
			->will($this->returnValue(array("code" => 200)));

		$this->client->rollbackTransaction($transaction);
	}

	public function testRollback_NoTransactionId_ThrowsException()
	{
		$transaction = new Transaction($this->client);

		$this->transport->expects($this->never())
			->method('delete');

		$this->setExpectedException('\Everyman\Neo4j\Exception');
		$this->client->rollbackTransaction($transaction);
	}

	public function testRollback_NoTransactionCapability_ThrowsException()
	{
		$this->client = $this->getMock('Everyman\Neo4j\Client', array('hasCapability'), array($this->transport));
		$this->client->expects($this->any())
			->method('hasCapability')
			->will($this->returnValue(false));

		$transaction = new Transaction($this->client);
		$transaction->setId(321);

		$this->transport->expects($this->never())
			->method('delete');

		$this->setExpectedException('\Everyman\Neo4j\Exception');
		$this->client->rollbackTransaction($transaction);
	}
}