text:
package org.apache.jmeter.gui.util;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;

import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JPanel;

public class HorizontalPanel extends JPanel {
    private static final long serialVersionUID = 240L;

    private final Box subPanel = Box.createHorizontalBox();

    private final float verticalAlign;

    private final int hgap;

    public HorizontalPanel() {
        this(5, CENTER_ALIGNMENT);
    }

    public HorizontalPanel(Color bk) {
        this();
        subPanel.setBackground(bk);
        this.setBackground(bk);
    }

    public HorizontalPanel(int hgap, float verticalAlign) {
        super(new BorderLayout());
        add(subPanel, BorderLayout.CENTER);
        this.hgap = hgap;
        this.verticalAlign = verticalAlign;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Component add(Component c) {
        // This won't work right if we remove components. But we don't, so I'm
        // not going to worry about it right now.
        if (hgap > 0 && subPanel.getComponentCount() > 0) {
            subPanel.add(Box.createHorizontalStrut(hgap));
        }

        if (c instanceof JComponent) {
            ((JComponent) c).setAlignmentY(verticalAlign);
        }
        return subPanel.add(c);
    }
}


text:
package email

import (
	"crypto/tls"
	"errors"
	"io"
	"net"
	"net/mail"
	"net/smtp"
	"net/textproto"
	"sync"
	"syscall"
	"time"
)

type Pool struct {
	addr         string
	auth         smtp.Auth
	max          int
	created      int
	clients      chan *client
	rebuild      chan struct{}
	mut          *sync.Mutex
	lastBuildErr *timestampedErr
	closing      chan struct{}
	tlsConfig    *tls.Config
}

type client struct {
	*smtp.Client
	failCount int
}

type timestampedErr struct {
	err error
	ts  time.Time
}

const maxFails = 4

var (
	ErrClosed  = errors.New("pool closed")
	ErrTimeout = errors.New("timed out")
)

func NewPool(address string, count int, auth smtp.Auth, opt_tlsConfig ...*tls.Config) (pool *Pool, err error) {
	pool = &Pool{
		addr:    address,
		auth:    auth,
		max:     count,
		clients: make(chan *client, count),
		rebuild: make(chan struct{}),
		closing: make(chan struct{}),
		mut:     &sync.Mutex{},
	}
	if len(opt_tlsConfig) == 1 {
		pool.tlsConfig = opt_tlsConfig[0]
	} else if host, _, e := net.SplitHostPort(address); e != nil {
		return nil, e
	} else {
		pool.tlsConfig = &tls.Config{ServerName: host}
	}
	return
}

// go1.1 didn't have this method
func (c *client) Close() error {
	return c.Text.Close()
}

func (p *Pool) get(timeout time.Duration) *client {
	select {
	case c := <-p.clients:
		return c
	default:
	}

	if p.created < p.max {
		p.makeOne()
	}

	var deadline <-chan time.Time
	if timeout < 0 {
		deadline = nil
	} else {
		deadline = time.After(timeout)
	}

	for {
		select {
		case c := <-p.clients:
			return c
		case <-p.rebuild:
			p.makeOne()
		case <-deadline:
			return nil
		case <-p.closing:
			return nil
		}
	}
}

func shouldReuse(err error) bool {
	// certainly not perfect, but might be close:
	//  - EOF: clearly, the connection went down
	//  - textproto.Errors were valid SMTP over a valid connection,
	//    but resulted from an SMTP error response
	//  - textproto.ProtocolErrors result from connections going down,
	//    invalid SMTP, that sort of thing
	//  - syscall.Errno is probably down connection/bad pipe, but
	//    passed straight through by textproto instead of becoming a
	//    ProtocolError
	//  - if we don't recognize the error, don't reuse the connection
	// A false positive will probably fail on the Reset(), and even if
	// not will eventually hit maxFails.
	// A false negative will knock over (and trigger replacement of) a
	// conn that might have still worked.
	if err == io.EOF {
		return false
	}
	switch err.(type) {
	case *textproto.Error:
		return true
	case *textproto.ProtocolError, textproto.ProtocolError:
		return false
	case syscall.Errno:
		return false
	default:
		return false
	}
}

func (p *Pool) replace(c *client) {
	p.clients <- c
}

func (p *Pool) inc() bool {
	if p.created >= p.max {
		return false
	}

	p.mut.Lock()
	defer p.mut.Unlock()

	if p.created >= p.max {
		return false
	}
	p.created++
	return true
}

func (p *Pool) dec() {
	p.mut.Lock()
	p.created--
	p.mut.Unlock()

	select {
	case p.rebuild <- struct{}{}:
	default:
	}
}

func (p *Pool) makeOne() {
	go func() {
		if p.inc() {
			if c, err := p.build(); err == nil {
				p.clients <- c
			} else {
				p.lastBuildErr = &timestampedErr{err, time.Now()}
				p.dec()
			}
		}
	}()
}

func startTLS(c *client, t *tls.Config) (bool, error) {
	if ok, _ := c.Extension("STARTTLS"); !ok {
		return false, nil
	}

	if err := c.StartTLS(t); err != nil {
		return false, err
	}

	return true, nil
}

func addAuth(c *client, auth smtp.Auth) (bool, error) {
	if ok, _ := c.Extension("AUTH"); !ok {
		return false, nil
	}

	if err := c.Auth(auth); err != nil {
		return false, err
	}

	return true, nil
}

func (p *Pool) build() (*client, error) {
	cl, err := smtp.Dial(p.addr)
	if err != nil {
		return nil, err
	}
	c := &client{cl, 0}

	if _, err := startTLS(c, p.tlsConfig); err != nil {
		c.Close()
		return nil, err
	}

	if p.auth != nil {
		if _, err := addAuth(c, p.auth); err != nil {
			c.Close()
			return nil, err
		}
	}

	return c, nil
}

func (p *Pool) maybeReplace(err error, c *client) {
	if err == nil {
		c.failCount = 0
		p.replace(c)
		return
	}

	c.failCount++
	if c.failCount >= maxFails {
		goto shutdown
	}

	if !shouldReuse(err) {
		goto shutdown
	}

	if err := c.Reset(); err != nil {
		goto shutdown
	}

	p.replace(c)
	return

shutdown:
	p.dec()
	c.Close()
}

func (p *Pool) failedToGet(startTime time.Time) error {
	select {
	case <-p.closing:
		return ErrClosed
	default:
	}

	if p.lastBuildErr != nil && startTime.Before(p.lastBuildErr.ts) {
		return p.lastBuildErr.err
	}

	return ErrTimeout
}

// Send sends an email via a connection pulled from the Pool. The timeout may
// be <0 to indicate no timeout. Otherwise reaching the timeout will produce
// and error building a connection that occurred while we were waiting, or
// otherwise ErrTimeout.
func (p *Pool) Send(e *Email, timeout time.Duration) (err error) {
	start := time.Now()
	c := p.get(timeout)
	if c == nil {
		return p.failedToGet(start)
	}

	defer func() {
		p.maybeReplace(err, c)
	}()

	recipients, err := addressLists(e.To, e.Cc, e.Bcc)
	if err != nil {
		return
	}

	msg, err := e.Bytes()
	if err != nil {
		return
	}

	from, err := emailOnly(e.From)
	if err != nil {
		return
	}
	if err = c.Mail(from); err != nil {
		return
	}

	for _, recip := range recipients {
		if err = c.Rcpt(recip); err != nil {
			return
		}
	}

	w, err := c.Data()
	if err != nil {
		return
	}
	if _, err = w.Write(msg); err != nil {
		return
	}

	err = w.Close()

	return
}

func emailOnly(full string) (string, error) {
	addr, err := mail.ParseAddress(full)
	if err != nil {
		return "", err
	}
	return addr.Address, nil
}

func addressLists(lists ...[]string) ([]string, error) {
	length := 0
	for _, lst := range lists {
		length += len(lst)
	}
	combined := make([]string, 0, length)

	for _, lst := range lists {
		for _, full := range lst {
			addr, err := emailOnly(full)
			if err != nil {
				return nil, err
			}
			combined = append(combined, addr)
		}
	}

	return combined, nil
}

// Close immediately changes the pool's state so no new connections will be
// created, then gets and closes the existing ones as they become available.
func (p *Pool) Close() {
	close(p.closing)

	for p.created > 0 {
		c := <-p.clients
		c.Quit()
		p.dec()
	}
}

redpajama_set_name: RedPajamaGithub


text: import 'antd/lib/checkbox/style/index'


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**ref_id** | **string** | A unique local identifier for this junction |
**label** | **string** |  |
**short_label** | **string** |  |
**local_type** | **string** |  | [optional]
**input_list** | [**\DataExchange\SIFUK20\Models\Input[]**](Input.md) |  |
**output_list** | [**\DataExchange\SIFUK20\Models\Output[]**](Output.md) |  |

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
Imports Leviathan.Caching
Namespace Configuration

	Public Class TypeConvertor

		#Region " Public Constants "

			''' <summary>
			''' Public Constant Reference to the Name of the ParseTypeFromString Method.
			''' </summary>
			''' <remarks></remarks>
			Public Const METHOD_PARSETYPEFROMSTRING As String = "ParseTypeFromString"

		#End Region

		#Region " Public Methods "

			''' <summary>
			''' Private Method Handling the Parsing of a Type Type.
			''' </summary>
			''' <param name="value">The String Value to Parse.</param>
			''' <param name="successfulParse">A ByRef/Out Parameter used to indicate whether the Parse was successfull or not.</param>
			''' <returns>The Parsed Object or Nothing.</returns>
			''' <remarks></remarks>
			Public Function ParseTypeFromString( _
				<ParsingInParameter()> ByVal value As String, _
				<ParsingSuccessParameter()> ByRef successfulParse As Boolean, _
				<ParsingTypeParameter()> ByVal typeToParseTo As Type _
			) As Object

				Dim cache As Simple = Simple.GetInstance(GetType(TypeConvertor).GetHashCode)

				Dim ret_Type As Type = Nothing

				If Not cache.TryGet(ret_Type, METHOD_PARSETYPEFROMSTRING.GetHashCode, value.GetHashCode) Then

					ret_Type = System.Type.GetType(value, False, True)

					If ret_Type Is Nothing Then

						Dim isArray As Boolean = value.EndsWith(SQUARE_BRACKET_START & SQUARE_BRACKET_END)

						If isArray Then value = value.TrimEnd(SQUARE_BRACKET_START, SQUARE_BRACKET_END)

						Dim search_Assembly As Assembly = Reflection.Assembly.GetEntryAssembly

						If search_Assembly Is Nothing Then _
							search_Assembly = Reflection.Assembly.GetCallingAssembly

						Dim types As System.Type() = Nothing

						If Not search_Assembly Is Nothing Then _
							types = AssemblyAnalyser.GetInstance(search_Assembly).FindType(value)

						If Not types Is Nothing AndAlso types.Length = 1 Then

							ret_Type = types(0)
							If isArray Then
								ret_Type = ret_Type.MakeArrayType
								value = value & SQUARE_BRACKET_START & SQUARE_BRACKET_END
							End If

						End If

					End If

					If ret_Type Is Nothing Then

						successfulParse = False
						Return Nothing

					Else

						cache.Set(ret_Type, METHOD_PARSETYPEFROMSTRING.GetHashCode, value.GetHashCode)

						successfulParse = True
						Return ret_Type

					End If

				Else

					successfulParse = True
					Return ret_Type

				End If

			End Function

		#End Region

	End Class

End Namespace


text:
package main

import (
	"github.com/drud/ddev/cmd/ddev/cmd"
	"github.com/drud/ddev/pkg/util"
	"os"
	"time"
)

func main() {
	runTime := util.TimeTrack(time.Now(), "main()")
	defer runTime()

	// Prevent running as root for most cases
	// We really don't want ~/.ddev to have root ownership, breaks things.
	if os.Geteuid() == 0 && len(os.Args) > 1 && os.Args[1] != "hostname" {
		util.Failed("ddev is not designed to be run with root privileges, please run as normal user and without sudo")
	}

	cmd.Execute()
}


text:
@interface PhoneBookContact : NSObject

//Input Properties
@property (strong, nonatomic) NSString *mobile;
@property (strong, nonatomic) NSString *name;

+ (PhoneBookContact *)contactWithName:(NSString *)name
                               mobile:(NSString *)mobile;

@end


text:
"""-------------------------------------------------
Satay Game Engine Copyright (C) 2013 Andy Brennan

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Satay on GitHub: https://github.com/Valdez42/Satay

 CreateWinEXE.py --
   Utility script to create a Windows executable from
   a main Satay game script. Uses py2exe for creation.
   This is a Windows-only utility.
-------------------------------------------------"""

import sys
import os
import webbrowser
import subprocess
import urllib2
import shutil
from zipfile import ZipFile

def CreatePromptCheck(*answers):
    return lambda prompt: raw_input(prompt).lower() in answers

Y = CreatePromptCheck('y', 'ye', 'yes')
N = CreatePromptCheck('n', 'no')

setup = """
# Auto-generated by Satay.Utilities.CreateWinEXE
from distutils.core import setup
import py2exe
import os

os.chdir(%r)
setup(
    console=[
        {
            "script":%r,
        }
    ]
)
"""

# Ensure the user has py2exe
try:
    import py2exe
except ImportError:
    print("You do not have py2exe installed.")
    if Y("Download py2exe? (y for yes): "):
        print("Choose the correct installer based on your python bit-type and version.")
        print("Once downloaded, run the installer, and then re-run this utility.")
        webbrowser.open("http://www.lfd.uci.edu/~gohlke/pythonlibs/#py2exe")
        sys.exit()
    else:
        print("You need py2exe to use this utility.")
        sys.exit()
else:
    print("py2exe exists, continuing.")

# Gather script location info
sdir = raw_input("Now point us to your main game script's folder (rel. or absolute dir):\n")
script = raw_input("What is the name of your game script? (e.g. agame.py):\n")
if Y("Do you have an icon to embed into your executable? (y for yes): "):
    icon = raw_input("What is the name of your .ico file?\n")
    iloc = setup.find('"script":%r,')
    setup = setup[0:iloc] + ' "icon_resources": [(0, %r)], ' % icon + setup[iloc:]

# Change CWD
os.chdir(sdir)
print('Changed working directory to "%s" ' % os.getcwd())

# Create the setup script
with open("setup_py2exe.py","w") as setupScript:
    setupScript.write(setup % (os.getcwd(), script))
print("Setup script created. Now running setup_py2exe.py...")

# Derive python path from os.__file__
dpos1 = os.__file__.rfind("\\")
dpos2 = os.__file__.rfind("\\", 0, dpos1 - 1)
pydir = os.__file__[0:dpos2+1]+"python.exe"

# Execute py2exe script
xcode = subprocess.call([pydir, os.getcwd()+"\\setup_py2exe.py", "py2exe"])

# Evaluate script's exit code, and remove script.
if Y("Cleanup unnecessary files? (y for yes): "):
    os.remove("./setup_py2exe.py")
    shutil.rmtree("./build")

if xcode == 0:
    print("Satay game built successfully.")
    print("The 'dist' folder in your game's directory contains your built program.")
    if Y("Do you need the MSVC90 DLL distro? (y for yes): "):
        print("Downloading and extracting the distro package to your dist directory...")
        request = urllib2.Request("http://www.fileden.com/files/2012/11/23/3369670/MSVC90_distro.zip")
        request.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11')
        with open("MSVC90_distro.zip", 'wb') as f:
            f.write(urllib2.urlopen(request).read())
        with ZipFile("MSVC90_distro.zip", 'r') as z:
            z.extractall("./dist")
        if Y("Cleanup .zip package? (y for yes): "):
            os.remove("./MSVC90_distro.zip")
    print("Your game is ready for distribution! Ensure you give people the entire 'dist' directory!")
    sys.exit()
else:
    print("py2exe failed with exit code %s" % xcode)
    sys.exit()


text:
import React from 'react';
import {expect} from 'chai';
import <%= componentName %> from './index';
import messages from './messages';
import { shallow, contains } from 'enzyme';

describe('<%= componentName %>', ()=>{
	describe("Tests", ()=>{
		it("has defined test", ()=>{
			expect(false).to.be.true;
		});
	});

	describe("i18n", ()=>{
		it("should not have placeholder message", ()=>{
			expect(messages.placeholderMsg).to.not.exist;
		});
	});
});


text:
import type {
  ValidationContext,
  SDLValidationContext,
} from '../ValidationContext';
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { DirectiveLocation } from '../../language/directiveLocation';
import type { ASTVisitor } from '../../language/visitor';
import { specifiedDirectives } from '../../type/directives';

export function unknownDirectiveMessage(directiveName: string): string {
  return `Unknown directive "${directiveName}".`;
}

export function misplacedDirectiveMessage(
  directiveName: string,
  location: string,
): string {
  return `Directive "${directiveName}" may not be used on ${location}.`;
}

/**
 * Known directives
 *
 * A GraphQL document is only valid if all `@directives` are known by the
 * schema and legally positioned.
 */
export function KnownDirectives(
  context: ValidationContext | SDLValidationContext,
): ASTVisitor {
  const locationsMap = Object.create(null);

  const schema = context.getSchema();
  const definedDirectives = schema
    ? schema.getDirectives()
    : specifiedDirectives;
  for (const directive of definedDirectives) {
    locationsMap[directive.name] = directive.locations;
  }

  const astDefinitions = context.getDocument().definitions;
  for (const def of astDefinitions) {
    if (def.kind === Kind.DIRECTIVE_DEFINITION) {
      locationsMap[def.name.value] = def.locations.map(name => name.value);
    }
  }

  return {
    Directive(node, key, parent, path, ancestors) {
      const name = node.name.value;
      const locations = locationsMap[name];

      if (!locations) {
        context.reportError(
          new GraphQLError(unknownDirectiveMessage(name), node),
        );
        return;
      }
      const candidateLocation = getDirectiveLocationForASTPath(ancestors);
      if (candidateLocation && locations.indexOf(candidateLocation) === -1) {
        context.reportError(
          new GraphQLError(
            misplacedDirectiveMessage(name, candidateLocation),
            node,
          ),
        );
      }
    },
  };
}

function getDirectiveLocationForASTPath(ancestors) {
  const appliedTo = ancestors[ancestors.length - 1];
  if (!Array.isArray(appliedTo)) {
    switch (appliedTo.kind) {
      case Kind.OPERATION_DEFINITION:
        switch (appliedTo.operation) {
          case 'query':
            return DirectiveLocation.QUERY;
          case 'mutation':
            return DirectiveLocation.MUTATION;
          case 'subscription':
            return DirectiveLocation.SUBSCRIPTION;
        }
        break;
      case Kind.FIELD:
        return DirectiveLocation.FIELD;
      case Kind.FRAGMENT_SPREAD:
        return DirectiveLocation.FRAGMENT_SPREAD;
      case Kind.INLINE_FRAGMENT:
        return DirectiveLocation.INLINE_FRAGMENT;
      case Kind.FRAGMENT_DEFINITION:
        return DirectiveLocation.FRAGMENT_DEFINITION;
      case Kind.VARIABLE_DEFINITION:
        return DirectiveLocation.VARIABLE_DEFINITION;
      case Kind.SCHEMA_DEFINITION:
      case Kind.SCHEMA_EXTENSION:
        return DirectiveLocation.SCHEMA;
      case Kind.SCALAR_TYPE_DEFINITION:
      case Kind.SCALAR_TYPE_EXTENSION:
        return DirectiveLocation.SCALAR;
      case Kind.OBJECT_TYPE_DEFINITION:
      case Kind.OBJECT_TYPE_EXTENSION:
        return DirectiveLocation.OBJECT;
      case Kind.FIELD_DEFINITION:
        return DirectiveLocation.FIELD_DEFINITION;
      case Kind.INTERFACE_TYPE_DEFINITION:
      case Kind.INTERFACE_TYPE_EXTENSION:
        return DirectiveLocation.INTERFACE;
      case Kind.UNION_TYPE_DEFINITION:
      case Kind.UNION_TYPE_EXTENSION:
        return DirectiveLocation.UNION;
      case Kind.ENUM_TYPE_DEFINITION:
      case Kind.ENUM_TYPE_EXTENSION:
        return DirectiveLocation.ENUM;
      case Kind.ENUM_VALUE_DEFINITION:
        return DirectiveLocation.ENUM_VALUE;
      case Kind.INPUT_OBJECT_TYPE_DEFINITION:
      case Kind.INPUT_OBJECT_TYPE_EXTENSION:
        return DirectiveLocation.INPUT_OBJECT;
      case Kind.INPUT_VALUE_DEFINITION:
        const parentNode = ancestors[ancestors.length - 3];
        return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION
          ? DirectiveLocation.INPUT_FIELD_DEFINITION
          : DirectiveLocation.ARGUMENT_DEFINITION;
    }
  }
}


text:
package com.lightcrafts.ui.browser.model;

import com.lightcrafts.image.ImageFileFilter;
import com.lightcrafts.utils.file.FileUtil;

import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Given a directory, this Thread polls image Files for changes in their
 * modification times and triggers appropriate refreshes on ImageDatums.
 */
class ImageListPoller implements Runnable {

    // The wait between scans for modifications, in milliseconds
    private final static long Interval = 3000;

    private ImageList list;

    private File directory;

    private Thread thread;

    private boolean pause;

    private boolean stop;

    ImageListPoller(ImageList list, File directory) {
        thread = new Thread(this, "Image List Poller");
        thread.setPriority(Thread.MIN_PRIORITY);
        this.list = list;
        this.directory = directory;
    }

    public void run() {
        while (! stop) {
            synchronized (this) {
                try {
                    poll();
                    wait(Interval);
                    if (pause) {
                        wait();
                    }
                }
                catch (Throwable e) {
                    if (e instanceof InterruptedException) {
                        // Probably a call to stop()
                        continue;
                    }
                    System.err.println("Error in ImageListPoller:");
                    e.printStackTrace();
                    // Keep going anyway
                }
            }
        }
    }

    void start() {
        if (! thread.isAlive()) {
            stop = false;
            thread.start();
        }
    }

    void stop() {
        stop = true;
        thread.interrupt();
    }

    // Blocks until the poller has paused.
    void pause() {
        synchronized (this) {
            pause = true;
        }
    }

    void resume() {
        synchronized (this) {
            pause = false;
            notifyAll();
        }
    }

    private void poll() {
        List<ImageDatum> data = list.getAllImageData();
        Set<File> listFiles = new HashSet<File>();
        for (Iterator<ImageDatum> i=data.iterator(); i.hasNext() && !stop; )  {
            ImageDatum datum = i.next();
            long oldTime = datum.getFileCacheTime();
            // If oldTime == 0, the datum is still initializing
            File file = datum.getFile();
            listFiles.add(file);
            if (oldTime > 0) {
                if (! file.isFile()) {
                    log("file disappeared", file);
                    list.removeImageData(datum);
                }
                else {
                    long newTime = file.lastModified();
                    if (newTime > oldTime) {
                        log("modification detected", file);
                        datum.refresh(false);
                        list.metadataChanged(datum);
                    }
                }
                File xmpFile = datum.getXmpFile();
                if (xmpFile == null) {
                    // XMP couldn't be determined, probably a metadata error
                    continue;
                }
                long oldXmpTime = datum.getXmpFileCacheTime();
                if (! xmpFile.isFile() && (oldXmpTime > 0)) {
                    log("XMP file disappeared", file);
                    datum.refresh(true);
                    list.metadataChanged(datum);
                }
                else if (xmpFile.lastModified() > oldXmpTime) {
                    log("XMP modification detected", file);
                    datum.refresh(true);
                    list.metadataChanged(datum);
                }
            }
        }
        File[] dirFiles =
            FileUtil.listFiles(directory, ImageFileFilter.INSTANCE, false );
        if (dirFiles != null) {
            for (int n=0; n<dirFiles.length && !stop; n++) {
                File file = dirFiles[n];
                if (! listFiles.contains(file)) {
                    log("file appeared", file);
                    list.addFile(file);
                }
            }
        }
    }

    private static void log(String message, File file) {
        System.out.println(message + " at " + file);
    }
}


text:
"""
Link Products Frame

Copyright (c) 2014, 2015 Andrew Hawkins

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

"""
Import Declarations
"""
import sqlite3
import threading as td
import wx

from forsteri.interface import data as idata
from forsteri.interface import sql as isql

"""
Constant Declarations
"""

"""
Frame Class
"""
class LinkFrame(wx.Frame):
    """
    """

    def __init__(self, *args, **kwargs):
        """
        Initialize the frame.

        Args:
          *args (): Any arguments to be passed directly to the super's
            constructor.
          **kwargs (): Any keyword arguments to be passed to the super's
            constructor.

        Returns:
          LinkFrame
        """

        ## Frame
        # Initialize by the parent's constructor.
        super(LinkFrame, self).__init__(*args, **kwargs)

        # Create the master panel.
        masterPanel = wx.Panel(self)

        # Create the master sizer.
        masterSizer = wx.BoxSizer(wx.VERTICAL)

        ## List Control
        # Create the list control.
        self.linkList = wx.ListCtrl(masterPanel, size=(300, 200),
            style=wx.LC_REPORT|wx.LC_HRULES|wx.LC_VRULES|wx.BORDER_SUNKEN)

        # Add columns to the list control.
        self.linkList.InsertColumn(0, "Old", width=145)
        self.linkList.InsertColumn(1, "New", width=145)

        # Bind the selection of an item to a function.
        self.linkList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelected)
        self.linkList.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.onSelected)
        self.linkList.Bind(wx.EVT_LEFT_DCLICK, self.onEdit)

        ## Manipulate Buttons
        # Create the manipulate sizer.
        manipSizer = wx.BoxSizer(wx.HORIZONTAL)

        # Create the buttons.
        self.addButton = wx.Button(masterPanel, id=wx.ID_ADD)
        self.editButton = wx.Button(masterPanel, id=wx.ID_EDIT)
        self.deleteButton = wx.Button(masterPanel, id=wx.ID_DELETE)

        # Add the buttons to the manipulate sizer.
        manipSizer.AddMany([self.addButton, (5, 0), self.editButton, (5, 0),
            self.deleteButton])

        # Bind button presses to functions.
        self.addButton.Bind(wx.EVT_BUTTON, self.onAdd)
        self.editButton.Bind(wx.EVT_BUTTON, self.onEdit)
        self.deleteButton.Bind(wx.EVT_BUTTON, self.onDelete)

        ## Finish Buttons
        # Create the finish sizer.
        finishSizer = wx.BoxSizer(wx.HORIZONTAL)

        # Create the buttons.
        okButton = wx.Button(masterPanel, id=wx.ID_OK)
        cancelButton = wx.Button(masterPanel, id=wx.ID_CANCEL)

        # Set the ok button to be the dafault button.
        okButton.SetDefault()

        # Add the buttons to the finish sizer.
        finishSizer.AddMany([okButton, (5, 0), cancelButton])

        # Bind the button presses to function.
        okButton.Bind(wx.EVT_BUTTON, self.onOK)
        cancelButton.Bind(wx.EVT_BUTTON, self.onCancel)

        ## Key Bindings
        # Create a new id for selecting all.
        selectAllId = wx.NewId()

        # Bind the id to a function.
        self.Bind(wx.EVT_MENU, self.selectAll, id=selectAllId)

        # Create a new accelerator table and set it to the frame.
        accelT = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord("A"), selectAllId)])
        self.SetAcceleratorTable(accelT)

        ## Frame Operations
        # Add everything to the master sizer.
        masterSizer.AddSpacer(10)
        masterSizer.Add(self.linkList, flag=wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER,
            border=5)
        masterSizer.Add(manipSizer, flag=wx.TOP|wx.ALIGN_CENTER, border=10)
        masterSizer.AddSpacer(9)
        masterSizer.Add(wx.StaticLine(masterPanel, size=(312, 2)),
            flag=wx.ALIGN_CENTER)
        masterSizer.AddSpacer(9)
        masterSizer.Add(finishSizer, flag=wx.RIGHT|wx.BOTTOM|wx.ALIGN_RIGHT,
            border=5)

        # Open a connection to the database.
        self.connection = sqlite3.connect(isql.MASTER)
        self.connection2 = sqlite3.connect(idata.MASTER)

        # Update the displayed list.
        self.initializeList(None)

        # Set the sizer for the master panel.
        masterPanel.SetSizer(masterSizer)

        # Bind closing the frame to a function.
        self.Bind(wx.EVT_CLOSE, self.onClose)

        # Set window properties.
        self.SetSize((328, 333))
        self.SetTitle("Link Products")
        self.Centre()
        self.Show(True)

    """
    Event Handlers
    """
    def initializeList(self, event):
        """
        """

        # Get the list of links.
        links = isql.getLinks(self.connection)

        # Iterate over the list and add each to the control.
        index = 0
        for (old, new) in links:
            # Add the items to the list control.
            self.linkList.InsertStringItem(index, old)
            self.linkList.SetStringItem(index, 1, new)

            # Increment the index.
            index += 1

    def updateList(self, event):
        """
        """

        # Get the list of links.
        links = isql.getLinks(self.connection)

        # Remove all items from the list control.
        self.linkList.DeleteAllItems()

        # Update the selected colors.
        self.onSelected(event)

        # Iterate over the list and add each to the control.
        index = 0
        for (old, new) in links:
            # Add the items to the list control.
            self.linkList.InsertItem(index, old)
            self.linkList.SetItem(index, 1, new)

            # Increment the index.
            index += 1

    def onSelected(self, event):
        """
        """

        # If multiple products are selected, set the edit and delete buttons
        # to be yellow.
        if self.linkList.GetSelectedItemCount() > 1:
            self.editButton.Disable()
            self.deleteButton.SetBackgroundColour("Yellow")
        # If only one product is selected, set the edit and delete buttons
        # to be the default color.
        else:
            self.editButton.Enable()
            self.deleteButton.SetBackgroundColour(wx.NullColour)

    def selectAll(self, event):
        """
        """

        # Iterate through the items in the list selecting each.
        for i in range(0, self.linkList.GetItemCount()):
            self.linkList.Select(i)

    def onAdd(self, event):
        """
        """

        # Create the dialog box.
        linkDlg = LinkDialog(self, title="Add Link")

        # Show the link dialog box.
        if linkDlg.ShowModal() == wx.ID_CANCEL:
            return

        # Get the selections from the dialog boxes.
        (old, new) = linkDlg.getSelection()

        # Destroy the dialog box.
        linkDlg.Destroy()

        # If either input is an empty string, show an error.
        if old == '' or new == '':
            errorDialog = wx.MessageDialog(self,
                "One of the entries was empty.", "Error", wx.OK|wx.ICON_ERROR)
            errorDialog.ShowModal()

            return

        # Add the link to the database.
        isql.addLink(old, new, self.connection)

        # Add the data link.
        idata.linkData(old, new, self.connection2)

        # Update the link list.
        self.updateList(event)

    def onEdit(self, event):
        """
        """

        # Create the dialog box.
        linkDlg = LinkDialog(self, title="Add Link")

        # Get the selected data.
        index = self.linkList.GetFirstSelected()

        # If nothing is selected, send an error.
        if index == -1:
            errorDialog = wx.MessageDialog(self, "No item was selected.",
                "Error", wx.OK|wx.ICON_ERROR)
            errorDialog.ShowModal()

            return

        # Get the string value of the old product.
        old1 = self.linkList.GetItemText(index)
        new1 = self.linkList.GetItemText(index, 1)

        # Set the text in the link dialog.
        linkDlg.setSelection(old1, new1)

        # Show the link dialog box.
        if linkDlg.ShowModal() == wx.ID_CANCEL:
            return

        # Get the selections from the dialog boxes.
        (old2, new2) = linkDlg.getSelection()

        # Destroy the dialog box.
        linkDlg.Destroy()

        # If either input is an empty string, show an error.
        if old2 == '' or new2 == '':
            errorDialog = wx.MessageDialog(self,
                "One of the entries was empty.", "Error", wx.OK|wx.ICON_ERROR)
            errorDialog.ShowModal()

            return

        # Edit the link in the database.
        if old1 == old2 and new1 == new2:
            pass
        elif old1 != old2 and new1 == new2:
            isql.setLink(old2, new2, 1, self.connection)
            idata.unlinkData(old1, new1, self.connection2)
            idata.linkData(old2, new2, self.connection2)
        elif old1 == old2 and new1 != new2:
            isql.setLink(old2, new2, 2, self.connection)
            idata.unlinkData(old1, new1, self.connection2)
            idata.linkData(old2, new2, self.connection2)
        else:
            isql.setLink(old2, new2, old1, self.connection)
            idata.unlinkData(old1, new1, self.connection2)
            idata.linkData(old2, new2, self.connection2)

        # Update the link list
        self.updateList(event)

    def onDelete(self, event):
        """
        """

        # Get the selected data.
        index = self.linkList.GetFirstSelected()

        # If nothing is selected, send an error.
        if index == -1:
            errorDialog = wx.MessageDialog(self, "No item was selected.",
                "Error", wx.OK|wx.ICON_ERROR)
            errorDialog.ShowModal()

            return False

        # Get the string value of the old product.
        old = self.linkList.GetItemText(index)
        new = self.linkList.GetItemText(index, 1)

        # Iterate until all selected are removed.
        run = True
        while run:
            # Remove the link from the database.
            isql.removeLink(old, new, self.connection)

            # Remove the data link.
            idata.unlinkData(old, new, self.connection2)

            # Get the next index.
            index = self.linkList.GetNextSelected(index)

            # If there is no next index stop the loop.
            if index == -1:
                run = False
            else:
                old = self.linkList.GetItemText(index)
                new = self.linkList.GetItemText(index, 1)

        # Update the link list.
        self.updateList(event)

    def onOK(self, event):
        """
        """

        # Commit and close the database.
        self.connection.commit()
        self.connection.close()
        self.connection2.commit()
        self.connection2.close()

        self.Close()

    def onCancel(self, event):
        """
        """

        # Close the database.
        self.connection.close()
        self.connection2.close()

        self.Close()

    def onClose(self, event):
        """
        """

        self.Destroy()

"""
"""
class LinkDialog(wx.Dialog):
    """
    """

    def __init__(self, *args, **kwargs):
        """
        """

        # Initialize by the parent's constructor.
        super(LinkDialog, self).__init__(*args, **kwargs)

        # Create the master panel.
        masterPanel = wx.Panel(self)

        # Create the master sizer.
        masterSizer = wx.BoxSizer(wx.VERTICAL)

        # Create the box sizers.
        oldSizer = wx.BoxSizer(wx.HORIZONTAL)
        newSizer = wx.BoxSizer(wx.HORIZONTAL)

        # Create the static text.
        oldLabel = wx.StaticText(masterPanel, label="Old Product")
        newLabel = wx.StaticText(masterPanel, label="New Product")

        # Create the old and new text entries.
        self.oldEntry = wx.TextCtrl(masterPanel, size=(150, -1))
        self.newEntry = wx.TextCtrl(masterPanel, size=(150, -1))

        # Add the label and entries to the sizers.
        oldSizer.AddMany([oldLabel, (5, 0), self.oldEntry])
        newSizer.AddMany([newLabel, (5, 0), self.newEntry])

        # Get the choices for auto complete.
        links = self.getChoices()

        # Set the auto complete for the text entries.
        self.oldEntry.AutoComplete(links)
        self.newEntry.AutoComplete(links)

        # Create the finish sizer.
        finishSizer = wx.BoxSizer(wx.HORIZONTAL)

        # Create the finish buttons.
        okButton = wx.Button(masterPanel, id=wx.ID_OK)
        cancelButton = wx.Button(masterPanel, id=wx.ID_CANCEL)

        # Set the OK button to be the dafault button.
        okButton.SetDefault()

        # Add the finish buttons to the sizer.
        finishSizer.AddMany([okButton, (5, 0), cancelButton])

        # Add the text and combo box to the sizer.
        masterSizer.AddSpacer(10)
        masterSizer.Add(oldSizer, flag=wx.LEFT|wx.BOTTOM|wx.RIGHT|
            wx.ALIGN_RIGHT, border=5)
        masterSizer.Add(newSizer, flag=wx.LEFT|wx.RIGHT|wx.ALIGN_RIGHT,
            border=5)
        masterSizer.Add(wx.StaticLine(masterPanel, size=(240, 20)),
            flag=wx.ALIGN_CENTER)
        masterSizer.Add(finishSizer, flag=wx.RIGHT|wx.BOTTOM|wx.ALIGN_RIGHT,
            border=5)

        # Set the master sizer.
        masterPanel.SetSizer(masterSizer)

        # Set the size of the window.
        self.SetSize((250, 150))

    def getChoices(self):
        """
        """

        # Get the list of variables.
        links = isql.getAttribute("product")

        # Extract only the first column.
        links = [link[0] for link in links]

        return links

    def getSelection(self):
        """
        """

        # Get the value of the text entries.
        old = self.oldEntry.GetValue()
        new = self.newEntry.GetValue()

        return old, new

    def setSelection(self, old, new):
        """
        """

        # Set the value of the text entries.
        self.oldEntry.SetValue(old)
        self.newEntry.SetValue(new)

        return True

"""
Start Application
"""
def main():
    """
    When the file is called independently create and display the manager frame.
    """

    app = wx.App()
    LinkFrame(None, style=wx.DEFAULT_FRAME_STYLE)#^wx.RESIZE_BORDER)
    app.MainLoop()

if __name__ == '__main__':
    main()


text:
define([
    'underscore',
    'backbone'
], function (_, Backbone) {
    var ProjectGridView = Backbone.View.extend({
        el: $(contentContainer),

        render: function () {
            var that = this,
                viewConfig = this.attributes.viewConfig,
                pagerOptions = viewConfig['pagerOptions'];

            var projectsRemoteConfig = {
                url: ctwc.getProjectsURL(ctwc.DEFAULT_DOMAIN),
                type: 'GET'
            };

            cowu.renderView4Config(that.$el, this.model, getProjectListViewConfig(projectsRemoteConfig, pagerOptions));
        }
    });

    var getProjectListViewConfig = function (projectsRemoteConfig, pagerOptions) {
        return {
            elementId: cowu.formatElementId([ctwl.MONITOR_PROJECT_LIST_VIEW_ID]),
            view: "SectionView",
            viewConfig: {
                rows: [
                    {
                        columns: [
                            {
                                elementId: ctwl.PROJECTS_GRID_ID,
                                title: ctwl.TITLE_PROJECTS,
                                view: "GridView",
                                viewConfig: {
                                    elementConfig: getProjectGridConfig(projectsRemoteConfig, pagerOptions)
                                }
                            }
                        ]
                    }
                ]
            }
        }
    };

    var getProjectGridConfig = function (projectsRemoteConfig, pagerOptions) {
        var gridElementConfig = {
            header: {
                title: {
                    text: ctwl.TITLE_PROJECTS_SUMMARY
                },
                defaultControls: {
                    collapseable: false,
                    exportable: true,
                    refreshable: true,
                    searchable: true
                }
            },
            body: {
                options: {
                    autoRefresh: false,
                    checkboxSelectable: false,
                    detail: {
                        template: cowu.generateDetailTemplateHTML(getProjectDetailsTemplateConfig(), cowc.APP_CONTRAIL_CONTROLLER)
                    },
                    fixedRowHeight: 30
                },
                dataSource: {
                    remote: {
                        ajaxConfig: projectsRemoteConfig,
                        hlRemoteConfig: nmwgc.getProjectDetailsHLazyRemoteConfig(),
                        dataParser: nmwp.projectDataParser
                    },
                    cacheConfig: {
                        ucid: ctwc.UCID_DEFAULT_DOMAIN_PROJECT_LIST // TODO: Handle multi-tenancy
                    }
                }
            },
            columnHeader: {
                columns: nmwgc.projectsColumns
            },
            footer: {
                pager: contrail.handleIfNull(pagerOptions, { options: { pageSize: 5, pageSizeSelect: [5, 10, 50, 100] } })
            }
        };
        return gridElementConfig;
    };

    function getProjectDetailsTemplateConfig() {
        return {
            templateGenerator: 'RowSectionTemplateGenerator',
            templateGeneratorConfig: {
                rows: [
                    {
                        templateGenerator: 'ColumnSectionTemplateGenerator',
                        templateGeneratorConfig: {
                            columns: [
                                {
                                    class: 'span6',
                                    rows: [
                                        {
                                            title: ctwl.TITLE_PROJECT_DETAILS,
                                            templateGenerator: 'BlockListTemplateGenerator',
                                            templateGeneratorConfig: [
                                                {
                                                    key: 'name',
                                                    templateGenerator: 'TextGenerator'
                                                },
                                                {
                                                    key: 'vnCnt',
                                                    templateGenerator: 'TextGenerator'
                                                },
                                                {
                                                    key: 'instCnt',
                                                    templateGenerator: 'TextGenerator'
                                                },
                                                {
                                                    key: 'intfCnt',
                                                    templateGenerator: 'TextGenerator'
                                                }
                                            ]
                                        }
                                    ]
                                },
                                {
                                    class: 'span6',
                                    rows: [
                                        {
                                            title: ctwl.TITLE_TRAFFIC_DETAILS,
                                            templateGenerator: 'BlockListTemplateGenerator',
                                            templateGeneratorConfig: [
                                                {
                                                    key: 'throughput',
                                                    templateGenerator: 'TextGenerator',
                                                    templateGeneratorConfig: {
                                                        formatter: 'throughput'
                                                    }
                                                },
                                                {
                                                    key: 'ingressFlowCount',
                                                    templateGenerator: 'TextGenerator'
                                                },
                                                {
                                                    key: 'egressFlowCount',
                                                    templateGenerator: 'TextGenerator'
                                                }
                                                /*
                                                {
                                                    key: 'inBytes',
                                                    templateGenerator: 'TextGenerator',
                                                    templateGeneratorConfig: {
                                                        formatter: 'byte'
                                                    }
                                                },
                                                {
                                                    key: 'outBytes',
                                                    templateGenerator: 'TextGenerator',
                                                    templateGeneratorConfig: {
                                                        formatter: 'byte'
                                                    }
                                                }
                                                {
                                                    key: 'inTpkts',
                                                    templateGenerator: 'TextGenerator'
                                                },
                                                {
                                                    key: 'outTpkts',
                                                    templateGenerator: 'TextGenerator'
                                                }
                                                */
                                            ]
                                        }
                                    ]
                                }
                            ]
                        }
                    }
                ]
            }
        };
    };

    return ProjectGridView;
});


text:
package org.apache.ibatis.type;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.io.ResolverUtil;
import org.apache.ibatis.io.Resources;

public class TypeAliasRegistry {

  private final HashMap<String, Class<?>> TYPE_ALIASES = new HashMap<String, Class<?>>();

  public TypeAliasRegistry() {
    registerAlias("string", String.class);

    registerAlias("byte", Byte.class);
    registerAlias("long", Long.class);
    registerAlias("short", Short.class);
    registerAlias("int", Integer.class);
    registerAlias("integer", Integer.class);
    registerAlias("double", Double.class);
    registerAlias("float", Float.class);
    registerAlias("boolean", Boolean.class);

    registerAlias("byte[]", Byte[].class);
    registerAlias("long[]", Long[].class);
    registerAlias("short[]", Short[].class);
    registerAlias("int[]", Integer[].class);
    registerAlias("integer[]", Integer[].class);
    registerAlias("double[]", Double[].class);
    registerAlias("float[]", Float[].class);
    registerAlias("boolean[]", Boolean[].class);

    registerAlias("_byte", byte.class);
    registerAlias("_long", long.class);
    registerAlias("_short", short.class);
    registerAlias("_int", int.class);
    registerAlias("_integer", int.class);
    registerAlias("_double", double.class);
    registerAlias("_float", float.class);
    registerAlias("_boolean", boolean.class);

    registerAlias("_byte[]", byte[].class);
    registerAlias("_long[]", long[].class);
    registerAlias("_short[]", short[].class);
    registerAlias("_int[]", int[].class);
    registerAlias("_integer[]", int[].class);
    registerAlias("_double[]", double[].class);
    registerAlias("_float[]", float[].class);
    registerAlias("_boolean[]", boolean[].class);

    registerAlias("date", Date.class);
    registerAlias("decimal", BigDecimal.class);
    registerAlias("bigdecimal", BigDecimal.class);
    registerAlias("biginteger", BigInteger.class);
    registerAlias("object", Object.class);

    registerAlias("date[]", Date[].class);
    registerAlias("decimal[]", BigDecimal[].class);
    registerAlias("bigdecimal[]", BigDecimal[].class);
    registerAlias("biginteger[]", BigInteger[].class);
    registerAlias("object[]", Object[].class);

    registerAlias("map", Map.class);
    registerAlias("hashmap", HashMap.class);
    registerAlias("list", List.class);
    registerAlias("arraylist", ArrayList.class);
    registerAlias("collection", Collection.class);
    registerAlias("iterator", Iterator.class);

    registerAlias("ResultSet", ResultSet.class);
  }

  @SuppressWarnings("unchecked")
  // throws class cast exception as well if types cannot be assigned
  public <T> Class<T> resolveAlias(String string) {
    try {
      if (string == null) return null;
      String key = string.toLowerCase(Locale.ENGLISH); // issue #748
      Class<T> value;
      if (TYPE_ALIASES.containsKey(key)) {
        value = (Class<T>) TYPE_ALIASES.get(key);
      } else {
        value = (Class<T>) Resources.classForName(string);
      }
      return value;
    } catch (ClassNotFoundException e) {
      throw new TypeException("Could not resolve type alias '" + string + "'.  Cause: " + e, e);
    }
  }

  public void registerAliases(String packageName){
    registerAliases(packageName, Object.class);
  }

  public void registerAliases(String packageName, Class<?> superType){
    ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
    resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
    Set<Class<? extends Class<?>>> typeSet = resolverUtil.getClasses();
    for(Class<?> type : typeSet){
      //Ignore inner classes and interfaces (including package-info.java)
      if (!type.isAnonymousClass() && !type.isInterface()) {
        registerAlias(type);
      }
    }
  }

  public void registerAlias(Class<?> type) {
    String alias = type.getSimpleName();
    Alias aliasAnnotation = type.getAnnotation(Alias.class);
    if (aliasAnnotation != null) {
      alias = aliasAnnotation.value();
    }
    registerAlias(alias, type);
  }

  public void registerAlias(String alias, Class<?> value) {
    if (alias == null) throw new TypeException("The parameter alias cannot be null");
    String key = alias.toLowerCase(Locale.ENGLISH); // issue #748
    if (TYPE_ALIASES.containsKey(key) && TYPE_ALIASES.get(key) != null && !TYPE_ALIASES.get(key).equals(value)) {
      throw new TypeException("The alias '" + alias + "' is already mapped to the value '" + TYPE_ALIASES.get(key).getName() + "'.");
    }
    TYPE_ALIASES.put(key, value);
  }

  public void registerAlias(String alias, String value) {
    try {
      registerAlias(alias, Resources.classForName(value));
    } catch (ClassNotFoundException e) {
      throw new TypeException("Error registering type alias "+alias+" for "+value+". Cause: " + e, e);
    }
  }

}


text:
---
layout: post
title: How to get latest entries from MongoDB collection with Mongoose
description: "Example on how to retrieve the latest entries from a MongoDB collection. Two possibilities are presented."
author: ama
permalink: /ama/how-to-get-latest-entries-from-mongodb-collection-with-mongoose
published: true
categories: [mongodb]
tags: [codingmarks, mongodb, mongoose, nodejs]
---

I have a use case where I need to retrieve the latest added public [codingmarks](https://github.com/Codingpedia/codingmarks).
They are store in a mongo database, and I use Mongoose as ORM.

I want to have two possibilites to achieve this:

1. specify the number of days to look back
2. specify the timestamp since when to look forward

I think the code is self explanatory
```
/**
 * Returns the codingmarks added recently.
 *
 * The since query parameter is a timestamp which specifies the date since we want to look forward to present time.
 * If this parameter is present it has priority. If it is not present, we might specify the number of days to look back via
 * the query parameter numberOfDays. If not present it defaults to 7 days, last week.
 *
 */
router.get('/latest-entries', async (req, res) => {
  try
  {

    if(req.query.since) {
      const bookmarks = await Bookmark.find(
        {
          createdAt: { $gte: new Date(parseFloat(req.query.since,0)) }
        }).sort({createdAt: 'desc'}).lean().exec();

      res.send(bookmarks);
    } else {
      const numberOfDaysToLookBack = req.query.days ? req.query.days : 7;

      const bookmarks = await Bookmark.find(
        {
          createdAt: { $gte: new Date((new Date().getTime() - (numberOfDaysToLookBack * 24 * 60 * 60 * 1000))) }
        }).sort({createdAt: 'desc'}).lean().exec();

      res.send(bookmarks);
    }

  }
  catch (err)
  {
    return res.status(500).send(err);
  }
});
```


text:
import { NgModule, Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
import { environment } from '../../../environments/environment';

@Injectable()
export class SocketLogs extends Socket {
    constructor() {
        super({ url: environment.socketio_url+'/logs', options: {autoConnect:false} });
    }
}

@Injectable()
export class SocketLogsStatistics extends Socket {
    constructor() {
        super({ url: environment.socketio_url+'/logs_statistics', options: {autoConnect:false} });
    }
}

@Injectable()
export class SocketJobs extends Socket {
    constructor() {
        super({ url: environment.socketio_url+'/jobs', options: {autoConnect:false} });
    }
}

@Injectable()
export class SocketInstance extends Socket {
    constructor() {
        super({ url: environment.socketio_url+'/instance', options: {autoConnect:false} });
    }
}

@NgModule({
  imports: [
    SocketIoModule,
  ],
  providers: [
    SocketLogs,
    SocketLogsStatistics,
    SocketJobs,
    SocketInstance,
  ],
})

export class SocketsModule {}


text:
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;

namespace SelfLoadRO.Business.ERLevel
{

    ///
    /// C06Level111 (read only object).

    /// This is a generated base class of <see cref="C06Level111"/> business object.
    ///
    /// <remarks>
    /// This class contains one child collection:

    /// - <see cref="C07Level1111Objects"/> of type <see cref="C07Level1111Coll"/> (1:M relation to <see cref="C08Level1111"/>)

    /// This class is an item of <see cref="C05Level111Coll"/> collection.
    /// </remarks>
    [Serializable]
    public partial class C06Level111 : ReadOnlyBase<C06Level111>
    {

        #region State Fields

        [NotUndoable]
        private byte[] _rowVersion = new byte[] {};

        #endregion

        #region Business Properties

        ///
        /// Maintains metadata about <see cref="Level_1_1_1_ID"/> property.
        ///
        public static readonly PropertyInfo<int> Level_1_1_1_IDProperty = RegisterProperty<int>(p => p.Level_1_1_1_ID, "Level_1_1_1 ID", -1);
        ///
        /// Gets the Level_1_1_1 ID.
        ///
        /// <value>The Level_1_1_1 ID.</value>
        public int Level_1_1_1_ID
        {
            get { return GetProperty(Level_1_1_1_IDProperty); }
        }

        ///
        /// Maintains metadata about <see cref="Level_1_1_1_Name"/> property.
        ///
        public static readonly PropertyInfo<string> Level_1_1_1_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_Name, "Level_1_1_1 Name");
        ///
        /// Gets the Level_1_1_1 Name.
        ///
        /// <value>The Level_1_1_1 Name.</value>
        public string Level_1_1_1_Name
        {
            get { return GetProperty(Level_1_1_1_NameProperty); }
        }

        ///
        /// Maintains metadata about <see cref="MarentID1"/> property.
        ///
        public static readonly PropertyInfo<int> MarentID1Property = RegisterProperty<int>(p => p.MarentID1, "Marent ID1");
        ///
        /// Gets the Marent ID1.
        ///
        /// <value>The Marent ID1.</value>
        public int MarentID1
        {
            get { return GetProperty(MarentID1Property); }
        }

        ///
        /// Maintains metadata about child <see cref="C07Level1111SingleObject"/> property.
        ///
        public static readonly PropertyInfo<C07Level1111Child> C07Level1111SingleObjectProperty = RegisterProperty<C07Level1111Child>(p => p.C07Level1111SingleObject, "A7 Level1111 Single Object");
        ///
        /// Gets the C07 Level1111 Single Object ("self load" child property).
        ///
        /// <value>The C07 Level1111 Single Object.</value>
        public C07Level1111Child C07Level1111SingleObject
        {
            get { return GetProperty(C07Level1111SingleObjectProperty); }
            private set { LoadProperty(C07Level1111SingleObjectProperty, value); }
        }

        ///
        /// Maintains metadata about child <see cref="C07Level1111ASingleObject"/> property.
        ///
        public static readonly PropertyInfo<C07Level1111ReChild> C07Level1111ASingleObjectProperty = RegisterProperty<C07Level1111ReChild>(p => p.C07Level1111ASingleObject, "A7 Level1111 ASimple Object");
        ///
        /// Gets the C07 Level1111 ASingle Object ("self load" child property).
        ///
        /// <value>The C07 Level1111 ASingle Object.</value>
        public C07Level1111ReChild C07Level1111ASingleObject
        {
            get { return GetProperty(C07Level1111ASingleObjectProperty); }
            private set { LoadProperty(C07Level1111ASingleObjectProperty, value); }
        }

        ///
        /// Maintains metadata about child <see cref="C07Level1111Objects"/> property.
        ///
        public static readonly PropertyInfo<C07Level1111Coll> C07Level1111ObjectsProperty = RegisterProperty<C07Level1111Coll>(p => p.C07Level1111Objects, "A7 Level1111 Objects");
        ///
        /// Gets the C07 Level1111 Objects ("self load" child property).
        ///
        /// <value>The C07 Level1111 Objects.</value>
        public C07Level1111Coll C07Level1111Objects
        {
            get { return GetProperty(C07Level1111ObjectsProperty); }
            private set { LoadProperty(C07Level1111ObjectsProperty, value); }
        }

        #endregion

        #region Factory Methods

        ///
        /// Factory method. Loads a <see cref="C06Level111"/> object from the given SafeDataReader.
        ///
        /// <param name="dr">The SafeDataReader to use.</param>
        /// <returns>A reference to the fetched <see cref="C06Level111"/> object.</returns>
        internal static C06Level111 GetC06Level111(SafeDataReader dr)
        {
            C06Level111 obj = new C06Level111();
            obj.Fetch(dr);
            return obj;
        }

        #endregion

        #region Constructor

        ///
        /// Initializes a new instance of the <see cref="C06Level111"/> class.
        ///
        /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
        private C06Level111()
        {
            // Prevent direct creation
        }

        #endregion

        #region Data Access

        ///
        /// Loads a <see cref="C06Level111"/> object from the given SafeDataReader.
        ///
        /// <param name="dr">The SafeDataReader to use.</param>
        private void Fetch(SafeDataReader dr)
        {
            // Value properties
            LoadProperty(Level_1_1_1_IDProperty, dr.GetInt32("Level_1_1_1_ID"));
            LoadProperty(Level_1_1_1_NameProperty, dr.GetString("Level_1_1_1_Name"));
            LoadProperty(MarentID1Property, dr.GetInt32("MarentID1"));
            _rowVersion = (dr.GetValue("RowVersion")) as byte[];
            var args = new DataPortalHookArgs(dr);
            OnFetchRead(args);
        }

        ///
        /// Loads child objects.
        ///
        internal void FetchChildren()
        {
            LoadProperty(C07Level1111SingleObjectProperty, C07Level1111Child.GetC07Level1111Child(Level_1_1_1_ID));
            LoadProperty(C07Level1111ASingleObjectProperty, C07Level1111ReChild.GetC07Level1111ReChild(Level_1_1_1_ID));
            LoadProperty(C07Level1111ObjectsProperty, C07Level1111Coll.GetC07Level1111Coll(Level_1_1_1_ID));
        }

        #endregion

        #region Pseudo Events

        ///
        /// Occurs after the low level fetch operation, before the data reader is destroyed.
        ///
        partial void OnFetchRead(DataPortalHookArgs args);

        #endregion

    }
}


text:
try:
    import redis
except ImportError:
    pass
else:
    from .types import *
    from .client import *

__version__ = "0.3"


text:
@require "github.com/jkroso/parse-json" parse => parseJSON
@require "github.com/coiljl/URI" encode encode_component
@require "github.com/JuliaWeb/Requests.jl" => Requests

# Some packages don't declare all their dependencies
const known_fuckups = Dict(
  "pg-cursor" => Dict("pg" => "latest"),
  "pg-then" => Dict("pg" => "latest"))

function install(dir::AbstractString, progress, spec_cache=Dict(), uri_cache=Dict(); development=false)
  haskey(uri_cache, dir) && return nothing
  uri_cache[dir] = dir
  progress.pending += 1

  json = open(parseJSON, joinpath(dir, "package.json"))
  dependencies = merge(get(json, "dependencies", Dict()),
                       get(json, "peerDependencies", Dict()))
  development && merge!(dependencies, get(json, "devDependencies", Dict()))
  haskey(known_fuckups, json["name"]) && merge!(dependencies, known_fuckups[json["name"]])

  @sync for spec in dependencies
    @async begin
      uri = need(resolve_spec(spec, dir, spec_cache))
      path = need(isabspath(uri) ? uri : download(uri, uri_cache))
      install(path, progress, spec_cache, uri_cache)
      linkpackage(dir, path)
    end
  end

  # unofficially its possible for modules to depend on themselves.
  # Some numskulls take advantage of this (babel-runtime) so we need
  # to replicate that feature
  link = joinpath(dir, "node_modules", json["name"])
  mkpath(dirname(link))
  islink(link) || symlink(dir, link)

  run_install_script(json, dir)
  progress.pending -= 1
end

function resolve_spec(spec, dir, cache)
  haskey(cache, spec) && return cache[spec]
  cache[spec] = @schedule(ismatch(r"^file:", spec[2])
                            ? joinpath(dir, spec[2][6:end])
                            : toURL(spec...))
end

need(value) = value
need(t::Task) = wait(t)

# spec at docs.npmjs.com/misc/scripts
# TODO: support config
function run_install_script(json, dir)
  scripts = get(json, "scripts", nothing)
  isa(scripts, Associative) || return nothing
  hook = if haskey(scripts, "install") scripts["install"]
     elseif haskey(scripts, "postinstall") scripts["postinstall"]
     elseif ispath(joinpath(dir, "binding.gyp")) "node-gyp rebuild"
     else   "" end
  isempty(hook) && return nothing
  PATH = ENV["PATH"] * ":" * joinpath(dir, "node_modules", ".bin")
  env = Dict("PATH" => PATH,
             "npm_package_name" => json["name"],
             "npm_package_version" => json["version"],
             "npm_lifecycle_event" => "install")
  cmd = setenv(@eval(@cmd $hook), merge(ENV, env))
  cd(()-> run(pipeline(cmd, stderr=DevNull, stdout=DevNull)), dir)
end

function linkpackage(from, to)
  json = open(parseJSON, joinpath(to, "package.json"))
  path = joinpath(from, "node_modules", json["name"])
  mkpath(dirname(path))
  islink(path) && rm(path)
  ispath(path) || symlink(to, path)
  # add its binaries to $from/node_modules/.bin
  for (name, script) in getbin(json, to)
    name = joinpath(from, "node_modules", ".bin", name)
    islink(name) && continue
    mkpath(dirname(name))
    symlink(joinpath(to, script), name)
  end
end

# spec at docs.npmjs.com/files/package.json#bin
function getbin(json, dir)
  if haskey(json, "bin")
    (isa(json["bin"], AbstractString)
      ? Dict(json["name"] => json["bin"])
      : json["bin"])
  else
    directories = get(json, "directories", Dict())
    name = get(directories, "bin", nothing)
    name == nothing && return Dict()
    foldl(Dict(), readdir(joinpath(dir, name))) do dict,filename
      push!(dict, filename => joinpath(dir, name, filename))
    end
  end
end

function download(url, cache)
  haskey(cache, url) && return cache[url]
  cache[url] = @schedule begin
    path = joinpath(homedir(), ".packin", replace(url, r"^.*://", ""))
    if !ispath(path)
      if ismatch(r"^git(?:\+ssh|https?)?://", url)
        m = match(r"#([^/]+)$", url)
        branch = "master"
        if m != nothing
          branch = m[1]
          url = url[1:m.offset - 1]
        end
        run(pipeline(`git clone $url $path --depth 1 --branch $branch`, stderr=DevNull))
      else
        data = GET(url)
        mkpath(path)
        stdin, proc = open(`tar --strip-components 1 -xmpf - -C $path`, "w")
        write(stdin, data)
        close(stdin)
        wait(proc)
      end
    end
    path
  end
end

const gh_shorthand = r"^([^/]+/[^#/]+)(?:#(.+))?$"
const npm_scoped = r"^@([^/]+)/(.+)$"
const full_url = r"^\w+://"

function toURL(name, spec)
  if spec == "latest" || spec == "" spec = "*" end

  if ismatch(full_url, spec)
    return spec
  end

  if ismatch(gh_shorthand, spec)
    name,tag = match(gh_shorthand, spec).captures
    if tag == nothing; tag = latest_gh_commit(name) end
    return "https://codeload.github.com/$name/legacy.tar.gz/$tag"
  end

  if ismatch(npm_scoped, name)
    name = replace(name, r"/", "%2f")
    spec = encode_component(spec)
  end

  parseJSON(GET("http://registry.npmjs.com/$name/$spec"))["dist"]["tarball"]
end

const headers = Dict(
  "Authorization" => "Basic $(base64encode(ENV["GITHUB_USERNAME"] * ":" * ENV["GITHUB_PASSWORD"]))")

function latest_gh_commit(name)
  head = GET("https://api.github.com/repos/$name/git/refs/heads/master", meta=headers)
  parseJSON(head)["object"]["sha"]
end

function GET(url; meta=Dict())
  response = Requests.get(encode(url); headers=meta)
  if response.status >= 400
    error("status $(response.status) for $(encode(url))")
  else
    response.data
  end
end


text:
#include <aws/redshift/model/SnapshotErrorMessage.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace Redshift
{
namespace Model
{

SnapshotErrorMessage::SnapshotErrorMessage() :
    m_snapshotIdentifierHasBeenSet(false),
    m_snapshotClusterIdentifierHasBeenSet(false),
    m_failureCodeHasBeenSet(false),
    m_failureReasonHasBeenSet(false)
{
}

SnapshotErrorMessage::SnapshotErrorMessage(const XmlNode& xmlNode) :
    m_snapshotIdentifierHasBeenSet(false),
    m_snapshotClusterIdentifierHasBeenSet(false),
    m_failureCodeHasBeenSet(false),
    m_failureReasonHasBeenSet(false)
{
  *this = xmlNode;
}

SnapshotErrorMessage& SnapshotErrorMessage::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode snapshotIdentifierNode = resultNode.FirstChild("SnapshotIdentifier");
    if(!snapshotIdentifierNode.IsNull())
    {
      m_snapshotIdentifier = Aws::Utils::Xml::DecodeEscapedXmlText(snapshotIdentifierNode.GetText());
      m_snapshotIdentifierHasBeenSet = true;
    }
    XmlNode snapshotClusterIdentifierNode = resultNode.FirstChild("SnapshotClusterIdentifier");
    if(!snapshotClusterIdentifierNode.IsNull())
    {
      m_snapshotClusterIdentifier = Aws::Utils::Xml::DecodeEscapedXmlText(snapshotClusterIdentifierNode.GetText());
      m_snapshotClusterIdentifierHasBeenSet = true;
    }
    XmlNode failureCodeNode = resultNode.FirstChild("FailureCode");
    if(!failureCodeNode.IsNull())
    {
      m_failureCode = Aws::Utils::Xml::DecodeEscapedXmlText(failureCodeNode.GetText());
      m_failureCodeHasBeenSet = true;
    }
    XmlNode failureReasonNode = resultNode.FirstChild("FailureReason");
    if(!failureReasonNode.IsNull())
    {
      m_failureReason = Aws::Utils::Xml::DecodeEscapedXmlText(failureReasonNode.GetText());
      m_failureReasonHasBeenSet = true;
    }
  }

  return *this;
}

void SnapshotErrorMessage::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
  if(m_snapshotIdentifierHasBeenSet)
  {
      oStream << location << index << locationValue << ".SnapshotIdentifier=" << StringUtils::URLEncode(m_snapshotIdentifier.c_str()) << "&";
  }

  if(m_snapshotClusterIdentifierHasBeenSet)
  {
      oStream << location << index << locationValue << ".SnapshotClusterIdentifier=" << StringUtils::URLEncode(m_snapshotClusterIdentifier.c_str()) << "&";
  }

  if(m_failureCodeHasBeenSet)
  {
      oStream << location << index << locationValue << ".FailureCode=" << StringUtils::URLEncode(m_failureCode.c_str()) << "&";
  }

  if(m_failureReasonHasBeenSet)
  {
      oStream << location << index << locationValue << ".FailureReason=" << StringUtils::URLEncode(m_failureReason.c_str()) << "&";
  }

}

void SnapshotErrorMessage::OutputToStream(Aws::OStream& oStream, const char* location) const
{
  if(m_snapshotIdentifierHasBeenSet)
  {
      oStream << location << ".SnapshotIdentifier=" << StringUtils::URLEncode(m_snapshotIdentifier.c_str()) << "&";
  }
  if(m_snapshotClusterIdentifierHasBeenSet)
  {
      oStream << location << ".SnapshotClusterIdentifier=" << StringUtils::URLEncode(m_snapshotClusterIdentifier.c_str()) << "&";
  }
  if(m_failureCodeHasBeenSet)
  {
      oStream << location << ".FailureCode=" << StringUtils::URLEncode(m_failureCode.c_str()) << "&";
  }
  if(m_failureReasonHasBeenSet)
  {
      oStream << location << ".FailureReason=" << StringUtils::URLEncode(m_failureReason.c_str()) << "&";
  }
}

} // namespace Model
} // namespace Redshift
} // namespace Aws


text:
class OrcidProfile
  attr_reader :response, :version, :uid, :dois

  def initialize(response)
    @response = JSON.parse(response)
  end

  def version
    response.fetch('message-version', nil)
  end

  def uid
    response.fetch('orcid-profile', {}).fetch('orcid-identifier', {}).fetch('path', nil)
  end

  def dois
    if !has_path?(response, ['orcid-profile', 'orcid-activities'])
      []
    else
      works = response['orcid-profile']['orcid-activities']['orcid-works']['orcid-work']

      extracted_dois = works.map do |work_loc|
        doi = nil
        if has_path?(work_loc, ['work-external-identifiers', 'work-external-identifier'])
          ids_loc = work_loc['work-external-identifiers']['work-external-identifier']

          ids_loc.each do |id_loc|
            id_type = id_loc['work-external-identifier-type']
            id_val = id_loc['work-external-identifier-id']['value']

            if id_type.upcase == 'DOI'
              doi = id_val
            end
          end

        end
        doi
      end

      extracted_dois.compact
    end
  end

  def has_path?(hsh, path)
    loc = hsh
    path.each do |path_item|
      if loc[path_item]
        loc = loc[path_item]
      else
        loc = nil
        break
      end
    end
    loc != nil
  end
end


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <title>OpenLayers: Vector Features</title>
    <link rel="stylesheet" href="../theme/default/style.css" type="text/css">
    <link rel="stylesheet" href="style.css" type="text/css">

Drawing Simple Vector Features Example

    vector, feature, light

    Shows the use of the shows drawing simple vector features, in different styles.

This example shows drawing simple vector features -- point, line, polygon
       in different styles, created 'manually', by constructing the entire style
       object, via 'copy', extending the default style object, and by
       inheriting the default style from the layer.

It also shows how to use external graphic files for point features
       and how to set their size: If either graphicWidth or graphicHeight is set,
       the aspect ratio of the image will be respected. If both graphicWidth and
       graphicHeight are set, it will be ignored. Alternatively, if graphicWidth
       and graphicHeight are omitted, pointRadius will be used to set the size
       of the image, which will then be twice the value of pointRadius with the
       original aspect ratio.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Axiinput
{
    class Maintainer : IDisposable
    {
        public delegate void MaintainerMethod();
        private List<MaintainerMethod> pMaintainMethods = new List<MaintainerMethod>();
        Thread MaintainerThread = null;
        private object MaintainerLock = new object();
        private short pMaintainInterval = 16;
        private bool pShouldRunMaintainer = true;
        public Maintainer()
        {
            MaintainerThread = new Thread(new ThreadStart(RunMaintainer));
            MaintainerThread.Start();
        }
        private void RunMaintainer()
        {
            while (pShouldRunMaintainer)
            {
                if (pMaintainMethods.Count > 0)
                {
                    lock (MaintainerLock)
                    {
                        for (ushort x = 0; x < pMaintainMethods.Count; x++)
                        {
                            pMaintainMethods[x].Invoke();
                        }
                    }
                }
                Thread.Sleep(pMaintainInterval);
            }
        }
        public void AddMethod(MaintainerMethod pMethod)
        {
            lock (MaintainerLock)
            {
                pMaintainMethods.Add(pMethod);
            }
        }
        public void Dispose()
        {
            pShouldRunMaintainer = false;
            MaintainerThread = null;
        }
    }
}


text:
'use strict';
import Twilio from '../twilio';

const twilio = new Twilio();

export default function (message, convo, bot) {
  convo.say('I hear something about a text message');
  convo.ask('Do you want me to text you something?', [
    {
      pattern: 'yes',
      callback: convoTextMessage
    },
    {
      pattern: 'no',
      callback: function(response, convo) {
        convo.stop();
      }
    },
    {
      default: true,
      callback: function(response, convo) {
        convo.repeat();
        convo.next();
      }
    }
  ]);

  convo.on('end', function(convo) {
    if (convo.status == 'completed') {
      if (twilio.isDefined()) {
        const message = convo.extractResponse('message');
        twilio.txtMessage(message);
      } else {
        bot.reply(message, 'Sorry, twilio keys are not defined!');
      }
    } else {
      bot.reply(message, 'OK, nevermind!');
    }
  });
}

function convoTextMessage(response, convo) {
  convo.ask('What would you want me to send?', function (response, convo) {
    convo.say(`Ok, I will send you this: \`${response.text}\``);
    convo.next();
  }, {'key': 'message'});

  convo.next();
}


text:
typedef enum NavigationPointId {
	NAV_NONE,
	NAV_HOME,
	NAV_DOCS,
	NAV_TOTAL_NUM
} NavigationPointId;

void ActiveLink(LCUI_Widget parent, const char *link_id);

void Navbar_Init(void);
void Navigation_Init(void);

void DocumentationView_Init(void);
void DocumentationView_Free(void);
void HomeView_Init(void);
void HomeView_Free(void);

void UI_InitMessageView(void);
void UI_InitNotificationView(void);


text:
using System.Collections.Generic;
using LLVMSharp;
using static LLVMSharp.LLVM;

namespace Flame.LLVM
{
    /// <summary>
    /// Defines an interface stub, which handles a single interface method.
    /// </summary>
    public sealed class InterfaceStub
    {
        public InterfaceStub(LLVMValueRef Function)
        {
            this.Function = Function;
            this.impls = new Dictionary<LLVMType, LLVMMethod>();
        }

        /// <summary>
        /// Gets the function that implements this stub.
        /// </summary>
        /// <returns>The function that implements this stub.</returns>
        public LLVMValueRef Function { get; private set; }

        private Dictionary<LLVMType, LLVMMethod> impls;

        /// <summary>
        /// Gets a dictionary that maps implementing types to implementations.
        /// </summary>
        /// <returns>A dictionary that maps implementing types to implementations.</returns>
        public IReadOnlyDictionary<LLVMType, LLVMMethod> Implementations { get; private set; }

        /// <summary>
        /// Registers the given method as the implementation for the given type.
        /// </summary>
        /// <param name="Type">The type that implements the method.</param>
        /// <param name="Method">The implementation method.</param>
        public void Implement(LLVMType Type, LLVMMethod Method)
        {
            impls.Add(Type, Method);
        }

        private LLVMBasicBlockRef WriteReturnBlock(string Name, LLVMValueRef Result)
        {
            var block = AppendBasicBlock(Function, Name);
            var builder = CreateBuilder();
            PositionBuilderAtEnd(builder, block);
            BuildRet(builder, Result);
            DisposeBuilder(builder);
            return block;
        }

        private LLVMBasicBlockRef WriteReturnBlock(
            LLVMType Type,
            LLVMMethod Implementation,
            LLVMModuleBuilder Module)
        {
            return WriteReturnBlock(Type.Name.ToString(), Module.DeclareVirtual(Implementation));
        }

        /// <summary>
        /// Defines this stub's body.
        /// </summary>
        /// <param name="Module">The module that defines the stub.</param>
        public void Emit(LLVMModuleBuilder Module)
        {
            var entryBlock = AppendBasicBlock(Function, "entry");

            var defaultBlock = AppendBasicBlock(Function, "unknown_type");
            var builder = CreateBuilder();
            PositionBuilderAtEnd(builder, defaultBlock);
            BuildUnreachable(builder);
            DisposeBuilder(builder);

            builder = CreateBuilder();
            PositionBuilderAtEnd(builder, entryBlock);
            var switchInstr = BuildSwitch(builder, GetParam(Function, 0), defaultBlock, (uint)impls.Count);
            foreach (var pair in impls)
            {
                switchInstr.AddCase(
                    ConstInt(Int64Type(), (ulong)Module.GetTypeIndex(pair.Key), false),
                    WriteReturnBlock(pair.Key, pair.Value, Module));
            }
            DisposeBuilder(builder);
        }
    }
}


text:
adra
====

A Nodejs Event driven and distributed processing framework (Incubation)


text:
@class CourseViewController;
@protocol CourseViewControllerDelegate <NSObject>
//刷新主界面
- (void)CourseViewControllerConfirm:(CourseViewController*)viewController;
- (void)CourseViewControllerDelete:(CourseViewController*)viewController;
@end

@interface CourseViewController : UIViewController
@property (nonatomic,weak) id <CourseViewControllerDelegate> delegate;

- (instancetype)initWithCourseModel:(NSMutableArray *)modelArray;
- (instancetype)init NS_UNAVAILABLE;
- (void)dataStore;
- (void)rightBarBtnCanBeSelected;
@end


text:
package pl.consdata.ico.sqcompanion.repository;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Objects;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Project {

    private String serverId;
    private String key;
    private String name;
    private String serverUrl;

    public static String getProjectUniqueId(final String serverId, final String projectKey) {
        return String.format("%s$%s", serverId, projectKey);
    }

    public Project withServerUrl(final String serverUrl) {
        return Project
                .builder()
                .serverId(serverId)
                .key(key)
                .name(name)
                .serverUrl(serverUrl)
                .build();
    }

    public String getId() {
        return getProjectUniqueId(serverId, key);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        final Project project = (Project) o;
        return Objects.equals(serverId, project.serverId) && Objects.equals(key, project.key);
    }

    @Override
    public int hashCode() {
        return Objects.hash(serverId, key);
    }

}


text:
import * as ko from "knockout";
import * as timeService from "../timeservice";

interface TapGestureEvent {
    gesture: {
        center: {
            pageX: number;
        };
    };
}

/** This is customization for tap event. */
interface TapEvent {
    originalEvent: Event & TapGestureEvent;
}

export class TableSlider {
    public current: KnockoutObservable<number>;
    public currentValue: KnockoutComputed<string>;
    public minimum: KnockoutObservable<number>;
    public maximum: KnockoutObservable<number>;
    public position: KnockoutComputed<number>;
    private step: number;
    private minRelative: KnockoutObservable<number>;
    private maxRelative: KnockoutObservable<number>;
    private translator: (x: number) => number;

    constructor() {
        const self = this;
        this.current = ko.observable<number>(null);
        this.minRelative = ko.observable<number>(null);
        this.maxRelative = ko.observable<number>(null);
        this.currentValue = ko.computed<string>({
            read() {
                const ivalue = self.current();
                if (ivalue === null) {
                    return "";
                }

                return ivalue.toString();
            },
            write(value) {
                let ivalue = parseInt(value, 10);
                if (isNaN(ivalue) || !isFinite(ivalue)) {
                    return;
                }

                if (ivalue >= self.maximum()) {
                    ivalue = self.maximum();
                }

                if (ivalue <= self.minimum()) {
                    ivalue = self.minimum();
                }

                self.current(ivalue);
            },
        });
        this.minimum = ko.observable<number>();
        this.maximum = ko.observable<number>();
        this.position = ko.computed<number>({
            read() {
                const pixelDistance = self.maxRelative() - self.minRelative();
                if (pixelDistance === 0) {
                    return self.maxRelative();
                }

                const delta = self.maximum() - self.minimum();
                if (delta === 0) {
                    return self.maxRelative();
                }

                const ratio = pixelDistance / delta;
                const currentRelative = Math.floor(ratio * (self.current() - self.minimum()));

                return self.minRelative() + currentRelative;
            },
            write(value) {
                if (value >= self.maxRelative()) {
                    self.current(self.maximum());
                    return;
                }

                if (value <= self.minRelative()) {
                    self.current(self.minimum());
                    return;
                }

                const pixelDistance = self.maxRelative() - self.minRelative();
                if (pixelDistance === 0) {
                    self.current(self.minimum());
                    return;
                }

                const delta = self.maximum() - self.minimum();
                if (delta === 0) {
                    self.current(self.minimum());
                    return;
                }

                const ratio = delta / pixelDistance;
                let currentAbsolute = Math.floor(ratio * (value - self.minRelative()));
                // Round currentAbsolute to step
                const currentAbsoluteAligned = Math.floor(currentAbsolute / self.step) * self.step;
                if ((currentAbsolute - currentAbsoluteAligned) < (currentAbsoluteAligned + self.step - currentAbsolute)) {
                    currentAbsolute = currentAbsoluteAligned;
                } else {
                    currentAbsolute = currentAbsoluteAligned + self.step;
                }

                if (currentAbsolute + self.minimum() > self.maximum()) {
                    self.current(self.maximum());
                    return;
                }

                if (currentAbsolute + self.minimum() < self.minimum()) {
                    self.current(self.minimum());
                    return;
                }

                self.current(currentAbsolute + self.minimum());
            },
        });
    }
    /**
     * Set bounds for the slider in the relative coordinates.
     * @param minRelative Number Minimum coordinate in the relative coordinates.
     * @param maxRelative Number Maximum coordinate in the relative coordinates.
     * @param translator Function Function which translate the page coordinates to the relative coordinates.
     */
    public setBounds(minRelative: number, maxRelative: number, translator: (x: number) => number) {
        this.minRelative(minRelative);
        this.maxRelative(maxRelative);
        this.translator = translator;
    }
    public setParameters(value: number, step: number, min: number, max: number) {
        this.current(value);
        this.minimum(min);
        this.maximum(max);
        this.position.notifySubscribers();
        this.step = step;
    }
    public setStep(step: number) {
        this.step = step;
    }
    public increase() {
        let current = this.current();
        current = Math.min(current + this.step, this.maximum());
        this.current(current);
        this.position.notifySubscribers();
    }
    public decrease() {
        let current = this.current();
        current = Math.max(current - this.step, this.minimum());
        this.current(current);
        this.position.notifySubscribers();
    }
    public withinRange(value: number) {
        value = Math.max(value, this.minimum());
        value = Math.min(value, this.maximum());
        return value;
    }
    public isWithinRange(value: number) {
        if (value >= this.minimum() && value <= this.maximum()) {
            return true;
        }

        return false;
    }
    public fixupValue() {
        const self = this;
        if (this.current() !== null && this.current() !== undefined) {
            this.currentValue(this.current().toFixed());

            timeService.setTimeout(function() {
                const c = self.current();
                self.current(0);
                self.current(c);
            }, 10);
        }
    }
    public selectManually(event: MouseEvent & TapEvent) {
        if (event.pageX) {
            const relativePosition = this.translator(event.pageX);
            this.setPosition(relativePosition);
            return true;
        } else {
            if (event.originalEvent.gesture) {
                const relativePosition = this.translator(event.originalEvent.gesture.center.pageX);
                this.setPosition(relativePosition);
                return true;
            } else {
                console.error("Invalid Tap event.");
                return false;
            }
        }
    }
    public setPosition(relativePosition: number) {
        relativePosition = Math.max(relativePosition, this.minRelative());
        relativePosition = Math.min(relativePosition, this.maxRelative());
        this.position(relativePosition);
    }
}


text:
package com.intellij.openapi.projectRoots.impl;

import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.BaseComponent;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.ProjectJdkTable;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.util.containers.ContainerUtil;

import java.util.Collection;
import java.util.List;

public class DefaultJdkConfigurator implements BaseComponent {
  private final JavaSdk myJavaSdk;
  private final PropertiesComponent myPropertiesComponent;
  private final ProjectJdkTable myProjectJdkTable;

  public DefaultJdkConfigurator(JavaSdk javaSdk, PropertiesComponent propertiesComponent, ProjectJdkTable projectJdkTable) {
    myJavaSdk = javaSdk;
    myPropertiesComponent = propertiesComponent;
    myProjectJdkTable = projectJdkTable;
  }

  @Override
  public void initComponent() {
    if (!myPropertiesComponent.getBoolean("defaultJdkConfigured", false)) {
      List<Sdk> jdks = myProjectJdkTable.getSdksOfType(myJavaSdk);
      if (jdks.isEmpty()) {
        Collection<String> homePaths = myJavaSdk.suggestHomePaths();
        String homePath = ContainerUtil.getFirstItem(homePaths);
        if (homePath != null && myJavaSdk.isValidSdkHome(homePath)) {
          String suggestedName = myJavaSdk.suggestSdkName(null, homePath);
          ApplicationManager.getApplication().runWriteAction(
            () -> myProjectJdkTable.addJdk(myJavaSdk.createJdk(suggestedName, homePath, false))
          );
        }
      }
      myPropertiesComponent.setValue("defaultJdkConfigured", true);
    }
  }
}


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Edit.Tools;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Objects.Drawables;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Game.Rulesets.Mania.Edit.Blueprints;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Edit.Compose.Components;
using osuTK;

namespace osu.Game.Rulesets.Mania.Edit
{
    [Cached(Type = typeof(IManiaHitObjectComposer))]
    public class ManiaHitObjectComposer : HitObjectComposer<ManiaHitObject>, IManiaHitObjectComposer
    {
        protected new DrawableManiaEditRuleset DrawableRuleset { get; private set; }

        public ManiaHitObjectComposer(Ruleset ruleset)
            : base(ruleset)
        {
        }

        /// <summary>
        /// Retrieves the column that intersects a screen-space position.
        /// </summary>
        /// <param name="screenSpacePosition">The screen-space position.</param>
        /// <returns>The column which intersects with <paramref name="screenSpacePosition"/>.</returns>
        public Column ColumnAt(Vector2 screenSpacePosition) => DrawableRuleset.GetColumnByPosition(screenSpacePosition);

        private DependencyContainer dependencies;

        protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
            => dependencies = new DependencyContainer(base.CreateChildDependencies(parent));

        public int TotalColumns => ((ManiaPlayfield)DrawableRuleset.Playfield).TotalColumns;

        protected override DrawableRuleset<ManiaHitObject> CreateDrawableRuleset(Ruleset ruleset, WorkingBeatmap beatmap)
        {
            DrawableRuleset = new DrawableManiaEditRuleset(ruleset, beatmap);

            // This is the earliest we can cache the scrolling info to ourselves, before masks are added to the hierarchy and inject it
            dependencies.CacheAs(DrawableRuleset.ScrollingInfo);

            return DrawableRuleset;
        }

        protected override IReadOnlyList<HitObjectCompositionTool> CompositionTools => new HitObjectCompositionTool[]
        {
            new NoteCompositionTool(),
            new HoldNoteCompositionTool()
        };

        public override SelectionHandler CreateSelectionHandler() => new ManiaSelectionHandler();

        public override SelectionBlueprint CreateBlueprintFor(DrawableHitObject hitObject)
        {
            switch (hitObject)
            {
                case DrawableNote note:
                    return new NoteSelectionBlueprint(note);
                case DrawableHoldNote holdNote:
                    return new HoldNoteSelectionBlueprint(holdNote);
            }

            return base.CreateBlueprintFor(hitObject);
        }
    }
}


text:
using System.Collections.Generic;
using MangaRipper.Core.Logging;
using MangaRipper.Core.Models;
using MangaRipper.Core.Plugins;

namespace MangaRipper.Infrastructure
{
    public class XPathSelectorLogging : IXPathSelector
    {
        private readonly IXPathSelector decoratee;
        private readonly ILogger logger;

        public XPathSelectorLogging(IXPathSelector decoratee, ILogger logger)
        {
            this.decoratee = decoratee;
            this.logger = logger;
        }

        public MyHtmlNode Select(string html, string xpath)
        {
            try
            {
                return decoratee.Select(html, xpath);
            }
            catch
            {
                logger.Info($"Xpath: {xpath}");
                logger.Fatal(html);
                throw;
            }
        }

        public IEnumerable<MyHtmlNode> SelectMany(string html, string xpath)
        {
            try
            {
                return decoratee.SelectMany(html, xpath);
            }
            catch
            {
                logger.Info($"Xpath: {xpath}");
                logger.Fatal(html);
                throw;
            }
        }
    }
}