text:
package org.o7planning.tutorial.jface.model;

import java.util.ArrayList;
import java.util.List;

public class DataModel {

  private static List<Article> articleList;
  private static List<Department> departmentList;
  private static List<AppMenu> appMenuList;

  public static List<Article> getArticles() {
    if (articleList == null) {
      articleList = new ArrayList<Article>();
      articleList.add(new Article("Java basic", "Tom", true));
      articleList.add(new Article("Hibernate for beginners", "Tran", true));
      articleList.add(new Article("Maven for beginners", "Smith", false));
    }
    return articleList;
  }

  public static List<Department> getDepartments() {
    if (departmentList == null) {

      Employee emp11 = new Employee("E11", "Michael", "Smith");
      Employee emp12 = new Employee("E12", "Susan", "Barker");
      List<Employee> empList1 = new ArrayList<Employee>();
      empList1.add(emp11);
      empList1.add(emp12);

      Department dept1 = new Department("D01", "Operation", empList1);
      //
      Employee emp21 = new Employee("E21", "Robert", "Tyler");
      List<Employee> empList2 = new ArrayList<Employee>();
      empList2.add(emp21);

      Department dept2 = new Department("D02", "Adminstration", empList2);
      //
      departmentList = new ArrayList<Department>();

      departmentList.add(dept1);
      departmentList.add(dept2);
    }
    return departmentList;
  }

  public static List<AppMenu> getAppMenus() {
    if (appMenuList == null) {
      appMenuList = new ArrayList<AppMenu>();

      AppMenu appMenu31 = new AppMenu("ErrorLog", "Error Log", null);
      AppMenu appMenu32 = new AppMenu("ProjectExplorer", "Project Explorer", null);

      List<AppMenu> list3 = new ArrayList<AppMenu>();
      list3.add(appMenu31);
      list3.add(appMenu32);

      AppMenu appMenu21 = new AppMenu("ShowView", "Show View", list3);
      AppMenu appMenu22 = new AppMenu("ClosePerspective", "Close perspective...", null);
      List<AppMenu> list2 = new ArrayList<AppMenu>();
      list2.add(appMenu21);
      list2.add(appMenu22);

      AppMenu appMenu1 = new AppMenu("Window", "Window", list2);

      appMenuList.add(appMenu1);
    }
    return appMenuList;
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/barmainlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/nursingSelectionLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <CheckBox
            android:id="@+id/leftSelection"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.33"
            android:text="@string/leftcbstring" />

        <CheckBox
            android:id="@+id/rightSelection"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.33"
            android:text="@string/rightcbstring" />

        <CheckBox
            android:id="@+id/bothSelection"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.33"
            android:text="@string/bothcbstring" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/nursingBarGraphLayout"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:baselineAligned="false" >

        <LinearLayout
            android:id="@+id/leftLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.33">
        </LinearLayout>
        <LinearLayout
            android:id="@+id/rightLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.33">
        </LinearLayout>
        <LinearLayout
            android:id="@+id/bothLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.33">
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
on.input.canvas = function() {
  output({
    context: $.create($.canvas.getContext('2d'))
  });
};


text:
module SFML.Audio.Listener
(
    setGlobalVolume
,   getGlobalVolume
,   setListenerPosition
,   getListenerPosition
,   setListenerDirection
,   getListenerDirection
,   setListenerUpVector
,   getListenerUpVector
)
where

import SFML.System.Vector3

import Control.Monad ((>=>))
import Foreign.C.Types
import Foreign.Marshal.Alloc (alloca)
import Foreign.Marshal.Utils (with)
import Foreign.Ptr (Ptr)
import Foreign.Storable (peek)

-- | Change the global volume of all the sounds and musics.
--
-- The volume is a number between 0 and 100; it is combined with
-- the individual volume of each sound or music.
--
-- The default value for the volume is 100 (maximum).
setGlobalVolume
    :: Float -- ^ New global volume, in the range [0, 100]
    -> IO ()

setGlobalVolume = sfListener_setGlobalVolume . realToFrac

foreign import ccall unsafe "sfListener_setGlobalVolume"
    sfListener_setGlobalVolume :: CFloat -> IO ()

--CSFML_AUDIO_API void sfListener_setGlobalVolume(float volume);

-- | Get the current value of the global volume.
getGlobalVolume :: IO Float -- ^ Current global volume, in the range [0, 100]
getGlobalVolume = fmap realToFrac sfListener_getGlobalVolume

foreign import ccall unsafe "sfListener_getGlobalVolume"
    sfListener_getGlobalVolume :: IO CFloat

--CSFML_AUDIO_API float sfListener_getGlobalVolume(void);

-- | Set the position of the listener in the scene.
--
-- The default listener's position is (0, 0, 0).
setListenerPosition :: Vec3f -> IO ()
setListenerPosition pos = with pos sfListener_setPosition_helper

foreign import ccall unsafe "sfListener_setPosition_helper"
    sfListener_setPosition_helper :: Ptr Vec3f -> IO ()

--CSFML_AUDIO_API void sfListener_setPosition(sfVector3f position);

-- | Get the current position of the listener in the scene.
getListenerPosition :: IO Vec3f
getListenerPosition = alloca $ \ptr -> sfListener_getPosition_helper ptr >> peek ptr

foreign import ccall unsafe "sfListener_getPosition_helper"
    sfListener_getPosition_helper :: Ptr Vec3f -> IO ()

--CSFML_AUDIO_API sfVector3f sfListener_getPosition();

-- | Set the orientation of the forward vector in the scene.
--
-- The direction (also called "at vector") is the vector
-- pointing forward from the listener's perspective. Together
-- with the up vector, it defines the 3D orientation of the
-- listener in the scene. The direction vector doesn't
-- have to be normalized.
--
-- The default listener's direction is (0, 0, -1).
setListenerDirection :: Vec3f -> IO ()
setListenerDirection dir = with dir sfListener_setDirection_helper

foreign import ccall unsafe "sfListener_setDirection_helper"
    sfListener_setDirection_helper :: Ptr Vec3f -> IO ()

--CSFML_AUDIO_API void sfListener_setDirection(sfVector3f orientation);

-- | Get the current orientation of the listener in the scene.
getListenerDirection :: IO Vec3f
getListenerDirection = alloca $ \ptr -> sfListener_getDirection_helper ptr >> peek ptr

foreign import ccall unsafe "sfListener_getDirection_helper"
    sfListener_getDirection_helper :: Ptr Vec3f -> IO ()

--CSFML_AUDIO_API sfVector3f sfListener_getDirection();

-- | Set the upward vector of the listener in the scene
--
-- The up vector is the vector that points upward from the
-- listener's perspective. Together with the direction, it
-- defines the 3D orientation of the listener in the scene.
-- The up vector doesn't have to be normalized.
-- The default listener's up vector is (0, 1, 0). It is usually
-- not necessary to change it, especially in 2D scenarios.
setListenerUpVector :: Vec3f -> IO ()
setListenerUpVector dir = with dir sfListener_setUpVector_helper

foreign import ccall unsafe "sfListener_setUpVector_helper"
    sfListener_setUpVector_helper :: Ptr Vec3f -> IO ()

--CSFML_AUDIO_API void sfListener_setUpVector(sfVector3f upVector);

-- | Get the current upward vector (unnormalised) of the listener in the scene.
getListenerUpVector :: IO Vec3f
getListenerUpVector = alloca $ \ptr -> sfListener_getUpVector_helper ptr >> peek ptr

foreign import ccall unsafe "sfListener_getUpVector_helper"
    sfListener_getUpVector_helper :: Ptr Vec3f -> IO ()

--CSFML_AUDIO_API sfVector3f sfListener_getUpVector();


text:
var os = require('os');
var events = require('events');
var util = require('util');

var io = require('socket.io-client');

var MockMonitor = function(url, key, callback) {
  var that = this;
  this.key = key;

  var options = {
    'log level': 1
  };

  var conn = this.conn = io.connect(url);

  // On connect register with server
  conn.on('connect', function() {
    that.register(callback);
  });

  conn.on('disconnect', function() {
    // @TODO need to handle disconnect
  });

  conn.on('data', function(data) {
    that.emit('data', data);
  });
};

util.inherits(MockMonitor, events.EventEmitter);

MockMonitor.prototype.register = function(callback) {
  var data = {
    'hostname': os.hostname(),
    'key': this.key,
    'type': 'monitor'
  };

  // Register with aggregator
  this.conn.emit('register', data, function(error, result) {
    if(error) {
      if(callback) {
        return callback(error);
      } else {
        throw error;
      }
    }

    if(callback) {
      callback(null, result);
    }
  });
};

MockMonitor.prototype.watch = function(watchable, callback) {
  this.conn.emit('watch', watchable, callback);
};

MockMonitor.prototype.unwatch = function(data, callback) {
  this.conn.emit('unwatch', data, callback);
};

MockMonitor.prototype.watchables = function(callback) {
  this.conn.emit('watchables', callback);
};

MockMonitor.prototype.disconnect = function() {
  this.conn.disconnect();
};

module.exports = MockMonitor;


text:
#include <aws/lex-models/model/MigrationStrategy.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace LexModelBuildingService
  {
    namespace Model
    {
      namespace MigrationStrategyMapper
      {

        static const int CREATE_NEW_HASH = HashingUtils::HashString("CREATE_NEW");
        static const int UPDATE_EXISTING_HASH = HashingUtils::HashString("UPDATE_EXISTING");

        MigrationStrategy GetMigrationStrategyForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == CREATE_NEW_HASH)
          {
            return MigrationStrategy::CREATE_NEW;
          }
          else if (hashCode == UPDATE_EXISTING_HASH)
          {
            return MigrationStrategy::UPDATE_EXISTING;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<MigrationStrategy>(hashCode);
          }

          return MigrationStrategy::NOT_SET;
        }

        Aws::String GetNameForMigrationStrategy(MigrationStrategy enumValue)
        {
          switch(enumValue)
          {
          case MigrationStrategy::CREATE_NEW:
            return "CREATE_NEW";
          case MigrationStrategy::UPDATE_EXISTING:
            return "UPDATE_EXISTING";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace MigrationStrategyMapper
    } // namespace Model
  } // namespace LexModelBuildingService
} // namespace Aws


text:
title: Javascript
position: 1.0
description: Introducción
---

JavaScript (abreviado JS) es un lenguaje interpretado, orientado a objetos, basado en prototipos, imperativo, debilmente tipado y dinamico.
{: .info }
Principalmente se usa del lado del cliente
{: .info }
Todos los navegadores modernos interpretan el código JavaScript.
{: .info }
Para interactuar con una página web se provee al lenguaje JavaScript de una implementación del Document Object Model (DOM).
{: .info }
Javascript corre del lado del cliente y tambien del lado del servidor (nodejs, io.js, etc)
{: .info }

~~~ javascript
//mensaje de alerta
alert("Hola Mundo");
//mensaje por consola
console.log("Hola Mundo");
//manipulación DOM
function cambiarTexto(){
  var elemento = document.getElementById("javascriptbooks_list");
  elemento.innerHTML= "Cambiando el texto con Javascript Puro";
};
var variableGlobal=0;
var elemento = document.getElementById("javascriptbooks_list");
//eventos
elemento.addEventListener("click",function(e){
  variableGlobal+=1;
  console.log("numero de clicks = "+variableGlobal);
},false);
~~~
{: title="Vanilla Js" }

~~~ javascript
function cambiarTexto(){
  var elemento = $("#javascriptbooks_list");
  elemento.text("Jquery cambió esto");
};
//defino una variable global
var variableGlobal=0;
//añadir eventos de click a un determinado elemento
$("h1").on('click',function(){
  variableGlobal+=1;
  console.log("numero de clicks = "+variableGlobal);
});
~~~
{: title="Jquery" }


text:
import {Compiler, CompilerOptions, ComponentFactory, Injector, NgModule, NgModuleRef, NgZone, Provider, Testability, Type} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';

import * as angular from './angular_js';
import {NG1_COMPILE, NG1_INJECTOR, NG1_PARSE, NG1_ROOT_SCOPE, NG1_TESTABILITY, NG2_COMPILER, NG2_COMPONENT_FACTORY_REF_MAP, NG2_INJECTOR, NG2_ZONE, REQUIRE_INJECTOR} from './constants';
import {DowngradeNg2ComponentAdapter} from './downgrade_ng2_adapter';
import {ComponentInfo, getComponentInfo} from './metadata';
import {UpgradeNg1ComponentAdapterBuilder} from './upgrade_ng1_adapter';
import {controllerKey, onError} from './util';

let upgradeCount: number = 0;

/**
 * Use `UpgradeAdapter` to allow AngularJS v1 and Angular v2 to coexist in a single application.
 *
 * The `UpgradeAdapter` allows:
 * 1. creation of Angular v2 component from AngularJS v1 component directive
 *    (See [UpgradeAdapter#upgradeNg1Component()])
 * 2. creation of AngularJS v1 directive from Angular v2 component.
 *    (See [UpgradeAdapter#downgradeNg2Component()])
 * 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks
 *    coexisting in a single application.
 *
 * ## Mental Model
 *
 * When reasoning about how a hybrid application works it is useful to have a mental model which
 * describes what is happening and explains what is happening at the lowest level.
 *
 * 1. There are two independent frameworks running in a single application, each framework treats
 *    the other as a black box.
 * 2. Each DOM element on the page is owned exactly by one framework. Whichever framework
 *    instantiated the element is the owner. Each framework only updates/interacts with its own
 *    DOM elements and ignores others.
 * 3. AngularJS v1 directives always execute inside AngularJS v1 framework codebase regardless of
 *    where they are instantiated.
 * 4. Angular v2 components always execute inside Angular v2 framework codebase regardless of
 *    where they are instantiated.
 * 5. An AngularJS v1 component can be upgraded to an Angular v2 component. This creates an
 *    Angular v2 directive, which bootstraps the AngularJS v1 component directive in that location.
 * 6. An Angular v2 component can be downgraded to an AngularJS v1 component directive. This creates
 *    an AngularJS v1 directive, which bootstraps the Angular v2 component in that location.
 * 7. Whenever an adapter component is instantiated the host element is owned by the framework
 *    doing the instantiation. The other framework then instantiates and owns the view for that
 *    component. This implies that component bindings will always follow the semantics of the
 *    instantiation framework. The syntax is always that of Angular v2 syntax.
 * 8. AngularJS v1 is always bootstrapped first and owns the bottom most view.
 * 9. The new application is running in Angular v2 zone, and therefore it no longer needs calls to
 *    `$apply()`.
 *
 * ### Example
 *
 * ```
 * var adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module), myCompilerOptions);
 * var module = angular.module('myExample', []);
 * module.directive('ng2Comp', adapter.downgradeNg2Component(Ng2Component));
 *
 * module.directive('ng1Hello', function() {
 *   return {
 *      scope: { title: '=' },
 *      template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
 *   };
 * });
 *
 *
 * @Component({
 *   selector: 'ng2-comp',
 *   inputs: ['name'],
 *   template: 'ng2[<ng1-hello [title]="name">transclude</ng1-hello>](<ng-content></ng-content>)',
 *   directives:
 * })
 * class Ng2Component {
 * }
 *
 * @NgModule({
 *   declarations: [Ng2Component, adapter.upgradeNg1Component('ng1Hello')],
 *   imports: [BrowserModule]
 * })
 * class MyNg2Module {}
 *
 *
 * document.body.innerHTML = '<ng2-comp name="World">project</ng2-comp>';
 *
 * adapter.bootstrap(document.body, ['myExample']).ready(function() {
 *   expect(document.body.textContent).toEqual(
 *       "ng2[ng1[Hello World!](transclude)](project)");
 * });
 *
 * ```
 *
 * @stable
 */
export class UpgradeAdapter {
  /* @internal */
  private idPrefix: string = `NG2_UPGRADE_${upgradeCount++}_`;
  /* @internal */
  private upgradedComponents: Type<any>[] = [];
  /**
   * An internal map of ng1 components which need to up upgraded to ng2.
   *
   * We can't upgrade until injector is instantiated and we can retrieve the component metadata.
   * For this reason we keep a list of components to upgrade until ng1 injector is bootstrapped.
   *
   * @internal
   */
  private ng1ComponentsToBeUpgraded: {[name: string]: UpgradeNg1ComponentAdapterBuilder} = {};
  /* @internal */
  private providers: Provider[] = [];

  constructor(private ng2AppModule: Type<any>, private compilerOptions?: CompilerOptions) {
    if (!ng2AppModule) {
      throw new Error(
          'UpgradeAdapter cannot be instantiated without an NgModule of the Angular 2 app.');
    }
  }

  /**
   * Allows Angular v2 Component to be used from AngularJS v1.
   *
   * Use `downgradeNg2Component` to create an AngularJS v1 Directive Definition Factory from
   * Angular v2 Component. The adapter will bootstrap Angular v2 component from within the
   * AngularJS v1 template.
   *
   * ## Mental Model
   *
   * 1. The component is instantiated by being listed in AngularJS v1 template. This means that the
   *    host element is controlled by AngularJS v1, but the component's view will be controlled by
   *    Angular v2.
   * 2. Even thought the component is instantiated in AngularJS v1, it will be using Angular v2
   *    syntax. This has to be done, this way because we must follow Angular v2 components do not
   *    declare how the attributes should be interpreted.
   *
   * ## Supported Features
   *
   * - Bindings:
   *   - Attribute: `<comp name="World">`
   *   - Interpolation:  `<comp greeting="Hello {{name}}!">`
   *   - Expression:  `<comp [name]="username">`
   *   - Event:  `<comp (close)="doSomething()">`
   * - Content projection: yes
   *
   * ### Example
   *
   * ```
   * var adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
   * var module = angular.module('myExample', []);
   * module.directive('greet', adapter.downgradeNg2Component(Greeter));
   *
   * @Component({
   *   selector: 'greet',
   *   template: '{{salutation}} {{name}}! - <ng-content></ng-content>'
   * })
   * class Greeter {
   *   @Input() salutation: string;
   *   @Input() name: string;
   * }
   *
   * @NgModule({
   *   declarations: [Greeter],
   *   imports: [BrowserModule]
   * })
   * class MyNg2Module {}
   *
   * document.body.innerHTML =
   *   'ng1 template: <greet salutation="Hello" [name]="world">text</greet>';
   *
   * adapter.bootstrap(document.body, ['myExample']).ready(function() {
   *   expect(document.body.textContent).toEqual("ng1 template: Hello world! - text");
   * });
   * ```
   */
  downgradeNg2Component(type: Type<any>): Function {
    this.upgradedComponents.push(type);
    const info: ComponentInfo = getComponentInfo(type);
    return ng1ComponentDirective(info, `${this.idPrefix}${info.selector}_c`);
  }

  /**
   * Allows AngularJS v1 Component to be used from Angular v2.
   *
   * Use `upgradeNg1Component` to create an Angular v2 component from AngularJS v1 Component
   * directive. The adapter will bootstrap AngularJS v1 component from within the Angular v2
   * template.
   *
   * ## Mental Model
   *
   * 1. The component is instantiated by being listed in Angular v2 template. This means that the
   *    host element is controlled by Angular v2, but the component's view will be controlled by
   *    AngularJS v1.
   *
   * ## Supported Features
   *
   * - Bindings:
   *   - Attribute: `<comp name="World">`
   *   - Interpolation:  `<comp greeting="Hello {{name}}!">`
   *   - Expression:  `<comp [name]="username">`
   *   - Event:  `<comp (close)="doSomething()">`
   * - Transclusion: yes
   * - Only some of the features of
   *   [Directive Definition Object](https://docs.angularjs.org/api/ng/service/$compile) are
   *   supported:
   *   - `compile`: not supported because the host element is owned by Angular v2, which does
   *     not allow modifying DOM structure during compilation.
   *   - `controller`: supported. (NOTE: injection of `$attrs` and `$transclude` is not supported.)
   *   - `controllerAs': supported.
   *   - `bindToController': supported.
   *   - `link': supported. (NOTE: only pre-link function is supported.)
   *   - `name': supported.
   *   - `priority': ignored.
   *   - `replace': not supported.
   *   - `require`: supported.
   *   - `restrict`: must be set to 'E'.
   *   - `scope`: supported.
   *   - `template`: supported.
   *   - `templateUrl`: supported.
   *   - `terminal`: ignored.
   *   - `transclude`: supported.
   *
   *
   * ### Example
   *
   * ```
   * var adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
   * var module = angular.module('myExample', []);
   *
   * module.directive('greet', function() {
   *   return {
   *     scope: {salutation: '=', name: '=' },
   *     template: '{{salutation}} {{name}}! - <span ng-transclude></span>'
   *   };
   * });
   *
   * module.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
   *
   * @Component({
   *   selector: 'ng2',
   *   template: 'ng2 template: <greet salutation="Hello" [name]="world">text</greet>'
   * })
   * class Ng2Component {
   * }
   *
   * @NgModule({
   *   declarations: [Ng2Component, adapter.upgradeNg1Component('greet')],
   *   imports: [BrowserModule]
   * })
   * class MyNg2Module {}
   *
   * document.body.innerHTML = '<ng2></ng2>';
   *
   * adapter.bootstrap(document.body, ['myExample']).ready(function() {
   *   expect(document.body.textContent).toEqual("ng2 template: Hello world! - text");
   * });
   * ```
   */
  upgradeNg1Component(name: string): Type<any> {
    if ((<any>this.ng1ComponentsToBeUpgraded).hasOwnProperty(name)) {
      return this.ng1ComponentsToBeUpgraded[name].type;
    } else {
      return (this.ng1ComponentsToBeUpgraded[name] = new UpgradeNg1ComponentAdapterBuilder(name))
          .type;
    }
  }

  /**
   * Bootstrap a hybrid AngularJS v1 / Angular v2 application.
   *
   * This `bootstrap` method is a direct replacement (takes same arguments) for AngularJS v1
   * [`bootstrap`](https://docs.angularjs.org/api/ng/function/angular.bootstrap) method. Unlike
   * AngularJS v1, this bootstrap is asynchronous.
   *
   * ### Example
   *
   * ```
   * var adapter = new UpgradeAdapter();
   * var module = angular.module('myExample', []);
   * module.directive('ng2', adapter.downgradeNg2Component(Ng2));
   *
   * module.directive('ng1', function() {
   *   return {
   *      scope: { title: '=' },
   *      template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
   *   };
   * });
   *
   *
   * @Component({
   *   selector: 'ng2',
   *   inputs: ['name'],
   *   template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)'
   * })
   * class Ng2 {
   * }
   *
   * @NgModule({
   *   declarations: [Ng2, adapter.upgradeNg1Component('ng1')],
   *   imports: [BrowserModule]
   * })
   * class MyNg2Module {}
   *
   * document.body.innerHTML = '<ng2 name="World">project</ng2>';
   *
   * adapter.bootstrap(document.body, ['myExample']).ready(function() {
   *   expect(document.body.textContent).toEqual(
   *       "ng2[ng1[Hello World!](transclude)](project)");
   * });
   * ```
   */
  bootstrap(element: Element, modules?: any[], config?: angular.IAngularBootstrapConfig):
      UpgradeAdapterRef {
    const ngZone =
        new NgZone({enableLongStackTrace: Zone.hasOwnProperty('longStackTraceZoneSpec')});
    const upgrade = new UpgradeAdapterRef();
    let ng1Injector: angular.IInjectorService = null;
    let moduleRef: NgModuleRef<any> = null;
    const delayApplyExps: Function[] = [];
    let original$applyFn: Function;
    let rootScopePrototype: any;
    let rootScope: angular.IRootScopeService;
    const componentFactoryRefMap: ComponentFactoryRefMap = {};
    const ng1Module = angular.module(this.idPrefix, modules);
    let ng1BootstrapPromise: Promise<any>;
    let ng1compilePromise: Promise<any>;
    ng1Module.factory(NG2_INJECTOR, () => moduleRef.injector.get(Injector))
        .value(NG2_ZONE, ngZone)
        .factory(NG2_COMPILER, () => moduleRef.injector.get(Compiler))
        .value(NG2_COMPONENT_FACTORY_REF_MAP, componentFactoryRefMap)
        .config([
          '$provide', '$injector',
          (provide: any /** TODO #???? */, ng1Injector: angular.IInjectorService) => {
            provide.decorator(NG1_ROOT_SCOPE, [
              '$delegate',
              function(rootScopeDelegate: angular.IRootScopeService) {
                // Capture the root apply so that we can delay first call to $apply until we
                // bootstrap Angular 2 and then we replay and restore the $apply.
                rootScopePrototype = rootScopeDelegate.constructor.prototype;
                if (rootScopePrototype.hasOwnProperty('$apply')) {
                  original$applyFn = rootScopePrototype.$apply;
                  rootScopePrototype.$apply = (exp: any) => delayApplyExps.push(exp);
                } else {
                  throw new Error('Failed to find \'$apply\' on \'$rootScope\'!');
                }
                return rootScope = rootScopeDelegate;
              }
            ]);
            if (ng1Injector.has(NG1_TESTABILITY)) {
              provide.decorator(NG1_TESTABILITY, [
                '$delegate',
                function(testabilityDelegate: angular.ITestabilityService) {

                  const originalWhenStable: Function = testabilityDelegate.whenStable;
                  const newWhenStable = (callback: Function): void => {
                    const whenStableContext: any = this;
                    originalWhenStable.call(this, function() {
                      const ng2Testability: Testability = moduleRef.injector.get(Testability);
                      if (ng2Testability.isStable()) {
                        callback.apply(this, arguments);
                      } else {
                        ng2Testability.whenStable(newWhenStable.bind(whenStableContext, callback));
                      }
                    });
                  };

                  testabilityDelegate.whenStable = newWhenStable;
                  return testabilityDelegate;
                }
              ]);
            }
          }
        ]);

    ng1compilePromise = new Promise((resolve, reject) => {
      ng1Module.run([
        '$injector', '$rootScope',
        (injector: angular.IInjectorService, rootScope: angular.IRootScopeService) => {
          ng1Injector = injector;
          UpgradeNg1ComponentAdapterBuilder.resolve(this.ng1ComponentsToBeUpgraded, injector)
              .then(() => {
                // At this point we have ng1 injector and we have lifted ng1 components into ng2, we
                // now can bootstrap ng2.
                const DynamicNgUpgradeModule =
                    NgModule({
                      providers: [
                        {provide: NG1_INJECTOR, useFactory: () => ng1Injector},
                        {provide: NG1_COMPILE, useFactory: () => ng1Injector.get(NG1_COMPILE)},
                        this.providers
                      ],
                      imports: [this.ng2AppModule]
                    }).Class({
                      constructor: function DynamicNgUpgradeModule() {},
                      ngDoBootstrap: function() {}
                    });

                (platformBrowserDynamic() as any)
                    ._bootstrapModuleWithZone(
                        DynamicNgUpgradeModule, this.compilerOptions, ngZone,
                        (componentFactories: ComponentFactory<any>[]) => {
                          componentFactories.forEach((componentFactory: ComponentFactory<any>) => {
                            const type: Type<any> = componentFactory.componentType;
                            if (this.upgradedComponents.indexOf(type) !== -1) {
                              componentFactoryRefMap[getComponentInfo(type).selector] =
                                  componentFactory;
                            }
                          });
                        })
                    .then((ref: NgModuleRef<any>) => {
                      moduleRef = ref;
                      angular.element(element).data(
                          controllerKey(NG2_INJECTOR), moduleRef.injector);
                      ngZone.onMicrotaskEmpty.subscribe({
                        next: (_: any) => ngZone.runOutsideAngular(() => rootScope.$evalAsync())
                      });
                    })
                    .then(resolve, reject);
              })
              .catch(reject);
        }
      ]);
    });

    // Make sure resumeBootstrap() only exists if the current bootstrap is deferred
    const windowAngular = (window as any /** TODO #???? */)['angular'];
    windowAngular.resumeBootstrap = undefined;

    ngZone.run(() => { angular.bootstrap(element, [this.idPrefix], config); });
    ng1BootstrapPromise = new Promise((resolve) => {
      if (windowAngular.resumeBootstrap) {
        const originalResumeBootstrap: () => void = windowAngular.resumeBootstrap;
        windowAngular.resumeBootstrap = function() {
          windowAngular.resumeBootstrap = originalResumeBootstrap;
          windowAngular.resumeBootstrap.apply(this, arguments);
          resolve();
        };
      } else {
        resolve();
      }
    });

    Promise.all([ng1BootstrapPromise, ng1compilePromise]).then(() => {
      moduleRef.injector.get(NgZone).run(() => {
        if (rootScopePrototype) {
          rootScopePrototype.$apply = original$applyFn;  // restore original $apply
          while (delayApplyExps.length) {
            rootScope.$apply(delayApplyExps.shift());
          }
          (<any>upgrade)._bootstrapDone(moduleRef, ng1Injector);
          rootScopePrototype = null;
        }
      });
    }, onError);
    return upgrade;
  }

  /**
   * Allows AngularJS v1 service to be accessible from Angular v2.
   *
   *
   * ### Example
   *
   * ```
   * class Login { ... }
   * class Server { ... }
   *
   * @Injectable()
   * class Example {
   *   constructor(@Inject('server') server, login: Login) {
   *     ...
   *   }
   * }
   *
   * var module = angular.module('myExample', []);
   * module.service('server', Server);
   * module.service('login', Login);
   *
   * var adapter = new UpgradeAdapter();
   * adapter.upgradeNg1Provider('server');
   * adapter.upgradeNg1Provider('login', {asToken: Login});
   *
   * adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
   *   var example: Example = ref.ng2Injector.get(Example);
   * });
   *
   * ```
   */
  public upgradeNg1Provider(name: string, options?: {asToken: any}) {
    const token = options && options.asToken || name;
    this.providers.push({
      provide: token,
      useFactory: (ng1Injector: angular.IInjectorService) => ng1Injector.get(name),
      deps: [NG1_INJECTOR]
    });
  }

  /**
   * Allows Angular v2 service to be accessible from AngularJS v1.
   *
   *
   * ### Example
   *
   * ```
   * class Example {
   * }
   *
   * var adapter = new UpgradeAdapter();
   *
   * var module = angular.module('myExample', []);
   * module.factory('example', adapter.downgradeNg2Provider(Example));
   *
   * adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
   *   var example: Example = ref.ng1Injector.get('example');
   * });
   *
   * ```
   */
  public downgradeNg2Provider(token: any): Function {
    const factory = function(injector: Injector) { return injector.get(token); };
    (<any>factory).$inject = [NG2_INJECTOR];
    return factory;
  }
}

interface ComponentFactoryRefMap {
  [selector: string]: ComponentFactory<any>;
}

function ng1ComponentDirective(info: ComponentInfo, idPrefix: string): Function {
  (<any>directiveFactory).$inject = [NG1_INJECTOR, NG2_COMPONENT_FACTORY_REF_MAP, NG1_PARSE];
  function directiveFactory(
      ng1Injector: angular.IInjectorService, componentFactoryRefMap: ComponentFactoryRefMap,
      parse: angular.IParseService): angular.IDirective {
    let idCount = 0;
    return {
      restrict: 'E',
      require: REQUIRE_INJECTOR,
      link: {
        post: (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes,
               parentInjector: any, transclude: angular.ITranscludeFunction): void => {
          const componentFactory: ComponentFactory<any> = componentFactoryRefMap[info.selector];
          if (!componentFactory)
            throw new Error('Expecting ComponentFactory for: ' + info.selector);

          if (parentInjector === null) {
            parentInjector = ng1Injector.get(NG2_INJECTOR);
          }
          const facade = new DowngradeNg2ComponentAdapter(
              idPrefix + (idCount++), info, element, attrs, scope, <Injector>parentInjector, parse,
              componentFactory);
          facade.setupInputs();
          facade.bootstrapNg2();
          facade.projectContent();
          facade.setupOutputs();
          facade.registerCleanup();
        }
      }
    };
  }
  return directiveFactory;
}

/**
 * Use `UpgradeAdapterRef` to control a hybrid AngularJS v1 / Angular v2 application.
 *
 * @stable
 */
export class UpgradeAdapterRef {
  /* @internal */
  private _readyFn: (upgradeAdapterRef?: UpgradeAdapterRef) => void = null;

  public ng1RootScope: angular.IRootScopeService = null;
  public ng1Injector: angular.IInjectorService = null;
  public ng2ModuleRef: NgModuleRef<any> = null;
  public ng2Injector: Injector = null;

  /* @internal */
  private _bootstrapDone(ngModuleRef: NgModuleRef<any>, ng1Injector: angular.IInjectorService) {
    this.ng2ModuleRef = ngModuleRef;
    this.ng2Injector = ngModuleRef.injector;
    this.ng1Injector = ng1Injector;
    this.ng1RootScope = ng1Injector.get(NG1_ROOT_SCOPE);
    this._readyFn && this._readyFn(this);
  }

  /**
   * Register a callback function which is notified upon successful hybrid AngularJS v1 / Angular v2
   * application has been bootstrapped.
   *
   * The `ready` callback function is invoked inside the Angular v2 zone, therefore it does not
   * require a call to `$apply()`.
   */
  public ready(fn: (upgradeAdapterRef?: UpgradeAdapterRef) => void) { this._readyFn = fn; }

  /**
   * Dispose of running hybrid AngularJS v1 / Angular v2 application.
   */
  public dispose() {
    this.ng1Injector.get(NG1_ROOT_SCOPE).$destroy();
    this.ng2ModuleRef.destroy();
  }
}


text:
//------------------------------------------------------------------------------
// <copyright file="ComponentEvent.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

/*
 */
namespace System.ComponentModel.Design {
    using Microsoft.Win32;
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Security.Permissions;

    /// <devdoc>
    /// <para>Provides data for the System.ComponentModel.Design.IComponentChangeService.ComponentEvent
    /// event raised for component-level events.</para>
    /// </devdoc>
    [HostProtection(SharedState = true)]
    [System.Runtime.InteropServices.ComVisible(true)]
    [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.InheritanceDemand, Name="FullTrust")]
    [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name="FullTrust")]
    public class ComponentEventArgs : EventArgs {

        private IComponent component;

        /// <devdoc>
        ///    <para>
        ///       Gets or sets the component associated with the event.
        ///    </para>
        /// </devdoc>
        public virtual IComponent Component {
            get {
                return component;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of the System.ComponentModel.Design.ComponentEventArgs class.
        ///    </para>
        /// </devdoc>
        public ComponentEventArgs(IComponent component) {
            this.component = component;
        }
    }
}


text:
<?php

namespace Squinones\Sunlight\Congress;

use Squinones\Sunlight\Congress\Api\ApiWrapper;
use Squinones\Sunlight\Congress\Containers\Filter;

/**
 * @link    https://sunlightlabs.github.io/congress/legislators.html
 * @author  Samantha Quinones <samantha@tembies.com>
 * @package Sunlight\Congress
 */
class Legislators extends ApiWrapper
{
    /**
     * @var string
     */
    protected $url = "https://congress.api.sunlightfoundation.com/legislators";

    /**
     * Query the /locate subordinate endpoint
     *
     * @link https://sunlightlabs.github.io/congress/legislators.html#methods/legislators-locate
     *
     * @param $location
     *
     * @return Api\ApiResponse
     */
    public function locate($location)
    {
        // Clone the wrapper
        $legislators = clone $this;

        // Create an empty filter
        $filter = new Filter();

        // If the location is an array, assume a lat/long pair, otherwise a zip code
        if (is_array($location)) {
            list($filter["latitude"], $filter["longitude"]) = $location;
        } else {
            $filter["zip"] = $location;
        }

        // Set the filter
        $legislators->filter($filter);

        // Set the url to /locate
        $legislators->setUrl($this->getUrl() . "/locate");

        // Run the find method
        return $legislators->filter($filter)->find();
    }
}


text:
<?php

namespace XSessionTest;

include_once 'smartloader.php';

use PHPUnit\Framework\TestCase;
use solutionstack\XSession\XSession;

class XSessionTest extends TestCase {

    protected $s;

    protected function setUp() {

        if (isset($_SESSION)) {
            unset($_SESSION);
        }

        //remove files from the session_save_path dir
        \shell_exec('rm -rf App/XSession/sess/*');
    }

    public function testSessionCreated() {

        $this->s = new XSession("test_session", 300);
        $this->s->start();

	//make sure the instance of the XSession class was created
	$this->assertInstanceOf( XSession::class, $this->s);

	//make sure session file gets created, in the save path
	$this->assertFileExists(__DIR__."/App/XSession/sess/sess_".$this->s->getSID(), "session file not created in save path");

	  $this->s->put("bar",2000);

	//read the stored session data
        $this->assertEquals(  $this->s->get("bar"), 2000, "Adding data to session failed");

	$this->s->end();

	$this->assertTrue(isset($_SESSION) === false);

	return $this->s;

    }

    protected function tearDown() {

 	//remove files from the session_save_path dir
        shell_exec('rm -rf App/XSession/sess/*');

    }

}


text:
package com.amazonaws.services.glacier.model.transform;

import java.util.Map;
import java.util.Map.Entry;

import com.amazonaws.services.glacier.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * Upload List Element JSON Unmarshaller
 */
public class UploadListElementJsonUnmarshaller implements Unmarshaller<UploadListElement, JsonUnmarshallerContext> {

    public UploadListElement unmarshall(JsonUnmarshallerContext context) throws Exception {
        UploadListElement uploadListElement = new UploadListElement();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null) token = context.nextToken();
        if (token == VALUE_NULL) return null;

        while (true) {
            if (token == null) break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("MultipartUploadId", targetDepth)) {
                    context.nextToken();
                    uploadListElement.setMultipartUploadId(StringJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("VaultARN", targetDepth)) {
                    context.nextToken();
                    uploadListElement.setVaultARN(StringJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("ArchiveDescription", targetDepth)) {
                    context.nextToken();
                    uploadListElement.setArchiveDescription(StringJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("PartSizeInBytes", targetDepth)) {
                    context.nextToken();
                    uploadListElement.setPartSizeInBytes(LongJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("CreationDate", targetDepth)) {
                    context.nextToken();
                    uploadListElement.setCreationDate(StringJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth) break;
                }
            }

            token = context.nextToken();
        }

        return uploadListElement;
    }

    private static UploadListElementJsonUnmarshaller instance;
    public static UploadListElementJsonUnmarshaller getInstance() {
        if (instance == null) instance = new UploadListElementJsonUnmarshaller();
        return instance;
    }
}


text:
package es.tid.pce.server.wson;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import es.tid.tedb.DomainTEDB;

public class ReservationManager {

	//private Timer timer;

	ScheduledThreadPoolExecutor executor;

	private DomainTEDB ted;
	private Logger log;

	private long reservationID;

	private Hashtable<Long,DeleteReservationTask> permanentReservationList;

	private Hashtable<Long,ScheduledFuture> scheduledReservationList;

	public ReservationManager(DomainTEDB ted){
		executor =new ScheduledThreadPoolExecutor(1);
		this.ted=ted;
		log=LoggerFactory.getLogger("PCEServer");
		reservationID=0;
		permanentReservationList=new Hashtable<Long,DeleteReservationTask>();
	}

	public long reserve(LinkedList<Object> sourceVertexList, LinkedList<Object> targetVertexList, int wavelength, long time, boolean bidirectional){
		//time Time in ms of the reservation
		log.info("Reserving lambda "+wavelength+" for "+time+" miliseconds");
		//SimpleDirectedWeightedGraph<Object,FiberLinkEdge> networkGraph=ted.getNetworkGraph();
		ted.notifyWavelengthReservation(sourceVertexList, targetVertexList, wavelength, bidirectional);
		DeleteReservationTask drt= new DeleteReservationTask();
		drt.setSourceVertexList(sourceVertexList);
		drt.setTargetVertexList(targetVertexList);
		drt.setWavelength(wavelength);
		drt.setBidirectional(bidirectional);
		drt.setTed(ted);
		long idReservation=getReservationID();
		if (time>=0xFFFFFFFFL){
			log.info("Permanent Reservation");
			permanentReservationList.put(idReservation, drt);

		}else{
			//timer.schedule(drt, time);
			log.info("Something will be reserved");
			ScheduledFuture<?> sf=executor.schedule(drt, time, TimeUnit.MILLISECONDS);
			//scheduledReservationList.put(idReservation, sf);
		}
		return idReservation;

	}
	public long reserve( LinkedList<Object> sourceVertexList, LinkedList<Object> targetVertexList, LinkedList<Integer> wlans, long time, boolean bidirectional, int m){
		//log.info("Reserving lambda "+wavelength+" for "+time+" miliseconds");
		ted.notifyWavelengthReservationWLAN(sourceVertexList, targetVertexList, wlans, bidirectional);

		DeleteReservationTask drt= new DeleteReservationTask();
		drt.setSourceVertexList(sourceVertexList);
		drt.setTargetVertexList(targetVertexList);
		drt.setM(m);
		drt.setWLANs(wlans);
		drt.setBidirectional(bidirectional);
		drt.setTed(ted);
		long idReservation=getReservationID();
		if (time>=0xFFFFFFFFL){
			log.info("Permanent Reservation");
			permanentReservationList.put(idReservation, drt);

		}else{
			log.info("Derreservar lambda en:"+time);
			//timer.schedule(drt, time);
			ScheduledFuture<?> sf=executor.schedule(drt, time, TimeUnit.MILLISECONDS);
			//scheduledReservationList.put(idReservation, sf);
		}
		return idReservation;

	}
	public long reserve( LinkedList<Object> sourceVertexList, LinkedList<Object> targetVertexList, int wavelength, long time, boolean bidirectional, int m){
		//log.info("Reserving lambda "+wavelength+" for "+time+" miliseconds");
		ted.notifyWavelengthReservationSSON(sourceVertexList, targetVertexList, wavelength, bidirectional, m);

		DeleteReservationTask drt= new DeleteReservationTask();
		drt.setSourceVertexList(sourceVertexList);
		drt.setTargetVertexList(targetVertexList);
		drt.setM(m);
		drt.setWavelength(wavelength);
		drt.setBidirectional(bidirectional);
		drt.setTed(ted);
		long idReservation=getReservationID();
		if (time>=0xFFFFFFFFL){
			log.info("Permanent Reservation");
			permanentReservationList.put(idReservation, drt);

		}else{
			log.info("Derreservar lambda en:"+time);
			//timer.schedule(drt, time);
			ScheduledFuture<?> sf=executor.schedule(drt, time, TimeUnit.MILLISECONDS);
			//scheduledReservationList.put(idReservation, sf);
		}
		return idReservation;

	}
	public void cancelReservation(long idReservation){
		DeleteReservationTask drt=permanentReservationList.remove(idReservation);
		//executor.execute(drt);
		if (drt!=null){
			drt.run();
		}

	}

	//public void permanentRe

	public synchronized long getReservationID(){
		reservationID+=1;
		return reservationID;
	}

	public void cancelAllReservations(){
		Enumeration<DeleteReservationTask> enu=permanentReservationList.elements();

		while (enu.hasMoreElements()){
			DeleteReservationTask drt= enu.nextElement();
			if (drt!=null){
				executor.execute(drt);
			}
		}
		permanentReservationList.clear();
	}

	public long getReservationQueueSize(){
		return permanentReservationList.size();
	}

	public DomainTEDB getTed() {
		return ted;
	}

	public void setTed(DomainTEDB ted) {
		this.ted = ted;
	}

}


text:
body{background: url(../images/congruent_pentagon.png);}

canvas { margin: 0 auto; border: 2px solid white;}


text:
/* $Id: strcpy.cpp $ */
/** @file
 * IPRT - CRT Strings, strcpy().
 */

/*
 * Copyright (C) 2006-2015 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 */

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include <iprt/string.h>

/**
 * Copy a string
 *
 * @returns Pointer to destination string
 * @param   pszDst      Will contain a copy of pszSrc.
 * @param   pszSrc      Zero terminated string.
 */
char* strcpy(char *pszDst, register const char *pszSrc)
{
    register char *psz = pszDst;
    while ((*psz++ = *pszSrc++))
        ;

    return pszDst;
}


text:
/**
 * Used to communicate with relays.
 */
package com.s13g.winston.lib.relay;


text:
class AddImageToOrganizations < ActiveRecord::Migration[5.0]
  def change
    add_column :organizations, :image, :string, default: 'https://placeholdit.imgix.net/~text?txtsize=23&txt=200%C3%97200&w=200&h=200'
  end
end


text:
require 'bundler/setup'
require 'benchmark'
require 'xap_ruby'

def bench name, count, &block
	puts "Running #{count} iterations of #{name}"
	result = Benchmark.measure do
		count.times &block
	end
	puts result.format("#{count} iterations: cpu=%t clock=%r")
	puts "#{count / result.real} per second"
	puts
end

if File.expand_path(__FILE__) == File.expand_path($0)
	msg = <<-EOF
xap-header
{
v=12
hop=1
uid=FF345600
class=AClass.AClassType
source=AVendor.ADevice.AnInstance
}
ASchema.ASchemaType
{
mybinary!68656C6C6F
}
Another.Block
{
mytext=6/3
}
	EOF

	count = ARGV[0] || 10000
	count = count.to_i

	hash = nil
	bench("ParseXap.simple_parse", count) {
		 hash = Xap::Parser::ParseXap.simple_parse(msg)
	}

	node = nil
	bench("ParseXap.parse", count) {
		node = Xap::Parser::ParseXap.parse(msg)
	}

	bench("node.to_hash", count) {
		hash = node.to_hash
	}
end


text:
#ifndef _ASM_S390_HUGETLB_H
#define _ASM_S390_HUGETLB_H

#include <asm/page.h>
#include <asm/pgtable.h>

#define is_hugepage_only_range(mm, addr, len)	0
#define hugetlb_free_pgd_range			free_pgd_range

void set_huge_pte_at(struct mm_struct *mm, unsigned long addr,
		     pte_t *ptep, pte_t pte);
pte_t huge_ptep_get(pte_t *ptep);
pte_t huge_ptep_get_and_clear(struct mm_struct *mm,
			      unsigned long addr, pte_t *ptep);

/*
 * If the arch doesn't supply something else, assume that hugepage
 * size aligned regions are ok without further preparation.
 */
static inline int prepare_hugepage_range(struct file *file,
			unsigned long addr, unsigned long len)
{
	if (len & ~HPAGE_MASK)
		return -EINVAL;
	if (addr & ~HPAGE_MASK)
		return -EINVAL;
	return 0;
}

#define hugetlb_prefault_arch_hook(mm)		do { } while (0)
#define arch_clear_hugepage_flags(page)		do { } while (0)

int arch_prepare_hugepage(struct page *page);
void arch_release_hugepage(struct page *page);

static inline void huge_pte_clear(struct mm_struct *mm, unsigned long addr,
				  pte_t *ptep)
{
	pte_val(*ptep) = _SEGMENT_ENTRY_EMPTY;
}

static inline void huge_ptep_clear_flush(struct vm_area_struct *vma,
					 unsigned long address, pte_t *ptep)
{
	huge_ptep_get_and_clear(vma->vm_mm, address, ptep);
}

static inline int huge_ptep_set_access_flags(struct vm_area_struct *vma,
					     unsigned long addr, pte_t *ptep,
					     pte_t pte, int dirty)
{
	int changed = !pte_same(huge_ptep_get(ptep), pte);
	if (changed) {
		huge_ptep_get_and_clear(vma->vm_mm, addr, ptep);
		set_huge_pte_at(vma->vm_mm, addr, ptep, pte);
	}
	return changed;
}

static inline void huge_ptep_set_wrprotect(struct mm_struct *mm,
					   unsigned long addr, pte_t *ptep)
{
	pte_t pte = huge_ptep_get_and_clear(mm, addr, ptep);
	set_huge_pte_at(mm, addr, ptep, pte_wrprotect(pte));
}

static inline pte_t mk_huge_pte(struct page *page, pgprot_t pgprot)
{
	return mk_pte(page, pgprot);
}

static inline int huge_pte_none(pte_t pte)
{
	return pte_none(pte);
}

static inline int huge_pte_write(pte_t pte)
{
	return pte_write(pte);
}

static inline int huge_pte_dirty(pte_t pte)
{
	return pte_dirty(pte);
}

static inline pte_t huge_pte_mkwrite(pte_t pte)
{
	return pte_mkwrite(pte);
}

static inline pte_t huge_pte_mkdirty(pte_t pte)
{
	return pte_mkdirty(pte);
}

static inline pte_t huge_pte_wrprotect(pte_t pte)
{
	return pte_wrprotect(pte);
}

static inline pte_t huge_pte_modify(pte_t pte, pgprot_t newprot)
{
	return pte_modify(pte, newprot);
}

#endif /* _ASM_S390_HUGETLB_H */


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sets</title>
</head>
<body>
<script>
  /* sets are like a unique array, can only add item once
   * cant access items individually and not index based
  */
  const people = new Set();
  people.add('Mike');
  people.add('Cassie');
  people.add('Jen');

  console.log(people.values()); // SetIterator -- can use generator .next()

  for (const person of people) {
    console.log(person);
  }

  // pass it an array to creat on the fly
  const students = new Set(['Wes', 'Kara', 'Tony']);

  const dogs = ['Snickers', 'Sunny'];
  const dogSet = new Set(dogs);

  // .has to see if in there
  console.log(students.has('Tony'));

</script>
</body>
</html>


text:
<?php

// if, elseif, else statement
if ($userAction == "open") {
	// Open the file
	print "Open file
";
} elseif ($userAction == "save") {
	// Save the file
	print "Save file
";
} elseif ($userAction == "close") {
	// Close the file
	print "Close file
";
} elseif ($userAction == "logout") {
	// Log the user out
	print "Log user out
";
} else {
	print "Please choose an option
";
}

// the above example written with swtich
switch ($userAction) {
	case "open";
		// Open the file
		print "Open file
";
		break;
	case "save";
		// Save the file
		print "Save file
";
		break;
	case "close";
		// Close the file
		print "Close file
";
		break;
	case "logout";
		// Log the user out
		print "Log user out
";
		break;
	default:
		print "Please choose an option
";
}

// ternary operator
$widgets = 23;
$plenty = "We have plenty of widgets in stock.
";
$few = "Less than 10 widgets left. Time to order some more!
";
echo ($widgets >= 10) ? $plenty : $few;

?>


text:
function [State] = GetGeneratorOnOff(Measure)
State = zeros(1,length(Measure));
for i = 1:1:length(State)
    if Measure(i) ~=0
        port = udp('192.168.0.8', Measure(i), 'LocalPort',Measure(i)+10000); %Pelgt generata [kW]
        fopen(port);
        State(i)=(str2double(char(fread(port))));
        fclose(port);
        delete(port);
    end
end


text:
#ifndef OPENSIM_MOCOGOAL_H
#define OPENSIM_MOCOGOAL_H

#include <SimTKcommon/internal/State.h>

#include <OpenSim/Common/Object.h>
#include <OpenSim/Moco/MocoBounds.h>
#include <OpenSim/Moco/MocoConstraintInfo.h>
#include <OpenSim/Moco/MocoScaleFactor.h>
#include <OpenSim/Moco/osimMocoDLL.h>

namespace OpenSim {

class Model;

// TODO give option to specify gradient and Hessian analytically.

/** A goal is a term in the cost functional to be minimized, or a set of endpoint
constraints that must lie within provided bounds. Goals depend on the
phase's initial and final states and controls, and optionally on the
integral of a quantity over the phase.
Not all goals support endpoint constraint mode; see
getSupportsEndpointConstraint(). If a goal does support endpoint constraint
mode, then the default mode is available via getMode(). Use endpoint
constraint mode if you require the goal to be met strictly and do not want
to allow a trade-off between this goal and other goals.
The calculation of the goal may differ between cost and endpoint constraint
modes; cost mode may require that outputs are squared, for example.

# Stage dependency
Some goals require less of IntegrandInput and GoalInput than others. To
ensure goals are computed efficiently, goals can specify a stage dependency,
which tells solvers what to do when preparing IntegrandInput and GoalInput.
Here are the expectations for each SimTK::Stage:

- SimTK::Stage::Topology: the time field of IntegrandInput and
    initial_time and final_time fields of GoalInput are available.
- SimTK::Stage::Model: controls fields of IntegrandInput and
    GoalInput are available.
- SimTK::Stage::Instance: MocoParameters are applied to the model.
- SimTK::Stage::Time: state variables (SimTK::State::getY(), etc.) are
    available, and SimTK::Stage::getTime() is updated.
- SimTK::Stage::Position: state, initial_state, and final_state can be used
    to compute position-dependent quantities.
- SimTK::Stage::Velocity: state, initial_state, and final_state can be used
    to compute velocity-dependent quantities.
- SimTK::Stage::Dynamics: state, initial_state, and final_state can be used
    to compute force-dependent quantities.
- SimTK::Stage::Acceleration: state, initial_state, and final_state can be
    used to compute acceleration-dependent quantities, such as body
    accelerations and joint reactions.

## Scale factors
Goals may include an option to add scale factors to the MocoProblem using
`appendScaleFactor()`, which takes a MocoScaleFactor object for its argument.
A copy of this component is added to the Model internal to MocoProblemRep and
its property value is optimized via a MocoParameter. Scale factor usage is
specific to each MocoGoal (if used at all).

@par For developers
Every time the problem is solved, a copy of this goal is used. An individual
instance of a goal is only ever used in a single problem. Therefore, there
is no need to clear cache variables that you create in initializeImpl().
Also, information stored in this goal does not persist across multiple
solves.
@ingroup mocogoal */
class OSIMMOCO_API MocoGoal : public Object {
    OpenSim_DECLARE_ABSTRACT_OBJECT(MocoGoal, Object);

public:
    MocoGoal();

    MocoGoal(std::string name);

    MocoGoal(std::string name, double weight);

    /// Set whether this goal is used in the problem.
    void setEnabled(bool enabled) { set_enabled(enabled); }
    bool getEnabled() const { return get_enabled(); }

    /// In cost mode, the goal is multiplied by this weight. Use the weight to
    /// control the relative importance of terms in the cost functional. The
    /// weight is ignored (e.g., set to 1) in endpoint constraint mode.
    void setWeight(double weight) { set_weight(weight); }
    double getWeight() const { return get_weight(); }

    enum class Mode { Cost, EndpointConstraint };
    /// Set the mode property to either 'cost' or 'endpoint_constraint'. This
    /// should be set before initializing. Setting to 'endpoint_constraint' if
    /// getSupportsEndpointConstraint() is false causes an exception during
    /// initializing.
    void setMode(std::string mode) { set_mode(mode); }
    /// This returns the default mode of the goal, unless the user overrode
    /// the default using setMode().
    std::string getModeAsString() const {
        return getMode() == Mode::Cost ? "cost" : "endpoint_constraint";
    }
    Mode getMode() const {
        OPENSIM_THROW_IF_FRMOBJ(
                !m_model, Exception, "Getting the mode requires initializing.");
        return m_modeToUse;
    }
    bool getModeIsCost() const { return getMode() == Mode::Cost; }
    bool getModeIsEndpointConstraint() const {
        return getMode() == Mode::EndpointConstraint;
    }

    /// Types of goals have a class-level default for whether they are enforced
    /// as a cost or endpoint constraint.
    Mode getDefaultMode() const { return getDefaultModeImpl(); }

    /// Can this goal be used in endpoint constraint mode?
    bool getSupportsEndpointConstraint() const {
        return getSupportsEndpointConstraintImpl();
    }

    /// Get bounds for the constraints that are enforced when using this goal in
    /// endpoint constraint mode.
    /// This info is ignored if getSupportsEndpointConstraint() is false.
    const MocoConstraintInfo& getConstraintInfo() const {
        return get_MocoConstraintInfo();
    }
    MocoConstraintInfo& updConstraintInfo() { return upd_MocoConstraintInfo(); }

    /// Get the length of the return value of calcGoal().
    int getNumOutputs() const {
        OPENSIM_THROW_IF_FRMOBJ(!m_model, Exception,
                "Getting the number of outputs requires initializing.");
        return getConstraintInfo().getNumEquations();
    }

    /// Get the number of integrals required by this cost.
    /// This returns either 0 (for a strictly-endpoint cost) or 1.
    /// @precondition initializeOnModel() has been invoked.
    int getNumIntegrals() const {
        OPENSIM_THROW_IF_FRMOBJ(m_numIntegrals == -1, Exception,
                "The goal must be initialized for the number of integrals to "
                "be available.");
        return m_numIntegrals;
    }

    /// Obtain the stage that this goal depends on. Solvers can use this to more
    /// efficiently decide how to set the IntegrandInput and GoalInput. See the
    /// MocoGoal class description for details about the different stages. The
    /// stage dependency is the same for both modes of the goal (cost and
    /// endpoint constraint).
    // TODO: create separate getIntegrandStageDependency() and
    // getEndpointStageDependency() rather than using the same stage dependency
    // for both (as is the case now).
    SimTK::Stage getStageDependency() const {
        return m_stageDependency;
    }

    struct IntegrandInput {
        /// Time is available regardless of the stage dependency.
        const SimTK::Real& time;
        /// The time in the state is only updated if the stage requirement is
        /// SimTK::Stage::Time or greater.
        /// If you need access to the state variables, you must set a stage
        /// requirement of SimTK::Stage::Time.
        const SimTK::State& state;
        /// Controls are available with a stage requirement of
        /// SimTK::Stage::Model.
        /// If you only need to access the controls, use this field.
        /// This vector has length Model::getNumControls(), and has slots for
        /// disabled actuators. The function createControlNamesForModel()
        /// provides data structures that can be indexed in the same way as this
        /// field. Use this field rather than Model::getControls().
        const SimTK::Vector& controls;
    };
    /// Calculate the integrand that should be integrated and passed to
    /// calcCost(). If getNumIntegrals() is not zero, this must be implemented.
    /// @precondition initializeOnModel() has been invoked.
    SimTK::Real calcIntegrand(const IntegrandInput& input) const {
        double integrand = 0;
        if (!get_enabled()) { return integrand; }
        const SimTK::Stage stageBefore = input.state.getSystemStage();

        calcIntegrandImpl(input, integrand);

        if (input.state.getSystemStage() > stageBefore) {
            SimTK_ERRCHK2_ALWAYS(
                    input.state.getSystemStage() <= m_stageDependency,
                    (getConcreteClassName() + "::calcIntegrand()").c_str(),
                    "This goal has a stage dependency of %s, but "
                    "calcIntegrandImpl() exceeded this stage by realizing "
                    "to %s.",
                    m_stageDependency.getName().c_str(),
                    input.state.getSystemStage().getName().c_str());
        }
        return integrand;
    }

    /// @see IntegrandInput.
    struct GoalInput {
        const SimTK::Real& initial_time;
        const SimTK::State& initial_state;
        const SimTK::Vector& initial_controls;
        const SimTK::Real& final_time;
        const SimTK::State& final_state;
        const SimTK::Vector& final_controls;
        /// The solver computes the integral by integrating calcIntegrand().
        const double& integral;
    };
    /// In cost mode, the returned cost includes the weight, and the elements of
    /// the returned vector should be summed by the caller to obtain the total
    /// cost. In endpoint constraint mode, each element of the vector is a
    /// different scalar equation to enforce as a constraint.
    /// The length of the returned vector is getNumOutputs().
    /// @precondition initializeOnModel() has been invoked.
    void calcGoal(const GoalInput& input, SimTK::Vector& goal) const {
        goal.resize(getNumOutputs());
        goal = 0;
        if (!get_enabled()) { return; }
        const SimTK::Stage initialStageBefore =
                input.initial_state.getSystemStage();
        const SimTK::Stage finalStageBefore =
                input.final_state.getSystemStage();

        calcGoalImpl(input, goal);

        if (input.initial_state.getSystemStage() > initialStageBefore) {
            SimTK_ERRCHK2_ALWAYS(
                    input.initial_state.getSystemStage() <= m_stageDependency,
                    (getConcreteClassName() + "::calcGoal()").c_str(),
                    "This goal has a stage dependency of %s, but "
                    "calcGoalImpl() exceeded this stage by realizing "
                    "initial_state to %s.",
                    m_stageDependency.getName().c_str(),
                    input.initial_state.getSystemStage().getName().c_str());
        }
        if (input.final_state.getSystemStage() > finalStageBefore) {
            SimTK_ERRCHK2_ALWAYS(
                    input.final_state.getSystemStage() <= m_stageDependency,
                    (getConcreteClassName() + "::calcGoal()").c_str(),
                    "This goal has a stage dependency of %s, but "
                    "calcGoalImpl() exceeded this stage by realizing "
                    "final_state to %s.",
                    m_stageDependency.getName().c_str(),
                    input.final_state.getSystemStage().getName().c_str());
        }
        goal *= m_weightToUse;
    }

    /// Perform error checks on user input for this goal, and cache
    /// quantities needed when computing the goal value.
    /// This function must be invoked before invoking calcIntegrand() or
    /// calcGoal().
    void initializeOnModel(const Model& model) const {
        m_model.reset(&model);
        if (!get_enabled()) { return; }

        // Set mode.
        Mode mode;
        if (getProperty_mode().empty()) {
            mode = getDefaultMode();
        } else {
            checkMode(get_mode());
            mode = (get_mode() == "cost") ? Mode::Cost
                                          : Mode::EndpointConstraint;
        }
        OPENSIM_THROW_IF_FRMOBJ(mode == Mode::EndpointConstraint &&
                                        !getSupportsEndpointConstraint(),
                Exception,
                "Endpoint constraint mode not supported by this goal.");
        m_modeToUse = mode;
        if (m_modeToUse == Mode::EndpointConstraint) {
            m_weightToUse = 1;
        } else {
            m_weightToUse = get_weight();
        }

        initializeOnModelImpl(model);

        OPENSIM_THROW_IF_FRMOBJ(m_numIntegrals == -1, Exception,
                "Expected setRequirements() to be invoked, "
                "but it was not.");
    }

    /// Get a vector of the MocoScaleFactors added to this MocoGoal.
    /// @details Note: the return value is constructed fresh on every call from
    /// the internal property. Avoid repeated calls to this function.
    std::vector<MocoScaleFactor> getScaleFactors() const {
        std::vector<MocoScaleFactor> scaleFactors;
        for (int i = 0; i < getProperty_scale_factors().size(); ++i) {
            scaleFactors.push_back(get_scale_factors(i));
        }
        return scaleFactors;
    }

    /// Print the name type and mode of this goal. In cost mode, this prints the
    /// weight.
    void printDescription() const;

protected:
    /// Perform any caching before the problem is solved.
    /// You must override this function and invoke setRequirements().
    /// @precondition The model is initialized (initSystem()) and getModel()
    /// is available.
    /// The passed-in model is equivalent to getModel().
    /// Use this opportunity to check for errors in user input.
    virtual void initializeOnModelImpl(const Model&) const = 0;

    /// Set the number of integral terms required by this goal and the length
    /// of the vector passed into calcGoalImpl().
    /// This must be set within initializeOnModelImpl(), otherwise an exception
    /// is thrown during initialization.
    /// The number of integrals must be either 0 or 1.
    /// The stageDependency can be set to lower stages to avoid unnecessary
    /// calculations. For example, if the goal does not depend on forces,
    /// then the solver does not need to prepare the
    /// IntegrandInput and GoalInput for force calculations.
    /// See the MocoGoal class description for help with choosing the stage
    /// dependency.
    /// If you are not sure what your stageDependency is, leave it as
    /// SimTK::Stage::Acceleration to be safe.
    ///
    /// You must still realize to the appropriate stage within the
    /// integrand and goal functions. Setting the stageDependency to stage X
    /// does not mean that the SimTK::State is realized to stage X as a
    /// precondition of calcIntegrandImpl() and calcGoalImpl().
    void setRequirements(int numIntegrals, int numOutputs,
            SimTK::Stage stageDependency = SimTK::Stage::Acceleration) const {
        OPENSIM_THROW_IF(numIntegrals < 0 || numIntegrals > 1, Exception,
                "Number of integrals must be 0 or 1.");
        OPENSIM_THROW_IF(numOutputs < 0, Exception,
                "Number of outputs must be non-negative.");
        m_numIntegrals = numIntegrals;
        const_cast<MocoGoal*>(this)->upd_MocoConstraintInfo().setNumEquations(
                numOutputs);
        m_stageDependency = stageDependency;
    }

    virtual Mode getDefaultModeImpl() const { return Mode::Cost; }
    virtual bool getSupportsEndpointConstraintImpl() const { return false; }
    /// You may need to realize the state to the stage required for your
    /// calculations.
    /// Do NOT realize to a stage higher than the goal's stage dependency;
    /// doing so will cause an exception to be thrown.
    /// The Lagrange multipliers for kinematic constraints are not available.
    virtual void calcIntegrandImpl(
            const IntegrandInput& input, SimTK::Real& integrand) const;
    /// You may need to realize the state to the stage required for your
    /// calculations.
    /// Do NOT realize to a stage higher than the goal's stage dependency;
    /// doing so will cause an exception to be thrown.
    /// The Lagrange multipliers for kinematic constraints are not available.
    virtual void calcGoalImpl(
            const GoalInput& input, SimTK::Vector& goal) const = 0;
    /// Print a more detailed description unique to each goal.
    virtual void printDescriptionImpl() const {};
    /// For use within virtual function implementations.
    const Model& getModel() const {
        OPENSIM_THROW_IF_FRMOBJ(!m_model, Exception,
                "Model is not available until the start of initializing.");
        return m_model.getRef();
    }

    double calcSystemDisplacement(
            const SimTK::State& initial, const SimTK::State& final) const;

    /// Append a MocoScaleFactor to this MocoGoal.
    void appendScaleFactor(const MocoScaleFactor& scaleFactor) {
        append_scale_factors(scaleFactor);
    }

private:
    OpenSim_DECLARE_PROPERTY(
            enabled, bool, "This bool indicates whether this goal is enabled.");
    OpenSim_DECLARE_PROPERTY(weight, double,
            "In cost mode, the goal is multiplied by this weight (default: "
            "1).");
    OpenSim_DECLARE_OPTIONAL_PROPERTY(mode, std::string,
            "'cost' to enforce as a penalty, 'endpoint_constraint' to enforce "
            "as a constraint.");
    OpenSim_DECLARE_UNNAMED_PROPERTY(MocoConstraintInfo,
            "The bounds and labels for this MocoGoal, if applied as an "
            "endpoint constraint.");
    OpenSim_DECLARE_LIST_PROPERTY(scale_factors, MocoScaleFactor,
            "Scale factors added by derived MocoGoal classes that are optimized "
            "via a MocoParameter. A copy of each MocoScaleFactor component is "
            "added to the model internal to MocoProblem, which makes the scale "
            "factors values available when computing the cost function for each "
            "MocoGoal.")

    void constructProperties();

    void checkMode(const std::string& mode) const {
        OPENSIM_THROW_IF_FRMOBJ(mode != "cost" && mode != "endpoint_constraint",
                Exception,
                fmt::format(
                        "Expected mode to be 'cost' or 'endpoint_constraint' "
                        "but got {}.",
                        mode));
    }

    mutable SimTK::ReferencePtr<const Model> m_model;
    mutable double m_weightToUse;
    mutable Mode m_modeToUse;
    mutable SimTK::Stage m_stageDependency = SimTK::Stage::Acceleration;
    mutable int m_numIntegrals = -1;
};

inline void MocoGoal::calcIntegrandImpl(
        const IntegrandInput&, SimTK::Real&) const {}

/** Endpoint cost for final time.
@ingroup mocogoal */
class OSIMMOCO_API MocoFinalTimeGoal : public MocoGoal {
    OpenSim_DECLARE_CONCRETE_OBJECT(MocoFinalTimeGoal, MocoGoal);

public:
    MocoFinalTimeGoal() = default;
    MocoFinalTimeGoal(std::string name) : MocoGoal(std::move(name)) {}
    MocoFinalTimeGoal(std::string name, double weight)
            : MocoGoal(std::move(name), weight) {}

protected:
    void initializeOnModelImpl(const Model&) const override {
        setRequirements(0, 1, SimTK::Stage::Topology);
    }
    void calcGoalImpl(
            const GoalInput& input, SimTK::Vector& cost) const override {
        cost[0] = input.final_time;
    }
};

/** This goal requires the average speed of the system to match a desired
average speed. The average speed of the system is the displacement of the
system's center of mass divided by the duration of the phase.

In endpoint constraint mode, the goal is computed as follows:

\f[
 v_\mathrm{des} - \frac{r_\mathrm{com}(t_f) - r_\mathrm{com}(t_i)}{t_f - t_i}
\f]

We use the following notation:
- \f$ v_\mathrm{des} \f$: desired average speed.
- \f$ r_\mathrm{com}(t) \f$: mass center position.
- \f$ t_i \f$: initial time.
- \f$ t_f \f$: final time.

In cost mode, the value of the goal is the above quantity squared.
@ingroup mocogoal */
class MocoAverageSpeedGoal : public MocoGoal {
    OpenSim_DECLARE_CONCRETE_OBJECT(MocoAverageSpeedGoal, MocoGoal);

public:
    OpenSim_DECLARE_PROPERTY(desired_average_speed, double,
            "The desired average speed of the system (m/s). Default: 0.");
    MocoAverageSpeedGoal() { constructProperties(); }
    MocoAverageSpeedGoal(std::string name) : MocoGoal(std::move(name)) {
        constructProperties();
    }

protected:
    bool getSupportsEndpointConstraintImpl() const override { return true; }
    Mode getDefaultModeImpl() const override {
        return Mode::EndpointConstraint;
    }
    void calcGoalImpl(
            const GoalInput& input, SimTK::Vector& values) const override {
        SimTK::Real timeInitial = input.initial_state.getTime();
        SimTK::Real timeFinal = input.final_state.getTime();
        SimTK::Real duration = timeFinal - timeInitial;

        SimTK::Vec3 comInitial =
                getModel().calcMassCenterPosition(input.initial_state);
        SimTK::Vec3 comFinal =
                getModel().calcMassCenterPosition(input.final_state);
        // TODO: Use distance squared for convexity.
        SimTK::Real displacement = (comFinal - comInitial).norm();
        // Calculate average gait speed.
        values[0] = get_desired_average_speed() - (displacement / duration);
        if (getModeIsCost()) { values[0] = SimTK::square(values[0]); }
    }
    void initializeOnModelImpl(const Model&) const override {
        setRequirements(0, 1);
    }

private:
    void constructProperties() { constructProperty_desired_average_speed(0); }
};

} // namespace OpenSim

#endif // OPENSIM_MOCOGOAL_H


text:
#!/usr/bin/env node

/**
 * Wrapper around agent entry point.
 */
var path = require('path');
var root = path.dirname(__filename);

// in-place path
require.paths.unshift(path.join(root, '../lib'));
require.paths.unshift(path.join(root, 'lib'));

var server = require('nodules-server/entry');

server.run();


text:
<md-toast class="md-action pip-toast"
          ng-class="{'pip-error': vm.toast.type=='error' || vm.toast.type=='clickable_error',
          'pip-column-toast': vm.toast.actions.length > 1 || vm.actionLenght > 4,
          'pip-no-action-toast': vm.actionLenght == 0}"
          style="height:initial; max-height: initial; ">

 0 || ((vm.toast.type=='error' || vm.toast.type=='clickable_error') && vm.toast.error)">

 1">

            <md-button class="flex-fixed pip-toast-button" ng-if="vm.toast.type=='error' && vm.toast.error && vm.showDetails" ng-click="vm.onDetails()">Details</md-button>
            <md-button class="flex-fixed pip-toast-button"
                    ng-click="vm.onAction(action)"
                    ng-repeat="action in vm.actions"
                    aria-label="{{::action| translate}}">
                {{::action| translate}}
            </md-button>

</md-toast>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.examw</groupId>
  <artifactId>examw-oa</artifactId>
  <version>1.0.0</version>
  <packaging>war</packaging>
  <name>examw-oa-web</name>
  <description>中华考试网办公管理系统</description>

  <!--定义参数变量-->
  <properties>
    <java.version>1.7</java.version>
    <encoding>UTF-8</encoding>
    <spring.version>3.2.4.RELEASE</spring.version>
    <hibernate.version>4.2.12.Final</hibernate.version>
    <hibernate-validator.version>4.2.0.Final</hibernate-validator.version>
    <mysql-connector.version>5.1.26</mysql-connector.version>
    <freemarker.version>2.3.20</freemarker.version>
    <sitemesh.version>2.4.2</sitemesh.version>
    <aspectjweaver.version>1.7.3</aspectjweaver.version>
    <slf4j-api.version>1.7.5</slf4j-api.version>
    <log4j.version>1.2.17</log4j.version>
    <druid.version>0.2.9</druid.version>
    <junit.version>4.11</junit.version>
    <shiro.version>1.2.3</shiro.version>
    <ehcache.version>2.6.9</ehcache.version>
    <jackson.version>1.9.13</jackson.version>
  </properties>

  <!-- 项目依赖 -->
  <dependencies>
  		<!-- serlvert -->
  		<dependency>
  			<groupId>javax.servlet</groupId>
		    <artifactId>servlet-api</artifactId>
            <version>2.5</version>
		    <scope>provided</scope>
  		</dependency>
  		<!-- ehcache-->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache-core</artifactId>
           <version>${ehcache.version}</version>
		</dependency>
  		<!--spring-->
  		<dependency>
  			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
  		    <version>${spring.version}</version>
       </dependency>
  	   <dependency>
  			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
  		    <version>${spring.version}</version>
        </dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
		   <artifactId>spring-expression</artifactId>
           <version>${spring.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
  		</dependency>
  		<!-- freemarker -->
  		<dependency>
  			<groupId>org.freemarker</groupId>
		    <artifactId>freemarker</artifactId>
            <version>${freemarker.version}</version>
  		</dependency>
  		<!-- hibernate -->
  		<dependency>
  			<groupId>org.hibernate</groupId>
	    	<artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>org.hibernate</groupId>
	    	<artifactId>hibernate-validator</artifactId>
            <version>${hibernate-validator.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>org.hibernate</groupId>
	    	<artifactId>hibernate-ehcache</artifactId>
            <version>${hibernate.version}</version>
  		</dependency>
  		<!-- mysql数据库驱动 -->
  		<dependency>
  			<groupId>mysql</groupId>
	  		<artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector.version}</version>
  		</dependency>
  		<!--druid数据源-->
  		<dependency>
  			<groupId>com.alibaba</groupId>
	  		<artifactId>druid</artifactId>
            <version>${druid.version}</version>
  		</dependency>
  		<!-- 日志 -->
  		<dependency>
  			<groupId>org.slf4j</groupId>
		    <artifactId>slf4j-api</artifactId>
            <version>${slf4j-api.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>log4j</groupId>
		    <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>org.slf4j</groupId>
		    <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j-api.version}</version>
  		</dependency>
  		<!-- aspectjweaver -->
  		<dependency>
  			<groupId>org.aspectj</groupId>
		    <artifactId>aspectjweaver</artifactId>
            <version>${aspectjweaver.version}</version>
  		</dependency>
  		<!-- json -->
  		<dependency>
  			<groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-lgpl</artifactId>
            <version>${jackson.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>${jackson.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
  		</dependency>
  		<dependency>
  			<groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-lgpl</artifactId>
            <version>${jackson.version}</version>
  		</dependency>
  		<!-- upload -->
  		<dependency>
  			<groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
  		</dependency>
  		<dependency>
  			<groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
  		</dependency>
  		<dependency>
  			<groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
  		</dependency>
		<!-- shiro -->
	  	<dependency>
	        <groupId>org.apache.shiro</groupId>
	        <artifactId>shiro-core</artifactId>
            <version>${shiro.version}</version>
	    </dependency>
	    <dependency>
	    	<groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-web</artifactId>
            <version>${shiro.version}</version>
	    </dependency>
	    <dependency>
	    	<groupId>org.apache.shiro</groupId>
    		<artifactId>shiro-ehcache</artifactId>
            <version>${shiro.version}</version>
	    </dependency>
	    <dependency>
	    	<groupId>org.apache.shiro</groupId>
    		<artifactId>shiro-quartz</artifactId>
            <version>${shiro.version}</version>
	    </dependency>
	    <dependency>
	    	<groupId>org.apache.shiro</groupId>
    		<artifactId>shiro-spring</artifactId>
            <version>${shiro.version}</version>
	    </dependency>

	    <!--xstream-->
		<dependency>
		    <groupId>com.thoughtworks.xstream</groupId>
		    <artifactId>xstream</artifactId>
		    <version>1.3.1</version>
		    <scope>test</scope>
		</dependency>

  		<!-- 项目依赖 -->
  		<dependency>
  			<groupId>com.examw</groupId>
	  		<artifactId>examw-core</artifactId>
            <version>1.0.0</version>
  		</dependency>

  		<!--test junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
  </dependencies>

  <!-- 编译 -->
  <build>
  		<finalName>examw-oa</finalName>
  		<plugins>
	    	<!--war -->
	    	<plugin>
	    		<groupId>org.apache.maven.plugins</groupId>
	    		<artifactId>maven-war-plugin</artifactId>
	    		<version>2.4</version>
	    	</plugin>
	    	<!--编译插件 -->
	    	<plugin>
	    		<groupId>org.apache.maven.plugins</groupId>
	    		<artifactId>maven-compiler-plugin</artifactId>
	    		<version>3.1</version>
	    		<configuration>
	    			<source>${java.version}</source>
	    			<target>${java.version}</target>
	    			<encoding>${encoding}</encoding>
	    		</configuration>
	    	</plugin>
	    	<!--源码插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<encoding>${encoding}</encoding>
				</configuration>
			</plugin>
			<!--javadoc插件-->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.9.1</version>
				<configuration>
					<encoding>${encoding}</encoding>
				</configuration>
			</plugin>
    </plugins>
  </build>
</project>


text:
var Ruut = require("../lib")
  , Assert = require("assert")
  ;

// Create the ruut instance
var router = Ruut([
    function (route) {
        console.log("This is the home page.", route);
        return "This is the home page"
    }
  , {
       ":user": ["user-profile", {
            ":project": {
                "build": "build"
              , "editor": [null, {}, "file-editor" ]
            }
        }]
      , "blog": ["Blog homepage", {
            "page": {
                ":page": "Blog page"
            }
          , ":article": ["Blog article", {
                "comments": ["comments", {
                    ":id": "Current comment"
                }]
            }]
        }]
        // Route: /signup
      , "signup": "Sign up route"
      , "users": ["Users list", {
            ":user": "User profile"
        }]
    }
]);

it("should support home page and function", function (cb) {
    Assert.deepEqual(router("/"), {
        data: "This is the home page"
      , params: {}
    });
    cb();
});

it("should support one level routes", function (cb) {
    Assert.deepEqual(router("/blog"), {
        data: "Blog homepage"
      , params: {}
    });
    cb();
});

it("should support parameters", function (cb) {
    Assert.deepEqual(router("/blog/page/10"), {
        data: "Blog page"
      , params: { page: '10' }
    });
    cb();
});

it("should support two level parameters", function (cb) {
    Assert.deepEqual(router("/blog/some-article"), {
        data: "Blog article"
      , params: { article: "some-article" }
    });
    cb();
});

it("should support more parameters in the same url", function (cb) {
    Assert.deepEqual(router("/blog/some-article/comments/my-comment"), {
        data: "Current comment"
      , params: {
            article: "some-article"
          , id: "my-comment"
        }
    });
    cb();
});

it("should support endless routes", function (cb) {
    Assert.deepEqual(router("/ionicabizau/my-project/editor/edit/some/file.js"), {
        data: "file-editor"
      , params: {
            user: "ionicabizau"
          , project: "my-project"
        }
    });
    cb();
});

it("should return null if the endless route is not configured", function (cb) {
    Assert.equal(router("/users/ionicabizau/and-invalid-route"), null);
    cb();
});


text:
package cloudcallcenter

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// BasicStatisticsReportSubItem is a nested struct in cloudcallcenter response
type BasicStatisticsReportSubItem struct {
	Value                            string         `json:"Value" xml:"Value"`
	Count                            int            `json:"Count" xml:"Count"`
	BasicStatisticsReportSubItemName string         `json:"BasicStatisticsReportSubItemName" xml:"BasicStatisticsReportSubItemName"`
	Percentage                       int            `json:"Percentage" xml:"Percentage"`
	Row                              []KeyValuePair `json:"Row" xml:"Row"`
}


text:
import json
if __name__ == "__main__":
    print("Hello World!")


text:
<!doctype html>

{% include _head.html %}

{% include _browser-upgrade.html %}

{% include _navigation.html %}

{% if page.image.feature %}

  {% if page.image.credit %}
    Photo Credit: {{ page.image.credit }}
  {% endif %}

{% endif %}

    {% include _author-bio-no-image.html %}

  My name is (Alex) Yuan Gao and I a PhD candidate at Uppsala University. I am also one of the founding members of the [Uppsala Social Robotics Lab](http://usr-lab.com) and [SoRoS Community](http://soros-community.github.io). My research interests are driven by a final goal of developing AI-driven robots that can think and feel like real humans (e.g. Ex Machina). This encircles robot's learning and control, natural language processing, image processing, neuroscience and computational phycology. In particular, I am interested in deep/reinforcement/neuro-based learning approaches for robotic perception, control, and physical modelling of the robot's environment, which can help us to understand ourselves and build a unified learning structure for an adaptive, efficient and robust complex robotic system.

    {% include _footer.html %}

{% include _scripts.html %}


text:
<ion-header>
  <ion-navbar color='primary'>
    <ion-title>Login</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <form [formGroup]='loginForm' (submit)='loginUser()' novalidate>
    <ion-item>
      <ion-label floating>Email</ion-label>
      <ion-input formControlName='email' type='email' [class.invalid]='!loginForm.controls.email.valid && loginForm.controls.email.dirty'>
      </ion-input>
    </ion-item>
    <ion-item class='error-message' *ngIf='!loginForm.controls.email.valid && loginForm.controls.email.dirty'>

Change that depend on Email Validation rules

    </ion-item>
    <ion-item>
      <ion-label floating>Password</ion-label>
      <ion-input formControlName='password' type='password' [class.invalid]='!loginForm.controls.password.valid && loginForm.controls.password.dirty'></ion-input>
    </ion-item>
    <ion-item class='error-message' *ngIf='!loginForm.controls.password.valid && loginForm.controls.password.dirty'>

Change that depend on password Validation rules

    </ion-item>
    <button ion-button block type="submit" [disabled]="!loginForm.valid">
      Login
    </button>
  </form>
  <button ion-button block clear (click)="goToSignup()">
    Create a new account
  </button>
  <button ion-button block clear (click)="goToResetPassword()">
    I forgot my password
  </button>
</ion-content>


text:
"""Download flags of countries (with error handling).

asyncio yield-from version

Sample run::

    $ python3 flags2_asyncio.py -s ERROR -e -m 200
    ERROR site: http://localhost:8003/flags
    Searching for 676 flags: from AA to ZZ
    200 concurrent connections will be used.
    --------------------
    146 flags downloaded.
    363 not found.
    167 errors.
    Elapsed time: 2.59s

"""
# BEGIN FLAGS2_ASYNCIO_TOP
import asyncio
import collections
import contextlib

import aiohttp
from aiohttp import web
import tqdm

from flags2_common import main, HTTPStatus, Result, save_flag

# default set low to avoid errors from remote site, such as
# 503 - Service Temporarily Unavailable
DEFAULT_CONCUR_REQ = 5
MAX_CONCUR_REQ = 1000

class FetchError(Exception):  # <1>
    def __init__(self, country_code):
        self.country_code = country_code

@asyncio.coroutine
def get_flag(base_url, cc): # <2>
    url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
    resp = yield from aiohttp.request('GET', url)
    with contextlib.closing(resp):
        if resp.status == 200:
            image = yield from resp.read()
            return image
        elif resp.status == 404:
            raise web.HTTPNotFound()
        else:
            raise aiohttp.HttpProcessingError(
                code=resp.status, message=resp.reason,
                headers=resp.headers)

@asyncio.coroutine
def download_one(cc, base_url, semaphore, verbose):  # <3>
    try:
        with (yield from semaphore):  # <4>
            image = yield from get_flag(base_url, cc)  # <5>
    except web.HTTPNotFound:  # <6>
        status = HTTPStatus.not_found
        msg = 'not found'
    except Exception as exc:
        raise FetchError(cc) from exc  # <7>
    else:
        save_flag(image, cc.lower() + '.gif')  # <8>
        status = HTTPStatus.ok
        msg = 'OK'

    if verbose and msg:
        print(cc, msg)

    return Result(status, cc)
# END FLAGS2_ASYNCIO_TOP

# BEGIN FLAGS2_ASYNCIO_DOWNLOAD_MANY
@asyncio.coroutine
def downloader_coro(cc_list, base_url, verbose, concur_req):  # <1>
    counter = collections.Counter()
    semaphore = asyncio.Semaphore(concur_req)  # <2>
    to_do = [download_one(cc, base_url, semaphore, verbose)
             for cc in sorted(cc_list)]  # <3>

    to_do_iter = asyncio.as_completed(to_do)  # <4>
    if not verbose:
        to_do_iter = tqdm.tqdm(to_do_iter, total=len(cc_list))  # <5>
    for future in to_do_iter:  # <6>
        try:
            res = yield from future  # <7>
        except FetchError as exc:  # <8>
            country_code = exc.country_code  # <9>
            try:
                error_msg = exc.__cause__.args[0]  # <10>
            except IndexError:
                error_msg = exc.__cause__.__class__.__name__  # <11>
            if verbose and error_msg:
                msg = '*** Error for {}: {}'
                print(msg.format(country_code, error_msg))
            status = HTTPStatus.error
        else:
            status = res.status

        counter[status] += 1  # <12>

    return counter  # <13>

def download_many(cc_list, base_url, verbose, concur_req):
    loop = asyncio.get_event_loop()
    coro = downloader_coro(cc_list, base_url, verbose, concur_req)
    counts = loop.run_until_complete(coro)  # <14>
    loop.close()  # <15>

    return counts

if __name__ == '__main__':
    main(download_many, DEFAULT_CONCUR_REQ, MAX_CONCUR_REQ)
# END FLAGS2_ASYNCIO_DOWNLOAD_MANY


text:
{% load static %}

<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Cello</title>
        <link href="{% static "bower_components/bootstrap/dist/css/bootstrap.css" %}" rel="stylesheet">
        <link href="{% static "bower_components/startbootstrap-simple-sidebar/css/simple-sidebar.css" %}" rel="stylesheet">

                            Start Bootstrap

                    {% for modulo in modulos %}

{{ modulo }}

                    {% endfor %}

                        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                            Toggle navigation

                        </button>
                        Cello

Principal (current)

Clientes

Produtos

                    {% block content %}
                    {% endblock %}