text:
package org.neotech.library.retainabletasks;

import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Nullable;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;

public final class AnnotationsProcessor extends AbstractProcessor {

    private static final String LIBRARY_PACKAGE = "org.neotech.library.retainabletasks";

    private static final ClassName CLASS_TASKATTACHBINDING = ClassName.get(LIBRARY_PACKAGE + ".internal", "TaskAttachBinding");
    private static final ClassName CLASS_TASK = ClassName.get(LIBRARY_PACKAGE, "Task");
    private static final ClassName CLASS_TASK_CALLBACK = CLASS_TASK.nestedClass("Callback");
    private static final ClassName CLASS_TASK_ADVANCEDCALLBACK = CLASS_TASK.nestedClass("AdvancedCallback");
    private static final ClassName CLASS_TASKMANAGEROWNER = ClassName.get(LIBRARY_PACKAGE, "TaskManagerOwner");

    private Filer filer;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        filer = processingEnv.getFiler();
    }

    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        final Set<String> types = new LinkedHashSet<>();
        for (Class<? extends Annotation> annotation : getSupportedAnnotations()) {
            types.add(annotation.getCanonicalName());
        }
        return types;
    }

    private Set<Class<? extends Annotation>> getSupportedAnnotations() {
        final Set<Class<? extends Annotation>> annotations = new LinkedHashSet<>();
        annotations.add(TaskAttach.class);
        annotations.add(TaskPreExecute.class);
        annotations.add(TaskPostExecute.class);
        annotations.add(TaskCancel.class);
        annotations.add(TaskProgress.class);
        return annotations;
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        final HashMap<TypeElement, TaskBindingContainer> classMap = new HashMap<>();

        for(TypeElement annotationType: annotations){
            processAnnotation(classMap, roundEnv, annotationType);
        }

        for(Map.Entry<TypeElement, TaskBindingContainer> entry: classMap.entrySet()) {
            try {
                createJavaFile(entry.getKey(), entry.getValue()).writeTo(filer);
            } catch (IOException e) {
                error(entry.getKey(), "Unable to write generate java binding file for class %s: %s", entry.getKey(), e.getMessage());
            }
        }
        return true;
    }

    private void processAnnotation(HashMap<TypeElement, TaskBindingContainer> classMap, RoundEnvironment roundEnvironment, TypeElement type){
        for (Element element : roundEnvironment.getElementsAnnotatedWith(type)) {
            final TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
            TaskBindingContainer binding = classMap.get(enclosingElement);
            System.out.println(enclosingElement);
            if(binding == null){
                binding = new TaskBindingContainer();
                classMap.put(enclosingElement, binding);
            }
            final Class<? extends Annotation> classType;
            try {
                //noinspection unchecked
                classType = (Class<? extends Annotation>) Class.forName(type.getQualifiedName().toString());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                error(element, "Could not find the Class object for TypeElement %s", type);
                return;
            }
            binding.add(element, classType);
        }
    }

    private JavaFile createJavaFile(TypeElement forTypeElement, TaskBindingContainer binding){

        final String packageName = processingEnv.getElementUtils().getPackageOf(forTypeElement).getQualifiedName().toString();
        final String className = forTypeElement.getQualifiedName().toString().substring(packageName.length() + 1).replace('.', '$');
        final ClassName bindingClassName = ClassName.get(packageName, className + "_TaskBinding");

        // Create the constructor which takes the target class (the class containing the annotated
        // methods) as argument.
        final MethodSpec constructor = MethodSpec.constructorBuilder()
                .addParameter(TypeVariableName.get("T"), "target", Modifier.FINAL)
                .addModifiers(Modifier.PUBLIC)
                .addStatement("this.target = target").build();

        // create (and implement) the getListenerFor method from the TaskAttachBinding interface
        final MethodSpec.Builder getListenerForMethod = MethodSpec.methodBuilder("getListenerFor")
                .addParameter(CLASS_TASK, "task")
                .addParameter(TypeName.BOOLEAN, "isReAttach")
                .addModifiers(Modifier.PUBLIC)
                .returns(CLASS_TASK_CALLBACK)
                .addAnnotation(Override.class);

        // Create a switch statement to switch between the different tasks
        getListenerForMethod.beginControlFlow("switch(task.getTag())");

        // Loop through the tasks and create switch cases for them.
        for(Map.Entry<String, TaskBinding> entry: binding.getTaskBindings().entrySet()){

            final TaskBinding methods = entry.getValue();

            if(methods.getElementForPostExecute() == null){
                note(forTypeElement, "No @TaskPostExecute annotated method found for task with tag '%s' while other annotated methods for that task have been found!");
            }

            getListenerForMethod.beginControlFlow("case \"$L\":\n", entry.getKey());

            // The getListenerFor method requires us to return an implementation of the
            // Task.Callback class, in this case (even though we might not need it) we use the
            // Task.AdvancedCallback instead of a simple Task.Callback implementation.
            final TypeSpec.Builder callbackImplementation = TypeSpec.anonymousClassBuilder("")
                    .addSuperinterface(CLASS_TASK_ADVANCEDCALLBACK);

            callbackImplementation.addMethod(createTaskCallbackMethod("onPreExecute", methods.getElementForPreExecute()));
            callbackImplementation.addMethod(createTaskCallbackMethod("onPostExecute", methods.getElementForPostExecute()));
            callbackImplementation.addMethod(createTaskCallbackMethod("onCanceled", methods.getElementForCancel()));
            callbackImplementation.addMethod(createTaskCallbackMethodForProgress(methods.getElementForProgress()));

            if(methods.getElementForAttach() != null) {
                final boolean onlyCallOnReAttach = methods.getElementForAttach().getAnnotation(TaskAttach.class).onlyCallOnReAttach();
                if(onlyCallOnReAttach){
                    getListenerForMethod.beginControlFlow("if(isReAttach)");
                }
                final List<? extends VariableElement> parameters = ((ExecutableElement) methods.getElementForAttach()).getParameters();
                if(parameters.size() == 0) {
                    getListenerForMethod.addStatement("target.$L()", methods.getElementForAttach().getSimpleName());
                } else {
                    // One parameter, check it and call the method.
                    final VariableElement parameter = parameters.get(0);
                    final TypeMirror taskType = processingEnv.getTypeUtils().erasure(processingEnv.getElementUtils().getTypeElement(CLASS_TASK.reflectionName()).asType());

                    if (!processingEnv.getTypeUtils().isAssignable(parameter.asType(), taskType)) {
                        // Parameter not an instance of Task
                        error(parameter, "Type of parameter '%s' is not an instance of '%s'!", parameter.getSimpleName(), taskType);
                    } else {
                        // Check if the class to cast too is accessible.
                        final Element requiredElement = processingEnv.getTypeUtils().asElement(parameter.asType());
                        if (!requiredElement.getModifiers().contains(Modifier.PUBLIC) && !requiredElement.getModifiers().contains(Modifier.PROTECTED)) {
                            error(parameter, "Type of parameter '%s' is not public or protected accessible! This prevents Android-Retainable-Tasks from casting '%s' to '%s'.\nTo fix this either the type of the parameter or make the class accessible by adding the public or protected modifier!", parameter.getSimpleName(), taskType, parameter.asType().toString());
                        }
                        getListenerForMethod.addStatement("target.$L(($T) task)", methods.getElementForAttach().getSimpleName(), parameter.asType());
                    }
                }
                if(onlyCallOnReAttach){
                    getListenerForMethod.endControlFlow();
                }
            }
            getListenerForMethod.addStatement("return $L", callbackImplementation.build());
            getListenerForMethod.endControlFlow();

        }

        // Add the default switch case
        getListenerForMethod.addCode("default:\n");
        getListenerForMethod.addStatement("return null");
        getListenerForMethod.endControlFlow();

        // Create an implementation of TaskAttachBinding interface.
        final TypeSpec generatedClass = TypeSpec.classBuilder(bindingClassName)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addField(TypeVariableName.get("T"), "target", Modifier.FINAL)
                .addMethod(constructor)
                .addTypeVariable(TypeVariableName.get("T", TypeName.get(forTypeElement.asType()), CLASS_TASKMANAGEROWNER))
                .addSuperinterface(CLASS_TASKATTACHBINDING)
                .addMethod(getListenerForMethod.build())
                .build();

        return JavaFile.builder(bindingClassName.packageName(), generatedClass)
                .addFileComment("Generated code from the Android Retainable Tasks annotations processor. Do not modify!")
                .build();
    }

    private MethodSpec createTaskCallbackMethodForProgress(@Nullable Element progressElement){
        MethodSpec.Builder progressUpdateMethod = MethodSpec.methodBuilder("onProgressUpdate")
                .addAnnotation(Override.class)
                .addModifiers(Modifier.PUBLIC)
                .addParameter(CLASS_TASK, "task")
                .addParameter(TypeName.OBJECT, "object");

        if(progressElement != null) {
            final List<? extends VariableElement> parameters = ((ExecutableElement) progressElement).getParameters();
            if(parameters.size() == 0) {
                progressUpdateMethod.addStatement("target.$L()", progressElement.getSimpleName());
            } else if(parameters.size() >= 1 && parameters.size() <= 2){
                // One or two parameters, check it and call the method.
                final VariableElement parameterTask = parameters.get(0);
                final TypeMirror taskType = processingEnv.getTypeUtils().erasure(processingEnv.getElementUtils().getTypeElement(CLASS_TASK.reflectionName()).asType());

                if (!processingEnv.getTypeUtils().isAssignable(parameterTask.asType(), taskType)) {
                    // Parameter not an instance of Task
                    error(parameterTask, "Type of parameter '%s' is not an instance of '%s'!", parameterTask.getSimpleName(), taskType);
                    return progressUpdateMethod.build();
                }
                // Check if the class to cast to is accessible.
                final Element requiredElement = processingEnv.getTypeUtils().asElement(parameterTask.asType());
                if (!requiredElement.getModifiers().contains(Modifier.PUBLIC) && !requiredElement.getModifiers().contains(Modifier.PROTECTED)) {
                    error(parameterTask, "Type of parameter '%s' is not public or protected accessible! This prevents Android-Retainable-Tasks from casting '%s' to '%s'.\nTo fix this either the type of the parameter or make the class accessible by adding the public or protected modifier!", parameterTask.getSimpleName(), taskType, parameterTask.asType().toString());
                    return progressUpdateMethod.build();
                }

                if(parameters.size() == 2){
                    progressUpdateMethod.addStatement("target.$L(($T) task, object)", progressElement.getSimpleName(), parameterTask.asType());
                } else {
                    progressUpdateMethod.addStatement("target.$L(($T) task)", progressElement.getSimpleName(), parameterTask.asType());
                }

            } else {
                progressUpdateMethod.addComment("No annotated method found for $L", progressElement.getSimpleName());
            }
        }
        return progressUpdateMethod.build();
    }

    private MethodSpec createTaskCallbackMethod(String methodName, @Nullable Element methodToCall){
        // Create the implementation of the onPreExecute method.
        final MethodSpec.Builder onPreExecuteMethod = MethodSpec.methodBuilder(methodName)
                .addAnnotation(Override.class)
                .addModifiers(Modifier.PUBLIC)
                .addParameter(CLASS_TASK, "task");

        if(methodToCall != null) {
            // There is a method known that should be called, check the parameters.
            final List<? extends VariableElement> parameters = ((ExecutableElement) methodToCall).getParameters();
            if(parameters.size() == 0){
                // Zero parameters, just call the method.
                onPreExecuteMethod.addStatement("target.$L()", methodToCall.getSimpleName());
            } else if(parameters.size() == 1){
                // One parameter, check it and call the method.
                final VariableElement parameter = parameters.get(0);
                final TypeMirror taskType = processingEnv.getTypeUtils().erasure(processingEnv.getElementUtils().getTypeElement(CLASS_TASK.reflectionName()).asType());

                if(!processingEnv.getTypeUtils().isAssignable(parameter.asType(), taskType)){
                    // Parameter not an instance of Task
                    error(parameter, "Type of parameter '%s' is not an instance of '%s'!", parameter.getSimpleName(), taskType);
                } else {
                    // Check if the class to cast too is accessible.
                    final Element requiredElement = processingEnv.getTypeUtils().asElement(parameter.asType());
                    if (!requiredElement.getModifiers().contains(Modifier.PUBLIC) && !requiredElement.getModifiers().contains(Modifier.PROTECTED)) {
                        error(parameter, "Type of parameter '%s' is not public or protected accessible! This prevents Android-Retainable-Tasks from casting '%s' to '%s'.\nTo fix this either the type of the parameter or make the class accessible by adding the public or protected modifier!", parameter.getSimpleName(), taskType, parameter.asType().toString());
                    }
                    onPreExecuteMethod.addStatement("target.$L(($T) task)", methodToCall.getSimpleName(), parameter.asType());
                }
            }
        } else {
            onPreExecuteMethod.addComment("No annotated method found for $L", methodName);
        }
        return onPreExecuteMethod.build();
    }

    private void error(Element element, String message, Object... args) {
        printMessage(Diagnostic.Kind.ERROR, element, message, args);
    }

    private void note(Element element, String message, Object... args) {
        printMessage(Diagnostic.Kind.NOTE, element, message, args);
    }

    private void printMessage(Diagnostic.Kind kind, Element element, String message, Object[] args) {
        if (args.length > 0) {
            message = String.format(message, args);
        }
        processingEnv.getMessager().printMessage(kind, message, element);
    }
}


text:
package org.apache.ddlutils.task;

import java.io.File;
import java.io.FileWriter;

import org.apache.ddlutils.io.DataDtdWriter;
import org.apache.ddlutils.model.Database;
import org.apache.tools.ant.BuildException;

/**
 * Creates a DTD that specifies the layout for data XML files.

 * This sub task does not require a database connection, so the dataSource
 * sub element of the enclosing task can be omitted.
 *
 * @version $Revision: 289996 $
 * @ant.task name="writeDtdToFile"
 */
public class WriteDtdToFileCommand extends Command
{
    /** The file to output the DTD to. */
    private File _outputFile;

    /**
     * Specifies the name of the file to write the DTD to.
     *
     * @param outputFile The output file
     * @ant.required
     */
    public void setOutputFile(File outputFile)
    {
        _outputFile = outputFile;
    }

    /**
     * {@inheritDoc}
     */
    public boolean isRequiringModel()
    {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    public void execute(DatabaseTaskBase task, Database model) throws BuildException
    {
        if (_outputFile == null)
        {
            throw new BuildException("No output file specified");
        }
        if (_outputFile.exists() && !_outputFile.canWrite())
        {
            throw new BuildException("Cannot overwrite output file " + _outputFile.getAbsolutePath());
        }

        try
        {
            FileWriter    outputWriter = new FileWriter(_outputFile);
            DataDtdWriter dtdWriter    = new DataDtdWriter();

            dtdWriter.writeDtd(model, outputWriter);
            outputWriter.close();
            _log.info("Written DTD to " + _outputFile.getAbsolutePath());
        }
        catch (Exception ex)
        {
            handleException(ex, "Failed to write to output file " + _outputFile.getAbsolutePath());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Accountable::Matchers
  # class ActsAsAccountorMatcher < Remarkable::ActiveRecord::Base
  #   arguments :instance
  #   assertion :is_applied?
  #
  #   protected
  #
  #   def is_applied?
  #
  #   end
  # end
  #
  # def act_as_accountor( *args )
  #   ActsAsAccountorMatcher.new( *args ).spec( self )
  # end
end


text:
(function($) {
    window.ListBlock = function(opts) {
        /* contents of 'opts':
            definitionPrefix (required)
            childInitializer (optional) - JS initializer function for each child
        */
        var listMemberTemplate = $('#' + opts.definitionPrefix + '-newmember').text();

        return function(elementPrefix) {
            var sequence = Sequence({
                prefix: elementPrefix,
                maxNumChildBlocks: Infinity,
                onInitializeMember: function(sequenceMember) {
                    /* initialize child block's JS behaviour */
                    if (opts.childInitializer) {
                        opts.childInitializer(sequenceMember.prefix + '-value');
                    }

                    /* initialise delete button */
                    $('#' + sequenceMember.prefix + '-delete').on('click', function() {
                        sequenceMember.delete();
                    });

                    /* initialise move up/down buttons */
                    $('#' + sequenceMember.prefix + '-moveup').on('click', function() {
                        sequenceMember.moveUp();
                    });

                    $('#' + sequenceMember.prefix + '-movedown').on('click', function() {
                        sequenceMember.moveDown();
                    });
                },

                onEnableMoveUp: function(sequenceMember) {
                    $('#' + sequenceMember.prefix + '-moveup').removeClass('disabled');
                },

                onDisableMoveUp: function(sequenceMember) {
                    $('#' + sequenceMember.prefix + '-moveup').addClass('disabled');
                },

                onEnableMoveDown: function(sequenceMember) {
                    $('#' + sequenceMember.prefix + '-movedown').removeClass('disabled');
                },

                onDisableMoveDown: function(sequenceMember) {
                    $('#' + sequenceMember.prefix + '-movedown').addClass('disabled');
                }
            });

            /* initialize 'add' button */
            $('#' + elementPrefix + '-add').on('click', function() {
                sequence.insertMemberAtEnd(listMemberTemplate);
            });
        };
    };
})(jQuery);


text:
// Copyright (c) 2015 Uber Technologies, Inc.
//
// 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.

'use strict';
var KafkaDataProducer = require('../index').KafkaDataProducer;
var ProducerRecord = require('../index').ProducerRecord;

var configs = {
    clientType: 'AtLeastOnce',
    proxyHost: 'localhost',
    proxyPort: 16947
};

function onConnect(err) {
    /* eslint-disable no-undef,no-console,block-scoped-var */
    if (!err) {
        console.log('KafkaRestClient connected to kafka');
    } else {
        console.log('KafkaRestClient could not connect to kafka');
    }
    /* eslint-enable no-undef,no-console,block-scoped-var */
}

var kafkaDataProducer = new KafkaDataProducer(configs);
kafkaDataProducer.connect(onConnect);

/* eslint-disable no-undef,no-console,block-scoped-var */
function msgCallback(err, res) {
    if (err) {
        console.log(err);
    } else {
        console.log(res);
    }
}
/* eslint-enable no-undef,no-console,block-scoped-var */

kafkaDataProducer.produceSync('test_hongxu', new ProducerRecord({value: 'value hahaha'}), msgCallback);
kafkaDataProducer.produceSync('test_hongxu', new ProducerRecord({key: 'test key', value: 'value hahaha'}), msgCallback);

/* eslint-disable no-undef,block-scoped-var */
setTimeout(function close() {
    kafkaDataProducer.close();
}, 1000);
/* eslint-enable no-undef,block-scoped-var */


text:
package org.hara.kvstore;

public interface KVInterface {

	KVMessage put(String key, String value) throws KVException;

	KVMessage get(String key) throws KVException;

	KVMessage del(String key) throws KVException;

}


text:
import {Component, Directive, Inject, Injectable, InjectionToken, Injector, NgModule, Optional, forwardRef} from '@angular/core';
import {TestBed, async, inject} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {onlyInIvy} from '@angular/private/testing';

describe('providers', () => {

  describe('inheritance', () => {

    it('should NOT inherit providers', () => {
      const SOME_DIRS = new InjectionToken('someDirs');

      @Directive({
        selector: '[super-dir]',
        providers: [{provide: SOME_DIRS, useClass: SuperDirective, multi: true}]
      })
      class SuperDirective {
      }

      @Directive({
        selector: '[sub-dir]',
        providers: [{provide: SOME_DIRS, useClass: SubDirective, multi: true}]
      })
      class SubDirective extends SuperDirective {
      }

      @Directive({selector: '[other-dir]'})
      class OtherDirective {
        constructor(@Inject(SOME_DIRS) public dirs: any) {}
      }

      @Component({selector: 'app-comp', template: `<div other-dir sub-dir></div>`})
      class App {
      }

      TestBed.configureTestingModule(
          {declarations: [SuperDirective, SubDirective, OtherDirective, App]});

      const fixture = TestBed.createComponent(App);
      fixture.detectChanges();

      const otherDir = fixture.debugElement.query(By.css('div')).injector.get(OtherDirective);
      expect(otherDir.dirs.length).toEqual(1);
      expect(otherDir.dirs[0] instanceof SubDirective).toBe(true);
    });

  });

  describe('lifecycles', () => {
    it('should inherit ngOnDestroy hooks on providers', () => {
      const logs: string[] = [];

      @Injectable()
      class SuperInjectableWithDestroyHook {
        ngOnDestroy() { logs.push('OnDestroy'); }
      }

      @Injectable()
      class SubInjectableWithDestroyHook extends SuperInjectableWithDestroyHook {
      }

      @Component({template: '', providers: [SubInjectableWithDestroyHook]})
      class App {
        constructor(foo: SubInjectableWithDestroyHook) {}
      }

      TestBed.configureTestingModule({declarations: [App]});
      const fixture = TestBed.createComponent(App);
      fixture.detectChanges();
      fixture.destroy();

      expect(logs).toEqual(['OnDestroy']);
    });

    it('should not call ngOnDestroy for providers that have not been requested', () => {
      const logs: string[] = [];

      @Injectable()
      class InjectableWithDestroyHook {
        ngOnDestroy() { logs.push('OnDestroy'); }
      }

      @Component({template: '', providers: [InjectableWithDestroyHook]})
      class App {
      }

      TestBed.configureTestingModule({declarations: [App]});
      const fixture = TestBed.createComponent(App);
      fixture.detectChanges();
      fixture.destroy();

      expect(logs).toEqual([]);
    });

    it('should only call ngOnDestroy once for multiple instances', () => {
      const logs: string[] = [];

      @Injectable()
      class InjectableWithDestroyHook {
        ngOnDestroy() { logs.push('OnDestroy'); }
      }

      @Component({selector: 'my-cmp', template: ''})
      class MyComponent {
        constructor(foo: InjectableWithDestroyHook) {}
      }

      @Component({
        template: `
          <my-cmp></my-cmp>
          <my-cmp></my-cmp>
        `,
        providers: [InjectableWithDestroyHook]
      })
      class App {
      }

      TestBed.configureTestingModule({declarations: [App, MyComponent]});
      const fixture = TestBed.createComponent(App);
      fixture.detectChanges();
      fixture.destroy();

      expect(logs).toEqual(['OnDestroy']);
    });

    it('should call ngOnDestroy when providing same token via useClass', () => {
      const logs: string[] = [];

      @Injectable()
      class InjectableWithDestroyHook {
        ngOnDestroy() { logs.push('OnDestroy'); }
      }

      @Component({
        template: '',
        providers: [{provide: InjectableWithDestroyHook, useClass: InjectableWithDestroyHook}]
      })
      class App {
        constructor(foo: InjectableWithDestroyHook) {}
      }

      TestBed.configureTestingModule({declarations: [App]});
      const fixture = TestBed.createComponent(App);
      fixture.detectChanges();
      fixture.destroy();

      expect(logs).toEqual(['OnDestroy']);
    });

    onlyInIvy('Destroy hook of useClass provider is invoked correctly')
        .it('should only call ngOnDestroy of value when providing via useClass', () => {
          const logs: string[] = [];

          @Injectable()
          class InjectableWithDestroyHookToken {
            ngOnDestroy() { logs.push('OnDestroy Token'); }
          }

          @Injectable()
          class InjectableWithDestroyHookValue {
            ngOnDestroy() { logs.push('OnDestroy Value'); }
          }

          @Component({
            template: '',
            providers: [
              {provide: InjectableWithDestroyHookToken, useClass: InjectableWithDestroyHookValue}
            ]
          })
          class App {
            constructor(foo: InjectableWithDestroyHookToken) {}
          }

          TestBed.configureTestingModule({declarations: [App]});
          const fixture = TestBed.createComponent(App);
          fixture.detectChanges();
          fixture.destroy();

          expect(logs).toEqual(['OnDestroy Value']);
        });

    it('should only call ngOnDestroy of value when providing via useExisting', () => {
      const logs: string[] = [];

      @Injectable()
      class InjectableWithDestroyHookToken {
        ngOnDestroy() { logs.push('OnDestroy Token'); }
      }

      @Injectable()
      class InjectableWithDestroyHookExisting {
        ngOnDestroy() { logs.push('OnDestroy Existing'); }
      }

      @Component({
        template: '',
        providers: [
          InjectableWithDestroyHookExisting, {
            provide: InjectableWithDestroyHookToken,
            useExisting: InjectableWithDestroyHookExisting
          }
        ]
      })
      class App {
        constructor(foo1: InjectableWithDestroyHookExisting, foo2: InjectableWithDestroyHookToken) {
        }
      }

      TestBed.configureTestingModule({declarations: [App]});
      const fixture = TestBed.createComponent(App);
      fixture.detectChanges();
      fixture.destroy();

      expect(logs).toEqual(['OnDestroy Existing']);
    });

  });

  describe('components and directives', () => {

    class MyService {
      value = 'some value';
    }

    @Component({selector: 'my-comp', template: ``})
    class MyComp {
      constructor(public svc: MyService) {}
    }

    @Directive({selector: '[some-dir]'})
    class MyDir {
      constructor(public svc: MyService) {}
    }

    it('should support providing components in tests without @Injectable', () => {
      @Component({selector: 'test-comp', template: '<my-comp></my-comp>'})
      class TestComp {
      }

      TestBed.configureTestingModule({
        declarations: [TestComp, MyComp],
        // providing MyComp is unnecessary but it shouldn't throw
        providers: [MyComp, MyService],
      });

      const fixture = TestBed.createComponent(TestComp);
      const myCompInstance = fixture.debugElement.query(By.css('my-comp')).injector.get(MyComp);
      expect(myCompInstance.svc.value).toEqual('some value');
    });

    it('should support providing directives in tests without @Injectable', () => {
      @Component({selector: 'test-comp', template: '<div some-dir></div>'})
      class TestComp {
      }

      TestBed.configureTestingModule({
        declarations: [TestComp, MyDir],
        // providing MyDir is unnecessary but it shouldn't throw
        providers: [MyDir, MyService],
      });

      const fixture = TestBed.createComponent(TestComp);
      const myCompInstance = fixture.debugElement.query(By.css('div')).injector.get(MyDir);
      expect(myCompInstance.svc.value).toEqual('some value');
    });

    describe('injection without bootstrapping', () => {
      beforeEach(() => {
        TestBed.configureTestingModule({declarations: [MyComp], providers: [MyComp, MyService]});
      });

      it('should support injecting without bootstrapping',
         async(inject([MyComp, MyService], (comp: MyComp, service: MyService) => {
           expect(comp.svc.value).toEqual('some value');
         })));
    });
  });

  describe('forward refs', () => {

    it('should support forward refs in provider deps', () => {
      class MyService {
        constructor(public dep: {value: string}) {}
      }

      class OtherService {
        value = 'one';
      }

      @Component({selector: 'app-comp', template: ``})
      class AppComp {
        constructor(public myService: MyService) {}
      }

      @NgModule({
        providers: [
          OtherService, {
            provide: MyService,
            useFactory: (dep: {value: string}) => new MyService(dep),
            deps: [forwardRef(() => OtherService)]
          }
        ],
        declarations: [AppComp]
      })
      class MyModule {
      }

      TestBed.configureTestingModule({imports: [MyModule]});

      const fixture = TestBed.createComponent(AppComp);
      expect(fixture.componentInstance.myService.dep.value).toBe('one');
    });

  });

  describe('flags', () => {

    class MyService {
      constructor(public value: OtherService|null) {}
    }

    class OtherService {}

    it('should support Optional flag in deps', () => {
      const injector =
          Injector.create([{provide: MyService, deps: [[new Optional(), OtherService]]}]);

      expect(injector.get(MyService).value).toBe(null);
    });

    it('should support Optional flag in deps without instantiating it', () => {
      const injector = Injector.create([{provide: MyService, deps: [[Optional, OtherService]]}]);

      expect(injector.get(MyService).value).toBe(null);
    });
  });
});


text:
from ..backends import TimerBase

from ..external.qt.QtCore import QTimer

class Timer(TimerBase):

    def __init__(self, interval, callback):
        self._timer = QTimer()
        self._timer.setInterval(interval)
        self._timer.timeout.connect(callback)

    def start(self):
        self._timer.start()

    def stop(self):
        self._timer.stop()


text:
#region License

// SLNTools
// Copyright (c) 2009
// by Christian Warren
//
// 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.

#endregion

using System;

namespace CWDev.SLNTools.Core.Merge
{
    public class EmptyElement
        : Element
    {
        public EmptyElement(ElementIdentifier identifier)
            : base(identifier)
        {
        }

        public override Difference CompareTo(Element oldElement)
        {
            if (oldElement == null)
                throw new ArgumentNullException("oldElement");
            if (!oldElement.Identifier.Equals(this.Identifier))
                throw new MergeException("Cannot compare elements that does not share the same identifier.");

            if (oldElement is ValueElement)
            {
                return new ValueDifference(
                            this.Identifier,
                            OperationOnParent.Removed,
                            ((ValueElement)oldElement).Value,
                            null);
            }
            else if (oldElement is NodeElement)
            {
                return new NodeDifference(
                            this.Identifier,
                            OperationOnParent.Removed,
                            null);
            }
            else
            {
                throw new MergeException(string.Format("Cannot compare a {0} to a {1}.", oldElement.GetType().Name, this.GetType().Name));
            }
        }

        public override Element Apply(Difference difference)
        {
            if (difference == null)
                throw new ArgumentNullException("difference");
            if (!difference.Identifier.Equals(this.Identifier))
                throw new MergeException("Cannot apply a difference that does not share the same identifier with the element.");

            if (difference is ValueDifference)
            {
                if (difference.OperationOnParent == OperationOnParent.Removed)
                    throw new MergeException("Cannot apply a 'remove' difference on a ValueElement.");
                return new ValueElement(
                            this.Identifier,
                            ((ValueDifference)difference).NewValue);
            }
            else if (difference is NodeDifference)
            {
                var emptyNodeElement = new NodeElement(this.Identifier, null);
                return emptyNodeElement.Apply(difference);
            }
            else
            {
                throw new MergeException(string.Format("Cannot apply a {0} on a {1}.", difference.GetType().Name, this.GetType().Name));
            }
        }
    }
}


text:
[![Build Status](https://travis-ci.org/CS2103JAN2017-W15-B4/main.svg?branch=master)](https://travis-ci.org/CS2103JAN2017-W15-B4/main)
[![Build status](https://ci.appveyor.com/api/projects/status/sh3iswuhfor7us5n?svg=true)](https://ci.appveyor.com/project/yirui94/main)
[![Coverage Status](https://coveralls.io/repos/github/CS2103JAN2017-W15-B4/main/badge.svg?branch=master)](https://coveralls.io/github/CS2103JAN2017-W15-B4/main?branch=master)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/43c1404bac364bb7852a769d8f796a9e)](https://www.codacy.com/app/yirui94/main?utm_source=github.com&utm_medium=referral&utm_content=CS2103JAN2017-W15-B4/main&utm_campaign=Badge_Grade)

* This is a desktop Task Manager application. It has a GUI but most of the user interactions happen using
  a CLI (Command Line Interface).
* It is a Java sample application intended for fulfilling Software Engineering Course Requirements while using Java as
  the main programming language.
* It is **written in OOP fashion**. It has a more sophisticated GUI that includes a list panel and an in-built Browser.
* It includes automated GUI testing and supports for *Build Automation* using Gradle and for *Continuous Integration* using Travis CI.

#### Site Map
* [User Guide](docs/UserGuide.md)
* [Developer Guide](docs/DeveloperGuide.md)
* [About Us](docs/AboutUs.md)
* [Contact Us](docs/ContactUs.md)

#### Acknowledgements

* This project is a morphing of [AddressBook Level 4](https://github.com/nus-cs2103-AY1617S2/addressbook-level4) which provides educational sample code for us.
* Some parts of this sample application are inspired by the excellent
  [Java FX tutorial](http://code.makery.ch/library/javafx-8-tutorial/) by *Marco Jakob*.

#### Dependencies

* Libraries
  * [Guava](https://github.com/google/guava)
  * [JavaFX](http://docs.oracle.com/javafx/2/overview/jfxpub-overview.htm)
  * [Jackson](http://wiki.fasterxml.com/JacksonHome)
  * [JFoenix](https://github.com/jfoenixadmin/JFoenix)
  * [TestFX](https://github.com/TestFX/TestFX)

* Testing Frameworks
  * [JUnit](https://github.com/junit-team/junit4)

#### Licence : [MIT](LICENSE)


text:
class IMetaResize < InstructionMeta
  set_cc 0xC
  set_char ?*

  set_mc 3

  def self.reference_card
    puts %q{
    Meta Instruction
    Provides an interface for metaprogramming.

    0bCCCCMMAAAAAAAAAAAAAAAAAA
    C = Control Code (Instruction)    [4 bits]
    M = Meta Command                  [2 bits]
    A = Meta Command Arguments        [18 bits]

      --Resize
      Resizes the instructions array

      0bX11111111Y22222222
      X = X sign
      1 = X value
      Y = Y sign
      2 = Y value
    }
  end
  #TODO: Finish MetaResize
end


text:
<!DOCTYPE html>

    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />

      <leaflet center="london" markers="markers" height="480px" width="640px">
      </leaflet>

change your icon here:

      <select ng-model="markers.m1.icon" ng-options="key for (key, val) in icons">
      </select>


text:
from __future__ import print_function

import argparse
import re
import sys
from os.path import basename

def validate_files(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('filenames', nargs='*')
    parser.add_argument(
        '--django', default=False, action='store_true',
        help='Use Django-style test naming pattern (test*.py)'
    )
    args = parser.parse_args(argv)

    retcode = 0
    test_name_pattern = 'test_.*.py' if args.django else '.*_test.py'
    for filename in args.filenames:
        base = basename(filename)
        if (
                not re.match(test_name_pattern, base) and
                not base == '__init__.py' and
                not base == 'conftest.py'
        ):
            retcode = 1
            print(
                '{0} does not match pattern "{1}"'.format(
                    filename, test_name_pattern
                )
            )

    return retcode

if __name__ == '__main__':
    sys.exit(validate_files())


text:
'use strict';

class BaseUpdater {
	constructor(quad) {
		this.quad = quad;

		// Updater's config
		var that = this;
		var updateConfig = function () {
			that.config = quad.config.updaters[that.name];
		};

		quad.on('config', updateConfig);
		updateConfig();
	}

	get name() {
		return null;
	}

	setTarget(target) {}
	reset() {}
	update(data) {}
}

module.exports = BaseUpdater;


text:
import { join } from 'path'
import { createElement } from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import send from 'send'
import generateETag from 'etag'
import fresh from 'fresh'
import requireModule from './require'
import getConfig from './config'
import resolvePath from './resolve'
import { Router } from '../lib/router'
import { loadGetInitialProps } from '../lib/utils'
import Head, { defaultHead } from '../lib/head'
import App from '../lib/app'
import ErrorDebug from '../lib/error-debug'

export async function render (req, res, pathname, query, opts) {
  const html = await renderToHTML(req, res, pathname, opts)
  sendHTML(req, res, html, req.method)
}

export function renderToHTML (req, res, pathname, query, opts) {
  return doRender(req, res, pathname, query, opts)
}

export async function renderError (err, req, res, pathname, query, opts) {
  const html = await renderErrorToHTML(err, req, res, query, opts)
  sendHTML(req, res, html, req.method)
}

export function renderErrorToHTML (err, req, res, pathname, query, opts = {}) {
  return doRender(req, res, pathname, query, { ...opts, err, page: '_error' })
}

async function doRender (req, res, pathname, query, {
  err,
  page,
  buildId,
  buildStats,
  hotReloader,
  assetPrefix,
  dir = process.cwd(),
  dev = false,
  staticMarkup = false
} = {}) {
  page = page || pathname

  await ensurePage(page, { dir, hotReloader })

  const dist = getConfig(dir).distDir

  let [Component, Document] = await Promise.all([
    requireModule(join(dir, dist, 'dist', 'pages', page)),
    requireModule(join(dir, dist, 'dist', 'pages', '_document'))
  ])
  Component = Component.default || Component
  Document = Document.default || Document
  const ctx = { err, req, res, pathname, query }
  const props = await loadGetInitialProps(Component, ctx)

  // the response might be finshed on the getinitialprops call
  if (res.finished) return

  const renderPage = () => {
    const app = createElement(App, {
      Component,
      props,
      router: new Router(pathname, query)
    })

    const render = staticMarkup ? renderToStaticMarkup : renderToString

    let html
    let head
    let errorHtml = ''
    try {
      html = render(app)
    } finally {
      head = Head.rewind() || defaultHead()
    }

    if (err && dev) {
      errorHtml = render(createElement(ErrorDebug, { error: err }))
    }

    return { html, head, errorHtml }
  }

  const docProps = await loadGetInitialProps(Document, { ...ctx, renderPage })

  if (res.finished) return

  const doc = createElement(Document, {
    __NEXT_DATA__: {
      props,
      pathname,
      query,
      buildId,
      buildStats,
      assetPrefix,
      err: (err && dev) ? errorToJSON(err) : null
    },
    dev,
    staticMarkup,
    ...docProps
  })

  return '<!DOCTYPE html>' + renderToStaticMarkup(doc)
}

export async function renderScript (req, res, page, opts) {
  try {
    const path = join(opts.dir, '.next', 'bundles', 'pages', page)
    const realPath = await resolvePath(path)
    await serveStatic(req, res, realPath)
  } catch (err) {
    if (err.code === 'ENOENT') {
      renderScriptError(req, res, page, err, {}, opts)
      return
    }

    throw err
  }
}

export async function renderScriptError (req, res, page, error, customFields, opts) {
  if (error.code === 'ENOENT') {
    res.setHeader('Content-Type', 'text/javascript')
    res.end(`
      window.__NEXT_REGISTER_PAGE('${page}', function() {
        var error = new Error('Page does not exist: ${page}')
        error.statusCode = 404

        return { error: error }
      })
    `)
    return
  }

  res.setHeader('Content-Type', 'text/javascript')
  const errorJson = {
    ...errorToJSON(error),
    ...customFields
  }

  res.end(`
    window.__NEXT_REGISTER_PAGE('${page}', function() {
      var error = ${JSON.stringify(errorJson)}
      return { error: error }
    })
  `)
}

export function sendHTML (req, res, html, method) {
  if (res.finished) return
  const etag = generateETag(html)

  if (fresh(req.headers, { etag })) {
    res.statusCode = 304
    res.end()
    return
  }

  res.setHeader('ETag', etag)
  res.setHeader('Content-Type', 'text/html')
  res.setHeader('Content-Length', Buffer.byteLength(html))
  res.end(method === 'HEAD' ? null : html)
}

export function sendJSON (res, obj, method) {
  if (res.finished) return

  const json = JSON.stringify(obj)
  res.setHeader('Content-Type', 'application/json')
  res.setHeader('Content-Length', Buffer.byteLength(json))
  res.end(method === 'HEAD' ? null : json)
}

function errorToJSON (err) {
  const { name, message, stack } = err
  const json = { name, message, stack }

  if (err.module) {
    // rawRequest contains the filename of the module which has the error.
    const { rawRequest } = err.module
    json.module = { rawRequest }
  }

  return json
}

export function serveStatic (req, res, path) {
  return new Promise((resolve, reject) => {
    send(req, path)
    .on('directory', () => {
      // We don't allow directories to be read.
      const err = new Error('No directory access')
      err.code = 'ENOENT'
      reject(err)
    })
    .on('error', reject)
    .pipe(res)
    .on('finish', resolve)
  })
}

async function ensurePage (page, { dir, hotReloader }) {
  if (!hotReloader) return
  if (page === '_error' || page === '_document') return

  await hotReloader.ensurePage(page)
}


text:
'use strict'

const HARError = require('../lib/error')
const invalid = require('./fixtures/request/invalid')
const tap = require('tap')
const valid = require('./fixtures/request/valid')
const validate = require('../lib/promise')

const errors = {
  object: new HARError([{ dataPath: '', message: "should have required property 'method'" }]),
  array: new HARError([{ dataPath: '', message: 'should be object' }]),
  undef: new HARError([{ dataPath: '', message: "should have required property 'method'" }]),
  url: new HARError([{ dataPath: '.url', message: 'should match format "uri"' }]),
  headers: new HARError([{ dataPath: '.headers', message: 'should be array' }]),
  malformed: new HARError([{ dataPath: '.headers[0]', message: "should have required property 'name'" }])
}

tap.test('request', assert => {
  assert.plan(7)

  return Promise.all([
    validate.request({}).catch(err => assert.match(err, errors.object, 'should fail with empty object')),
    validate.request([]).catch(err => assert.match(err, errors.array, 'should fail with empty array')),
    validate.request(undefined).catch(err => assert.match(err, errors.undef, 'should fail with undefined')),
    validate.request(invalid.url).catch(err => assert.match(err, errors.url, 'should fail on bad "url"')),
    validate.request(invalid.headers).catch(err => assert.match(err, errors.headers, 'should fail on bad "headers"')),
    validate.request(invalid.malformed).catch(err => assert.match(err, errors.malformed, 'should fail on malformed "headers"')),
    validate.request(valid).then(out => assert.equal(out, valid, 'should not fail with full example'))
  ])
})


text: Rails.application.config.session_store :cookie_store, key: '_playtest-set-game_session'


text:
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<database name="bookstore" defaultIdMethod="native"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    namespace="Propel\Tests\Bookstore">

        <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" description="Book Id"/>
        <column name="title" type="VARCHAR" required="true" description="Book Title" primaryString="true"/>
        <column name="isbn" required="true" type="VARCHAR" size="24" phpName="ISBN" description="ISBN Number" primaryString="false"/>
        <column name="price" required="false" type="FLOAT" description="Price of the book."/>
        <column name="publisher_id" required="false" type="INTEGER" description="Foreign Key Publisher"/>
        <column name="author_id" required="false" type="INTEGER" description="Foreign Key Author"/>
        <foreign-key foreignTable="publisher" onDelete="setnull">
            <reference local="publisher_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="author" onDelete="setnull" onUpdate="cascade">
            <reference local="author_id" foreign="id"/>
        </foreign-key>

        <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" description="Publisher Id"/>
        <column name="name" required="true" type="VARCHAR" size="128" default="Penguin" description="Publisher Name"/>

        <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" description="Author Id"/>
        <column name="first_name" required="true" type="VARCHAR" size="128" description="First Name"/>
        <column name="last_name" required="true" type="VARCHAR" size="128" description="Last Name"/>
        <column name="email" type="VARCHAR" size="128" description="E-Mail Address"/>
        <column name="age" type="INTEGER" description="The authors age"/>

        <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER"/>
        <column name="book_id" required="true" type="INTEGER"/>
        <column name="summary" required="true" type="LONGVARCHAR"/>
        <foreign-key phpName="SummarizedBook" foreignTable="book" onDelete="cascade">
            <reference local="book_id" foreign="id"/>
        </foreign-key>

        <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" description="Review Id"/>
        <column name="reviewed_by" required="true" type="VARCHAR" size="128" description="Reviewer Name"/>
        <column name="review_date" required="true" type="DATE" default="2001-01-01" description="Date of Review"/>
        <column name="recommended" required="true" type="BOOLEAN" description="Does reviewer recommend book?"/>
        <column name="status" type="VARCHAR" size="8" description="The status of this review."/>
        <column name="book_id" required="false" type="INTEGER" description="Book ID for this review"/>
        <foreign-key foreignTable="book" onDelete="cascade">
            <reference local="book_id" foreign="id"/>
        </foreign-key>

        <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER"/>
        <column name="title" type="VARCHAR" required="true" primaryString="true"/>
        <column name="first_author_id" required="false" type="INTEGER" description="Foreign Key Author"/>
        <column name="second_author_id" required="false" type="INTEGER" description="Foreign Key Author"/>
        <column name="subtitle" type="VARCHAR" phpName="SecondTitle"/>
        <column name="next_essay_id" required="false" type="INTEGER" description="Book Id"/>
        <foreign-key foreignTable="author" onDelete="setnull" onUpdate="cascade" phpName="FirstAuthor">
            <reference local="first_author_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="author" defaultJoin="INNER JOIN" onDelete="setnull" onUpdate="cascade" phpName="SecondAuthor">
            <reference local="second_author_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="essay" onDelete="setnull" onUpdate="cascade">
            <reference local="next_essay_id" foreign="id"/>
        </foreign-key>

        <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER"/>
        <column name="title" type="VARCHAR" required="true" primaryString="true"/>
        <column name="first_essay_id" required="false" type="INTEGER" description="Book Id"/>
        <column name="second_essay_id" required="false" type="INTEGER" description="Book Id"/>
        <foreign-key foreignTable="composite_essay" onDelete="setnull" onUpdate="cascade" phpName="firstEssay">
            <reference local="first_essay_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="composite_essay" onDelete="setnull" onUpdate="cascade" phpName="secondEssay">
            <reference local="second_essay_id" foreign="id"/>
        </foreign-key>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
        <column name="wife_id" type="INTEGER"/>
        <foreign-key foreignTable="woman" onDelete="setnull">
            <reference local="wife_id" foreign="id"/>
        </foreign-key>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true" required="true"/>
        <column name="husband_id" type="INTEGER"/>
        <foreign-key foreignTable="man">
            <reference local="husband_id" foreign="id"/>
        </foreign-key>

        <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" description="Media Id"/>
        <column name="cover_image" type="BLOB" lazyLoad="true" description="The image of the book cover."/>
        <column name="excerpt" type="CLOB" lazyLoad="true" description="An excerpt from the book."/>
        <column name="book_id" required="true" type="INTEGER" description="Book ID for this media collection."/>
        <foreign-key foreignTable="book" onDelete="cascade">
            <reference local="book_id" foreign="id"/>
        </foreign-key>

        <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" description="Unique ID for a school reading list."/>
        <column name="group_leader" required="true" type="VARCHAR" size="100" description="The name of the teacher in charge of summer reading."/>
        <column name="theme" required="false" type="VARCHAR" size="50" description="The theme, if applicable, for the reading list."/>
        <column name="created_at" required="false" type="TIMESTAMP"/>

        <column name="book_id" primaryKey="true" type="INTEGER" description="Fkey to book.id"/>
        <column name="book_club_list_id" primaryKey="true" type="INTEGER" description="Fkey to book_club_list.id"/>
        <foreign-key foreignTable="book" onDelete="cascade">
            <reference local="book_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="book_club_list" onDelete="cascade">
            <reference local="book_club_list_id" foreign="id"/>
        </foreign-key>

        <column name="book_id" primaryKey="true" type="INTEGER" description="Fkey to book.id"/>
        <column name="book_club_list_id" primaryKey="true" type="INTEGER" description="Fkey to book_club_list.id"/>
        <foreign-key foreignTable="book" phpName="FavoriteBook" onDelete="cascade">
            <reference local="book_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="book_club_list" phpName="FavoriteBookClubList" onDelete="cascade">
            <reference local="book_club_list_id" foreign="id"/>
        </foreign-key>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true" description="Employee ID number"/>
        <column name="class_key" type="INTEGER" required="true" default="0" inheritance="single">
            <inheritance key="0" class="BookstoreEmployee"/>
            <inheritance key="1" class="BookstoreManager" extends="BookstoreEmployee"/>
            <inheritance key="2" class="BookstoreCashier" extends="BookstoreEmployee"/>
            <inheritance key="3" class="BookstoreHead" extends="BookstoreManager"/>
        </column>
        <column name="name" type="VARCHAR" size="32" description="Employee name"/>
        <column name="job_title" type="VARCHAR" size="32" description="Employee job title"/>
        <column name="supervisor_id" type="INTEGER" description="Fkey to supervisor."/>
        <column name="photo" type="BLOB" lazyLoad="true"/>
        <foreign-key foreignTable="bookstore_employee" phpName="Supervisor" refPhpName="Subordinate" onDelete="setnull">
            <reference local="supervisor_id" foreign="id"/>
        </foreign-key>

        <column name="employee_id" type="INTEGER" primaryKey="true" description="Primary key for the account ..."/>
        <column name="login" type="VARCHAR" size="32"/>
        <column name="password" type="VARCHAR" size="100" default="'@''34""/>
        <column name="enabled" type="BOOLEAN" default="true"/>
        <column name="not_enabled" type="BOOLEAN" default="false"/>
        <column name="created" type="TIMESTAMP" defaultExpr="CURRENT_TIMESTAMP"/>
        <column name="role_id" type="INTEGER" required="false" default="null"/>
        <column name="authenticator" type="VARCHAR" size="32" defaultExpr="'Password'"/>
        <foreign-key foreignTable="bookstore_employee" onDelete="cascade">
            <reference local="employee_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="acct_access_role" onDelete="setnull">
            <reference local="role_id" foreign="id"/>
        </foreign-key>
        <unique>
            <unique-column name="login"/>
        </unique>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
        <column name="uid" type="VARCHAR" size="32" required="true"/>
        <column name="message" type="VARCHAR" size="255"/>
        <foreign-key foreignTable="bookstore_employee_account" onDelete="cascade">
            <reference local="uid" foreign="login"/>
        </foreign-key>
        <index>
            <index-column name="id"/>
            <index-column name="uid"/>
        </index>
        <unique>
            <unique-column name="uid"/>
            <unique-column name="message"/>
        </unique>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true" description="Role ID number"/>
        <column name="name" type="VARCHAR" size="25" required="true"/>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true" description="Book reader ID number"/>
        <column name="name" type="VARCHAR" size="50"/>

        <column name="book_id" type="INTEGER" primaryKey="true"/>
        <column name="reader_id" type="INTEGER" primaryKey="true"/>
        <column name="rating" type="DECIMAL"/>
        <column name="recommend_to_friend" type="BOOLEAN"/>
        <foreign-key foreignTable="book" onDelete="cascade">
            <reference local="book_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="book_reader" onDelete="cascade">
            <reference local="reader_id" foreign="id"/>
        </foreign-key>

        <column name="book_id" type="INTEGER" primaryKey="true"/>
        <column name="reader_id" type="INTEGER" primaryKey="true"/>
        <foreign-key foreignTable="book" onDelete="cascade">
            <reference local="book_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="book_reader" onDelete="cascade">
            <reference local="reader_id" foreign="id"/>
        </foreign-key>

        <foreign-key foreignTable="book_opinion" onDelete="cascade">
            <reference local="book_id" foreign="book_id"/>
            <reference local="reader_id" foreign="reader_id"/>
        </foreign-key>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true" description="Book store ID number"/>
        <column name="store_name" type="VARCHAR" size="50" required="true"/>
        <column name="location" type="VARCHAR" size="100"/>
        <column name="population_served" type="BIGINT"/>
        <column name="total_books" type="INTEGER"/>
        <column name="store_open_time" type="TIME"/>
        <column name="website" type="VARCHAR" size="255"/>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
        <column name="bookstore_id" type="INTEGER" required="false" default="1"/>
        <column name="publisher_id" type="INTEGER" required="false"/>
        <column name="sale_name" type="VARCHAR" size="100" required="false"/>
        <column name="discount" type="TINYINT" description="Discount percentage" defaultExpr="10"/>
        <foreign-key foreignTable="bookstore" onDelete="cascade">
            <reference local="bookstore_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="publisher" onDelete="setnull">
            <reference local="publisher_id" foreign="id"/>
        </foreign-key>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
        <column name="name" type="VARCHAR" size="255"/>
        <column name="join_date" type="DATE"/>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
        <column name="name" type="VARCHAR" size="100"/>
        <column name="country_code" type="VARCHAR" size="6"/>
        <foreign-key foreignTable="country" onDelete="setnull">
          <reference local="country_code" foreign="code"/>
        </foreign-key>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
        <column name="country_code" type="VARCHAR" size="6"/>
        <column name="language_code" type="VARCHAR" size="6"/>
        <column name="label" type="VARCHAR" size="100"/>
        <index>
            <index-column name="country_code"/>
        </index>
        <foreign-key foreignTable="country" onDelete="cascade">
            <reference local="country_code" foreign="code"/>
        </foreign-key>

        <column name="code" type="VARCHAR" size="6" primaryKey="true"/>
        <column name="capital" type="VARCHAR" size="100"/>

        <column name="bookstore_id" type="INTEGER" primaryKey="true"/>
        <column name="contest_id" type="INTEGER" primaryKey="true"/>
        <column name="prize_book_id" type="INTEGER"/>
        <foreign-key foreignTable="bookstore" onDelete="cascade">
            <reference local="bookstore_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="contest" onDelete="cascade">
            <reference local="contest_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="book" onDelete="setnull" phpName="Work">
            <reference local="prize_book_id" foreign="id"/>
        </foreign-key>

        <column name="bookstore_id" type="INTEGER" primaryKey="true"/>
        <column name="contest_id" type="INTEGER" primaryKey="true"/>
        <column name="customer_id" type="INTEGER" primaryKey="true"/>
        <column name="entry_date" type="TIMESTAMP" defaultExpr="CURRENT_TIMESTAMP"/>
        <foreign-key foreignTable="bookstore" onDelete="cascade">
            <reference local="bookstore_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="customer" onDelete="cascade">
            <reference local="customer_id" foreign="id"/>
        </foreign-key>
        <foreign-key foreignTable="bookstore_contest" onDelete="cascade">
            <reference local="bookstore_id" foreign="bookstore_id"/>
            <reference local="contest_id" foreign="contest_id"/>
        </foreign-key>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
        <column name="title" type="VARCHAR"/>
        <column name="style" type="ENUM" valueSet="novel, essay, poetry"/>
        <column name="style2" type="SET" valueSet="novel, essay, poetry"/>
        <column name="tags" type="ARRAY"/>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
        <column name="name" type="VARCHAR"/>
        <column name="type" type="INTEGER" required="true" default="0" inheritance="single">
            <inheritance key="44" class="DistributionStore"/>
            <inheritance key="23" class="DistributionOnline" extends="DistributionStore"/>
            <inheritance key="3838" class="DistributionVirtualStore" extends="DistributionStore"/>
        </column>
        <column name="distribution_manager_id" type="INTEGER" required="true"/>
        <foreign-key foreignTable="distribution_manager" onDelete="cascade">
            <reference local="distribution_manager_id" foreign="id"/>
        </foreign-key>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
        <column name="name" type="VARCHAR"/>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
        <column name="abbr" type="VARCHAR" size="5" primaryKey="true" required="true"/>
        <column name="name" type="VARCHAR"/>

        <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
        <column name="record_label_id" type="INTEGER" required="true"/>
        <column name="record_label_abbr" type="VARCHAR" size="5" required="true"/>
        <column name="name" type="VARCHAR"/>
        <foreign-key foreignTable="record_label" onDelete="cascade">
            <reference local="record_label_id" foreign="id"/>
            <reference local="record_label_abbr" foreign="abbr"/>
        </foreign-key>

        <column name="id" primaryKey="true" autoIncrement="true" type="INTEGER"/>
        <column name="message" type="VARCHAR" required="true"/>
        <column name="target_id" required="false" type="INTEGER"/>
        <column name="target_type" required="false" type="VARCHAR" size="55"/>

        <foreign-key foreignTable="author" onDelete="setnull" onUpdate="cascade">
            <reference local="target_type" value="author"/>
            <reference local="target_id" foreign="id"/>
        </foreign-key>

        <foreign-key foreignTable="book" onDelete="setnull" onUpdate="cascade">
            <reference local="target_type" value="book"/>
            <reference local="target_id" foreign="id"/>
        </foreign-key>

</database>


text:
<!doctype html>

		<title>Zabuun - Learn Arabic for English Speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

						Modern Standard Arabic (MSA) | Egyptian Colloquial Arabic (ECA) | Both

College Life

In Need of a Counselor

  A: I would like to see my counselor now.
 B: Sorry, she doesn't have any time today.
 A: Are you serious?
 B: Yes, I am. Please make an appointment for next week.
 A: I really need to see her.
 B: I'm sorry, but you really can't.
 A: I swear, I will bang on her door and scream.
 B: Don't make a scene.
 A: If you don't want me to make a scene, tell the counselor I'm here.
 B: Fine! You can only talk to her for five minutes, though.
 A: That's all I need.
 B: Next time, you'd better make an appointment.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
package org.apache.geronimo.axis2.client;

import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.jaxws.ClientConfigurationFactory;
import org.apache.axis2.jaxws.description.impl.DescriptionFactoryImpl;
import org.apache.axis2.metadata.registry.MetadataFactoryRegistry;
import org.apache.geronimo.axis2.osgi.Axis2ModuleRegistry;
import org.apache.geronimo.gbean.AbstractName;
import org.apache.geronimo.gbean.GBeanLifecycle;
import org.apache.geronimo.gbean.annotation.GBean;
import org.apache.geronimo.gbean.annotation.ParamAttribute;
import org.apache.geronimo.gbean.annotation.ParamReference;
import org.apache.geronimo.gbean.annotation.ParamSpecial;
import org.apache.geronimo.gbean.annotation.SpecialAttributeType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@GBean(name="Axis2ConfigGBean")
public class Axis2ConfigGBean implements GBeanLifecycle {

    private final static Logger LOG = LoggerFactory.getLogger(Axis2ConfigGBean.class);

    private AbstractName moduleName;
    private ClassLoader classLoder;
    private Axis2ModuleRegistry axis2ModuleRegistry;

    public Axis2ConfigGBean(@ParamAttribute(name = "moduleName") AbstractName moduleName,
                                                   @ParamReference(name = "Axis2ModuleRegistry") Axis2ModuleRegistry axis2ModuleRegistry,
                                                   @ParamSpecial(type = SpecialAttributeType.classLoader) ClassLoader classLoader) {
        this.moduleName = moduleName;
        this.classLoder = classLoader;
        this.axis2ModuleRegistry = axis2ModuleRegistry;
    }

    public synchronized static Axis2ClientConfigurationFactory registerClientConfigurationFactory(Axis2ModuleRegistry axis2ModuleRegistry) {
        ClientConfigurationFactory factory =
            (ClientConfigurationFactory)MetadataFactoryRegistry.getFactory(ClientConfigurationFactory.class);
        if (factory instanceof Axis2ClientConfigurationFactory) {
            return (Axis2ClientConfigurationFactory)factory;
        } else {
            factory = new Axis2ClientConfigurationFactory(axis2ModuleRegistry, false);
            MetadataFactoryRegistry.setFactory(ClientConfigurationFactory.class, factory);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Registered client configuration factory: " + factory);
            }
            // ensure that the factory was installed at the right time
            if (factory != DescriptionFactoryImpl.getClientConfigurationFactory()) {
                throw new RuntimeException("Client configuration factory was registered too late");
            }
            return (Axis2ClientConfigurationFactory)factory;
        }
    }

    public void doStart() throws Exception {
        registerClientConfigurationFactory(axis2ModuleRegistry);
    }

    public void doStop() throws Exception {
        ConfigurationContext configContext =
            registerClientConfigurationFactory(axis2ModuleRegistry).clearCache(this.classLoder);
        DescriptionFactoryImpl.clearServiceDescriptionCache(configContext);
    }

    public void doFail() {
    }
}


text:
package com.giikey.cdb;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JFrame;
import javax.swing.UIManager;

import com.giikey.cdb.game.Manage;
import com.giikey.cdb.util.Key;

public class Main {
	public JFrame f;
	public BufferStrategy bs;
	private Manage manage;
	public static final int h = 480, w = 640, FONTSIZE = 15;
	public static Key k;
	private boolean stop = false;
	public static final String name = "Crazy Dancing Ball";
//	public static Clip[] clips;

	public static void main(String[] args) {
		new Main();
	}

	public Main(){
		try{
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		}catch(Exception e){
			e.printStackTrace();
		}

		f = new JFrame();
		manage = new Manage();
		k = new Key();

/*		try {
			clips = new Clip[3];
			clips[0] = (Clip) AudioSystem.getLine(new DataLine.Info(Clip.class,AudioSystem.getAudioInputStream(getClass().getResource("1.wav")).getFormat()));
			clips[1] = (Clip) AudioSystem.getLine(new DataLine.Info(Clip.class,AudioSystem.getAudioInputStream(getClass().getResource("2.wav")).getFormat()));
			clips[2] = (Clip) AudioSystem.getLine(new DataLine.Info(Clip.class,AudioSystem.getAudioInputStream(getClass().getResource("3.wav")).getFormat()));
			clips[0].open(AudioSystem.getAudioInputStream(getClass().getResource("1.wav")));
			clips[1].open(AudioSystem.getAudioInputStream(getClass().getResource("2.wav")));
			clips[2].open(AudioSystem.getAudioInputStream(getClass().getResource("3.wav")));
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		} catch (UnsupportedAudioFileException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}*/

		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setBackground(new Color(30, 35, 30));
		f.addKeyListener(new KL());
		f.setResizable(false);
		f.setVisible(true);
		Insets insets = f.getInsets();
		f.setSize(w + insets.left + insets.right, h + insets.top + insets.bottom);
		f.setLocationRelativeTo(null);
		f.setIgnoreRepaint(true);

		f.createBufferStrategy(2);
		bs=f.getBufferStrategy();

		Timer t=new Timer();
		t.schedule(new TT(), 5, 10);
	}

	public class TT extends TimerTask{

		@Override
		public void run() {
			Graphics g = bs.getDrawGraphics();
			Insets in = f.getInsets();
			g.translate(in.left, in.top);
			g.setColor(new Color(30, 35, 30));
			g.fillRect(0, 0, w, h);
			if(k.esc){
				if(!stop)
					stop=true;
				else
					stop=false;
				k.offAll();
			}
			if(!stop){
				manage.loop(g, k);
			}

			bs.show();
			g.dispose();
		}

	}

	public class KL extends KeyAdapter{

		@Override
		public void keyPressed(KeyEvent ke) {
			if(ke.getKeyCode() == KeyEvent.VK_W){
				k.w = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_A){
				k.a = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_S){
				k.s = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_D){
				k.d = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_UP){
				k.w = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_LEFT){
				k.a = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_DOWN){
				k.s = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_RIGHT){
				k.d = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_SPACE){
				k.space = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_ENTER){
				k.space = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_Z){
				k.space = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_SHIFT){
				k.space = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_Q){
				k.q = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_R){
				k.r = Key.ON;
			}
			if(ke.getKeyCode() == KeyEvent.VK_ESCAPE){
				k.esc = Key.ON;
			}
		}

		@Override
		public void keyReleased(KeyEvent ke) {
			if(ke.getKeyCode() == KeyEvent.VK_W){
				k.w = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_A){
				k.a = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_S){
				k.s = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_D){
				k.d = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_UP){
				k.w = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_LEFT){
				k.a = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_DOWN){
				k.s = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_RIGHT){
				k.d = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_SPACE){
				k.space = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_ENTER){
				k.space = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_Z){
				k.space = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_SHIFT){
				k.space = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_Q){
				k.q = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_R){
				k.r = Key.OFF;
			}
			if(ke.getKeyCode() == KeyEvent.VK_ESCAPE){
				k.esc = Key.OFF;
			}
		}

	}

	public static void offKeys(){
		k.offAll();
	}

}


text:
//
//  NSDictionary+Categories.m
//  AuthProject
//
//  Created by Marco Sanson on 10/4/12.
//  Copyright (c) 2012 D-still Inc. All rights reserved.
//

#import "Categories.h"
#import <QuartzCore/QuartzCore.h>

static NSString * escapeString(NSString *unencodedString)
{
    return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                      (CFStringRef)unencodedString,
                                                                      NULL,
                                                                      (CFStringRef)@"!*'\"();:@&=+$,/?%#[]%. ",
                                                                      kCFStringEncodingUTF8));
}

@implementation NSDictionary (QueryStringBuilder)

@end

@implementation UIImage (DrawImage)

+ (UIImage *) bitmapFromRetinaImage:(UIImage *)img
{
    CGSize finalSize = (CGSize){ img.size.width * .5, img.size.height * .5 };

    UIGraphicsBeginImageContext(finalSize);
    [img drawInRect:(CGRect){0, 0, finalSize}];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

+ (UIImage *) drawImageFromView:(UIView *)contentView
{
    CGSize viewSize = contentView.frame.size;

    if([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2) {
        UIGraphicsBeginImageContextWithOptions(viewSize, NO, 2.0f);
    }else{
        UIGraphicsBeginImageContext(viewSize);
    }

    CGContextRef resizedContext = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(resizedContext, 0, 0);
    [contentView.layer renderInContext:resizedContext];

    CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), kCGInterpolationHigh);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

+ (UIImage *) imageFromColor:(UIColor *)color
                        rect:(CGRect)rect
                     corners:(UIRectCorner)corners
                       radii:(CGSize)radii
{
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [[UIScreen mainScreen] scale]);
    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextSetFillColorWithColor(context, [color CGColor]);
//    CGContextFillRect(context, rect);
    UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect:(CGRect){0, 0, rect.size.width, rect.size.height}
                                                               byRoundingCorners:corners
                                                                     cornerRadii:radii];
    CGContextSaveGState(context);
    [color setFill];
    [roundedRectanglePath fill];
    [roundedRectanglePath addClip];

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return img;
}

@end

@implementation UIImage (PrintBackground)

+ (UIImage *) returnImageFromView:(UIView *)view withRect:(CGRect)rect
{
    CGSize pageSize = rect.size;

    if([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2) {
        UIGraphicsBeginImageContextWithOptions(pageSize, NO, 2.0f);
    }else{
        UIGraphicsBeginImageContext(pageSize);
    }

    CGContextRef resizedContext = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(resizedContext, -rect.origin.x, 0);

    [[view layer] renderInContext:resizedContext];

    CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), kCGInterpolationHigh);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}

+ (UIImage *) rotateImage:(UIImage *)image
{

    CGImageRef imgRef = image.CGImage;

    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);

    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);

    if([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2) {
        UIGraphicsBeginImageContextWithOptions(bounds.size, NO, 2.0f);
    }else{
        UIGraphicsBeginImageContext(bounds.size);
    }

    CGFloat boundHeight;

    boundHeight = bounds.size.height;
    bounds.size.height = bounds.size.width;
    bounds.size.width = boundHeight;
    transform = CGAffineTransformMakeScale(-1.0, 1.0);
    transform = CGAffineTransformRotate(transform, M_PI / 2.0); //use angle/360 *MPI

    UIGraphicsBeginImageContext(bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextConcatCTM(context, transform);
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return imageCopy;
}

@end

@implementation NSDate (JSONDate)

+ (NSDate *) dateFromJSONDate:(NSString *)date
{
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SS'Z'"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

    return [NSDate dateToGMT:[dateFormatter dateFromString:date]];
}

+ (NSDate *) dateToGMT:(NSDate *)sourceDate
{
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:destinationGMTOffset sinceDate:sourceDate];
    return destinationDate;
}

+ (NSString *) dateToJSONDate:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SS'Z'"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

    return [dateFormatter stringFromDate:date];
}

+ (NSDate *) birthNSDateFromString:(NSString *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    NSRange stringRange = [date rangeOfString:@"/" options:NSCaseInsensitiveSearch];
    if( stringRange.location != NSNotFound ) {
        [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    } else {
        [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
        [dateFormatter setDateStyle:NSDateFormatterLongStyle];
    }

    return [dateFormatter dateFromString:date];
}

@end

@implementation NSObject (ObjectValidation)

- (BOOL)isValidObject
{
    if (self && ![self isEqual:[NSNull null]] && [self isKindOfClass:[NSObject class]]) {
        return YES;
    } else
        return NO;
}

- (BOOL)isValidString
{
    if ([self isValidObject] && [self isKindOfClass:[NSString class]] && ![(NSString *)self isEqualToString:@""]) {
        return YES;
    } else
        return NO;
}

@end

@implementation UIColor (RandomColor)

+ (UIColor *)randomColor
{
    return [self randomColorWithLimit:255];
}

+ (UIColor *)randomColorWithLimit:(int)limit
{
    return [[UIColor alloc] initWithRed:((arc4random()%limit)/255.0f) green:((arc4random()%limit)/255.0f)  blue:((arc4random()%limit)/255.0f) alpha:1];
}

@end

@implementation NSString (linkString)

- (NSString *)bodyOfLink
{
    return [[[[self lowercaseString] stringByReplacingOccurrencesOfString:@"https://" withString:@""] stringByReplacingOccurrencesOfString:@"http://" withString:@""] stringByReplacingOccurrencesOfString:@"www." withString:@""];
}

@end

@implementation UIImage (ResizeCategory)

-(UIImage*)resizeImageToSize:(CGSize)dstSize andScale:(CGFloat)scale{
    UIImage *resizedImage = [self resizedImageToSize:dstSize];
    return [UIImage imageWithCGImage:resizedImage.CGImage scale:scale orientation:resizedImage.imageOrientation];
}

-(UIImage*)resizedImageToSize:(CGSize)dstSize
{
	CGImageRef imgRef = self.CGImage;
	// the below values are regardless of orientation : for UIImages from Camera, width>height (landscape)
	CGSize  srcSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef)); // not equivalent to self.size (which is dependant on the imageOrientation)!

    /* Don't resize if we already meet the required destination size. */
    if (CGSizeEqualToSize(srcSize, dstSize)) {
        return self;
    }

	CGFloat scaleRatio = dstSize.width / srcSize.width;
	UIImageOrientation orient = self.imageOrientation;
	CGAffineTransform transform = CGAffineTransformIdentity;
	switch(orient) {

		case UIImageOrientationUp: //EXIF = 1
			transform = CGAffineTransformIdentity;
			break;

		case UIImageOrientationUpMirrored: //EXIF = 2
			transform = CGAffineTransformMakeTranslation(srcSize.width, 0.0);
			transform = CGAffineTransformScale(transform, -1.0, 1.0);
			break;

		case UIImageOrientationDown: //EXIF = 3
			transform = CGAffineTransformMakeTranslation(srcSize.width, srcSize.height);
			transform = CGAffineTransformRotate(transform, M_PI);
			break;

		case UIImageOrientationDownMirrored: //EXIF = 4
			transform = CGAffineTransformMakeTranslation(0.0, srcSize.height);
			transform = CGAffineTransformScale(transform, 1.0, -1.0);
			break;

		case UIImageOrientationLeftMirrored: //EXIF = 5
			dstSize = CGSizeMake(dstSize.height, dstSize.width);
			transform = CGAffineTransformMakeTranslation(srcSize.height, srcSize.width);
			transform = CGAffineTransformScale(transform, -1.0, 1.0);
			transform = CGAffineTransformRotate(transform, 3.0 * M_PI_2);
			break;

		case UIImageOrientationLeft: //EXIF = 6
			dstSize = CGSizeMake(dstSize.height, dstSize.width);
			transform = CGAffineTransformMakeTranslation(0.0, srcSize.width);
			transform = CGAffineTransformRotate(transform, 3.0 * M_PI_2);
			break;

		case UIImageOrientationRightMirrored: //EXIF = 7
			dstSize = CGSizeMake(dstSize.height, dstSize.width);
			transform = CGAffineTransformMakeScale(-1.0, 1.0);
			transform = CGAffineTransformRotate(transform, M_PI_2);
			break;

		case UIImageOrientationRight: //EXIF = 8
			dstSize = CGSizeMake(dstSize.height, dstSize.width);
			transform = CGAffineTransformMakeTranslation(srcSize.height, 0.0);
			transform = CGAffineTransformRotate(transform, M_PI_2);
			break;

		default:
			[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];

	}

	/////////////////////////////////////////////////////////////////////////////
	// The actual resize: draw the image on a new context, applying a transform matrix
	UIGraphicsBeginImageContextWithOptions(dstSize, NO, self.scale);

	CGContextRef context = UIGraphicsGetCurrentContext();

    if (!context) {
        return nil;
    }

	if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
		CGContextScaleCTM(context, -scaleRatio, scaleRatio);
		CGContextTranslateCTM(context, -srcSize.height, 0);
	} else {
		CGContextScaleCTM(context, scaleRatio, -scaleRatio);
		CGContextTranslateCTM(context, 0, -srcSize.height);
	}

	CGContextConcatCTM(context, transform);

	// we use srcSize (and not dstSize) as the size to specify is in user space (and we use the CTM to apply a scaleRatio)
	CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, srcSize.width, srcSize.height), imgRef);
	UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();

	return resizedImage;
}

/////////////////////////////////////////////////////////////////////////////

-(UIImage*)resizedImageToFitInSize:(CGSize)boundingSize scaleIfSmaller:(BOOL)scale
{
	// get the image size (independant of imageOrientation)
	CGImageRef imgRef = self.CGImage;
	CGSize srcSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef)); // not equivalent to self.size (which depends on the imageOrientation)!

	// adjust boundingSize to make it independant on imageOrientation too for farther computations
	UIImageOrientation orient = self.imageOrientation;
	switch (orient) {
		case UIImageOrientationLeft:
		case UIImageOrientationRight:
		case UIImageOrientationLeftMirrored:
		case UIImageOrientationRightMirrored:
			boundingSize = CGSizeMake(boundingSize.height, boundingSize.width);
			break;
        default:
            // NOP
            break;
	}

	// Compute the target CGRect in order to keep aspect-ratio
	CGSize dstSize;

	if ( !scale && (srcSize.width < boundingSize.width) && (srcSize.height < boundingSize.height) ) {
		//NSLog(@"Image is smaller, and we asked not to scale it in this case (scaleIfSmaller:NO)");
		dstSize = srcSize; // no resize (we could directly return 'self' here, but we draw the image anyway to take image orientation into account)
	} else {
		CGFloat wRatio = boundingSize.width / srcSize.width;
		CGFloat hRatio = boundingSize.height / srcSize.height;

		if (wRatio < hRatio) {
			//NSLog(@"Width imposed, Height scaled ; ratio = %f",wRatio);
			dstSize = CGSizeMake(boundingSize.width, floorf(srcSize.height * wRatio));
		} else {
			//NSLog(@"Height imposed, Width scaled ; ratio = %f",hRatio);
			dstSize = CGSizeMake(floorf(srcSize.width * hRatio), boundingSize.height);
		}
	}

	return [self resizedImageToSize:dstSize];
}

-(UIImage*)resizedImageToFitInSize:(CGSize)boundingSize scaleIfSmaller:(BOOL)scaleIfSmaller andScale:(CGFloat)scale{
    UIImage *resizedImage = [self resizedImageToFitInSize:boundingSize scaleIfSmaller:scaleIfSmaller];
    return [UIImage imageWithCGImage:resizedImage.CGImage scale:scale orientation:resizedImage.imageOrientation];
}

@end

@implementation UIImage (NYX_Resizing)

-(UIImage*)cropToSize:(CGSize)newSize usingMode:(NYXCropMode)cropMode
{
    const CGSize size = self.size;
    CGFloat x, y;
    switch (cropMode)
    {
        case NYXCropModeTopLeft:
            x = y = 0.0f;
            break;
        case NYXCropModeTopCenter:
            x = (size.width - newSize.width) * 0.5f;
            y = 0.0f;
            break;
        case NYXCropModeTopRight:
            x = size.width - newSize.width;
            y = 0.0f;
            break;
        case NYXCropModeBottomLeft:
            x = 0.0f;
            y = size.height - newSize.height;
            break;
        case NYXCropModeBottomCenter:
            x = (size.width - newSize.width) * 0.5f;
            y = size.height - newSize.height;
            break;
        case NYXCropModeBottomRight:
            x = size.width - newSize.width;
            y = size.height - newSize.height;
            break;
        case NYXCropModeLeftCenter:
            x = 0.0f;
            y = (size.height - newSize.height) * 0.5f;
            break;
        case NYXCropModeRightCenter:
            x = size.width - newSize.width;
            y = (size.height - newSize.height) * 0.5f;
            break;
        case NYXCropModeCenter:
            x = (size.width - newSize.width) * 0.5f;
            y = (size.height - newSize.height) * 0.5f;
            break;
        default: // Default to top left
            x = y = 0.0f;
            break;
    }

    if (self.imageOrientation == UIImageOrientationLeft || self.imageOrientation == UIImageOrientationLeftMirrored || self.imageOrientation == UIImageOrientationRight || self.imageOrientation == UIImageOrientationRightMirrored)
    {
        CGFloat temp = x;
        x = y;
        y = temp;
    }

    CGRect cropRect = CGRectMake(x * self.scale, y * self.scale, newSize.width * self.scale, newSize.height * self.scale);

    /// Create the cropped image
    CGImageRef croppedImageRef = CGImageCreateWithImageInRect(self.CGImage, cropRect);
    UIImage* cropped = [UIImage imageWithCGImage:croppedImageRef scale:self.scale orientation:self.imageOrientation];

    /// Cleanup
    CGImageRelease(croppedImageRef);

    return cropped;
}

/* Convenience method to crop the image from the top left corner */
-(UIImage*)cropToSize:(CGSize)newSize
{
    return [self cropToSize:newSize usingMode:NYXCropModeTopLeft];
}

-(UIImage*)scaleByFactor:(float)scaleFactor
{
    CGSize scaledSize = CGSizeMake(self.size.width * scaleFactor, self.size.height * scaleFactor);
    return [self scaleToFillSize:scaledSize];
}

-(UIImage*)scaleToSize:(CGSize)newSize usingMode:(NYXResizeMode)resizeMode
{
    switch (resizeMode)
    {
        case NYXResizeModeAspectFit:
            return [self scaleToFitSize:newSize];
        case NYXResizeModeAspectFill:
            return [self scaleToCoverSize:newSize];
        default:
            return [self scaleToFillSize:newSize];
    }
}

/* Convenience method to scale the image using the NYXResizeModeScaleToFill mode */
-(UIImage*)scaleToSize:(CGSize)newSize
{
    return [self scaleToFillSize:newSize];
}

-(UIImage*)scaleToFillSize:(CGSize)newSize
{
    size_t destWidth = (size_t)(newSize.width * self.scale);
    size_t destHeight = (size_t)(newSize.height * self.scale);
    if (self.imageOrientation == UIImageOrientationLeft
        || self.imageOrientation == UIImageOrientationLeftMirrored
        || self.imageOrientation == UIImageOrientationRight
        || self.imageOrientation == UIImageOrientationRightMirrored)
    {
        size_t temp = destWidth;
        destWidth = destHeight;
        destHeight = temp;
    }

    /// Create an ARGB bitmap context
    CGContextRef bmContext = NYXCreateARGBBitmapContext(destWidth, destHeight, destWidth * kNyxNumberOfComponentsPerARBGPixel, NYXImageHasAlpha(self.CGImage));
    if (!bmContext)
        return nil;

    /// Image quality
    CGContextSetShouldAntialias(bmContext, true);
    CGContextSetAllowsAntialiasing(bmContext, true);
    CGContextSetInterpolationQuality(bmContext, kCGInterpolationHigh);

    /// Draw the image in the bitmap context

    UIGraphicsPushContext(bmContext);
    CGContextDrawImage(bmContext, CGRectMake(0.0f, 0.0f, destWidth, destHeight), self.CGImage);
    UIGraphicsPopContext();

    /// Create an image object from the context
    CGImageRef scaledImageRef = CGBitmapContextCreateImage(bmContext);
    UIImage* scaled = [UIImage imageWithCGImage:scaledImageRef scale:self.scale orientation:self.imageOrientation];

    /// Cleanup
    CGImageRelease(scaledImageRef);
    CGContextRelease(bmContext);

    return scaled;
}

-(UIImage*)scaleToFitSize:(CGSize)newSize
{
    /// Keep aspect ratio
    size_t destWidth, destHeight;
    if (self.size.width > self.size.height)
    {
        destWidth = (size_t)newSize.width;
        destHeight = (size_t)(self.size.height * newSize.width / self.size.width);
    }
    else
    {
        destHeight = (size_t)newSize.height;
        destWidth = (size_t)(self.size.width * newSize.height / self.size.height);
    }
    if (destWidth > newSize.width)
    {
        destWidth = (size_t)newSize.width;
        destHeight = (size_t)(self.size.height * newSize.width / self.size.width);
    }
    if (destHeight > newSize.height)
    {
        destHeight = (size_t)newSize.height;
        destWidth = (size_t)(self.size.width * newSize.height / self.size.height);
    }
    return [self scaleToFillSize:CGSizeMake(destWidth, destHeight)];
}

-(UIImage*)scaleToCoverSize:(CGSize)newSize
{
    size_t destWidth, destHeight;
    CGFloat widthRatio = newSize.width / self.size.width;
    CGFloat heightRatio = newSize.height / self.size.height;
    /// Keep aspect ratio
    if (heightRatio > widthRatio)
    {
        destHeight = (size_t)newSize.height;
        destWidth = (size_t)(self.size.width * newSize.height / self.size.height);
    }
    else
    {
        destWidth = (size_t)newSize.width;
        destHeight = (size_t)(self.size.height * newSize.width / self.size.width);
    }
    return [self scaleToFillSize:CGSizeMake(destWidth, destHeight)];
}

@end


text:
 For best results, consider using Opera or Chrome

    <button type="button">dismiss</button>

 This website may not display properly using your browser. Consider using Opera or Chrome


text:
---
uid: SolidEdgeDraft.BlockOccurrences.Parent
summary:
remarks:
---