text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package keylistenerscenario;

import com.jogamp.newt.event.NEWTEvent;
import com.jogamp.newt.event.NEWTEventFiFo;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

/**
 *
 * @author gbarbieri
 */
public class EC_GUI extends javax.swing.JFrame {

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        border_panel = new javax.swing.JPanel();
        centerPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        border_panel.setLayout(new java.awt.BorderLayout());

        centerPanel.setLayout(new java.awt.BorderLayout());
        border_panel.add(centerPanel, java.awt.BorderLayout.CENTER);

        getContentPane().add(border_panel, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(EC_GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//        //</editor-fold>
//
//        //</editor-fold>
//        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                EC_GUI ec_gui = new EC_GUI();
                ec_gui.pack();
                ec_gui.setVisible(true);
            }
        });
    }

    private GlViewer glViewer;
    public static EC_GUI main;
    private boolean oPressed = false;
    private boolean ctrlPressed = false;
    private NEWTEventFiFo newtEventFifo;
    private NEWTEvent newtEvent;

    /**
     * Creates new form EC_GUI1
     */
    public EC_GUI() {

        JFrame.setDefaultLookAndFeelDecorated(false);
//        this.setUndecorated(true);

//        addKeyListener(new KeyListener() {
//
//            @Override
//            public void keyTyped(KeyEvent e) {
//                System.out.println("typed ");
////                System.out.println(
////                        +e.getExtendedKeyCode()
////                        + " " + e.getID()
////                        + " " + e.getKeyChar()
////                        + " " + e.getKeyCode()
////                        + " " + e.getKeyLocation()
////                        + " " + e.getModifiers()
////                        + " " + e.getModifiersEx()
////                );
//            }
//
//            @Override
//            public void keyPressed(KeyEvent e) {
//                System.out.println("pressed");
////                System.out.println(
////                        +e.getExtendedKeyCode()
////                        + " " + e.getID()
////                        + " " + e.getKeyChar()
////                        + " " + e.getKeyCode()
////                        + " " + e.getKeyLocation()
////                        + " " + e.getModifiers()
////                        + " " + e.getModifiersEx()
////                );
//                switch (e.getKeyCode()) {
//
//                    case KeyEvent.VK_CONTROL:
//                        ctrlPressed = true;
//                        break;
//                    case KeyEvent.VK_O:
//                        oPressed = true;
//                        break;
//                }
//                check();
//            }
//
//            @Override
//            public void keyReleased(KeyEvent e) {
//                System.out.println("released");
//                switch (e.getKeyCode()) {
//
//                    case KeyEvent.VK_CONTROL:
//                        ctrlPressed = false;
//                        break;
//                    case KeyEvent.VK_O:
//                        oPressed = false;
//                        break;
//                }
//            }
//        });
        initComponents();

//        Action openFileChooserAction = new AbstractAction() {
//
//            @Override
//            public void actionPerformed(ActionEvent e) {
//                System.out.println("actionPerformed");
//                openFileChooser();
//            }
//        };
//        KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_W, 0);
//        centerPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "openFileChooser");
//        centerPanel.getActionMap().put("openFileChooser", openFileChooserAction);
//
//        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
//        manager.addKeyEventDispatcher(new MyDispatcher());

        setSize(800, 600);
        setLocation(30, 30);

        main = this;

        initGlViewer();

//        InputListener2 listener2 = new InputListener2();
//        listener2.run();
//        Thread thread = new Thread(new InputListener2());
//        thread.start();

//        setVisible(true);

//        glViewer.getNewtCanvasAWT().requestFocus();
    }

    private void check() {

        if (oPressed && ctrlPressed) {

            openFileChooser();
        }
    }

    private void openFileChooser() {
        //            System.out.println(""+SwingUtilities.isEventDispatchThread());
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                System.out.println("fileChooser opens");
                JFileChooser fileChooser = new JFileChooser();

                if (fileChooser.showOpenDialog(EC_GUI.main) != JFileChooser.APPROVE_OPTION) {
                    System.out.println("fileChooser closed");
                }
            }
        });
    }

    private void initGlViewer() {
        /**
         * Viewer.
         */
        glViewer = new GlViewer();
        glViewer.setup();
//        System.out.println(""+SwingUtilities.isEventDispatchThread());
        centerPanel.add(glViewer.getNewtCanvasAWT());
//        centerPanel.setFocusable(false);
//        SwingUtilities.invokeLater(new Runnable() {
//
//            @Override
//            public void run() {
//                centerPanel.add(glViewer.getNewtCanvasAWT());
//                centerPanel.setFocusable(false);
//            }
//        });
    }

    private class MyDispatcher implements KeyEventDispatcher {

        @Override
        public boolean dispatchKeyEvent(KeyEvent e) {

            if (e.getID() == KeyEvent.KEY_PRESSED) {

                System.out.println("pressed");

            } else if (e.getID() == KeyEvent.KEY_RELEASED) {

                System.out.println("released");

            } else if (e.getID() == KeyEvent.KEY_TYPED) {

                System.out.println("typed");

            }
            return false;
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel border_panel;
    private javax.swing.JPanel centerPanel;
    // End of variables declaration//GEN-END:variables
}


text:
I use this application along with the [grails-plugin-test-script](https://github.com/kensiprell/grails-plugin-test-script) for testing the [grails-atmosphere-meteor](https://github.com/kensiprell/grails-atmosphere-meteor) plugin.

If you have a question, problem, suggestion, or want to report a bug, please submit an [issue](https://github.com/kensiprell/grails-atmosphere-meteor-sample/issues?state=open). I will reply as soon as I can.

```
git clone git://github.com/kensiprell/grails-atmosphere-meteor-sample.git

cd grails-atmosphere-meteor-sample

grails refresh-dependencies

grails run-app
```

You will have a simple application that performs the following tasks out of the box. Please note that this sample is not production ready. It merely incorporates some of the lessons I have learned and provides a point of departure for your own application.

* Chat (open two different browsers on your computer and start chatting)

* Sends a one-time, client-triggered notification to subscribers

* Automatically updates the web page at predefined intervals

You can review the files below to understand how it all works.

* The files in grails-app/atmosphere/org/grails/plugins/atmosphere_meteor_sample/

* grails-app/conf/AtmosphereMeteorConfig.groovy

* grails-app/controllers/org/grails/plugins/atmosphere_meteor_sample/AtmosphereTestController.groovy

* grails-app/services/org/grails/plugins/atmosphere_meteor_sample/AtmosphereTestService.groovy

* grails-app/views/AtmosphereTest/index.gsp: This file contains all internal JavaScript.

The application also has eight geb functional tests. Use the command below to run the tests in Chrome although you'll have to set the path to the driver in test/functional/GebConfig.groovy:

```
git clone git://github.com/kensiprell/grails-atmosphere-meteor-sample.git

cd grails-atmosphere-meteor-sample

grails refresh-dependencies

grails -Dgeb.env=chrome test-app functional:
```
Use the command below to run the tests in Firefox. However, I could not get Selenium to send an ENTER key in Firefox, so the chat test could fail.

```
git clone git://github.com/kensiprell/grails-atmosphere-meteor-sample.git

cd grails-atmosphere-meteor-sample

grails refresh-dependencies

grails test-app functional:
```

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
Copyright 2011 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

<!--
   Congratulations, if you're reading this comment, you're probably
   one of first in the world to look at this code!

   We checked in this first draft once we had the initial features
   working and the basic structure in place, and now the next step
   is to get a proper code review and start improving the quality
   of the code.  All the code below this line is eagerly awaiting
   your review comments.
-->

  <servlet>
    <servlet-name>profileServlet</servlet-name>
    <servlet-class>com.google.dotorg.translation_workflow.servlet.ProfileServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>profileServlet</servlet-name>
    <url-pattern>/profile</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>projectServlet</servlet-name>
    <servlet-class>com.google.dotorg.translation_workflow.servlet.ProjectServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>projectServlet</servlet-name>
    <url-pattern>/project</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>lexiconServlet</servlet-name>
    <servlet-class>com.google.dotorg.translation_workflow.servlet.LexiconServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>lexiconServlet</servlet-name>
    <url-pattern>/term/*</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>claimServlet</servlet-name>
    <servlet-class>com.google.dotorg.translation_workflow.servlet.ClaimServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>claimServlet</servlet-name>
    <url-pattern>/claim_item</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>uploadServlet</servlet-name>
    <servlet-class>com.google.dotorg.translation_workflow.servlet.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>uploadServlet</servlet-name>
    <url-pattern>/upload_csv</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>importServlet</servlet-name>
    <servlet-class>com.google.dotorg.translation_workflow.servlet.ImportServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>importServlet</servlet-name>
    <url-pattern>/import_spreadsheet</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>validateServlet</servlet-name>
    <servlet-class>com.google.dotorg.translation_workflow.servlet.NicknameValidateServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>validateServlet</servlet-name>
    <url-pattern>/validate_nickname</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>refreshProgressServlet</servlet-name>
    <servlet-class>com.google.dotorg.translation_workflow.servlet.RefreshProgressServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>refreshProgressServlet</servlet-name>
    <url-pattern>/refresh_progress</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>allProjectsJSP</servlet-name>
    <jsp-file>/page/all_projects.jsp</jsp-file>
  </servlet>
  <servlet-mapping>
    <servlet-name>allProjectsJSP</servlet-name>
    <url-pattern>/all_projects</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>myTranslationsJSP</servlet-name>
    <jsp-file>/page/my_translations.jsp</jsp-file>
  </servlet>
  <servlet-mapping>
    <servlet-name>myTranslationsJSP</servlet-name>
    <url-pattern>/my_translations</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>myProfileJSP</servlet-name>
    <jsp-file>/page/profile.jsp</jsp-file>
  </servlet>
  <servlet-mapping>
    <servlet-name>myProfileJSP</servlet-name>
    <url-pattern>/my_profile</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>projectOverviewJSP</servlet-name>
    <jsp-file>/page/project_overview.jsp</jsp-file>
  </servlet>
  <servlet-mapping>
    <servlet-name>projectOverviewJSP</servlet-name>
    <url-pattern>/project_overview</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>helpJSP</servlet-name>
    <jsp-file>/page/help.jsp</jsp-file>
  </servlet>
  <servlet-mapping>
    <servlet-name>helpJSP</servlet-name>
    <url-pattern>/help</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>startJSP</servlet-name>
    <jsp-file>/page/start.jsp</jsp-file>
  </servlet>
  <servlet-mapping>
    <servlet-name>startJSP</servlet-name>
    <url-pattern>/start</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>homeJSP</servlet-name>
    <jsp-file>/site-config/home.jsp</jsp-file>
  </servlet>
  <servlet-mapping>
    <servlet-name>homeJSP</servlet-name>
    <url-pattern>/home</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>learnmoreJSP</servlet-name>
    <jsp-file>/site-config/learnmore.jsp</jsp-file>
  </servlet>
  <servlet-mapping>
    <servlet-name>learnmoreJSP</servlet-name>
    <url-pattern>/learnmore</url-pattern>
  </servlet-mapping>
  <!-- Default page to serve -->
  <welcome-file-list>
    <welcome-file>start</welcome-file>
  </welcome-file-list>

  <!-- Error pages -->
  <error-page>
    <error-code>500</error-code>
    <location>/page/server_error.jsp</location>
  </error-page>

  <error-page>
    <error-code>404</error-code>
    <location>/page/not_found_error.jsp</location>
  </error-page>

  <!-- Enable Appstats performance profiling -->

  <filter>
    <filter-name>appstats</filter-name>
    <filter-class>com.google.appengine.tools.appstats.AppstatsFilter</filter-class>
    <init-param>
      <param-name>logMessage</param-name>
      <param-value>Appstats available: /appstats/details?time={ID}</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>appstats</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>appstats</servlet-name>
    <servlet-class>com.google.appengine.tools.appstats.AppstatsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>appstats</servlet-name>
    <url-pattern>/appstats/*</url-pattern>
  </servlet-mapping>

  <security-constraint>
    <web-resource-collection>
      <url-pattern>/appstats/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
      <role-name>admin</role-name>
    </auth-constraint>
  </security-constraint>

</web-app>


text:
package org.collectionspace.services.client.test;

import java.util.Arrays;
import javax.ws.rs.core.Response;

/**
 * ServiceRequestType, identifies types of service requests
 * and the valid HTTP status codes that can be returned from
 * each type of request.
 *
 * Used by client tests of services.
 *
 * $LastChangedRevision: 566 $
 * $LastChangedDate$
 */
public enum ServiceRequestType {

    // Define each of the service request types and their valid HTTP status codes.
    CREATE {

        @Override
        public int[] validStatusCodes() {
            final int[] STATUS_CODES = {
                Response.Status.CREATED.getStatusCode(),
                Response.Status.BAD_REQUEST.getStatusCode(),
                Response.Status.UNAUTHORIZED.getStatusCode(),
                Response.Status.FORBIDDEN.getStatusCode(),
                Response.Status.CONFLICT.getStatusCode(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()
            };
            Arrays.sort(STATUS_CODES);
            return STATUS_CODES;
        }

        @Override
        public boolean isValidStatusCode(int statusCode) {
            if (Arrays.binarySearch(CREATE.validStatusCodes(), statusCode) >= 0) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public String validStatusCodesAsString() {
            return Arrays.toString(CREATE.validStatusCodes());
        }

        @Override
        public String httpMethodName() {
            return javax.ws.rs.HttpMethod.POST;
        }
    }, // Note that commas are required at the end of each enum block, except the last.

    READ {

        @Override
        public int[] validStatusCodes() {
            final int[] STATUS_CODES = {
                Response.Status.OK.getStatusCode(),
                Response.Status.BAD_REQUEST.getStatusCode(),
                Response.Status.UNAUTHORIZED.getStatusCode(),
                Response.Status.FORBIDDEN.getStatusCode(),
                Response.Status.NOT_FOUND.getStatusCode(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()
            };
            Arrays.sort(STATUS_CODES);
            return STATUS_CODES;
        }

        @Override
        public boolean isValidStatusCode(int statusCode) {
            if (Arrays.binarySearch(READ.validStatusCodes(), statusCode) >= 0) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public String validStatusCodesAsString() {
            return Arrays.toString(READ.validStatusCodes());
        }

        @Override
        public String httpMethodName() {
            return javax.ws.rs.HttpMethod.GET;
        }
    },
    READ_LIST {

        @Override
        public int[] validStatusCodes() {
            final int[] STATUS_CODES = {
                Response.Status.OK.getStatusCode(),
                Response.Status.BAD_REQUEST.getStatusCode(),
                Response.Status.UNAUTHORIZED.getStatusCode(),
                Response.Status.FORBIDDEN.getStatusCode(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()
            };
            Arrays.sort(STATUS_CODES);
            return STATUS_CODES;
        }

        @Override
        public boolean isValidStatusCode(int statusCode) {
            if (Arrays.binarySearch(READ_LIST.validStatusCodes(), statusCode) >= 0) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public String validStatusCodesAsString() {
            return Arrays.toString(READ_LIST.validStatusCodes());
        }

        @Override
        public String httpMethodName() {
            return javax.ws.rs.HttpMethod.GET;
        }
    },
    UPDATE {

        @Override
        public int[] validStatusCodes() {
            final int[] STATUS_CODES = {
                Response.Status.OK.getStatusCode(),
                Response.Status.BAD_REQUEST.getStatusCode(),
                Response.Status.UNAUTHORIZED.getStatusCode(),
                Response.Status.FORBIDDEN.getStatusCode(),
                Response.Status.NOT_FOUND.getStatusCode(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()
            };
            Arrays.sort(STATUS_CODES);
            return STATUS_CODES;
        }

        @Override
        public boolean isValidStatusCode(int statusCode) {
            if (Arrays.binarySearch(UPDATE.validStatusCodes(), statusCode) >= 0) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public String validStatusCodesAsString() {
            return Arrays.toString(UPDATE.validStatusCodes());
        }

        @Override
        public String httpMethodName() {
            return javax.ws.rs.HttpMethod.PUT;
        }
    },
    DELETE {

        @Override
        public int[] validStatusCodes() {
            final int[] STATUS_CODES = {
                Response.Status.OK.getStatusCode(),
                Response.Status.UNAUTHORIZED.getStatusCode(),
                Response.Status.FORBIDDEN.getStatusCode(),
                Response.Status.NOT_FOUND.getStatusCode(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()
            };
            Arrays.sort(STATUS_CODES);
            return STATUS_CODES;
        }

        @Override
        public boolean isValidStatusCode(int statusCode) {
            if (Arrays.binarySearch(DELETE.validStatusCodes(), statusCode) >= 0) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public String validStatusCodesAsString() {
            return Arrays.toString(DELETE.validStatusCodes());
        }

        @Override
        public String httpMethodName() {
            return javax.ws.rs.HttpMethod.DELETE;
        }
    },
    SEARCH {

        @Override
        public int[] validStatusCodes() {
            final int[] STATUS_CODES = {
                Response.Status.OK.getStatusCode(),
                Response.Status.UNAUTHORIZED.getStatusCode(),
                Response.Status.FORBIDDEN.getStatusCode(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()
            };
            Arrays.sort(STATUS_CODES);
            return STATUS_CODES;
        }

        @Override
        public boolean isValidStatusCode(int statusCode) {
            if (Arrays.binarySearch(SEARCH.validStatusCodes(), statusCode) >= 0) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public String validStatusCodesAsString() {
            return Arrays.toString(SEARCH.validStatusCodes());
        }

        @Override
        public String httpMethodName() {
            return javax.ws.rs.HttpMethod.GET;
        }
    },
    // Used by guard code.
    NON_EXISTENT {

        @Override
        public int[] validStatusCodes() {
            final int[] STATUS_CODES = {0};
            Arrays.sort(STATUS_CODES);
            return STATUS_CODES;
        }

        @Override
        public boolean isValidStatusCode(int statusCode) {
            return false;
        }

        @Override
        public String validStatusCodesAsString() {
            return Arrays.toString(NON_EXISTENT.validStatusCodes());
        }

        @Override
        public String httpMethodName() {
            return "";
        }
    };

    // Template methods to be implemented by each ServiceRequestType.
    public abstract int[] validStatusCodes();

    public abstract boolean isValidStatusCode(int statusCode);

    public abstract String validStatusCodesAsString();

    public abstract String httpMethodName();
}


text:
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
import os

from hello import *

app.config.from_object(os.environ['APP_SETTINGS'])

migrate = Migrate(app, db)
manager = Manager(app)

manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()


text:
package com.linkedin.thirdeye.datalayer.bao;

import com.linkedin.thirdeye.datalayer.dto.ClassificationConfigDTO;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestClassificationJobConfigManager extends AbstractManagerTestBase {
  private static final List<Long> MAIN_FUNCTION_ID = Collections.singletonList(101L);

  private static final String NAME1 = "test classification name1";
  private static final List<Long> MAIN_FUNCTION_ID1 = MAIN_FUNCTION_ID;
  private static List<Long> AUX_FUNCTION_IDS1 = new ArrayList<Long>() {{
    addAll(MAIN_FUNCTION_ID1);
    add(102L);
    add(103L);
  }};

  private static final String NAME2 = "test classification name2";
  private static final List<Long> MAIN_FUNCTION_ID2 = MAIN_FUNCTION_ID;
  private static List<Long> AUX_FUNCTION_IDS2 = new ArrayList<Long>() {{
    addAll(MAIN_FUNCTION_ID2);
    add(103L);
    add(204L);
  }};

  private Long configId1;
  private Long configId2;

  @BeforeClass
  void beforeClass() {
    super.init();
  }

  @AfterClass(alwaysRun = true)
  void afterClass() {
    super.cleanup();
  }

  @Test
  public void testCreateConfig() {
    ClassificationConfigDTO classificationConfig1 = this.getTestClassificationConfig(NAME1, MAIN_FUNCTION_ID1,
        AUX_FUNCTION_IDS1);
    configId1 = classificationConfigDAO.save(classificationConfig1);
    Assert.assertTrue(configId1 > 0);

    ClassificationConfigDTO classificationConfig2 = this.getTestClassificationConfig(NAME2, MAIN_FUNCTION_ID2,
        AUX_FUNCTION_IDS2);
    classificationConfig2.setActive(false);
    configId2 = classificationConfigDAO.save(classificationConfig2);
    Assert.assertTrue(configId2 > 0);
  }

  @Test (dependsOnMethods = {"testCreateConfig"})
  public void testFetchConfig() {
    ClassificationConfigDTO response = classificationConfigDAO.findById(configId1);
    Assert.assertNotNull(response);
    Assert.assertEquals(response.getId(), configId1);
    Assert.assertEquals(response.getName(), NAME1);

    response = classificationConfigDAO.findByName(NAME1);
    Assert.assertNotNull(response);
    Assert.assertEquals(response.getId(), configId1);
    Assert.assertEquals(response.getName(), NAME1);
    Assert.assertEquals(response.isActive(), true);
    Assert.assertEquals(response.getAuxFunctionIdList(), AUX_FUNCTION_IDS1);

    response = classificationConfigDAO.findByName(NAME2);
    Assert.assertNotNull(response);
    Assert.assertEquals(response.getId(), configId2);
    Assert.assertEquals(response.getName(), NAME2);
    Assert.assertEquals(response.isActive(), false);
    Assert.assertEquals(response.getAuxFunctionIdList(), AUX_FUNCTION_IDS2);
  }

  @Test (dependsOnMethods = {"testFetchConfig"})
  public void testDeleteConfig() {
    classificationConfigDAO.deleteById(configId1);
    List<ClassificationConfigDTO> allDTO =  classificationConfigDAO.findAll();
    Assert.assertEquals(allDTO.size(), 1);
  }
}


text:
"""Relative imports for gramcore.data"""
import gramcore.data.images
import gramcore.data.arrays


text:
<?xml version='1.0' encoding='UTF-8'?>
<ListDirectoryResponse xmlns='http://www.emc.com/cos/'>
    <DirectoryList/>
</ListDirectoryResponse>


text:
<input type="hidden" name="last_4_digits" id="last_4_digits" value="{{ form.last_4_digits.value }}">
            <input type="hidden" name="stripe_token" id="stripe_token" value="{{ form.stripe_token.value }}">

              <p>
                This form requires Javascript to use
              </p>

                Credit card number

                  <input class="field" id="credit_card_number" type="text">

                Security code (CVV)

                  <input class="small" id="cvv" type="text">

                Expiry date

                  <select class="small" id="expiry_month">
                  {% for month in months %}
                    <option value="{{ month }}"{% if soon.month == month %} selected{% endif %}>{{ month }}</option>
                  {% endfor %}
                  </select>
                  <select class="small" id="expiry_year">
                  {% for year in years %}
                    <option value="{{ year }}"{% if soon.year == year %} selected{% endif %}>{{ year }}</option>
                  {% endfor %}
                  </select>

                Your credit card details will be sent directly to our payment processor

              <input class="btn primary" id="user_submit" name="commit" type="submit" value="Register">


text:
namespace instrument {
namespace transforms {

namespace {

using block_graph::BasicBlock;
using block_graph::BasicCodeBlock;
using block_graph::BasicBlockDecomposer;
using block_graph::BasicBlockSubGraph;
using block_graph::BlockGraph;
using block_graph::Instruction;
using common::IndexedFrequencyData;

class TestJumpTableCaseCountTransform : public JumpTableCaseCountTransform {
 public:
  using JumpTableCaseCountTransform::add_frequency_data;
  using JumpTableCaseCountTransform::jump_table_case_counter_hook_ref;
  using JumpTableCaseCountTransform::thunk_section;

  BlockGraph::Block* frequency_data_block() {
    return add_frequency_data()->frequency_data_block();
  }

  BlockGraph::Block* frequency_data_buffer_block() {
    return add_frequency_data()->frequency_data_buffer_block();
  }
};

typedef testing::TestDllTransformTest JumpTableCaseCountTransformTest;

// Ensures that the @p block is a jump table case count thunk.
void CheckBlockIsAThunk(BlockGraph::Block* block) {
  // Decompose the block to basic-blocks.
  BasicBlockSubGraph subgraph;
  BasicBlockDecomposer bb_decomposer(block, &subgraph);
  ASSERT_TRUE(bb_decomposer.Decompose());

  ASSERT_EQ(2u, subgraph.basic_blocks().size());
  const BasicCodeBlock* bb = BasicCodeBlock::Cast(
      *subgraph.basic_blocks().begin());
  ASSERT_TRUE(bb != NULL);
  ASSERT_FALSE(bb->is_padding());

  ASSERT_EQ(2U, bb->instructions().size());
  BasicBlock::Instructions::const_iterator inst_iter =
      bb->instructions().begin();

  // Instruction 1 should push the case id.
  EXPECT_EQ(I_PUSH, inst_iter->representation().opcode);

  // Instruction 2 should call the jump table counter hook.
  ++inst_iter;
  EXPECT_EQ(I_CALL, inst_iter->representation().opcode);

  EXPECT_EQ(BasicBlock::BASIC_END_BLOCK,
            (*subgraph.basic_blocks().rbegin())->type());
}

}  // namespace

TEST_F(JumpTableCaseCountTransformTest, Apply) {
  ASSERT_NO_FATAL_FAILURE(DecomposeTestDll());

  // Apply the transform.
  TestJumpTableCaseCountTransform tx;
  ASSERT_TRUE(block_graph::ApplyBlockGraphTransform(
      &tx, policy_, &block_graph_, header_block_));
  ASSERT_TRUE(tx.frequency_data_block() != NULL);
  ASSERT_TRUE(tx.thunk_section() != NULL);
  ASSERT_TRUE(tx.jump_table_case_counter_hook_ref() != NULL);
  ASSERT_TRUE(tx.jump_table_case_counter_hook_ref()->IsValid());

  // Validate the jump table frequency data structure.
  block_graph::ConstTypedBlock<IndexedFrequencyData> frequency_data;
  ASSERT_TRUE(frequency_data.Init(0, tx.frequency_data_block()));
  EXPECT_EQ(sizeof(uint32), frequency_data->frequency_size);
  EXPECT_EQ(common::kJumpTableCountAgentId, frequency_data->agent_id);
  EXPECT_EQ(common::kJumpTableFrequencyDataVersion, frequency_data->version);
  EXPECT_EQ(IndexedFrequencyData::JUMP_TABLE, frequency_data->data_type);
  EXPECT_EQ(sizeof(IndexedFrequencyData), tx.frequency_data_block()->size());
  EXPECT_EQ(sizeof(IndexedFrequencyData),
            tx.frequency_data_block()->data_size());
  EXPECT_TRUE(frequency_data.HasReferenceAt(
      frequency_data.OffsetOf(frequency_data->frequency_data)));
  BlockGraph::Reference frequency_data_reference;
  ASSERT_TRUE(frequency_data.block()->GetReference(
      frequency_data.OffsetOf(frequency_data->frequency_data),
      &frequency_data_reference));
  EXPECT_EQ(frequency_data_reference.referenced(),
            tx.frequency_data_buffer_block());
  EXPECT_EQ(frequency_data->num_entries * frequency_data->frequency_size,
            tx.frequency_data_buffer_block()->size());

  // Examine each eligible block to verify that all the jump tables have
  // been instrumented.
  size_t jump_table_entries = 0;
  for (BlockGraph::BlockMap::const_iterator block_iter(
           block_graph_.blocks().begin());
      block_iter != block_graph_.blocks().end();
      ++block_iter) {
    const BlockGraph::Block& block = block_iter->second;

    // Skip non-code blocks.
    if (block.type() != BlockGraph::CODE_BLOCK)
      continue;

    // We don't want to check the thunk blocks.
    if (block.section() == tx.thunk_section()->id())
      continue;

    // Iterate over the labels to find the jump tables.
    for (BlockGraph::Block::LabelMap::const_iterator iter_label(
             block.labels().begin());
        iter_label != block.labels().end();
        ++iter_label) {
      if (!iter_label->second.has_attributes(BlockGraph::JUMP_TABLE_LABEL))
        continue;

      size_t table_size = 0;
      ASSERT_TRUE(
          block_graph::GetJumpTableSize(&block, iter_label, &table_size));

      BlockGraph::Block::ReferenceMap::const_iterator iter_ref =
          block.references().find(iter_label->first);
      ASSERT_TRUE(iter_ref != block.references().end());

      // Iterate over the references and ensure that they are thunked.
      for (size_t i = 0; i < table_size; ++i) {
        BlockGraph::Block* ref_block = iter_ref->second.referenced();
        CheckBlockIsAThunk(ref_block);
        ++iter_ref;
      }

      jump_table_entries += table_size;
    }
  }
  DCHECK_EQ(frequency_data->num_entries, jump_table_entries);
}

}  // namespace transforms
}  // namespace instrument


text:
import {objectDiff} from '../src/utils';
import test from './test';

test('Object Difference Calculation');

let objA = {test: 123, me: 'test', x: {list: [1, 2, 3]}};

test('compare same objects', t => {
	let result = objectDiff(objA, objA);
	t.false(result, false, 'same ');
});

test('compare two different objects', t => {
	let objB = {test: 123, me: 'test', x: {list: [1, 2, 4]}};
	let result = objectDiff(objA, objB);
	t.not(result, false, 'objA and objB are different');
	t.false(objectDiff(result, {x: {list: {2: 4}}}), 'locates incorrect entry in array');
});

test('different values', t => {
	let objC = {test: 12, me: 'txst', x: {list: [1, 2, 3]}};
	let result = objectDiff(objA, objC);
	t.not(result, false, 'objA and objC are different');
	t.false(objectDiff(result, {test: 12, me: 'txst'}), 'locates incorrect entries in object');
});

test('different properties', t => {
	let objD = {test: 123, entry: {test: 12}};
	let result = objectDiff(objA, objD);
	t.not(result, false, 'objA and objD are different');
	t.false(objectDiff(result, {me: 'test', x: {list: [1, 2, 3]}, entry: {test: 12}}), 'locates differences in both objects ');
});

test('different order', t => {
	let objE = {me: 'test', test: 123, x: {list: [1, 2, 3]}};
	let result = objectDiff(objA, objE);
	t.not(result, false, 'objA and objE are different');
	t.false(objectDiff(result, {me: 'test', test: 123}), 'locates swapped attribute positions ');
});


text:
Node.js can read from Environment Variables. These can be useful for storing bits of data like connection strings and usernames.

To run the example first set an environment variable from your terminal.

On UNIX systems use

    export SECRET_KEY='c6YFPvdT7Yh3JAFW62EBa5LDe4X'

On Windows systems use

    SET SECRET_KEY='c6YFPvdT7Yh3JAFW62EBa5LDe4X'

Then run the script

    node app.js

You should see

    c6YFPvdT7Yh3JAFW62EBa5LDe4X

Examine app.js to see that is just a single line to get this data.


text:
.class final Landroid/view/ViewRootImpl$ImeInputStage;
.super Landroid/view/ViewRootImpl$AsyncInputStage;
.source "ViewRootImpl.java"

# interfaces
.implements Landroid/view/inputmethod/InputMethodManager$FinishedInputEventCallback;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/view/ViewRootImpl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x10
    name = "ImeInputStage"
.end annotation

# instance fields
.field final synthetic this$0:Landroid/view/ViewRootImpl;

# direct methods
.method public constructor <init>(Landroid/view/ViewRootImpl;Landroid/view/ViewRootImpl$InputStage;Ljava/lang/String;)V
    .locals 0
    .param p2, "next"    # Landroid/view/ViewRootImpl$InputStage;
    .param p3, "traceCounter"    # Ljava/lang/String;

    .prologue
    .line 3935
    iput-object p1, p0, Landroid/view/ViewRootImpl$ImeInputStage;->this$0:Landroid/view/ViewRootImpl;

    .line 3936
    invoke-direct {p0, p1, p2, p3}, Landroid/view/ViewRootImpl$AsyncInputStage;-><init>(Landroid/view/ViewRootImpl;Landroid/view/ViewRootImpl$InputStage;Ljava/lang/String;)V

    .line 3937
    return-void
.end method

# virtual methods
.method public onFinishedInputEvent(Ljava/lang/Object;Z)V
    .locals 4
    .param p1, "token"    # Ljava/lang/Object;
    .param p2, "handled"    # Z

    .prologue
    .line 3969
    move-object v0, p1

    check-cast v0, Landroid/view/ViewRootImpl$QueuedInputEvent;

    .line 3971
    .local v0, "q":Landroid/view/ViewRootImpl$QueuedInputEvent;
    # getter for: Landroid/view/ViewRootImpl;->DEBUG_IMF:Z
    invoke-static {}, Landroid/view/ViewRootImpl;->access$1400()Z

    move-result v1

    if-eqz v1, :cond_0

    .line 3972
    const-string v2, "ViewRootImpl"

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v3, "IME handled="

    invoke-virtual {v1, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    if-eqz p2, :cond_1

    const-string v1, "T"

    :goto_0
    invoke-virtual {v3, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v2, v1}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I

    .line 3975
    :cond_0
    if-eqz p2, :cond_2

    .line 3976
    const/4 v1, 0x1

    invoke-virtual {p0, v0, v1}, Landroid/view/ViewRootImpl$ImeInputStage;->finish(Landroid/view/ViewRootImpl$QueuedInputEvent;Z)V

    .line 3980
    :goto_1
    return-void

    .line 3972
    :cond_1
    const-string v1, "F"

    goto :goto_0

    .line 3979
    :cond_2
    invoke-virtual {p0, v0}, Landroid/view/ViewRootImpl$ImeInputStage;->forward(Landroid/view/ViewRootImpl$QueuedInputEvent;)V

    goto :goto_1
.end method

.method protected onProcess(Landroid/view/ViewRootImpl$QueuedInputEvent;)I
    .locals 8
    .param p1, "q"    # Landroid/view/ViewRootImpl$QueuedInputEvent;

    .prologue
    const/4 v3, 0x1

    const/4 v4, 0x0

    .line 3941
    iget-object v5, p0, Landroid/view/ViewRootImpl$ImeInputStage;->this$0:Landroid/view/ViewRootImpl;

    iget-boolean v5, v5, Landroid/view/ViewRootImpl;->mLastWasImTarget:Z

    if-eqz v5, :cond_4

    iget-object v5, p0, Landroid/view/ViewRootImpl$ImeInputStage;->this$0:Landroid/view/ViewRootImpl;

    # invokes: Landroid/view/ViewRootImpl;->isInLocalFocusMode()Z
    invoke-static {v5}, Landroid/view/ViewRootImpl;->access$1000(Landroid/view/ViewRootImpl;)Z

    move-result v5

    if-nez v5, :cond_4

    .line 3942
    invoke-static {}, Landroid/view/inputmethod/InputMethodManager;->peekInstance()Landroid/view/inputmethod/InputMethodManager;

    move-result-object v1

    .line 3943
    .local v1, "imm":Landroid/view/inputmethod/InputMethodManager;
    if-eqz v1, :cond_4

    .line 3944
    iget-object v0, p1, Landroid/view/ViewRootImpl$QueuedInputEvent;->mEvent:Landroid/view/InputEvent;

    .line 3946
    .local v0, "event":Landroid/view/InputEvent;
    # getter for: Landroid/view/ViewRootImpl;->DEBUG_IMF:Z
    invoke-static {}, Landroid/view/ViewRootImpl;->access$1400()Z

    move-result v5

    if-eqz v5, :cond_0

    .line 3947
    const-string v5, "ViewRootImpl"

    const-string v6, "IME send"

    invoke-static {v5, v6}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I

    .line 3949
    :cond_0
    iget-object v5, p0, Landroid/view/ViewRootImpl$ImeInputStage;->this$0:Landroid/view/ViewRootImpl;

    iget-object v5, v5, Landroid/view/ViewRootImpl;->mHandler:Landroid/view/ViewRootImpl$ViewRootHandler;

    invoke-virtual {v1, v0, p1, p0, v5}, Landroid/view/inputmethod/InputMethodManager;->dispatchInputEvent(Landroid/view/InputEvent;Ljava/lang/Object;Landroid/view/inputmethod/InputMethodManager$FinishedInputEventCallback;Landroid/os/Handler;)I

    move-result v2

    .line 3950
    .local v2, "result":I
    # getter for: Landroid/view/ViewRootImpl;->DEBUG_IMF:Z
    invoke-static {}, Landroid/view/ViewRootImpl;->access$1400()Z

    move-result v5

    if-eqz v5, :cond_1

    .line 3951
    const-string v5, "ViewRootImpl"

    new-instance v6, Ljava/lang/StringBuilder;

    invoke-direct {v6}, Ljava/lang/StringBuilder;-><init>()V

    const-string v7, "IME dispatch="

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    invoke-virtual {v6, v2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v6

    invoke-virtual {v6}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v6

    invoke-static {v5, v6}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I

    .line 3954
    :cond_1
    if-ne v2, v3, :cond_2

    .line 3964
    .end local v0    # "event":Landroid/view/InputEvent;
    .end local v1    # "imm":Landroid/view/inputmethod/InputMethodManager;
    .end local v2    # "result":I
    :goto_0
    return v3

    .line 3956
    .restart local v0    # "event":Landroid/view/InputEvent;
    .restart local v1    # "imm":Landroid/view/inputmethod/InputMethodManager;
    .restart local v2    # "result":I
    :cond_2
    if-nez v2, :cond_3

    move v3, v4

    .line 3958
    goto :goto_0

    .line 3960
    :cond_3
    const/4 v3, 0x3

    goto :goto_0

    .end local v0    # "event":Landroid/view/InputEvent;
    .end local v1    # "imm":Landroid/view/inputmethod/InputMethodManager;
    .end local v2    # "result":I
    :cond_4
    move v3, v4

    .line 3964
    goto :goto_0
.end method


text:
import { Component } from '@angular/core';
import { Router } from "@angular/router";
import { AF } from "./providers/af";
import * as firebase from 'firebase';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  public isLoggedIn: boolean;

  constructor(public afService: AF, private router: Router){
    // This asynchronously checks if our user is logged it and will automatically
    // redirect them to the Login page when the status changes.
    this.afService.userLog().subscribe(
      (auth) => {
        if(auth == null) {
          console.log("Not Logged in.");
          this.isLoggedIn = false;
          this.router.navigate(['login']);
        }

        else {
          console.log("Successfully Logged in.");
          this.isLoggedIn = true;
          this.router.navigate(['']);
        }
      });
  }

  logout() {
    this.afService.logout();
  }

}


text:
// Copyright Contributors to the Open Shading Language project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/AcademySoftwareFoundation/OpenShadingLanguage

#pragma once

#include <optix.h>

#if (OPTIX_VERSION < 70000)
#include <optixu/optixu_math_namespace.h>
#include <optixu/optixu_vector_types.h>
typedef optix::float3 float3;
typedef optix::uchar4 uchar4;
#endif

#include <stdint.h>

struct PRD_radiance
{
    float3 result;
};

struct RayGeometry {
    float3 origin;
    float3 direction;
};

static __device__ __inline__
uchar4 make_color (const float3& c)
{
    return make_uchar4 (static_cast<unsigned char>(__saturatef(c.z)*255.99f),  /* B */
                        static_cast<unsigned char>(__saturatef(c.y)*255.99f),  /* G */
                        static_cast<unsigned char>(__saturatef(c.x)*255.99f),  /* R */
                        255u);                                                 /* A */
}


text:
static const int DEFAULT_MAX_SESSION_AGE = 25 * 60; // 25 minutes

@interface ZKAuthInfoBase()
@property (retain) NSString *sessionId;
@property (retain) NSURL *instanceUrl;
@property (retain) NSDate *sessionExpiresAt;
@property (retain) NSString *clientId;
@end

@implementation ZKAuthInfoBase

@synthesize sessionId, instanceUrl, sessionExpiresAt, clientId;

-(void)dealloc {
    [sessionId release];
    [instanceUrl release];
    [sessionExpiresAt release];
    [clientId release];
    [super dealloc];
}

-(void)refresh {
    // override me!
}

-(BOOL)refreshIfNeeded {
	if ((sessionExpiresAt && [sessionExpiresAt timeIntervalSinceNow] < 0) || (sessionId == nil)) {
		[self refresh];
        return TRUE;
    }
    return FALSE;
}

@end

@implementation ZKOAuthInfo

@synthesize apiVersion, refreshToken, authHostUrl=authUrl;

+(NSDictionary *)decodeParams:(NSString *)params {
    NSMutableDictionary *results = [NSMutableDictionary dictionary];
    for (NSString *param in [params componentsSeparatedByString:@"&"]) {
        NSArray *paramParts = [param componentsSeparatedByString:@"="];
        NSString *name = [[paramParts objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *val = [paramParts count] == 1 ? @"" : [[paramParts objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [results setObject:val forKey:name];
    }
    if ([results objectForKey:@"error"] != nil)
        @throw [NSException exceptionWithName:@"OAuth Error"
                                       reason:[NSString stringWithFormat:@"%@ : %@", [results objectForKey:@"error"], [results objectForKey:@"error_description"]]
                                     userInfo:results];
    return results;
}

+(id)oauthInfoFromCallbackUrl:(NSURL *)callbackUrl clientId:(NSString *)cid {
    // callbackUrl will be something:///blah/blah#p=1&q=2&foo=bar
    // we need to get our params out of the callback fragment
    NSDictionary *params = [self decodeParams:[callbackUrl fragment]];

    return [ZKOAuthInfo oauthInfoWithRefreshToken:[params objectForKey:@"refresh_token"]
                                         authHost:[NSURL URLWithString:[params objectForKey:@"id"]]
                                        sessionId:[params objectForKey:@"access_token"]
                                      instanceUrl:[NSURL URLWithString:[params objectForKey:@"instance_url"]]
                                         clientId:cid];
}

+(id)oauthInfoWithRefreshToken:(NSString *)tkn authHost:(NSURL *)auth clientId:(NSString *)cid {
    return [[[ZKOAuthInfo alloc] initWithRefreshToken:tkn authHost:auth sessionId:nil instanceUrl:nil clientId:cid] autorelease];
}

+(id)oauthInfoWithRefreshToken:(NSString *)tkn authHost:(NSURL *)auth sessionId:(NSString *)sid instanceUrl:(NSURL *)inst clientId:(NSString *)cid {
    return [[[ZKOAuthInfo alloc] initWithRefreshToken:tkn authHost:auth sessionId:sid instanceUrl:inst clientId:cid] autorelease];
}

-(id)initWithRefreshToken:(NSString *)tkn authHost:(NSURL *)auth sessionId:(NSString *)sid instanceUrl:(NSURL *)inst clientId:(NSString *)cid {
    self = [super init];
    clientId = [cid retain];
    sessionId = [sid retain];
    refreshToken = [tkn retain];
    instanceUrl = [inst retain];
    authUrl = [[NSURL URLWithString:@"/" relativeToURL:auth] retain];
    self.sessionExpiresAt = [NSDate dateWithTimeIntervalSinceNow:DEFAULT_MAX_SESSION_AGE];
    return self;
}

-(void)dealloc {
    [refreshToken release];
    [authUrl release];
    [super dealloc];
}

-(NSURL *)instanceUrl {
    return [NSURL URLWithString:[NSString stringWithFormat:@"/services/Soap/u/%d.0", apiVersion] relativeToURL:instanceUrl];
}

-(void)refresh {
    NSURL *token = [NSURL URLWithString:@"/services/oauth2/token" relativeToURL:authUrl];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:token];
    [req setHTTPMethod:@"POST"];
    NSString *params = [NSString stringWithFormat:@"grant_type=refresh_token&refresh_token=%@&client_id=%@&format=urlencoded",
                      [refreshToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                      [clientId stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    [req setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
    [req addValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

 	NSHTTPURLResponse *resp = nil;
	NSError *err = nil;
	NSData *respPayload = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:&err];
    NSString *respBody = [[[NSString alloc] initWithBytes:[respPayload bytes] length:[respPayload length] encoding:NSUTF8StringEncoding] autorelease];
    NSDictionary *results = [ZKOAuthInfo decodeParams:respBody];

    self.sessionId = [results objectForKey:@"access_token"];
    self.instanceUrl = [NSURL URLWithString:[results objectForKey:@"instance_url"]];
    self.sessionExpiresAt = [NSDate dateWithTimeIntervalSinceNow:DEFAULT_MAX_SESSION_AGE];
}

-(BOOL)refreshIfNeeded {
    BOOL r = [super refreshIfNeeded];
    self.sessionExpiresAt = [NSDate dateWithTimeIntervalSinceNow:DEFAULT_MAX_SESSION_AGE];
    return r;
}

@end

@implementation ZKSoapLogin

-(id)initWithUsername:(NSString *)un password:(NSString *)pwd authHost:(NSURL *)auth apiVersion:(int)v clientId:(NSString *)cid {
    self = [super init];
    username = [un retain];
    password = [pwd retain];
    clientId = [cid retain];
    client = [[ZKBaseClient alloc] init];
	client.endpointUrl = [NSURL URLWithString:[NSString stringWithFormat:@"/services/Soap/u/%d.0", v] relativeToURL:auth];
    return self;
}

-(void)dealloc {
    [username release];
    [password release];
    [client release];
    [super dealloc];
}

-(void)refresh {
    [self login];
}

-(ZKLoginResult *)login {
	ZKEnvelope *env = [[ZKPartnerEnvelope alloc] initWithSessionHeader:nil clientId:clientId];
	[env startElement:@"login"];
	[env addElement:@"username" elemValue:username];
	[env addElement:@"password" elemValue:password];
	[env endElement:@"login"];
	[env endElement:@"s:Body"];
	NSString *xml = [env end];
	[env release];

	zkElement *resp = [client sendRequest:xml];
	zkElement *result = [[resp childElements:@"result"] objectAtIndex:0];
	ZKLoginResult *lr = [[[ZKLoginResult alloc] initWithXmlElement:result] autorelease];

	self.instanceUrl = [NSURL URLWithString:[lr serverUrl]];
	self.sessionId = [lr sessionId];

	// if we have a sessionSecondsValid in the UserInfo, use that to control when we re-authenticate, otherwise take the default.
	int sessionAge = [[lr userInfo] sessionSecondsValid] > 0 ? [[lr userInfo] sessionSecondsValid] - 60 : DEFAULT_MAX_SESSION_AGE;
	self.sessionExpiresAt = [NSDate dateWithTimeIntervalSinceNow:sessionAge];
	return lr;
}

+(id)soapLoginWithUsername:(NSString *)un password:(NSString *)pwd authHost:(NSURL *)auth apiVersion:(int)v clientId:(NSString *)cid {
    return [[[ZKSoapLogin alloc] initWithUsername:un password:pwd authHost:auth apiVersion:v clientId:cid] autorelease];
}

@end


text:
var usedColors = [];
var fadeTime = 400;

function getColor() {
    let colors = ['#98dafc', '#b0aac2', '#f2efe8', '#c2d4d8', '#dbe9d8'];
    let vibrants = ['#92DCE5' ,'#B8B8F3', '#D7B8F3', '#F397D6', '#F42272', '#232E21', '#000000'];
    let greyscale = ['#FFFBFE', '#7A7D7D', '#D0CFCF', '#565254'];

    let color = vibrants[Math.floor(Math.random() * 100 * colors.length) % colors.length];

    if (usedColors.length === colors.length) usedColors = [];
    if (usedColors.indexOf(color) !== -1) return getColor();

    usedColors.push(color);

    return color;
}

function isHidden(el) {
    return (el.offsetParent === null);
}

function fadeIn(el) {
    let opacity = parseInt(window.getComputedStyle(el).opacity);

    let interval = setInterval( () => {
        if (opacity > 0.99) clearInterval(interval);
        opacity += 0.01;
        el.style.opacity = opacity;
    });
}

function toggleDescription(e) {
    let descr = e.target.nextSibling;

    if (!descr) descr = e.target.parentNode.nextSibling;

    descr.style.display = isHidden(descr) ? "block" : "none";
}

function randOffsetCenter(el, prev) {
    let amt = rand(-60, 40) - prev;
    el.style.transform = `translateX(${amt}%)`;
    return amt;
}

function rand(min, max) {
    return Math.random() * (max - min) + min;
}

function showMenu(artists) {
  console.log("showMenu()");
  if (!document.getElementById("artists")) return setTimeout( () => showMenu(artists), 1000);

  console.log("showMenu() 2");
  console.log(artists);
    let menu = document.createElement("div");
    menu.setAttribute("id", "artist-menu");

    artists.forEach( (artist, index) => {
        let anchor = document.createElement("a");
        anchor.href = `#artist-${index}`;
        anchor.textContent = artist.name;
        menu.appendChild(anchor);
    });

    console.log(menu);

    document.querySelector("#artists").insertBefore(menu, document.querySelector(".artist-wrap"));
}

function animatePhotos() {
  let photos = document.querySelectorAll(".artist-photo-wrap");
  if (!photos.length) return;

  animated = true;
  photos.forEach( (photo, idx) => {
      let prevOffset = 0;
      setTimeout( () => {
          prevOffset = randOffsetCenter(photo, prevOffset);
      }, idx * fadeTime);
  }, 1000);

}


text:
if __name__ == "__main__":
    from app import application
    application.app.debug = True
    application.app.run()


text:
import {TestBed, ComponentFixture}  from '@angular/core/testing';
import {Component} from '@angular/core';
import {createGenericTestComponent} from '../../../test/util/helpers';
import {NglFormsModule} from '../module';

const createTestComponent = (html?: string, detectChanges?: boolean) =>
  createGenericTestComponent(TestComponent, html, detectChanges) as ComponentFixture<TestComponent>;

export function getLabelElement(element: Element): HTMLLabelElement {
  return <HTMLLabelElement>element.querySelector('label');
}

function getInputElement(element: Element): HTMLInputElement {
  return <HTMLInputElement>element.querySelector('input');
}

export function getErrorElement(element: Element): HTMLDivElement {
  return <HTMLDivElement>element.querySelector('.slds-form-element__help');
}

export function getRequiredElement(element: Element): HTMLDivElement {
  return <HTMLDivElement>element.querySelector('abbr');
}

describe('`NglFormInput`', () => {

  beforeEach(() => TestBed.configureTestingModule({declarations: [TestComponent], imports: [NglFormsModule]}));

  it('should render correctly', () => {
    const fixture = createTestComponent();
    const element = fixture.nativeElement.firstElementChild;
    expect(element).toHaveCssClass('slds-form-element');

    const labelEl = getLabelElement(element);
    expect(labelEl).toHaveText('My label');

    const inputEl = getInputElement(element);
    expect(inputEl).toHaveCssClass('slds-input');

    const inputId = inputEl.getAttribute('id');
    expect(inputId).toMatch(/form_element_/);
    expect(inputId).toEqual(labelEl.getAttribute('for'));
  });

  it('should be able to change label', () => {
    const fixture = createTestComponent();
    fixture.componentInstance.label = 'Another label';
    fixture.detectChanges();

    const labelEl = getLabelElement(fixture.nativeElement);
    expect(labelEl).toHaveText('Another label');
  });

  it('should render error message', () => {
    const fixture = createTestComponent(`<ngl-form-element [error]="error"><input nglFormControl type="text"></ngl-form-element>`);
    const element = fixture.nativeElement.firstElementChild;

    expect(element).not.toHaveCssClass('slds-has-error');
    expect(getErrorElement(element)).toBeFalsy();
    fixture.componentInstance.error = 'This is an error!';
    fixture.detectChanges();

    const errorEl = getErrorElement(element);
    const inputEl = getInputElement(element);
    expect(element).toHaveCssClass('slds-has-error');
    expect(errorEl.id).toEqual(inputEl.getAttribute('aria-describedby'));
    expect(errorEl).toHaveText('This is an error!');
  });

  it('should throw error if structure is wrong', () => {
    expect(() => createTestComponent(`<ngl-form-element><input type="input"></ngl-form-element>`)).toThrowError();
  });

});

@Component({
  template: `
    <ngl-form-element [label]="label">
      <input nglFormControl type="text">
    </ngl-form-element>
  `,
})
export class TestComponent {
  label: string = 'My label';
  error: string;
}


text:
namespace gamelib
{
    constexpr const char* buttonStrings[] = {
        "Select Tool",
        "Sprite Tool",
        "Brush Tool",
        "Vertex Tool",
        "Entity Tool"
    };

    // Strips PolygonBrushComponents from output
    void defaultExport(const std::string& fname);

    void hideRenderSystem();
    void showRenderSystem();

    void addRenderSystemFlags(unsigned int flags);
    void removeRenderSystemFlags(unsigned int flags);
    void toggleRenderSystemFlags(unsigned int flags);

    Editor::Editor() :
        GameState(gamestate_freeze),
        _exportcallback(defaultExport),
        _currenttool(nullptr),
        _cam("editorcam"),
        _camctrl(&_cam),
        _entsearch(false),
        _drag(false),
        _grid(32, 32),
        _snap(true),
        _gridontop(false),
        _run(false),
        _hidegui(true)
    { }

    bool Editor::init(Game* game)
    {
        LOG_DEBUG("Init Editor...");
        EditorShared::_editor = this;

        _cam.loadFromFile("assets/editorcam.json");

        _updateRunFlags();

        _tools[ToolSelect].reset(new SelectTool());
        _tools[ToolSprite].reset(new SpriteTool());
        _tools[ToolBrush].reset(new BrushTool());
        _tools[ToolVertex].reset(new VertexTool());
        _tools[ToolEntity].reset(new EntityTool());
        setTool(ToolBrush);

        _evSelected = registerEvent<OnSelectEvent>(+[](Editor*, EventPtr ev) {
            if (ev->get<OnSelectEvent>()->entity)
                ImGui::SetWindowFocus(entity_properties_window_name);
        }, this);

        return true;
    }

    void Editor::quit()
    {
        _resviewer.close();

        _evSelected.unregister();

        _currenttool = nullptr;
        for (auto& i : _tools)
            i.reset();

        LOG_DEBUG("Editor unloaded");
    }

    void Editor::update(float elapsed)
    {
        auto input = getSubsystem<InputSystem>();
        _mouseSnapped = EditorShared::snap(input->getMouse().world);

        // Temporary set RenderSystem to visible, so that visible checks in SelectTool work
        if (!_run)
            showRenderSystem();

        if (input->isKeyPressed(sf::Keyboard::F5))
        {
            _run = !_run;
            _updateRunFlags();
        }

        _overlay.drawDebugOverlay();

        if (!_run || !_hidegui)
            _drawGui();

        if (!_run)
        {
            _handleInput();
            _camctrl.update(elapsed);
            hideRenderSystem();
        }
    }

    void Editor::render(sf::RenderTarget& target)
    {
        // if (_run && _hidegui)
        //     return;

        _cam.apply(target);

        if (!_run)
        {
            if (_snap && !_gridontop)
                _grid.render(target);

            auto rensys = getSubsystem<RenderSystem>();

            showRenderSystem();
            rensys->render(target, _cam.getCamRect());
            hideRenderSystem();

            _cam.apply(target);

            if (_snap && _gridontop)
                _grid.render(target);
        }
        else if (!_hidegui)
            _grid.render(target);

        // necessary, otherwise things will disappear randomly
        // getSubsystem<Game>()->getWindow().resetGLStates();

        if (!_run || !_hidegui)
        {
            if (_currenttool)
                _currenttool->render(target);

            _overlay.render(target);
        }
    }

    void Editor::setTool(Tools tool)
    {
        _currenttool = _tools[tool].get();
    }

    SelectTool& Editor::getSelectTool()
    {
        return *(SelectTool*)_tools[ToolSelect].get();
    }

    void Editor::pause()
    {
        _run = false;
        _updateRunFlags();
    }

    void Editor::unpause()
    {
        _run = true;
        _updateRunFlags();
    }

    bool Editor::load()
    {
        bool success = _savefile.empty() ? false : gamelib::loadSave(_savefile);
        setTool(ToolSelect);
        _updateRunFlags();
        return success;
    }

    bool Editor::load(const std::string& fname)
    {
        _savefile = fname;
        return load();
    }

    bool Editor::save()
    {
        return _savefile.empty() ? false : gamelib::save(_savefile);
    }

    bool Editor::save(const std::string& fname)
    {
        _savefile = fname;
        return this->save();
    }

    void Editor::registerExportCallback(ExportFunction callback)
    {
        _exportcallback = callback ? callback : defaultExport;
    }

    void Editor::_updateRunFlags()
    {
        if (_run)
        {
            RMFLAG(flags, gamestate_freeze);
            removeRenderSystemFlags(render_noparallax | render_drawhidden);
            showRenderSystem(); // show RenderSystem for ingame rendering
        }
        else
        {
            ADDFLAG(flags, gamestate_freeze);
            addRenderSystemFlags(render_noparallax | render_drawhidden);

            // Hack to prevent RenderSystem from rendering so the editor can render it manually with its own camera
            hideRenderSystem();
        }
    }

    void Editor::_drawGui()
    {
        static bool testwindow = false;
        static bool jsonwindow = false;
        static bool toolbar = true;
        static bool toolprops = true;
        static bool layerbox = false;
        static bool cambox = false;
        static bool entprops = true;
        static bool entlist = true;
        static bool entfac = false;
        static bool gamecfg = false;
        static FileDialog loaddlg(FileDialog::Load);
        static FileDialog savedlg;
        static FileDialog exportdlg;

        auto selected = getSelectTool().getSelected();
        auto input = getSubsystem<InputSystem>();

        auto viewport = ImGui::GetMainViewport();
        ImGuiID dockspace_id = ImGui::GetID("editorDockSpace");

        { // Setup docking window
            ImGui::SetNextWindowPos(viewport->Pos);
            ImGui::SetNextWindowSize(viewport->Size);
            ImGui::SetNextWindowViewport(viewport->ID);

            ImGuiWindowFlags host_window_flags = 0;
            host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
            host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
            host_window_flags |= ImGuiWindowFlags_NoBackground;
            host_window_flags |= ImGuiWindowFlags_MenuBar;

            ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
            ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
            ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
            ImGui::Begin("editor_viewport", NULL, host_window_flags);
            ImGui::PopStyleVar(3);

            ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_PassthruCentralNode);
        }

        if (ImGui::BeginMenuBar())
        {
            if (ImGui::BeginMenu("File"))
            {
                if (ImGui::MenuItem("Save", nullptr, nullptr, !_savefile.empty()))
                    save();

                if (ImGui::MenuItem("Save as"))
                    savedlg.open();

                if (ImGui::MenuItem("Load"))
                    loaddlg.open();

                if (ImGui::MenuItem("Reload"))
                    load();

                if (ImGui::MenuItem("Export"))
                    exportdlg.open();

                if (ImGui::MenuItem("Quit"))
                    getSubsystem<Game>()->close();

                ImGui::EndMenu();
            }
            if (ImGui::BeginMenu("Edit"))
            {
                if (ImGui::MenuItem("Run", "F5", &_run))
                    _updateRunFlags();
                ImGui::EndMenu();
            }
            if (ImGui::BeginMenu("View"))
            {
                if (ImGui::BeginMenu("Selected entity"))
                {
                    ImGui::MenuItem("Show solids", nullptr, &_overlay.renderSolid);
                    ImGui::MenuItem("Show solid normals", nullptr, &_overlay.renderNormals);
                    ImGui::MenuItem("Show velocity", nullptr, &_overlay.renderVel);
                    ImGui::EndMenu();
                }

                ImGui::MenuItem("Show mouse coordinates", nullptr, &_overlay.showCoords);
                ImGui::MenuItem("Show cameras", nullptr, &_overlay.renderCams);

                auto rensys = getSubsystem<RenderSystem>();
                const auto& renflags = rensys->getRootOptions().flags;

                if (ImGui::MenuItem("Show hidden", nullptr, renflags & render_drawhidden))
                    toggleRenderSystemFlags(render_drawhidden);

                if (ImGui::MenuItem("Enable parallax", nullptr, !(renflags & render_noparallax)))
                    toggleRenderSystemFlags(render_noparallax);

                ImGui::MenuItem("Hide Editor when running", nullptr, &_hidegui);

                ImGui::EndMenu();
            }
            if (ImGui::BeginMenu("Tools"))
            {
                ImGui::MenuItem("Toolbar", nullptr, &toolbar);
                ImGui::MenuItem("Tool properties", nullptr, &toolprops);
                ImGui::MenuItem("Entity properties", nullptr, &entprops);
                ImGui::MenuItem("Entity list", nullptr, &entlist);
                ImGui::MenuItem("Layer settings", nullptr, &layerbox);
                ImGui::MenuItem("Camera settings", nullptr, &cambox);
                ImGui::MenuItem("Global game config", nullptr, &gamecfg);
                ImGui::Separator();
                ImGui::MenuItem("Json viewer", nullptr, &jsonwindow);
                ImGui::MenuItem("Entity Factory", nullptr, &entfac);
                if (ImGui::MenuItem("Resource Manager"))
                    _resviewer.open();
                ImGui::Separator();
                ImGui::MenuItem("Test window", nullptr, &testwindow);
                ImGui::EndMenu();
            }
            if (ImGui::BeginMenu("Grid"))
            {
                ImGui::MenuItem("Snap to grid", "G", &_snap);
                ImGui::MenuItem("Grid on top", nullptr, &_gridontop);
                if (ImGui::MenuItem("Increase", "Q"))
                    _grid.increase();
                if (ImGui::MenuItem("Decrease", "E"))
                    _grid.decrease();
                ImGui::EndMenu();
            }
            ImGui::EndMenuBar();
        }

        // End docking window
        ImGui::End();

        { // Toolbar
            // ImGui::SetNextWindowPos(ImVec2(0, ImGui::GetItemRectSize().y));
            // ImGui::SetNextWindowSize(ImVec2(viewport->Size.x, -1));
            // ImGui::SetNextWindowSize(ImVec2(-1, -1));

            if (toolbar && ImGui::Begin("toolbar", &toolbar, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize |
                        ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoFocusOnAppearing))
            {
                for (size_t i = 0; i < NumTools; ++i)
                {
                    if (ImGui::Button(buttonStrings[i]))
                    {
                        setTool(static_cast<Tools>(i));
                        ImGui::SetNextWindowFocus();
                    }
                    ImGui::SameLine();
                    ImGui::Spacing();
                    ImGui::SameLine();
                }
            }
            ImGui::End();

            if (toolprops && ImGui::Begin("Tool Properties", &toolprops, ImVec2(250, 125)))
                _currenttool->drawGui();
            ImGui::End();
        }

        { // Loading / Saving
            if (loaddlg.process())
                load(loaddlg.getPath());

            if (savedlg.process())
                this->save(savedlg.getPath());

            if (exportdlg.process())
                _exportcallback(exportdlg.getPath());
        }

        if (ImGui::BeginPopupContextVoid("Context Menu", sf::Mouse::Right))
        {
            if (ImGui::Selectable("Move entity here") && selected)
                selected->getTransform().setPosition(input->getMouse().world);
            ImGui::EndPopup();
        }

        { // Dialogues
            if (testwindow)
                ImGui::ShowDemoWindow(&testwindow);

            if (jsonwindow)
                drawJsonView(&jsonwindow);

            if (layerbox)
                drawLayerUI(&layerbox);

            if (cambox)
                drawCameraUI(&cambox);

            if (entlist)
                drawEntityList(&entlist);

            if (entfac)
                drawEntityFactory(&entfac);

            if (_entsearch)
                drawSearchPopup(&_entsearch);

            if (gamecfg)
                drawGameConfig(&gamecfg);

            if (entprops)
                drawEntityProperties(&entprops);

            _resviewer.draw();
            _overlay.drawGui();
        }
    }

    void Editor::_handleInput()
    {
        auto input = getSubsystem<InputSystem>();
        Tool* realtool = _currenttool;  // backup

        { // Keyboard
            if (input->isKeyDown(sf::Keyboard::LControl))
            {
                _currenttool = &getSelectTool();

                if (input->isKeyPressed(sf::Keyboard::S))
                    save();
                else if (input->isKeyPressed(sf::Keyboard::R))
                {
                    getSelectTool().select(nullptr);
                    load();
                }
            }

            if (input->isKeyPressed(sf::Keyboard::F))
                _entsearch = true;

            if (input->isKeyPressed(sf::Keyboard::Delete) && getSelectTool().getSelected())
            {
                getSelectTool().getSelected()->destroy();
                getSelectTool().select(nullptr);
            }

            if (input->isKeyPressed(sf::Keyboard::Q))
                _grid.increase();

            if (input->isKeyPressed(sf::Keyboard::E))
                _grid.decrease();

            if (input->isKeyPressed(sf::Keyboard::G))
                _snap = !_snap;

            if (input->isKeyPressed(sf::Keyboard::Z))
            {
                auto selected = getSelectTool().getSelected();
                if (selected)
                {
                    _cam.center(selected->getTransform().getPosition());
                    _cam.zoom = 1;
                }
            }
        }

        { // Mouse
            auto& mouse = input->getMouse();

            if (!input->isMouseConsumed())
            {
                if (mouse.wheel)
                    _cam.zoomTowards(mouse.world.x, mouse.world.y, mouse.wheel / -10.0);
            }

            if (input->getMouse().moved)
            {
                if (_drag)
                    _currenttool->onDrag();
                else
                    _currenttool->onMouseMove();
            }

            if (input->isMousePressed(sf::Mouse::Left))
            {
                _currenttool->onMousePressed();
                _drag = true;
            }
            else if (_drag && !input->isMouseDown(sf::Mouse::Left))
                // Use !mouseDown because if mouse is consumed, mouseReleased will never be true
            {
                _currenttool->onMouseRelease();
                _drag = false;
            }
        }

        _currenttool = realtool;
    }

    void defaultExport(const std::string& fname)
    {
        // TODO: strip PolygonBrushComponent
        // TODO: export as entity
        save(fname);
        LOG("Map exported to ", fname);
    }

    void hideRenderSystem()
    {
        addRenderSystemFlags(render_invisible);
    }

    void showRenderSystem()
    {
        removeRenderSystemFlags(render_invisible);
    }

    void addRenderSystemFlags(unsigned int flags)
    {
        auto rensys = getSubsystem<RenderSystem>();
        auto renflags = rensys->getRootOptions().flags;
        ADDFLAG(renflags, flags);
        rensys->setRootOptions(&renflags);
    }

    void removeRenderSystemFlags(unsigned int flags)
    {
        auto rensys = getSubsystem<RenderSystem>();
        auto renflags = rensys->getRootOptions().flags;
        RMFLAG(renflags, flags);
        rensys->setRootOptions(&renflags);
    }

    void toggleRenderSystemFlags(unsigned int flags)
    {
        auto rensys = getSubsystem<RenderSystem>();
        auto renflags = rensys->getRootOptions().flags;
        TOGGLEFLAG(renflags, flags);
        rensys->setRootOptions(&renflags);
    }
}


text:
#ifndef COMPUTEDISTANCE_H_
#define COMPUTEDISTANCE_H_

	#include <fstream>
	#include <string>
	#include <boost/foreach.hpp>
	#include <iostream>
	#include <string>
	#include <string.h>
	#include <boost/tokenizer.hpp>
	#include <sstream>
	#include <boost/lexical_cast.hpp>
	#include <vector>
	#include <cstdio>
	#include <cstdlib>
	#include <cstring>
	#include <cmath>
	#include <cstring>
	#include <algorithm>
	#include <string>

	#define MaxValue 4294967295
	#define MaxRow 8192
	#define MaxCol 128

	using std::vector;
	using namespace std;
	int nRow; //Total Number rows in the input matrix
	int nCol; //Total Number columns in the input matrix
	std::string line;
	std::string token;
	vector < string > nameExp;
	vector < string > nameGenes;
	vector < string > classExp;
	std::string filenameIn;
	std::string filenameOutS;
	std::string filenameNode;
	char *filenameOut;
	struct tm *current;
	time_t now;
	float *Ina; // Holds the input matrix
	float *Da;  // Holds chunk of the original distance matrix

	int type; // 2: distance matrix, 1: gene expression
	int k;
	int chunkSize;
	int knn(char *name,float *Ina, int nRow, int nCol, int chunkSize, int k);

#endif /* COMPUTEDISTANCE_H_ */


text:
When /^I visit the git description page$/ do
  visit '/_deployed'
end

Then /^I should see the most recent commit's SHA$/ do
  page.should have_content(latest_commit_id_abbrev)
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Deprecated List (JADE v4.3.1 API)</title>
<meta name="date" content="2013-12-04">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Deprecated API

Contents

Deprecated Interfaces

Deprecated Fields

Deprecated Methods

Deprecated Constructors

Deprecated Interfaces

Interface and Description

jade.proto.FIPAProtocolNames

Use jade.domain.FIPANames.InteractionProtocol instead

Deprecated Fields

Field and Description

jade.proto.ContractNetResponder.PROPOSE_ACCEPTANCE_KEY

Use either ACCEPT_PROPOSAL_KEY or
         REJECT_PROPOSAL_KEY according to the message
         that has been received

jade.proto.ContractNetResponder.RESPONSE_KEY

Use REPLY_KEY

jade.content.lang.sl.SL0Vocabulary.RESULT_ITEMS

Use RESULT_VALUE instead

jade.proto.ContractNetResponder.RESULT_NOTIFICATION_KEY

Use REPLY_KEY

Deprecated Methods

Method and Description

jade.domain.DFService.getNonBlockingBehaviour(Agent, AID, String)

Use AchieveREInitiator instead

jade.domain.DFService.getNonBlockingBehaviour(Agent, AID, String, DFAgentDescription)

Use AchieveREInitiator instead

jade.domain.DFService.getNonBlockingBehaviour(Agent, AID, String, DFAgentDescription, SearchConstraints)

Use AchieveREInitiator instead

jade.domain.DFService.getNonBlockingBehaviour(Agent, String)

Use AchieveREInitiator instead

jade.domain.DFService.getNonBlockingBehaviour(Agent, String, DFAgentDescription)

Use AchieveREInitiator instead

jade.domain.DFService.getNonBlockingBehaviour(Agent, String, DFAgentDescription, SearchConstraints)

Use AchieveREInitiator instead

jade.lang.acl.ACLMessage.getReplyBy()

Since the value of this slot is a Date by definition, then
         the getReplyByDate should be used that returns a Date

jade.domain.DFService.getSubscriptionMessage(Agent, AID, DFAgentDescription, SearchConstraints)

Use createSubscriptionMessage() instead

jade.core.behaviours.WakerBehaviour.handleElapsedTimeout()

Use onWake() instead

jade.proto.SubscriptionResponder.prepareResponse(ACLMessage)

Use handleSubscription() instead

jade.proto.ContractNetResponder.prepareResponse(ACLMessage)

Use handleCfp() instead

jade.proto.AchieveREResponder.prepareResponse(ACLMessage)

Use handleRequest() instead

jade.proto.ContractNetResponder.prepareResultNotification(ACLMessage, ACLMessage, ACLMessage)

Use handleAcceptProposal() instead.

jade.proto.SubscriptionResponder.registerPrepareResponse(Behaviour)

Use registerHandleSubscription() instead.

jade.proto.ContractNetResponder.registerPrepareResponse(Behaviour)

Use registerHandleCfp() instead.

jade.proto.AchieveREResponder.registerPrepareResponse(Behaviour)

Use registerHandleRequest() instead.

jade.proto.ContractNetResponder.registerPrepareResultNotification(Behaviour)

Use registerHandleAcceptProposal() instead.

jade.util.Event.resetProcessed()

Use reset() instead

jade.content.onto.BasicOntology.resolveNumericValue(Object, Class)

Use adjustPrimitiveValue() instead

Deprecated Constructors

Constructor and Description

jade.lang.acl.ACLMessage()

Since every ACL Message must have a message type, you
         should use the new constructor which gets a message type as a
         parameter.  To avoid problems, now this constructor silently sets
         the message type to not-understood.

jade.core.AID(String)

This constructor might generate a wrong AID, if
 the passed parameter is not a guid (globally unique identifier), but
 the local name of an agent (e.g. "da0").

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

These are the official JADE API. For these API backward compatibility is guaranteed accross JADE versions


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1" />

        <link rel="stylesheet" href="lib/reset.css" />


text:
var BaseError = require( './base' );

var UnknownError = module.exports = function( message ) {
    BaseError.call( this, message );
};

UnknownError.prototype = Object.create( BaseError.prototype );

UnknownError.prototype.code = 500;

UnknownError.prototype.name = 'unknown_error';


text:
/* globals require, test, expect, describe, it */

import * as actions from '../../actions/frontend'

describe('actions frontend', () => {
    it('types', () => {
      expect(Object.keys(actions.types).length).toEqual(16)
    })
    it('showNavigation should create an action to show the navigation', () => {
      const expectedAction = {
          type: actions.types.SHOW_NAVIGATION,
      }
      expect(actions.showNavigation()).toEqual(expectedAction)
    })
    it('hideNavigation should create an action to hide the navigation', () => {
      const expectedAction = {
          type: actions.types.HIDE_NAVIGATION,
      }
      expect(actions.hideNavigation()).toEqual(expectedAction)
    })
    it('toggleNavigation should create an action to toggle the navigation', () => {
      const expectedAction = {
          type: actions.types.TOGGLE_NAVIGATION,
      }
      expect(actions.toggleNavigation()).toEqual(expectedAction)
    })
    it('showFilters should create an action to show the filters', () => {
      const expectedAction = {
          type: actions.types.SHOW_FILTERS,
      }
      expect(actions.showFilters()).toEqual(expectedAction)
    })
    it('hideFilters should create an action to hide the filters', () => {
      const expectedAction = {
          type: actions.types.HIDE_FILTERS,
      }
      expect(actions.hideFilters()).toEqual(expectedAction)
    })
    it('toggleFilters should create an action to toggle the filters', () => {
      const expectedAction = {
          type: actions.types.TOGGLE_FILTERS,
      }
      expect(actions.toggleFilters()).toEqual(expectedAction)
    })
    it('showModalConfirm should create an action to show a modal window', () => {
      const options = {}
      const expectedAction = {
          type: actions.types.SHOW_MODAL_CONFIRM,
          options,
      }
      expect(actions.showModalConfirm(options)).toEqual(expectedAction)
    })
    it('hideModalConfirm should create an action to hide a modal window', () => {
      const expectedAction = {
          type: actions.types.HIDE_MODAL_CONFIRM,
      }
      expect(actions.hideModalConfirm()).toEqual(expectedAction)
    })
    it('pageNotFoundMessage should create an action for page not found', () => {
      const message = 'xxx'
      const expectedAction = {
          type: actions.types.PAGE_NOT_FOUND_MESSAGE,
          message,
      }
      expect(actions.pageNotFoundMessage(message)).toEqual(expectedAction)
    })
    it('showBlockOverlay should create an action to block the ui', () => {
      const expectedAction = {
          type: actions.types.SHOW_BLOCK_OVERLAY,
      }
      expect(actions.showBlockOverlay()).toEqual(expectedAction)
    })
    it('hideBlockOverlay should create an action to enable the ui', () => {
      const expectedAction = {
          type: actions.types.HIDE_BLOCK_OVERLAY,
      }
      expect(actions.hideBlockOverlay()).toEqual(expectedAction)
    })
})


text:
'use strict';

const listToArray = require('list-to-array');
const qs = require('qs');
const xhr = require('xhr');

function getColumns (list) {
	return list.uiElements.map((col) => {
		if (col.type === 'heading') {
			return { type: 'heading', content: col.content };
		} else {
			var field = list.fields[col.field];
			return field ? { type: 'field', field: field, title: field.label, path: field.path } : null;
		}
	}).filter(i => i);
}

function getFilters (filterArray) {
	var filters = {};
	filterArray.forEach((filter) => {
		filters[filter.field.path] = filter.value;
	});
	return filters;
};

function getSortString (sort) {
	return sort.paths.map(i => {
		return i.invert ? '-' + i.path : i.path;
	}).filter(i => i).join(',');
};

function buildQueryString (options) {
	const query = {};
	if (options.search) query.search = options.search;
	if (options.filters.length) query.filters = JSON.stringify(getFilters(options.filters));
	if (options.columns) query.select = options.columns.map(i => i.path).join(',');
	if (options.page && options.page.size) query.limit = options.page.size;
	if (options.page && options.page.index > 1) query.skip = (options.page.index - 1) * options.page.size;
	if (options.sort) query.sort = getSortString(options.sort);
	query.expandRelationshipFields = true;
	return '?' + qs.stringify(query);
};

const List = function (options) {
	Object.assign(this, options);
	this.columns = getColumns(this);
	this.expandedDefaultColumns = this.expandColumns(this.defaultColumns);
	this.defaultColumnPaths = this.expandedDefaultColumns.map(i => i.path).join(',');
};

List.prototype.createItem = function (values, callback) {
	xhr({
		url: `${Keystone.adminPath}/api/${this.path}/create`,
		responseType: 'json',
		method: 'POST',
		headers: Keystone.csrf.header,
		json: values,
	}, (err, resp, data) => {
		if (resp.statusCode === 200) {
			callback(null, data);
		} else {
			callback(err, null);
		}
	});
};

List.prototype.expandColumns = function (input) {
	let nameIncluded = false;
	const cols = listToArray(input).map(i => {
		let split = i.split('|');
		let path = split[0];
		if (path === '__name__') {
			path = this.namePath;
		}
		if (path === this.namePath) {
			nameIncluded = true;
		}
		let field = this.fields[path];
		if (!field) {
			// TODO: Support arbitary document paths
			console.warn('Invalid Column specified:', i);
			return;
		}
		return {
			field: field,
			type: field.type,
			label: field.label,
			path: field.path
		};
	}).filter(i => i);
	if (!nameIncluded) {
		cols.unshift({
			type: 'id',
			label: 'ID',
			path: 'id'
		});
	}
	return cols;
};

List.prototype.expandSort = function (input) {
	const sort = {
		rawInput: input || this.defaultSort,
		isDefaultSort: false
	};
	sort.input = sort.rawInput;
	if (sort.input === '__default__') {
		sort.isDefaultSort = true;
		sort.input = this.sortable ? 'sortOrder' : this.namePath;
	}
	sort.paths = listToArray(sort.input).map(path => {
		let invert = false;
		if (path.charAt(0) === '-') {
			invert = true;
			path = path.substr(1);
		}
		const field = this.fields[path];
		if (!field) {
			// TODO: Support arbitary document paths
			console.warn('Invalid Sort specified:', path);
			return;
		}
		return {
			field: field,
			type: field.type,
			label: field.label,
			path: field.path,
			invert: invert
		};
	}).filter(i => i);
	return sort;
};

List.prototype.loadItem = function (itemId, options, callback) {
	if (arguments.length === 2 && typeof options === 'function') {
		callback = options;
		options = null;
	}
	let url = Keystone.adminPath + '/api/' + this.path + '/' + itemId;
	let query = qs.stringify(options);
	if (query.length) url += '?' + query;
	xhr({
		url: url,
		responseType: 'json',
	}, (err, resp, data) => {
		if (err) return callback(err);
		// TODO: check resp.statusCode
		callback(err, data);
	});
};

List.prototype.loadItems = function (options, callback) {
	const url = Keystone.adminPath + '/api/' + this.path + buildQueryString(options);
	xhr({
		url: url,
		responseType: 'json',
	}, (err, resp, data) => {
		// TODO: check resp.statusCode
		callback(err, data);
	});
};

List.prototype.getDownloadURL = function (options) {
	const url = Keystone.adminPath + '/api/' + this.path;
	const parts = [];
	if (options.format !== 'json') {
		options.format = 'csv';
	}
	parts.push(options.search ? 'search=' + options.search : '');
	parts.push(options.filters.length ? 'filters=' + JSON.stringify(getFilters(options.filters)) : '');
	parts.push(options.columns ? 'select=' + options.columns.map(i => i.path).join(',') : '');
	parts.push(options.sort ? 'sort=' + getSortString(options.sort) : '');
	parts.push('expandRelationshipFields=true');
	return url + '/export.' + options.format + '?' + parts.filter(i => i).join('&');
};

List.prototype.deleteItem = function (itemId, callback) {
	this.deleteItems([itemId], callback);
};

List.prototype.deleteItems = function (itemIds, callback) {
	const url = Keystone.adminPath + '/api/' + this.path + '/' + itemIds.join(',') + '/delete';
	xhr({
		url: url,
		method: 'POST',
		headers: Keystone.csrf.header
	}, (err, resp, body) => {
		if (err) return callback(err);
		// TODO: check resp.statusCode
		try {
			body = JSON.parse(body);
		} catch(e) {
			console.log('Error parsing results json:', e, body);
			return callback(e);
		}
		callback(null, body);
	});
};

List.prototype.reorderItems = function (item, oldSortOrder, newSortOrder, pageOptions, callback) {
	const url = Keystone.adminPath + '/api/' + this.path + '/' + item.id + '/sortOrder/' + oldSortOrder + '/' + newSortOrder + '/' + buildQueryString(pageOptions);
	xhr({
		url: url,
		method: 'POST',
		headers: Keystone.csrf.header
	}, (err, resp, body) => {
		if (err) return callback(err);
		// TODO: check resp.statusCode
		try {
			body = JSON.parse(body);
		} catch(e) {
			console.log('Error parsing results json:', e, body);
			return callback(e);
		}
		callback(null, body);
	});
};

module.exports = List;


text:
const meriyah = require('meriyah')

module.exports = function parse (source, options) {
  return meriyah.parseModule(source, options)
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Cms.Core.ContentApps;
using Umbraco.Cms.Core.Mapping;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Cms.Core.Models.Membership;
using Umbraco.Cms.Core.Services;
using Umbraco.Extensions;
using UserProfile = Umbraco.Cms.Core.Models.ContentEditing.UserProfile;

namespace Umbraco.Cms.Core.Models.Mapping
{
    public class CommonMapper
    {
        private readonly IUserService _userService;
        private readonly IContentTypeBaseServiceProvider _contentTypeBaseServiceProvider;
        private readonly ContentAppFactoryCollection _contentAppDefinitions;
        private readonly ILocalizedTextService _localizedTextService;

        public CommonMapper(IUserService userService, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider,
            ContentAppFactoryCollection contentAppDefinitions, ILocalizedTextService localizedTextService)
        {
            _userService = userService;
            _contentTypeBaseServiceProvider = contentTypeBaseServiceProvider;
            _contentAppDefinitions = contentAppDefinitions;
            _localizedTextService = localizedTextService;
        }

        public UserProfile GetOwner(IContentBase source, MapperContext context)
        {
            var profile = source.GetCreatorProfile(_userService);
            return profile == null ? null : context.Map<IProfile, UserProfile>(profile);
        }

        public UserProfile GetCreator(IContent source, MapperContext context)
        {
            var profile = source.GetWriterProfile(_userService);
            return profile == null ? null : context.Map<IProfile, UserProfile>(profile);
        }

        public ContentTypeBasic GetContentType(IContentBase source, MapperContext context)
        {
            var contentType = _contentTypeBaseServiceProvider.GetContentTypeOf(source);
            var contentTypeBasic = context.Map<IContentTypeComposition, ContentTypeBasic>(contentType);
            return contentTypeBasic;
        }

        public IEnumerable<ContentApp> GetContentApps(IUmbracoEntity source)
        {
            return GetContentAppsForEntity(source);
        }

        public IEnumerable<ContentApp> GetContentAppsForEntity(IEntity source)
        {
            var apps = _contentAppDefinitions.GetContentAppsFor(source).ToArray();

            // localize content app names
            foreach (var app in apps)
            {
                var localizedAppName = _localizedTextService.Localize("apps", app.Alias);
                if (localizedAppName.Equals($"[{app.Alias}]", StringComparison.OrdinalIgnoreCase) == false)
                {
                    app.Name = localizedAppName;
                }
            }

            return apps;
        }
    }
}


text:
<?php

namespace app\models;

use app\behaviors\TimeBehavior;
use developeruz\behaviors\ThumbBehavior;
use Yii;
use yii\web\UploadedFile;

class Sale extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sale';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['party_id', 'sale_type', 'created_at', 'started_at', 'finished_at'], 'required'],
            [['party_id', 'sale_type', 'created_at'], 'integer'],
            [['eventbrite_html','started_at', 'finished_at', 'top_text','bottom_text','bottom_text_8'], 'safe']
        ];
    }

    public function behaviors()
    {
        return  [
            'startTimeBehavior' => [
                'class' => TimeBehavior::className(),
                'dateTimeFields' => 'started_at',
            ],
            'endTimeBehavior' => [
                'class' => TimeBehavior::className(),
                'dateTimeFields' => 'finished_at',
            ],
        ];
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'party_id' => 'Party ID',
            'sale_type' => 'Sale Type',
            'created_at' => 'Created At',
            'started_at' => 'Started At',
            'finished_at' => 'Finished At',
            'thumbnail' => 'Thumbnail',
            'mini_flyer' => 'Mini Flyer',
            'flyer_top' => 'Flyer Top',
            'flyer_bottom' => 'Flyer Bottom',
            'message_banner' => 'Message Banner',
            'top_text' => 'Top Text',
            'bottom_text' => 'Bottom Text',
            'bottom_text_8' => 'Bottom Text 8',
	    'eventbrite_html'=> 'EventBrite HTML',
	    'party_first' => 'Party First',
	    'party_last' => 'Party Last',
	    'party_more' => 'Party More'
        ];
    }

    public static function getSaleType($type=null)
    {
        $saleType = [
            0 => 'Flash Sale',
            1 => 'Regular Sale'
        ];

        if(!is_numeric($type)) return $saleType;
        else return $saleType[$type];
    }

    public function loadPhoto($attribute)
    {
        $image = UploadedFile::getInstance($this, $attribute);
        if (!empty($image)) {
            $uniqName = Yii::$app->security->generateRandomString() . '.' . $image->getExtension();
            if ($image->saveAs(Yii::$app->basePath . Yii::$app->params['flayerUploadDir'] . $uniqName)) {
                $this->{$attribute} = $uniqName;
            }
        }
    }

    public function getTicket()
    {
        return $this->hasMany(TicketType::className(), ['sale_id' => 'id']);
    }
    public function getUsers()
    {
        return $this->hasMany(User::className(), ['sale_id' => 'id']);
    }

    public function getParty()
    {
        return $this->hasOne(Party::className(), ['id' => 'party_id']);
    }

    public function getDashboardTitle($title = ''){

        if($this->sale_type !== 1){
            return "Flash Sale $title Sale Ends ". date('M d', strtotime($this->finished_at));
        }
        return  $title. ' - Limited tickets available';
    }
}


text:
HC      = ghc
LIBDIR  = $(shell $(HC) --print-libdir)
CFLAGS  = -fobjc-arc -I$(LIBDIR)/include -I$(LIBDIR)/../../includes
HCFLAGS =
LDFLAGS = -package template-haskell -package language-c-quote -package language-c-inline -framework Foundation

OBJS = Main.o Main_objc.o

default: Minimal

%.o: %.hs
	$(HC) -c $< $(HCFLAGS)

Main.o:

Main_objc.m: Main.o

Minimal: $(OBJS)
	$(HC) -o $@ $^ $(LDFLAGS)

.PHONY: clean

clean:
	rm -f *.o *.hi Main_objc.[hm] Minimal


text:
<?php

use Sunlight\Message;

return function ($type, $text, $isHtml = true) {
    return (string) new Message($type, $text, $isHtml);
};