text:
// Filename: IBExplicitHierarchyIntegrator.h
// Created on 12 Jul 2004 by Boyce Griffith
//
// Copyright (c) 2002-2013, Boyce Griffith
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of New York University nor the names of its
//      contributors may be used to endorse or promote products derived from
//      this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef included_IBExplicitHierarchyIntegrator
#define included_IBExplicitHierarchyIntegrator

/////////////////////////////// INCLUDES /////////////////////////////////////

#include <string>

#include "ibamr/IBHierarchyIntegrator.h"
#include "tbox/Pointer.h"

namespace IBAMR {
class IBStrategy;
class INSHierarchyIntegrator;
}  // namespace IBAMR
namespace SAMRAI {
namespace hier {
template <int DIM> class PatchHierarchy;
}  // namespace hier
namespace mesh {
template <int DIM> class GriddingAlgorithm;
}  // namespace mesh
namespace tbox {
class Database;
}  // namespace tbox
}  // namespace SAMRAI

/////////////////////////////// CLASS DEFINITION /////////////////////////////

namespace IBAMR
{
/*!
 * \brief Class IBExplicitHierarchyIntegrator is an implementation of a formally
 * second-order accurate, semi-implicit version of the immersed boundary method.
 */
class IBExplicitHierarchyIntegrator
    : public IBHierarchyIntegrator
{
public:
    /*!
     * The constructor for class IBExplicitHierarchyIntegrator sets some default
     * values, reads in configuration information from input and restart
     * databases, and registers the integrator object with the restart manager
     * when requested.
     */
    IBExplicitHierarchyIntegrator(
        const std::string& object_name,
        SAMRAI::tbox::Pointer<SAMRAI::tbox::Database> input_db,
        SAMRAI::tbox::Pointer<IBStrategy> ib_method_ops,
        SAMRAI::tbox::Pointer<INSHierarchyIntegrator> ins_hier_integrator,
        bool register_for_restart=true);

    /*!
     * The destructor for class IBExplicitHierarchyIntegrator unregisters the
     * integrator object with the restart manager when the object is so
     * registered.
     */
    ~IBExplicitHierarchyIntegrator();

    /*!
     * Prepare to advance the data from current_time to new_time.
     */
    void
    preprocessIntegrateHierarchy(
        double current_time,
        double new_time,
        int num_cycles=1);

    /*!
     * Synchronously advance each level in the hierarchy over the given time
     * increment.
     */
    void
    integrateHierarchy(
        double current_time,
        double new_time,
        int cycle_num=0);

    /*!
     * Clean up data following call(s) to integrateHierarchy().
     */
    void
    postprocessIntegrateHierarchy(
        double current_time,
        double new_time,
        bool skip_synchronize_new_state_data,
        int num_cycles=1);

    /*!
     * Initialize the variables, basic communications algorithms, solvers, and
     * other data structures used by this time integrator object.
     *
     * This method is called automatically by initializePatchHierarchy() prior
     * to the construction of the patch hierarchy.  It is also possible for
     * users to make an explicit call to initializeHierarchyIntegrator() prior
     * to calling initializePatchHierarchy().
     */
    void
    initializeHierarchyIntegrator(
        SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > hierarchy,
        SAMRAI::tbox::Pointer<SAMRAI::mesh::GriddingAlgorithm<NDIM> > gridding_alg);

protected:
    /*!
     * Write out specialized object state to the given database.
     */
    void
    putToDatabaseSpecialized(
        SAMRAI::tbox::Pointer<SAMRAI::tbox::Database> db);

private:
    /*!
     * \brief Default constructor.
     *
     * \note This constructor is not implemented and should not be used.
     */
    IBExplicitHierarchyIntegrator();

    /*!
     * \brief Copy constructor.
     *
     * \note This constructor is not implemented and should not be used.
     *
     * \param from The value to copy to this object.
     */
    IBExplicitHierarchyIntegrator(
        const IBExplicitHierarchyIntegrator& from);

    /*!
     * \brief Assignment operator.
     *
     * \note This operator is not implemented and should not be used.
     *
     * \param that The value to assign to this object.
     *
     * \return A reference to this object.
     */
    IBExplicitHierarchyIntegrator&
    operator=(
        const IBExplicitHierarchyIntegrator& that);

    /*!
     * Read object state from the restart file and initialize class data
     * members.
     */
    void
    getFromRestart();
};
}// namespace IBAMR

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

#endif //#ifndef included_IBExplicitHierarchyIntegrator


text:
import { Component, ChangeDetectionStrategy, Input, Output, EventEmitter } from '@angular/core';
import { boolFromNumberString, getPathAndParamsFromEmbedURL, buildSourceURL } from '../embed.utils';
import { queryParamsFromPropertiesMap, openLinkInNewTab } from 'cd-utils/url';
import { YOUTUBE_EMBED_URL, YOUTUBE_WATCH_URL, YouTubeParams } from './youtube.config';

@Component({
  selector: 'app-youtube-props',
  templateUrl: './youtube-props.component.html',
  styleUrls: ['./youtube-props.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class YoutubePropsComponent {
  private _src = '';
  public showControls = false;
  public autoPlay = false;
  public videoId = '';

  @Input()
  set src(value: string) {
    this._src = value;
    this.extractParamsFromSource(value);
  }
  get src(): string {
    return this._src;
  }

  @Output() srcChange = new EventEmitter<string>();

  extractParamsFromSource(value: string) {
    const [videoId, queryString] = getPathAndParamsFromEmbedURL(value, YOUTUBE_EMBED_URL);
    const params = new URLSearchParams(queryString);
    const autoplay = params.get(YouTubeParams.AutoPlay);
    const controls = params.get(YouTubeParams.Controls);
    this.autoPlay = boolFromNumberString(autoplay);
    this.showControls = boolFromNumberString(controls);
    this.videoId = videoId;
  }

  updateParams(autoplay: boolean, controls = this.showControls, videoId?: string) {
    const params = queryParamsFromPropertiesMap({
      [YouTubeParams.AutoPlay]: Number(autoplay),
      [YouTubeParams.Controls]: Number(controls),
      [YouTubeParams.JSApi]: 1,
    });
    const id = videoId ?? this.videoId;
    const src = buildSourceURL(YOUTUBE_EMBED_URL, id, params);
    this.srcChange.emit(src);
  }

  onVideoIdChange(videoId: string) {
    this.updateParams(this.autoPlay, this.showControls, videoId);
  }

  onAutoplayChange(autoplay: boolean) {
    this.updateParams(autoplay, this.showControls);
  }

  onShowControlsChange(controls: boolean) {
    this.updateParams(this.autoPlay, controls);
  }

  onOpenURL() {
    const { videoId } = this;
    if (!videoId) return;
    const url = `${YOUTUBE_WATCH_URL}${videoId}`;
    openLinkInNewTab(url);
  }
}

redpajama_set_name: RedPajamaGithub


text:
%% Read image

imPath = 'Imagens/parafuso_porca.bmp';
im = imread(imPath);

%% Histogram

% Here we resize the image since we don't need a high resolution image
% to have an idea about its pixel destribution
imResize = imresize(im,1/15);
histogram(imResize(:))
options.threshold = 170; %170 seems to be an good choice
title('Click in the figure to continue with procedure')
waitforbuttonpress

%% Detect Bolts and Nuts
detect_nut_bolt(imPath,options) % correct indentification
title('Click in the figure to continue with procedure')
waitforbuttonpress

%% Detect in another image
imPath = 'Imagens/objetos.bmp';
detect_nut_bolt(imPath,options) % correct indentification


text:
import BL from './blockList.js';
import Filter from './Filter.js';

BL.init()
  .then(() => BL.setDomainSetting(''))
  .then(() => {
    Filter.init();
  });


text:
/*! formstone v1.4.20 [cookie.js] 2021-01-29 | GPL-3.0 License | formstone.it */
/* global define */

(function(factory) {
    if (typeof define === "function" && define.amd) {
      define([
        "jquery",
        "./core"
      ], factory);
    } else {
      factory(jQuery, Formstone);
    }
  }(function($, Formstone) {

    "use strict";

    /**
     * @method private
     * @name delegate
     * @param key [string] "Cookie key"
     * @param value [string] "Cookie value"
     * @param options [object] "Options object"
     * @return [null || string] "Cookie value, if 'read'"
     */

    function delegate(key, value, options) {
      if (typeof key === "object") {

        // Set defaults

        Defaults = $.extend(Defaults, key);
      } else {

        // Delegate intent

        options = $.extend({}, Defaults, options || {});

        if (typeof key !== "undefined") {
          if (typeof value !== "undefined") {
            if (value === null) {
              eraseCookie(key, options);
            } else {
              createCookie(key, value, options);
            }
          } else {
            return readCookie(key);
          }
        }
      }

      return null;
    }

    /**
     * @method
     * @name create
     * @description Creates a cookie.
     * @param key [string] "Cookie key"
     * @param value [string] "Cookie value"
     * @param options [object] "Options object"
     * @example $.cookie(key, value, options);
     */

    function createCookie(key, value, options) {
      var expiration = false,
        date = new Date();

      // Check Expiration Date

      if (options.expires && typeof options.expires === "number") {
        date.setTime(date.getTime() + options.expires);
        expiration = date.toGMTString();
      }

      var domain = (options.domain) ? "; domain=" + options.domain : "",
        expires = (expiration) ? "; expires=" + expiration : "",
        maxAge = (expiration) ? "; max-age=" + (options.expires / 1000) : "", // to seconds
        path = (options.path) ? "; path=" + options.path : "",
        secure = (options.secure) ? "; secure" : "";

      // Set Cookie

      Document.cookie = key + "=" + value + expires + maxAge + domain + path + secure;
    }

    /**
     * @method
     * @name read
     * @description Returns a cookie's value, or null.
     * @param key [string] "Cookie key"
     * @return [string | null] "Cookie's value, or null"
     * @example var value = $.cookie(key);
     */

    function readCookie(key) {
      var keyString = key + "=",
        cookies = Document.cookie.split(';');

      // Loop Cookies

      for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];

        while (cookie.charAt(0) === ' ') {
          cookie = cookie.substring(1, cookie.length);
        }

        // Return Match

        if (cookie.indexOf(keyString) === 0) {
          return cookie.substring(keyString.length, cookie.length);
        }
      }

      return null;
    }

    /**
     * @method
     * @name erase
     * @description Deletes a cookie.
     * @param key [string] "Cookie key"
     * @example $.cookie(key, null);
     */

    function eraseCookie(key, options) {
      createCookie(key, "", $.extend({}, options, {
        expires: -604800000 // -7 days
      }));
    }

    /**
     * @plugin
     * @name Cookie
     * @description A jQuery plugin for simple access to browser cookies.
     * @type utility
     * @main cookie.js
     * @dependency jQuery
     * @dependency core.js
     */

    var Plugin = Formstone.Plugin("cookie", {
        utilities: {
          _delegate: delegate
        }
      }),

      /**
       * @options
       * @param domain [string] "Cookie domain"
       * @param expires [int] <604800000> "Time until cookie expires"
       * @param path [string] "Cookie path"
       */

      Defaults = {
        domain: null,
        expires: 604800000, // 7 days
        path: null,
        secure: null
      },

      // Localize References

      Document = Formstone.document;

  })

);


text:
package com.yammer.backups.lock;

import com.microsoft.windowsazure.services.core.storage.StorageException;
import io.dropwizard.util.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URISyntaxException;

public class DistributedLockManager {

    private static final Logger LOG = LoggerFactory.getLogger(DistributedLockManager.class);
    private static final String LOCK_KEY_TEMPLATE = "%s.lock";

    private final LockManager lockManager;
    private final Duration timeout;
    private final Duration retryDelay;

    public DistributedLockManager(LockManager lockManager, Duration timeout, Duration retryDelay) {
        this.lockManager = lockManager;
        this.timeout = timeout;
        this.retryDelay = retryDelay;
    }

    public DistributedLock lock(String id) {
        try {
            final String key = String.format(LOCK_KEY_TEMPLATE, id);
            return new DistributedLock(lockManager.getLock(key));
        }
        catch (StorageException | URISyntaxException e) {
            LOG.error("Failed to acquire lock for: " + id, e);
            throw new LockException(e);
        }
    }

    public void acquire(DistributedLock lock) {
        lock.acquire(timeout, retryDelay);
    }
}


text:
"use strict";

(function () {
    $('.vote-control .vote').click(function (e) {
        e.preventDefault();
        var voteUrl = $(this).attr('data-vote-url');
        if (voteUrl) {
            $.ajax({
                dataType: 'json',
                url: voteUrl
            }).done(function (response) {
                    if ('success' == response.result) {
                        var $voteCountElem = $('.voteCount');
                        var voteCount = parseInt($voteCountElem.text()) + 1;
                        $voteCountElem.text(voteCount);
                        alert(response.message)
                    }
                    else {
                        alert(response.errorMessage);
                    }
                }
            );
        }
    });
})();


text:
using System;
using System.Collections.Generic;
using Xamarin.Forms;

namespace WackyTrivia.Abstracts
{
    /*
     * View Factory implemented from Xamarin's TodoMvvm example - Called to create all views
     * and bind ViewModels to those views.
     * https://github.com/conceptdev/xamarin-forms-samples/blob/master/TodoMvvm/TodoMvvm/ViewFactory.cs
     */

    [AttributeUsage(AttributeTargets.Class, Inherited = false)]
    public class ViewTypeAttribute : Attribute
    {
        public Type ViewType { get; private set; }

        public ViewTypeAttribute(Type viewType)
        {
            ViewType = viewType;
        }
    }

    static class ViewFactory
    {
        static readonly Dictionary<Type, Type> TypeDictionary = new Dictionary<Type, Type>();
        public static void Register<TView, TViewModel>()
            where TView : Page
            where TViewModel : BaseViewModel
        {
            TypeDictionary[typeof(TViewModel)] = typeof(TView);
        }

        public static Page CreatePage(Type viewModelType)
        {
            Type viewType;

            if (TypeDictionary.ContainsKey(viewModelType))
            {
                viewType = TypeDictionary[viewModelType];
            }
            else
            {
                throw new InvalidOperationException("Unknown View for ViewModelType");
            }

            var page = (Page)Activator.CreateInstance(viewType);
            var viewModel = (BaseViewModel)Activator.CreateInstance(viewModelType);

            viewModel.Navigation = new ViewModelNavigation(page);
            page.BindingContext = viewModel;

            return page;
        }

        public static Page CreatePage(BaseViewModel viewModel)
        {
            Type viewType;
            if (TypeDictionary.ContainsKey(viewModel.GetType()))
            {
                viewType = TypeDictionary[viewModel.GetType()];
            }
            else
            {
                throw new InvalidOperationException("Unknown View for ViewModel object");
            }

            var page = (Page)Activator.CreateInstance(viewType);

            viewModel.Navigation = new ViewModelNavigation(page);
            page.BindingContext = viewModel;

            return page;
        }

        public static Page CreatePage<TViewModel>()
            where TViewModel : BaseViewModel
        {
            var viewModelType = typeof(TViewModel);
            return CreatePage(viewModelType);
        }
    }
}


text:
static DismissBlock _dismissBlock;
static CancelBlock _cancelBlock;

@implementation UIAlertView (Blocks)

+ (UIAlertView *)showAlertViewWithTitle:(NSString *)title
                                message:(NSString *)message
                      cancelButtonTitle:(NSString *)cancelButtonTitle
                      otherButtonTitles:(NSArray*)otherButtons
                              onDismiss:(DismissBlock)dismissed
                               onCancel:(CancelBlock)cancelled
{
    _cancelBlock  = [cancelled copy];

    _dismissBlock  = [dismissed copy];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:message
                                                   delegate:[self self]
                                          cancelButtonTitle:cancelButtonTitle
                                          otherButtonTitles:nil];

    for(NSString *buttonTitle in otherButtons)
    {
        [alert addButtonWithTitle:buttonTitle];
    }

    [alert show];
    return alert;
}

//处理UIAlertViewDelegate
+ (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == [alertView cancelButtonIndex])
    {
        _cancelBlock();
    }
    else
    {
        _dismissBlock(buttonIndex - 1); // cancel button is button 0
    }
}

@end


text:
"""
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from dataclasses import dataclass
from email.utils import formataddr
from typing import List

@dataclass(frozen=True)
class Sender:
    address: str
    name: str

    def format(self):
        """Format the sender as a string value suitable for an e-mail header."""
        realname = self.name if self.name else False
        return formataddr((realname, self.address))

@dataclass(frozen=True)
class EmailConfig:
    id: str
    sender: Sender
    contact_address: str

@dataclass(frozen=True)
class Message:
    sender: Sender
    recipients: List[str]
    subject: str
    body: str


text:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Button } from 'reactstrap';

class PrevLessonButton extends Component {
    render(){
        const { Location, block } = this.props;
        return (
            <Button color="secondary" block={block}>
                <Link to={Location} style={{color: "white"}}>Previous Lesson</Link>
            </Button>
        )
    }
}
export { PrevLessonButton };


text:
package com.wonderant.ssh;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;

public class ScpTest {

	private File expectedFile;
	private File expectedFileRemote;
	private String dirRemote;
	private SecureContext context;

	@Before
	public void Before() throws IOException {
		dirRemote = "target/testFolderRemote";
		expectedFile = new File("target/temp.tar.gz");
		expectedFileRemote = new File("target/temp2.tar.gz");
		context = new SecureContext(System.getProperty("user.name"),
				"localhost").setTrustAllHosts(true);
		FileUtils.deleteQuietly(expectedFile);
		FileUtils.deleteQuietly(expectedFileRemote);
		try {
			FileUtils.deleteDirectory(new File(dirRemote));
		} catch (IOException e) {
		}
		FileUtils.writeStringToFile(expectedFile, "mydata");
	}

	@Test
	public void testScpWithKey() throws Exception {
		String linuxPath = new File("target").getCanonicalPath()
				.replaceAll("\\\\", "/").replace("C:", "/cygdrive/c")
				.replaceAll(" ", "\\ ")
				+ "/temp2.tar.gz";

		context.setPrivateKeyFile(new File(
				"C:\\cygwin\\home\\will\\.ssh\\id_rsa"));
		Scp.exec(context, expectedFile.getPath(), linuxPath);
		assertTrue(
				"file not found: "
						+ new File("target/temp2.tar.gz").getCanonicalPath(),
				new File("target/temp2.tar.gz").exists());

	}

	@Test
	public void testScpWithBadPassword() throws Exception {
		String linuxPath = new File("target").getCanonicalPath()
				.replaceAll("\\\\", "/").replace("C:", "/cygdrive/c")
				.replaceAll(" ", "\\ ")
				+ "/temp2.tar.gz";

		context.setPassword("");
		try {
			Scp.exec(context, expectedFile.getPath(), linuxPath);
			fail("should throw error");
		} catch (Exception e) {
			// expected
		}
	}

	@Test
	public void testScpWithNeitherSet() throws Exception {
		String linuxPath = new File("target").getCanonicalPath()
				.replaceAll("\\\\", "/").replace("C:", "/cygdrive/c")
				.replaceAll(" ", "\\ ")
				+ "/temp2.tar.gz";

		try {
			Scp.exec(context, expectedFile.getPath(), linuxPath);
			fail("should throw error");
		} catch (Exception e) {
			// expected
		}
	}

	@Test
	public void testScpWithMissingKey() throws Exception {
		String linuxPath = new File("target").getCanonicalPath()
				.replaceAll("\\\\", "/").replace("C:", "/cygdrive/c")
				.replaceAll(" ", "\\ ")
				+ "/temp2.tar.gz";
		context.setPrivateKeyFile(new File("missing"));
		try {
			Scp.exec(context, expectedFile.getPath(), linuxPath);
			fail("should throw error");
		} catch (Exception e) {
			// expected
		}
	}

	@Test
	public void testScpWithBadKey() throws Exception {
		String linuxPath = new File("target").getCanonicalPath()
				.replaceAll("\\\\", "/").replace("C:", "/cygdrive/c")
				.replaceAll(" ", "\\ ")
				+ "/temp2.tar.gz";

		context.setPrivateKeyFile(expectedFile);
		try {
			Scp.exec(context, expectedFile.getPath(), linuxPath);
			fail("should throw error");
		} catch (Exception e) {
			// expected
		}
	}
}


text:
layout: post
date: 2017-03-20
title: "Watters - Wtoo Wtoo Maids Dress 813 2015 Spring Sleeveless Floor-Length Aline/Princess"
category: Watters - Wtoo
tags: [Watters - Wtoo,Wtoo,Aline/Princess ,One shoulder,Floor-Length,Sleeveless,2015,Spring]
---
### Watters - Wtoo Wtoo Maids Dress 813
Just **$179.99**
### 2015 Spring Sleeveless Floor-Length Aline/Princess

BRANDS	Wtoo

Silhouette	Aline/Princess

Neckline	One shoulder

Hemline/Train	Floor-Length

Sleeve	Sleeveless

Years	2015

Season	Spring

Buy it: [https://www.readybrides.com/en/watters-wtoo/14639-watters-dress-813.html](https://www.readybrides.com/en/watters-wtoo/14639-watters-dress-813.html)


text:
require 'spec_helper'

describe Roo::LibreOffice do
  describe '.new' do
    subject do
      Roo::LibreOffice.new('test/files/numbers1.ods')
    end

    it 'creates an instance' do
      expect(subject).to be_a(Roo::LibreOffice)
    end
  end
end


text:
package controllers

import com.codahale.metrics.json.MetricsModule
import com.codahale.metrics.{Gauge, Metric, MetricFilter}
import com.fasterxml.jackson.databind.{ObjectMapper, ObjectWriter}
import org.coursera.metrics.datadog.DatadogReporter
import org.coursera.metrics.datadog.DatadogReporter.Expansion._
import org.coursera.metrics.datadog.transport.HttpTransport
import java.io.StringWriter
import java.util.concurrent.TimeUnit
import java.util.EnumSet

import models.Metrics
import models.ZkKafka
import org.coursera.metrics.datadog.TaggedName
import org.coursera.metrics.datadog.TaggedName.TaggedNameBuilder
import play.api.Play.current
import play.api._
import play.api.mvc._

import scala.language.implicitConversions
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat

object Application extends Controller {

  val validUnits = Some(Set("NANOSECONDS", "MICROSECONDS", "MILLISECONDS", "SECONDS", "MINUTES", "HOURS", "DAYS"))
  val mapper = new ObjectMapper()

  def registryName = Play.configuration.getString("capillary.metrics.name").getOrElse("default")
  def rateUnit     = Play.configuration.getString("capillary.metrics.rateUnit", validUnits).getOrElse("SECONDS")
  def durationUnit = Play.configuration.getString("capillary.metrics.durationUnit", validUnits).getOrElse("SECONDS")
  def showSamples  = Play.configuration.getBoolean("capillary.metrics.showSamples").getOrElse(false)
  def ddAPIKey     = Play.configuration.getString("capillary.metrics.datadog.apiKey")

  val module = new MetricsModule(rateUnit, durationUnit, showSamples)
  mapper.registerModule(module)

  val topologies = ZkKafka.getTopologies

  topologies.map({ t =>
    val deltas = ZkKafka.getTopologyDeltas(t.name+"/"+t.spoutRoot, t.topic)._2
    deltas.map({ d =>
      val name = new TaggedNameBuilder().metricName("kafkaLag")
        .addTag("app", "storm")
        .addTag("topology", t.name)
        .addTag("spout", t.spoutRoot)
        .addTag("consumer", t.name+"/"+t.spoutRoot)
        .addTag("object-type", t.name.split("-").head)
        .addTag("topic", t.topic)
        .addTag("partition", d.partition.toString)
        .build()
        .encode()

      if (!Metrics.metricRegistry.getGauges.containsKey(name)) {
        Metrics.metricRegistry.register(name, new Gauge[Long]() {
          var topoRoot = s"${t.name}/${t.spoutRoot}"
          var topic = s"${t.topic}"
          var partition = d.partition

          override def getValue: Long = {
            ZkKafka.getTopologyDeltas(t.name + "/" + t.spoutRoot, t.topic)._2.filter({ p => p.partition == partition }).head.amount.get
          }
        })
      }
    })
  })

  println("apikey1: " + ddAPIKey)

  ddAPIKey.map({ apiKey =>
    println("Starting Datadog Reporter")
    Logger.info("Starting Datadog Reporter")
    val expansions = EnumSet.of(COUNT, RATE_1_MINUTE, RATE_15_MINUTE, MEDIAN, P95, P99)
    val httpTransport = new HttpTransport.Builder().withApiKey(apiKey).build()
    val reporter = DatadogReporter.forRegistry(Metrics.metricRegistry)
      .withEC2Host()
      .withTransport(httpTransport)
      .withExpansions(expansions)
      .filter(new MetricFilter {
        override def matches(name: String, metric: Metric): Boolean = !TaggedName.decode(name).getEncodedTags().isEmpty()
      })
      .build()

    reporter.start(20, TimeUnit.SECONDS)
  })

  implicit def stringToTimeUnit(s: String) : TimeUnit = TimeUnit.valueOf(s)

  def index = Action { implicit request =>

    val topos = ZkKafka.getTopologies

    Ok(views.html.index(topos))
  }

  def topo(name: String, topoRoot: String, topic: String) = Action { implicit request =>

    val totalsAndDeltas = ZkKafka.getTopologyDeltas(topoRoot, topic)
    val dateFormat  = DateTimeFormat.fullDateTime()
    val generatedAt = new DateTime().toString(dateFormat)
    Ok(views.html.topology(name, topic, totalsAndDeltas._1, totalsAndDeltas._2.toSeq, generatedAt))
  }

  def metrics = Action {
    val writer: ObjectWriter = mapper.writerWithDefaultPrettyPrinter()
    val stringWriter = new StringWriter()
    writer.writeValue(stringWriter, Metrics.metricRegistry)
    Ok(stringWriter.toString).as("application/json").withHeaders("Cache-Control" -> "must-revalidate,no-cache,no-store")
  }
}


text:
(function () {
  'use strict';

  angular.module('common')
    .controller('ProjectRequestsListController', Controller);

  /** @ngInject */
  function Controller($state, ProjectRequestService) {
    var ctrl = this;

    ctrl.reloading = false;

    ctrl.$onChanges = onChanges;
    ctrl.onView = onView;
    ctrl.reload = reload;
    ctrl.changePage = changePage;

    function onChanges(changes) {
      if (changes.query) {
        ctrl.query = angular.copy(ctrl.query);
      }
    }

    function onView(event) {
      $state.go('projects.show-request', {id: event.projectRequest.id});
    }

    function reload() {
      ctrl.reloading = true;

      ProjectRequestService.search(ctrl.query)
        .then(function (results) {
          ctrl.projectRequests = results;
        })
        .finally(function () {
          ctrl.reloading = false;
        });
    }

    function changePage(event) {
      $state.go('.', {page: event.page}, {notify: false});
      ctrl.query.page.number = event.page;
      reload();
    }
  }
})();


text:
namespace Jayrock.Json.Conversion.Converters
{
    #region Imports

    using System;
    using System.Collections.Specialized;

    #endregion

    public class NameValueCollectionImporter : ImporterBase
    {
        public NameValueCollectionImporter() :
            base(typeof(NameValueCollection)) { }

        protected override object ImportFromObject(ImportContext context, JsonReader reader)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (reader == null)
                throw new ArgumentNullException("reader");

            //
            // Reader must be sitting on an object.
            //

            if (reader.TokenClass != JsonTokenClass.Object)
                throw new JsonException("Expecting object.");

            reader.Read();

            //
            // Create the NameValueCollection object being deserialized.
            // If a hint was supplied, then that's what we will create
            // here because it could be that the caller wants to
            // return a subtype of NameValueCollection.
            //

            NameValueCollection collection = CreateCollection();

            //
            // Loop through all members of the object.
            //

            while (reader.TokenClass != JsonTokenClass.EndObject)
            {
                string name = reader.ReadMember();

                //
                // If the value is an array, then it's a multi-value
                // entry otherwise a single-value one.
                //

                if (reader.TokenClass == JsonTokenClass.Array)
                {
                    reader.Read();

                    while (reader.TokenClass != JsonTokenClass.EndArray)
                    {
                        collection.Add(name, GetValueAsString(reader));
                        reader.Read();
                    }
                }
                else
                {
                    collection.Add(name, GetValueAsString(reader));
                }

                reader.Read(); // EndArray/String
            }

            return collection;
        }

        protected virtual string GetValueAsString(JsonReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            if (reader.TokenClass == JsonTokenClass.String ||
                reader.TokenClass == JsonTokenClass.Boolean ||
                reader.TokenClass == JsonTokenClass.Number)
            {
                return reader.Text;
            }
            else if (reader.TokenClass == JsonTokenClass.Null)
            {
                return null;
            }
            else
            {
                throw new JsonException(string.Format("Cannot put a JSON {0} value in a NameValueCollection instance.", reader.TokenClass));
            }
        }

        protected virtual NameValueCollection CreateCollection()
        {
            return new NameValueCollection();
        }
    }
}


text:
package com.arkcraft.module.creature.init;

import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.RenderSnowball;
import net.minecraftforge.fml.client.registry.RenderingRegistry;

import com.arkcraft.module.creature.client.model.ModelBrontosaurus;
import com.arkcraft.module.creature.client.model.ModelDodo;
import com.arkcraft.module.creature.client.model.ModelRaptor;
import com.arkcraft.module.creature.client.model.ModelSabertooth;
import com.arkcraft.module.creature.client.render.RenderBrontosaurus;
import com.arkcraft.module.creature.client.render.RenderDodo;
import com.arkcraft.module.creature.client.render.RenderRaptor;
import com.arkcraft.module.creature.client.render.RenderSabertooth;
import com.arkcraft.module.creature.common.entity.aggressive.EntitySabertooth;
import com.arkcraft.module.creature.common.entity.neutral.EntityBrontosaurus;
import com.arkcraft.module.creature.common.entity.passive.EntityDodo;
import com.arkcraft.module.creature.common.entity.test.EntityRaptor;
import com.arkcraft.module.items.ARKCraftItems;
import com.arkcraft.module.items.common.entity.EntityDodoEgg;

public class Models
{
	public static void init()
	{
		RenderingRegistry.registerEntityRenderingHandler(EntityDodoEgg.class,
				new RenderSnowball(Minecraft.getMinecraft().getRenderManager(),
						ARKCraftItems.dodo_egg, Minecraft.getMinecraft()
								.getRenderItem()));
		RenderingRegistry.registerEntityRenderingHandler(EntityRaptor.class,
				new RenderRaptor(new ModelRaptor(), 0.5F));
		RenderingRegistry.registerEntityRenderingHandler(
				EntitySabertooth.class, new RenderSabertooth(
						new ModelSabertooth(), 0.5F));
		RenderingRegistry.registerEntityRenderingHandler(EntityDodo.class,
				new RenderDodo(new ModelDodo(), 0.3F));
		RenderingRegistry.registerEntityRenderingHandler(
				EntityBrontosaurus.class, new RenderBrontosaurus(
						new ModelBrontosaurus(), 0.5f));
	}
}


text:
using System;
using System.Text.Json;
using Azure.Core;

namespace Azure.AI.MetricsAdvisor.Models
{
    internal partial class ServicePrincipalInKVCredential : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("parameters");
            writer.WriteObjectValue(Parameters);
            writer.WritePropertyName("dataSourceCredentialType");
            writer.WriteStringValue(DataSourceCredentialType.ToString());
            writer.WritePropertyName("dataSourceCredentialName");
            writer.WriteStringValue(DataSourceCredentialName);
            if (Optional.IsDefined(DataSourceCredentialDescription))
            {
                writer.WritePropertyName("dataSourceCredentialDescription");
                writer.WriteStringValue(DataSourceCredentialDescription);
            }
            writer.WriteEndObject();
        }

        internal static ServicePrincipalInKVCredential DeserializeServicePrincipalInKVCredential(JsonElement element)
        {
            ServicePrincipalInKVParam parameters = default;
            DataSourceCredentialType dataSourceCredentialType = default;
            Optional<Guid> dataSourceCredentialId = default;
            string dataSourceCredentialName = default;
            Optional<string> dataSourceCredentialDescription = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("parameters"))
                {
                    parameters = ServicePrincipalInKVParam.DeserializeServicePrincipalInKVParam(property.Value);
                    continue;
                }
                if (property.NameEquals("dataSourceCredentialType"))
                {
                    dataSourceCredentialType = new DataSourceCredentialType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("dataSourceCredentialId"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    dataSourceCredentialId = property.Value.GetGuid();
                    continue;
                }
                if (property.NameEquals("dataSourceCredentialName"))
                {
                    dataSourceCredentialName = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("dataSourceCredentialDescription"))
                {
                    dataSourceCredentialDescription = property.Value.GetString();
                    continue;
                }
            }
            return new ServicePrincipalInKVCredential(dataSourceCredentialType, Optional.ToNullable(dataSourceCredentialId), dataSourceCredentialName, dataSourceCredentialDescription.Value, parameters);
        }
    }
}


text:
<?php

/**
 * Index
 */

// Not really used, since we have a home, single, and search page.
?>
<!-- Index -->


text:
import DetailsSection from "./DetailsSection/index";
import {connect, MapDispatchToProps, MapStateToProps} from "react-redux";
import {Cast, Crew, Genre, Studio} from "../../reducers/movies";
import {asyncRequestShowDetails, asyncRequestUsersRatingForShow} from "../../actions/shows";
import {asyncRequestMovieDetails, asyncRequestUsersRatingForMovie} from "../../actions/movies";
import {asyncFacebookLogin, asyncGoogleLogin, signOut} from "../../actions/auth";

import { map, size, assign } from "lodash";
import {
    asyncRequestMovieAnswers, asyncRequestQuestions, asyncRequestShowAnswers, nextMovieQuestion, nextShowQuestion,
    previousMovieQuestion,
    previousShowQuestion, selectAnswer, asyncSendAnswer, AnswersType, asyncSendReview
} from "../../actions/thetest";
import {push} from "react-router-redux";
import {buildExtendedId} from "../ReviewsSectionContainer";
import {Rating} from "../../reducers/ratings";
import * as jwtDecode from "jwt-decode";
import {receivedRatings} from "../../actions/ratings";

declare global {
    interface Window {
        gapi: any;
        FB: any;
    }
}

interface DetailsSectionContainerProps {
    match: {
        params: {
            type: AnswersType;
            id: number;
        }
    };
    location: {
        pathname: string;
    }
}

const isMovie = (props: DetailsSectionContainerProps) => props.match.params.type === 'movie';

const mapStateToProps: MapStateToProps<{}, DetailsSectionContainerProps, any> = (state: any, ownProps: DetailsSectionContainerProps) => {
    const id = ownProps.match.params.id;
    const source = isMovie(ownProps) ? state.movies.moviesById[id] : state.shows.showsById[id];

    // TODO replace Any to JWT interface
    const userId = state.auth.isAuthenticated ? jwtDecode<any>(state.auth.token).sub : null;

    const extendedId = buildExtendedId(isMovie(ownProps), id);
    const rating: Rating =
        state.auth.isAuthenticated && state.ratings.itemsByExtendedItemId[extendedId]
            ? state.ratings.itemsByExtendedItemId[extendedId][userId]
            : null;

    const itemDetails = source ? {
        posterImage: source.poster_image,
        backdropImage: source.backdrop_image,
        title: isMovie(ownProps) ? source.title : source.name,
        releaseDate: isMovie(ownProps) ? source.release_date : source.first_air_date,
        genres: map(source.genres,(v: Genre) => v.name),
        studios: map(isMovie(ownProps) ? source.studios : source.production_companies,(v: Studio) => v.name),
        boxOffice: isMovie(ownProps) ? source.revenue : null,
        rating: source.rating,
        ratingsCounter: source.ratings_counter,
        reviewsCounter: source.reviews_counter,
        cast: map(source.cast,(v: Cast) => ({photo: v.profile_path, fullName: v.name, id: v.credit_id})),
        crew: map(source.crew,(v: Crew) => (
                {
                    photo: v.profile_path,
                    fullName: v.name,
                    id: v.credit_id,
                    job: v.job,
                    department: v.department
                }
            )
        ),
        hasDetails: source.hasDetails,
        usersRating: rating && rating.usersRating ? rating.usersRating : source.usersRating,
        didUserLeftComment: rating ? !!rating.review : true,
        ratingObject: rating
    } : {
        posterImage: '',
        backdropImage: '',
        title: '',
        releaseDate: '',
        genres: '',
        studios: '',
        boxOffice: 0,
        rating: '',
        ratingsCounter: 0,
        reviewsCounter: 0,
        cast: [{id: 0, photo: '', fullName: ''}],
        crew: [{id: 0, photo: '', fullName: ''}],
        hasDetails: false
    };

    const sourceAnswers = isMovie(ownProps) ? state.thetest.movieAnswers[id] : state.thetest.showAnswers[id];

    const theTestParams = {
        isUserAuthenticated: state.auth.isAuthenticated,
        isAuthenticatedByGoogle: state.auth.isAuthenticatedByGoogle,
        isTestFinished: sourceAnswers && size(sourceAnswers) === size(state.thetest.questions),
        totalQuestions: size(state.thetest.questions),
        currentQuestion: state.thetest.activeQuestion,
        selectedAnswer: state.thetest.activeAnswer,
        isBackButtonDisabled: state.thetest.activeQuestion === 0,
        isNextButtonDisabled: state.thetest.activeAnswer === null,
        ...state.thetest.questions[state.thetest.activeQuestion],
    };

    return {
        ...itemDetails,
        ...theTestParams,
        isMobile: state.browser.lessThan.large,
        type: isMovie(ownProps) ? 'Movies' : 'Shows',
        id: id
    }
};

const mapDispatchToProps: MapDispatchToProps<{}, DetailsSectionContainerProps> = (dispatch, ownProps) => {
    const itemId = ownProps.match.params.id;

    const initSecured = () => {
        isMovie(ownProps)
            ? dispatch(asyncRequestMovieAnswers(itemId))
            : dispatch(asyncRequestShowAnswers(itemId));

        dispatch(asyncRequestQuestions());
    };

    return {
        init: (isUserAuthenticated: boolean, hasDetails: boolean ) => {
            dispatch(selectAnswer(null));

            if(!hasDetails) {
                isMovie(ownProps)
                    ? dispatch(asyncRequestMovieDetails(itemId))
                    : dispatch(asyncRequestShowDetails(itemId));
            }

            if (isUserAuthenticated) {
                initSecured();
            }
        },
        initFinalStep: (isUserAuthenticated: boolean) => {
            if (isUserAuthenticated) {
                isMovie(ownProps)
                    ? dispatch(asyncRequestUsersRatingForMovie(itemId))
                    : dispatch(asyncRequestUsersRatingForShow(itemId));
            }
        },
        loginFacebook: (facebookToken: string, name: string, email: string, userId: string) =>
            dispatch(asyncFacebookLogin(facebookToken, name, email, userId)).then(initSecured),
        loginGoogle: (googleToken: string, name: string) => dispatch(asyncGoogleLogin(googleToken, name)).then(initSecured),
        backButtonHandler: () => {
            isMovie(ownProps)
                ? dispatch(previousMovieQuestion(itemId))
                : dispatch(previousShowQuestion(itemId))
        },
        nextButtonHandler: (questionId: string, answer: number) => {
            isMovie(ownProps)
                ? dispatch(nextMovieQuestion(itemId))
                : dispatch(nextShowQuestion(itemId));
            dispatch(asyncSendAnswer(ownProps.match.params.type, itemId, questionId, answer));
        },
        answerHandler: (answerId: number) => dispatch(selectAnswer(answerId)),
        sendReviewAndOpenReviewsPage: (review: string, rating: Rating) => {
            const updatedRating = assign({}, rating, { review });
            dispatch(receivedRatings([updatedRating]));
            dispatch(asyncSendReview(ownProps.match.params.type, itemId, review));
            dispatch(push(`/details/${ownProps.match.params.type}/${itemId}/reviews/`));
        },
        signOutHandler: (isAuthenticatedByGoogle: boolean) => {
            if(isAuthenticatedByGoogle) {
                let auth2 = window.gapi.auth2.getAuthInstance();
                auth2.signOut().then(function () {
                    dispatch(signOut());
                });
            } else {
                window.FB.logout(function() {
                    dispatch(signOut());
                });
            }
        }
    };
};

const DetailsSectionContainer = connect(
    mapStateToProps,
    mapDispatchToProps
)(DetailsSection);

export default DetailsSectionContainer;


text:
<?php
$root = __DIR__.'/../../../';
$src = $root.'src/uVicate/';
$oauth = $root.'oauth/';

include_once $oauth.'cors.php';
include_once $oauth.'2/server.php';
include_once $src.'Member.php';
$member = new \uVicate\Member;

$method = $_SERVER['REQUEST_METHOD'];
$success = false;

$resp;
switch($method){
	case 'GET':
		if(array_key_exists($GLOBALS['auth_cookie'], $_COOKIE)){
			$id = $_COOKIE[$GLOBALS['auth_cookie']];
			$key = $_COOKIE[$GLOBALS['pass_cookie']];
			$resp = $member->verify_credentials($id, $key);
		}else{
			include_once $oauth.'2/scope_setter.php';
			$r = $server->verifyResourceRequest($request);
			$re = array('success' => $r);

			$t = $server->getAccessTokenData($request);
			if(array_key_exists('user_id', $t)){
				$re['user_id'] = $t['user_id'];
			}

			$resp = json_encode($re);
		}
		$success = true;
	break;
	case 'POST':
		$resp = $member->login($_POST['username'], $_POST['password']);
		$success = true;
	break;
	case 'DELETE':
		$member->logout();

		$t = $server->getAccessTokenData($request);
		$token = $t['0d1030265298206fb518115fea43e1873621cadc'];

		$query = $oauth_fpdo->deleteFrom('oauth_access_tokens')->where('acces_token', $token);
		$query->execute();

		$success = true;
	break;
	default:
	break;
}

if($success === false){
	header("HTTP/1.0 404 Not Found", TRUE, 404);
}

echo $resp;

?>


text:
/*global describe, it */
'use strict';

describe("home controller test", function () {
  var ctrl, scope, createController;

  beforeEach(module('ten20Angular'));

  beforeEach(inject(function ($rootScope, $controller) {

    scope = $rootScope.$new();

    createController = function() {
      return $controller('HomeCtrl', {'$scope' : scope});
    };
  }));

  it("controller init correctly", function () {
    createController();
    expect(scope.navs).toBeDefined();
    expect(scope.masterMap).toBeDefined();
    expect(scope.featuresMap.length).toBe(3);
  });

});


text:
namespace native{
namespace utils{

Void ArrayBufferView_obj::__construct(Dynamic inLengthOrBuffer,hx::Null< int >  __o_inByteOffset,Dynamic inLength)
{
HX_STACK_PUSH("ArrayBufferView::new","native/utils/ArrayBufferView.hx",23);
int inByteOffset = __o_inByteOffset.Default(0);
{
	HX_STACK_LINE(25)
	if ((::Std_obj::is(inLengthOrBuffer,hx::ClassOf< ::Int >()))){
		HX_STACK_LINE(27)
		this->byteLength = ::Std_obj::_int(inLengthOrBuffer);
		HX_STACK_LINE(28)
		this->byteOffset = (int)0;
		HX_STACK_LINE(29)
		this->buffer = ::native::utils::ByteArray_obj::__new(::Std_obj::_int(inLengthOrBuffer));
	}
	else{
		HX_STACK_LINE(33)
		this->buffer = inLengthOrBuffer;
		HX_STACK_LINE(35)
		if (((this->buffer == null()))){
			HX_STACK_LINE(36)
			hx::Throw (HX_CSTRING("Invalid input buffer"));
		}
		HX_STACK_LINE(38)
		this->byteOffset = inByteOffset;
		HX_STACK_LINE(40)
		if (((this->byteOffset > this->buffer->length))){
			HX_STACK_LINE(41)
			hx::Throw (HX_CSTRING("Invalid starting position"));
		}
		HX_STACK_LINE(43)
		if (((inLength == null()))){
			HX_STACK_LINE(43)
			this->byteLength = (this->buffer->length - inByteOffset);
		}
		else{
			HX_STACK_LINE(49)
			this->byteLength = inLength;
			HX_STACK_LINE(51)
			if ((((this->byteLength + this->byteOffset) > this->buffer->length))){
				HX_STACK_LINE(52)
				hx::Throw (HX_CSTRING("Invalid buffer length"));
			}
		}
	}
	HX_STACK_LINE(58)
	this->buffer->bigEndian = false;
	HX_STACK_LINE(61)
	this->bytes = this->buffer->b;
}
;
	return null();
}

ArrayBufferView_obj::~ArrayBufferView_obj() { }

Dynamic ArrayBufferView_obj::__CreateEmpty() { return  new ArrayBufferView_obj; }
hx::ObjectPtr< ArrayBufferView_obj > ArrayBufferView_obj::__new(Dynamic inLengthOrBuffer,hx::Null< int >  __o_inByteOffset,Dynamic inLength)
{  hx::ObjectPtr< ArrayBufferView_obj > result = new ArrayBufferView_obj();
	result->__construct(inLengthOrBuffer,__o_inByteOffset,inLength);
	return result;}

Dynamic ArrayBufferView_obj::__Create(hx::DynamicArray inArgs)
{  hx::ObjectPtr< ArrayBufferView_obj > result = new ArrayBufferView_obj();
	result->__construct(inArgs[0],inArgs[1],inArgs[2]);
	return result;}

hx::Object *ArrayBufferView_obj::__ToInterface(const type_info &inType) {
	if (inType==typeid( ::native::utils::IMemoryRange_obj)) return operator ::native::utils::IMemoryRange_obj *();
	return super::__ToInterface(inType);
}

Void ArrayBufferView_obj::setFloat32( int bytePos,Float v){
{
		HX_STACK_PUSH("ArrayBufferView::setFloat32","native/utils/ArrayBufferView.hx",89);
		HX_STACK_THIS(this);
		HX_STACK_ARG(bytePos,"bytePos");
		HX_STACK_ARG(v,"v");
		HX_STACK_LINE(89)
		::__hxcpp_memory_set_float(this->bytes,(bytePos + this->byteOffset),v);
	}
return null();
}

HX_DEFINE_DYNAMIC_FUNC2(ArrayBufferView_obj,setFloat32,(void))

Float ArrayBufferView_obj::getFloat32( int bytePos){
	HX_STACK_PUSH("ArrayBufferView::getFloat32","native/utils/ArrayBufferView.hx",73);
	HX_STACK_THIS(this);
	HX_STACK_ARG(bytePos,"bytePos");
	HX_STACK_LINE(73)
	return ::__hxcpp_memory_get_float(this->bytes,(bytePos + this->byteOffset));
}

HX_DEFINE_DYNAMIC_FUNC1(ArrayBufferView_obj,getFloat32,return )

int ArrayBufferView_obj::getLength( ){
	HX_STACK_PUSH("ArrayBufferView::getLength","native/utils/ArrayBufferView.hx",70);
	HX_STACK_THIS(this);
	HX_STACK_LINE(70)
	return this->byteLength;
}

HX_DEFINE_DYNAMIC_FUNC0(ArrayBufferView_obj,getLength,return )

int ArrayBufferView_obj::getStart( ){
	HX_STACK_PUSH("ArrayBufferView::getStart","native/utils/ArrayBufferView.hx",69);
	HX_STACK_THIS(this);
	HX_STACK_LINE(69)
	return this->byteOffset;
}

HX_DEFINE_DYNAMIC_FUNC0(ArrayBufferView_obj,getStart,return )

::native::utils::ByteArray ArrayBufferView_obj::getByteBuffer( ){
	HX_STACK_PUSH("ArrayBufferView::getByteBuffer","native/utils/ArrayBufferView.hx",68);
	HX_STACK_THIS(this);
	HX_STACK_LINE(68)
	return this->buffer;
}

HX_DEFINE_DYNAMIC_FUNC0(ArrayBufferView_obj,getByteBuffer,return )

::String ArrayBufferView_obj::invalidDataIndex;

ArrayBufferView_obj::ArrayBufferView_obj()
{
}

void ArrayBufferView_obj::__Mark(HX_MARK_PARAMS)
{
	HX_MARK_BEGIN_CLASS(ArrayBufferView);
	HX_MARK_MEMBER_NAME(bytes,"bytes");
	HX_MARK_MEMBER_NAME(byteLength,"byteLength");
	HX_MARK_MEMBER_NAME(byteOffset,"byteOffset");
	HX_MARK_MEMBER_NAME(buffer,"buffer");
	HX_MARK_END_CLASS();
}

void ArrayBufferView_obj::__Visit(HX_VISIT_PARAMS)
{
	HX_VISIT_MEMBER_NAME(bytes,"bytes");
	HX_VISIT_MEMBER_NAME(byteLength,"byteLength");
	HX_VISIT_MEMBER_NAME(byteOffset,"byteOffset");
	HX_VISIT_MEMBER_NAME(buffer,"buffer");
}

Dynamic ArrayBufferView_obj::__Field(const ::String &inName,bool inCallProp)
{
	switch(inName.length) {
	case 5:
		if (HX_FIELD_EQ(inName,"bytes") ) { return bytes; }
		break;
	case 6:
		if (HX_FIELD_EQ(inName,"buffer") ) { return buffer; }
		break;
	case 8:
		if (HX_FIELD_EQ(inName,"getStart") ) { return getStart_dyn(); }
		break;
	case 9:
		if (HX_FIELD_EQ(inName,"getLength") ) { return getLength_dyn(); }
		break;
	case 10:
		if (HX_FIELD_EQ(inName,"setFloat32") ) { return setFloat32_dyn(); }
		if (HX_FIELD_EQ(inName,"getFloat32") ) { return getFloat32_dyn(); }
		if (HX_FIELD_EQ(inName,"byteLength") ) { return byteLength; }
		if (HX_FIELD_EQ(inName,"byteOffset") ) { return byteOffset; }
		break;
	case 13:
		if (HX_FIELD_EQ(inName,"getByteBuffer") ) { return getByteBuffer_dyn(); }
		break;
	case 16:
		if (HX_FIELD_EQ(inName,"invalidDataIndex") ) { return invalidDataIndex; }
	}
	return super::__Field(inName,inCallProp);
}

Dynamic ArrayBufferView_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp)
{
	switch(inName.length) {
	case 5:
		if (HX_FIELD_EQ(inName,"bytes") ) { bytes=inValue.Cast< Array< unsigned char > >(); return inValue; }
		break;
	case 6:
		if (HX_FIELD_EQ(inName,"buffer") ) { buffer=inValue.Cast< ::native::utils::ByteArray >(); return inValue; }
		break;
	case 10:
		if (HX_FIELD_EQ(inName,"byteLength") ) { byteLength=inValue.Cast< int >(); return inValue; }
		if (HX_FIELD_EQ(inName,"byteOffset") ) { byteOffset=inValue.Cast< int >(); return inValue; }
		break;
	case 16:
		if (HX_FIELD_EQ(inName,"invalidDataIndex") ) { invalidDataIndex=inValue.Cast< ::String >(); return inValue; }
	}
	return super::__SetField(inName,inValue,inCallProp);
}

void ArrayBufferView_obj::__GetFields(Array< ::String> &outFields)
{
	outFields->push(HX_CSTRING("bytes"));
	outFields->push(HX_CSTRING("byteLength"));
	outFields->push(HX_CSTRING("byteOffset"));
	outFields->push(HX_CSTRING("buffer"));
	super::__GetFields(outFields);
};

static ::String sStaticFields[] = {
	HX_CSTRING("invalidDataIndex"),
	String(null()) };

static ::String sMemberFields[] = {
	HX_CSTRING("setFloat32"),
	HX_CSTRING("getFloat32"),
	HX_CSTRING("getLength"),
	HX_CSTRING("getStart"),
	HX_CSTRING("getByteBuffer"),
	HX_CSTRING("bytes"),
	HX_CSTRING("byteLength"),
	HX_CSTRING("byteOffset"),
	HX_CSTRING("buffer"),
	String(null()) };

static void sMarkStatics(HX_MARK_PARAMS) {
	HX_MARK_MEMBER_NAME(ArrayBufferView_obj::__mClass,"__mClass");
	HX_MARK_MEMBER_NAME(ArrayBufferView_obj::invalidDataIndex,"invalidDataIndex");
};

static void sVisitStatics(HX_VISIT_PARAMS) {
	HX_VISIT_MEMBER_NAME(ArrayBufferView_obj::__mClass,"__mClass");
	HX_VISIT_MEMBER_NAME(ArrayBufferView_obj::invalidDataIndex,"invalidDataIndex");
};

Class ArrayBufferView_obj::__mClass;

void ArrayBufferView_obj::__register()
{
	Static(__mClass) = hx::RegisterClass(HX_CSTRING("native.utils.ArrayBufferView"), hx::TCanCast< ArrayBufferView_obj> ,sStaticFields,sMemberFields,
	&__CreateEmpty, &__Create,
	&super::__SGetClass(), 0, sMarkStatics, sVisitStatics);
}

void ArrayBufferView_obj::__boot()
{
	invalidDataIndex= HX_CSTRING("Invalid data index");
}

} // end namespace native
} // end namespace utils


text:
layout: post
title: Hello World!
author: myers
date: 2016-08-23
excerpt_separator: <!--more-->
---

>
> **Alexa, what is bespoken.tools?**
>

>
> *Bespoken.tools is a set of open source tools built specifically for Alexa Skills Kit development.*
>
<!--more-->
<br/>

Hello!

We are the [developers at XAPPmedia](http://developer.xappmedia.com), the team behind bespoken.tools.  For the past couple of years, we have been building out voice interactive audio services for mobile devices.  With the introduction of the Amazon Echo and the underlying Alexa Skills Kit platform, we are excited about applying our years of expertise and experience to this new era of voice first devices.

We are happy to introduce bespoken.tools (**bst** for short), a set of open source tools built specifically for Alexa Skills Kit development.  The goal of **bst** is to help you develop skills not just faster but also better.

We will be releasing our first tool this week and another shortly thereafter. Subscribe to the mailing list so you are notified when the new tools come out. We won't send you superfluous emails, just messages when new tools, features or examples are made available.

**Stay updated, get this blog sent directly to your inbox.**

{% include subscribe.html %}


text:
"""
ref: http://www.programmerinterview.com/index.php/general-miscellaneous/find-continuous-sequence-with-largest-sum/
"""


text:
'use strict';

/**
 * @ngdoc function
 * @name app.controller:AppCtrl
 * @description
 * # MainCtrl
 * Controller of the app
 */
angular.module('app')
  .controller('AppCtrl', ['$scope', '$translate', '$localStorage', '$window', '$document', '$location', '$rootScope', '$timeout', '$mdSidenav', '$mdColorPalette',
    function (             $scope,   $translate,   $localStorage,   $window,   $document,   $location,   $rootScope,   $timeout,   $mdSidenav,   $mdColorPalette ) {
      // add 'ie' classes to html
      var isIE = !!navigator.userAgent.match(/MSIE/i) || !!navigator.userAgent.match(/Trident.*rv:11\./);
      isIE && angular.element($window.document.body).addClass('ie');
      isSmartDevice( $window ) && angular.element($window.document.body).addClass('smart');
      // config
      $scope.app = {
        name: 'Materil',
        version: '1.0.1',
        // for chart colors
        color: {
          primary: '#3f51b5',
          info:    '#2196f3',
          success: '#4caf50',
          warning: '#ffc107',
          danger:  '#f44336',
          accent:  '#7e57c2',
          white:   '#ffffff',
          light:   '#f1f2f3',
          dark:    '#475069'
        },
        setting: {
          theme: {
            primary: 'indigo',
            accent: 'purple',
            warn: 'amber'
          },
          asideFolded: false
        },
        search: {
          content: '',
          show: false
        }
      }

      $scope.setTheme = function(theme){
        $scope.app.setting.theme = theme;
      }

      // save settings to local storage
      if ( angular.isDefined($localStorage.appSetting) ) {
        $scope.app.setting = $localStorage.appSetting;
      } else {
        $localStorage.appSetting = $scope.app.setting;
      }
      $scope.$watch('app.setting', function(){
        $localStorage.appSetting = $scope.app.setting;
      }, true);

      // angular translate
      $scope.langs = {en:'English', zh_CN:'中文'};
      $scope.selectLang = $scope.langs[$translate.proposedLanguage()] || "English";
      $scope.setLang = function(langKey) {
        // set the current lang
        $scope.selectLang = $scope.langs[langKey];
        // You can change the language during runtime
        $translate.use(langKey);
      };

      function isSmartDevice( $window ) {
        // Adapted from http://www.detectmobilebrowsers.com
        var ua = $window['navigator']['userAgent'] || $window['navigator']['vendor'] || $window['opera'];
        // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
        return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
      };

      $scope.getColor = function(color, hue){
        if(color == "bg-dark" || color == "bg-white") return $scope.app.color[ color.substr(3, color.length) ];
        return rgb2hex($mdColorPalette[color][hue]['value']);
      }

      //Function to convert hex format to a rgb color
      function rgb2hex(rgb) {
        return "#" + hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
      }

      function hex(x) {
        var hexDigits = new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
        return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
      }

      $rootScope.$on('$stateChangeSuccess', openPage);

      function openPage() {
        $scope.app.search.content = '';
        $scope.app.search.show = false;
        $scope.closeAside();
      }

      $scope.goBack = function () {
        $window.history.back();
      }

      $scope.openAside = function () {
        $timeout(function() { $mdSidenav('aside').open(); });
      }
      $scope.closeAside = function () {
        $timeout(function() { $document.find('#aside').length && $mdSidenav('aside').close(); });
      }

    }
  ]);