text:
.class public final Lcom/helloworld/R$menu;
.super Ljava/lang/Object;
.source "R.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/helloworld/R;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "menu"
.end annotation

# static fields
.field public static final main:I = 0x7f070000

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 32
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
module Analytical
  module Google
    class Api
      include Analytical::Base::Api

      def initialize(parent, options={})
        super
        @tracking_command_location = :body_prepend
      end

      def init_javascript(location)
        init_location(location) do
          js = <<-HTML
          <!-- Analytical Init: Google -->
          <script type="text/javascript">
            var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
            document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
          </script>
          <script type="text/javascript">
            var googleAnalyticsTracker = _gat._getTracker("#{options[:key]}");
            googleAnalyticsTracker._initData();
            googleAnalyticsTracker._trackPageview();
          </script>
          HTML
          js
        end
      end

      def track(*args)
        "googleAnalyticsTracker._trackPageview(\"#{args.first}\");"
      end

    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
//----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------

/*
 * Created on Jun 29, 2014
 */
package org.griphyn.vdl.karajan.monitor.monitors.http;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.globus.cog.abstraction.interfaces.JobSpecification;
import org.globus.cog.abstraction.interfaces.Task;
import org.globus.cog.util.json.JSONEncoder;
import org.griphyn.vdl.karajan.monitor.SystemState;
import org.griphyn.vdl.karajan.monitor.items.ApplicationItem;
import org.griphyn.vdl.karajan.monitor.items.ApplicationState;
import org.griphyn.vdl.karajan.monitor.items.TaskItem;
import org.griphyn.vdl.karajan.monitor.monitors.http.BrowserDataBuilder.AppEntry;
import org.griphyn.vdl.karajan.monitor.monitors.http.BrowserDataBuilder.TimedValue;

public class AppInstanceBuilder {

    private BrowserDataBuilder db;
    private String id;
    private Map<String, AppEntry> entries;
    private SystemState state;

    public AppInstanceBuilder(BrowserDataBuilder db, String id) {
        this.db = db;
        this.id = id;
        this.entries = db.getEntries();
        this.state = db.getState();
    }

    public void getData(JSONEncoder e) throws IOException {
        AppEntry ae = entries.get(id);
        if (ae == null) {
            throw new IllegalArgumentException("Unknown application ID: " + id);
        }

        ApplicationItem app = ae.item;

        e.beginMap();
        e.writeMapItem("id", id);
        e.writeMapItem("name", app.getName());
        e.writeMapItem("args", app.getArguments());
        e.writeMapItem("host", app.getHost());
        e.writeMapItem("crtState", app.getState().ordinal());
        e.writeMapItem("totalTime", getTotalTime(ae.stateTimeline));
        e.writeMapItem("runTime", getRunTime(ae.stateTimeline));
        e.writeMapItem("timeline", db.getStateTimes(app));

        if (app.getWorkerId() != null) {
            e.writeMapItem("workerid", app.getWorkerId());
        }

        TaskItem et = null;

        if (ae.tasks != null) {
            for (TaskItem it : ae.tasks) {
                if (it.getType() == Task.JOB_SUBMISSION) {
                    et = it;
                }
            }
        }

        if (et != null) {
            Task t = et.getTask();
            JobSpecification spec = (JobSpecification) t.getSpecification();
            List<String> args = spec.getArgumentsAsList();
            extractJobInfo(e, args);
            e.writeMapItem("directory", spec.getDirectory());
        }
        e.endMap();
    }

    private int getTotalTime(List<TimedValue<ApplicationState>> tl) {
        if (tl == null || tl.isEmpty()) {
            return 0;
        }
        TimedValue<ApplicationState> lastState = tl.get(tl.size() - 1);
        return (int) (lastState.time - tl.get(0).time);
    }

    private int getRunTime(List<TimedValue<ApplicationState>> tl) {
        if (tl == null || tl.isEmpty()) {
            return 0;
        }
        TimedValue<ApplicationState> lastState = tl.get(tl.size() - 1);
        long lastTime = lastState.time;
        if (!lastState.value.isTerminal()) {
            lastTime = state.getCurrentTime();
        }
        TimedValue<ApplicationState> lastStageIn = null;
        for (TimedValue<ApplicationState> p : tl) {
            if (p.value == ApplicationState.STAGE_IN) {
                lastStageIn = p;
            }
        }
        if (lastStageIn != null) {
            return (int) (lastTime - lastStageIn.time);
        }
        else {
            return 0;
        }
    }

    private void extractJobInfo(JSONEncoder e, List<String> args) throws IOException {
        String key = null;
        List<String> l = new ArrayList<String>();
        for (String arg : args) {
            if (arg.startsWith("-")) {
                if (key != null) {
                    writeJobInfoItem(e, key, l);
                }
                key = arg;
                l.clear();
            }
            else {
                if ("-of".equals(key) || "-if".equals(key)) {
                    l.add(arg.replace("|", ", "));
                }
                else {
                    l.add(arg);
                }
            }
        }
    }

    private void writeJobInfoItem(JSONEncoder e, String key, List<String> l) throws IOException {
        if (l.size() == 0) {
            return;
        }
        if (key.equals("-e")) {
            e.writeMapItem("executable", l.get(0));
        }
        else if (key.equals("-out")) {
            e.writeMapItem("stdout", l.get(0));
        }
        else if (key.equals("-err")) {
            e.writeMapItem("stderr", l.get(0));
        }
        else if (key.equals("-i")) {
            e.writeMapItem("stdin", l.get(0));
        }
        else if (key.equals("-if")) {
            e.writeMapItem("stagein", l);
        }
        else if (key.equals("-of")) {
            e.writeMapItem("stageout", l);
        }
        else if (key.equals("-a")) {
            e.writeMapItem("args", l);
        }
    }

}


text:
define({
  "_widgetLabel": "Filter",
  "toggleTip": "Klicka om du vill visa/dölja filterinställningar"
});


text:
package org.elastic.rest.scala.driver.utils

import utest._
import org.elastic.rest.scala.driver.RestBaseImplicits.CustomTypedToString
import org.elastic.rest.scala.driver.utils.NoJsonHelpers.{SimpleObjectDescription => obj}
import org.elastic.rest.scala.driver.utils.NoJsonHelpers.SimpleObjectDescription
import org.elastic.rest.scala.driver.utils.NoJsonHelpers.SimpleObjectDescription._
import io.circe.parser.parse
import org.elastic.rest.scala.driver.RestBase.ToStringAnyVal

import scala.util.Try

case class ValueClassTest(value: String) extends AnyVal with ToStringAnyVal[String]

object SimpleObjectDescriptionTests extends TestSuite {
  val tests = this {
    "Basic mock functionality - handled" - {

      /** (Package declaration == "obj")
        * `KeyValue` with no `extras`, `FieldValue`, `Constant`, `MultiTypeField` with cardinality == 0 */
      case class Test
        (field1: Either[String, Boolean], `termName`: ValueClassTest, termValue: List[Int], valOrVals: List[String],
         kvMap: Map[String, Option[String]], optionStr: Option[String])
        extends CustomTypedToString
      {
        @SimpleObjectDescription("obj",
          obj.SimpleObject("insert_here") (
            obj.Field("field1"),
            obj.Constant("const", true),
            obj.KeyValue("`termName`")(
              obj.SimpleObject(
                obj.Field("termValue"),
                obj.MultiTypeField("valOrVals")
              )
            ),
            obj.KeyValue("termName", "raw.")(obj.FieldValue("termValue")),
            obj.KeyValue("termName", "extras.")("termValue", obj.Field("optionStr"))
          ),
          obj.KeyValues("kvMap", "a.")()
        )
        override def fromTyped: String = AutoGenerated
      }
      val test1 = Test(
        field1 = Left("test"), `termName` = ValueClassTest("myTermName"), termValue = List(1, 2, 3), valOrVals = List(),
       kvMap = Map("x" -> None, "y" -> Some("yV"), "z" -> None, "t" -> Some("tV")), optionStr = None
      )

      parse(test1.fromTyped) ==> parse(
        """{ "insert_here": {
              "field1": "test",
              "const": true,
              "myTermName": {
                "termValue": [ 1, 2, 3 ]
              },
              "raw.myTermName": [ 1, 2, 3 ],
              "extras.myTermName": [ 1, 2, 3 ]
          },
          "a.y": "yV",
          "a.t": "tV"
        }""".stripMargin)

      case class Injected(b: Boolean, d: Double) extends CustomTypedToString {
        @SimpleObjectDescription("obj",
          obj.Field("d"),
          obj.Field("b")
        )
        override def fromTyped: String = AutoGenerated
      }

      /** (No package declaration),
        * Optional `Fields`, `KeyValue` with `extras`, `MultiTypeField` with cardinality == 1 and >1 */
      case class Test2
        (field1: Either[String, Boolean],
         maybeField2: Option[String], maybeField3: Option[String],
         termName: String, termValue: List[Int], valOrVals: List[String],
         `multiVals`: List[Injected], emptyMap: Map[String, String]
        )
        extends CustomTypedToString
      {
        @SimpleObjectDescription("",
          SimpleObject("insert_here") (
            Field("field1", "test.prefix."),
            Field("maybeField2"),
            Field("maybeField3"),
            Field("emptyMap", "empty-"),
            MultiTypeField("emptyMap"),
            KeyValue("termName")(
              SimpleObject(
                Field("termValue"),
                MultiTypeField("valOrVals", arrayIfSingleton = false)
              ),
              "value", MultiTypeField("`multiVals`", arrayIfSingleton = false, "prefix.test.")
            ),
            KeyValue("termName", "constant.")(ConstantValue("constValue"))
          )
        )
        override def fromTyped: String = AutoGenerated
      }

      val test2 = Test2(Right(false),
        None, Some("test"),
        "myTermName", List(1, 2, 3), List("a"),
        List(Injected(b = true, d = 0.0), Injected(b = false, d = 1.0)),
        emptyMap = Map()
      )

      parse(test2.fromTyped) ==> parse(
        """{ "insert_here": {
            "test.prefix.field1": false,
            "maybeField3": "test",
            "empty-emptyMap": {},
            "myTermName": {
              "value": {
                "termValue": [ 1, 2, 3 ],
                "valOrVals": "a"
              },
              "prefix.test.multiVals": [ { "d": 0.0, "b": true }, { "d": 1.0, "b": false } ]
            },
            "constant.myTermName": "constValue"
          }
        }""".stripMargin)

      /** Tests an unpleasant case where the macro/runtime logic breaks down */
      case class Test3(o1: Option[String], o2: Option[String], o3: Option[String], o4: Option[String])
        extends CustomTypedToString
      {
        @SimpleObjectDescription("",
          Field("o1"), Field("o2"), Field("o3"), Field("o4")
        )
        override def fromTyped: String = AutoGenerated
      }
      val test3_1 = Test3(None, Some("b"), Some("c"), None)
      parse(test3_1.fromTyped) ==> parse("""{"o2": "b", "o3":"c"}""")

      /** This case is similar to `Test3` ... except the underlying logic works OK so
        * it's just here for illustration
        */
      case class Test4(key: String, value: String,
                       o1: Option[String], o2: Option[String], o3: Option[String], o4: Option[String])
        extends CustomTypedToString
      {
        @SimpleObjectDescription("",
          KeyValue("key")("value", Field("o1"), Field("o2"), Field("o3"), Field("o4"))
        )
        override def fromTyped: String = AutoGenerated
      }
      val test4_1 = Test4("mykey", "myval", None, Some("b"), Some("c"), None)

      parse(test4_1.fromTyped) ==> parse(
        """{ "mykey":
          |{"value": "myval", "o2": "b", "o3":"c"} }
          |""".stripMargin)

    }
    "Coverage for val2str" - {

      /** Can't embed arbitrary case classes because we don't have a built-in JSON deser */
      case class WontWork()

      compileError("""
        case class NotSupportedExtras(kvs: Map[String, String]) extends CustomTypedToString {
          @SimpleObjectDescription("",
            KeyValues("kvs")("injectKey", obj.Constant("const", true))
          )
          override def fromTyped: String = AutoGenerated
      }""")

      // Check a couple of error cases
      Try { any2Str("a", "", WontWork(), isFirst = true) }.isFailure ==> true
      Try { any2Str(WontWork()) }.isFailure ==> true

      // Check the number combos:
      any2Str("a", "", 1.1.toFloat, isFirst = true).trim().replaceAll("1[.]1[0-9]+", "1.1") ==> """ "a":  1.1 """.trim()
      any2Str("a", "", 1.1, isFirst = true).trim().replaceAll("1[.]1[0-9]+", "1.1") ==> """ "a":  1.1 """.trim()
      any2Str("a", "", 1.toLong, isFirst = true).trim() ==> """ "a":  1 """.trim()
      any2Str("a", "", 1, isFirst = true).trim() ==> """ "a":  1 """.trim()

      // Internal map
      parse(s"""{ ${any2Str("a", "", Map("k" -> "v", "b" -> true), isFirst = true)} }""") ==>
        parse("""{ "a": { "k": "v", "b": true } }""")

      //(everything else is tested above)
    }
  }
}


text:
package net.foreworld.rvt.controller;

import java.util.Date;

import javax.servlet.http.HttpSession;

import net.foreworld.rvt.service.TaskTakeService;
import net.foreworld.util.DateUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DefaultController {

	@Autowired
	public TaskTakeService taskTakeService;

	@RequestMapping(value = { "/" }, method = RequestMethod.GET)
	public ModelAndView indexUI(HttpSession session) {
		Object obj = session.getAttribute("session.user");
		if (null == obj) {
			return new ModelAndView("redirect:/login");
		} // END
		ModelAndView result = new ModelAndView("default/1.0.2/index");
		// TODO
		result.addObject("data_session_user", obj);
		result.addObject("data_session_time",
				session.getAttribute("session.time"));
		return result;
	}

	@RequestMapping(value = { "/welcome" }, method = RequestMethod.GET)
	public ModelAndView welcomeUI(HttpSession session,
			@RequestParam(required = false) String create_time) {
		ModelAndView result = new ModelAndView("default/1.0.2/welcome");

		Date date = DateUtil.checkDateFormat("yyyy-MM", create_time);
		if (null == date)
			date = new Date();

		result.addObject("data_current_time", new Date());
		result.addObject("data_create_time", date);

		result.addObject("data_tasktakes", taskTakeService.findByUserId(session
				.getAttribute("session.user.id").toString(), date));

		return result;
	}
}


text:
use core::default; //~ ERROR unresolved import `core`

fn main() {
    let _: u8 = ::core::default::Default(); //~ ERROR failed to resolve
}


text:
<?php

namespace Sparkson\DataExporterBundle\Exporter\OutputAdapter;

use Sparkson\DataExporterBundle\Exporter\Column\Column;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Abstract flattened output adapter.
 *
 * The output column (and the exported record) can be nested. To simplify the
 * job of output adapters, this class flattens the nested properties into
 * a two dimensional array. Adapters extending from this class only needs to
 * implement the writeHeaderRow() and writeRecordRow() methods.
 *
 * @author Tamcy <tamcyhk@outlook.com>
 */
abstract class BaseFlattenAdapter extends AbstractAdapter
{
    private $waitForFirstRecord = true;

    private $flatColumns = array();

    /**
     * {@inheritdoc}
     */
    public function begin()
    {
        $this->waitForFirstRecord = true;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'header' => true,
        ));
    }

    protected function getColumnName(Column $column, array $prefixes)
    {
        if (!$prefixes) {
            return $column->getName();
        }

        return implode('.', $prefixes) . '.' . $column->getName();
    }

    protected function flattenColumns(array $columns, array $prefixes = [])
    {
        /** @var Column $column */
        foreach ($columns as $column) {
            if ($column->hasChildren()) {
                $prefixes[] = $column->getName();
                $this->flattenColumns($column->getBuiltColumns(), $prefixes);
            } else {
                $this->flatColumns[$this->getColumnName($column, $prefixes)] = $column;
            }
        }
    }

    protected function initializeHeader(array $columns)
    {
        $this->flattenColumns($columns);

        if ($this->options['header']) {
            $this->writeHeaderRow($this->flatColumns);
        }
    }

    protected function flattenRecord(&$result, $record, array $columns, array $prefixes = [])
    {
        /** @var Column $column */
        foreach ($columns as $column) {
            if ($column->hasChildren()) {
                $prefixes[] = $column->getName();
                $this->flattenRecord($result, $record[$column->getName()], $column->getBuiltColumns(), $prefixes);
            } else {
                $key = $this->getColumnName($column, $prefixes);
                $result[$key] = $record[$column->getName()];
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function writeRecord(array $columns, array $record)
    {
        if ($this->waitForFirstRecord) {
            $this->initializeHeader($columns);
            $this->waitForFirstRecord = false;
        }

        $this->flattenRecord($result, $record, $columns);
        $this->writeRecordRow($this->flatColumns, $result);
    }

    /**
     * Writes the header row.
     *
     * This method will be called before the first record is written when `header` is
     * set to true in options.
     *
     * @param Column[] $columns
     */
    abstract protected function writeHeaderRow(array $columns);

    /**
     * Writes the record row.
     *
     * This method will be called on each record.
     * $columnLabels is a sorted associative array with key equals to a unique column name and
     * value equals to header label.
     * $record is an associative array with key equals to a unique column name.
     *
     * @param Column[] $columns The column
     * @param array    $record The record
     */
    abstract protected function writeRecordRow(array $columns, array $record);

}


text:
#include "aeongames/ProtoBufClasses.h"
#include "OpenGLFrameBuffer.h"

namespace AeonGames
{
    OpenGLFrameBuffer::OpenGLFrameBuffer() = default;
    OpenGLFrameBuffer::~OpenGLFrameBuffer()
    {
        Finalize();
    }

    void OpenGLFrameBuffer::Initialize()
    {
        // Frame Buffer
        glGenFramebuffers ( 1, &mFBO );
        OPENGL_CHECK_ERROR_THROW;
        glBindFramebuffer ( GL_FRAMEBUFFER, mFBO );
        OPENGL_CHECK_ERROR_THROW;

        // Color Buffer
        glGenTextures ( 1, &mColorBuffer );
        OPENGL_CHECK_ERROR_THROW;
        glBindTexture ( GL_TEXTURE_2D, mColorBuffer );
        OPENGL_CHECK_ERROR_THROW;
        glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, 800, 600, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr );
        OPENGL_CHECK_ERROR_THROW;
        glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
        OPENGL_CHECK_ERROR_THROW;
        glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
        OPENGL_CHECK_ERROR_THROW;
        glBindTexture ( GL_TEXTURE_2D, 0 );
        OPENGL_CHECK_ERROR_THROW;

        glFramebufferTexture2D ( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mColorBuffer, 0 );
        OPENGL_CHECK_ERROR_THROW;
        // Render Buffer
        glGenRenderbuffers ( 1, &mRBO );
        OPENGL_CHECK_ERROR_THROW;
        glBindRenderbuffer ( GL_RENDERBUFFER, mRBO );
        OPENGL_CHECK_ERROR_THROW;
        glRenderbufferStorage ( GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 800, 600 );
        OPENGL_CHECK_ERROR_THROW;
        glBindRenderbuffer ( GL_RENDERBUFFER, 0 );
        OPENGL_CHECK_ERROR_THROW;

        glFramebufferRenderbuffer ( GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mRBO );
        OPENGL_CHECK_ERROR_THROW;
        if ( glCheckFramebufferStatus ( GL_FRAMEBUFFER ) != GL_FRAMEBUFFER_COMPLETE )
        {
            throw std::runtime_error ( "Incomplete Framebuffer." );
        }
        OPENGL_CHECK_ERROR_THROW;

        glBindFramebuffer ( GL_FRAMEBUFFER, 0 );
        OPENGL_CHECK_ERROR_THROW;
    }

    void OpenGLFrameBuffer::Finalize()
    {
        if ( glIsRenderbuffer ( mRBO ) )
        {
            OPENGL_CHECK_ERROR_NO_THROW;
            glDeleteRenderbuffers ( 1, &mRBO );
            OPENGL_CHECK_ERROR_NO_THROW;
            mRBO = 0;
        }
        if ( glIsTexture ( mColorBuffer ) )
        {
            OPENGL_CHECK_ERROR_NO_THROW;
            glDeleteTextures ( 1, &mColorBuffer );
            OPENGL_CHECK_ERROR_NO_THROW;
            mColorBuffer = 0;
        }
        if ( glIsFramebuffer ( mFBO ) )
        {
            OPENGL_CHECK_ERROR_NO_THROW;
            glDeleteFramebuffers ( 1, &mFBO );
            OPENGL_CHECK_ERROR_NO_THROW;
            mFBO = 0;
        }
        OPENGL_CHECK_ERROR_NO_THROW;
    }

    void OpenGLFrameBuffer::Resize ( uint32_t aWidth, uint32_t aHeight )
    {
        glBindTexture ( GL_TEXTURE_2D, mColorBuffer );
        glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, aWidth, aHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr );
        glBindRenderbuffer ( GL_RENDERBUFFER, mRBO );
        glRenderbufferStorage ( GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, aWidth, aHeight );
        glBindRenderbuffer ( GL_RENDERBUFFER, 0 );
    }
    void OpenGLFrameBuffer::Bind()
    {
        glBindFramebuffer ( GL_FRAMEBUFFER, mFBO );
        OPENGL_CHECK_ERROR_NO_THROW;
    }
    void OpenGLFrameBuffer::Unbind()
    {
        glBindFramebuffer ( GL_FRAMEBUFFER, 0 );
        OPENGL_CHECK_ERROR_NO_THROW;
    }
    GLuint OpenGLFrameBuffer::GetFBO() const
    {
        return mFBO;
    }

    OpenGLFrameBuffer::OpenGLFrameBuffer ( OpenGLFrameBuffer&& aOpenGLFrameBuffer )
    {
        std::swap ( mFBO, aOpenGLFrameBuffer.mFBO );
        std::swap ( mColorBuffer, aOpenGLFrameBuffer.mColorBuffer );
        std::swap ( mRBO, aOpenGLFrameBuffer.mRBO );
    }
}


text:
package armaddons_test

import (
	"context"
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/addons/armaddons"
)

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/addons/resource-manager/Microsoft.Addons/preview/2018-03-01/examples/SupportPlanTypes_Get.json
func ExampleSupportPlanTypesClient_Get() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armaddons.NewSupportPlanTypesClient("d18d258f-bdba-4de1-8b51-e79d6c181d5e", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	res, err := client.Get(ctx,
		"Canonical",
		armaddons.PlanTypeNameStandard,
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	// TODO: use response item
	_ = res
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/addons/resource-manager/Microsoft.Addons/preview/2018-03-01/examples/SupportPlanTypes_CreateOrUpdate.json
func ExampleSupportPlanTypesClient_BeginCreateOrUpdate() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armaddons.NewSupportPlanTypesClient("d18d258f-bdba-4de1-8b51-e79d6c181d5e", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	poller, err := client.BeginCreateOrUpdate(ctx,
		"Canonical",
		armaddons.PlanTypeNameStandard,
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	res, err := poller.PollUntilDone(ctx, nil)
	if err != nil {
		log.Fatalf("failed to pull the result: %v", err)
	}
	// TODO: use response item
	_ = res
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/addons/resource-manager/Microsoft.Addons/preview/2018-03-01/examples/SupportPlanTypes_Delete.json
func ExampleSupportPlanTypesClient_BeginDelete() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armaddons.NewSupportPlanTypesClient("d18d258f-bdba-4de1-8b51-e79d6c181d5e", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	poller, err := client.BeginDelete(ctx,
		"Canonical",
		armaddons.PlanTypeNameStandard,
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	_, err = poller.PollUntilDone(ctx, nil)
	if err != nil {
		log.Fatalf("failed to pull the result: %v", err)
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/addons/resource-manager/Microsoft.Addons/preview/2018-03-01/examples/CanonicalListSupportPlanInfo_Post.json
func ExampleSupportPlanTypesClient_ListInfo() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armaddons.NewSupportPlanTypesClient("d18d258f-bdba-4de1-8b51-e79d6c181d5e", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	res, err := client.ListInfo(ctx,
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	// TODO: use response item
	_ = res
}


text:
- Added changelog
- Added release / close connection

## v0.1.0+2
- Fix pubspec.yaml
- Fix example

## v0.1.0
- First release


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/analytics/data/v1alpha/data.proto

package com.google.analytics.data.v1alpha;

public interface StringFilterOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.analytics.data.v1alpha.StringFilter)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The match type for this filter.
   *

   *
   * .google.analytics.data.v1alpha.StringFilter.MatchType match_type = 1;
   *
   * @return The enum numeric value on the wire for matchType.
   */
  int getMatchTypeValue();
  /**
   *
   *
   *

   * The match type for this filter.
   *

   *
   * .google.analytics.data.v1alpha.StringFilter.MatchType match_type = 1;
   *
   * @return The matchType.
   */
  com.google.analytics.data.v1alpha.StringFilter.MatchType getMatchType();

  /**
   *
   *
   *

   * The string value used for the matching.
   *

   *
   * string value = 2;
   *
   * @return The value.
   */
  java.lang.String getValue();
  /**
   *
   *
   *

   * The string value used for the matching.
   *

   *
   * string value = 2;
   *
   * @return The bytes for value.
   */
  com.google.protobuf.ByteString getValueBytes();

  /**
   *
   *
   *

   * If true, the string value is case sensitive.
   *

   *
   * bool case_sensitive = 3;
   *
   * @return The caseSensitive.
   */
  boolean getCaseSensitive();
}


text:
import FWCore.ParameterSet.Config as cms

#-------------------------------------------------------------------------------
#   Option parsing
#-------------------------------------------------------------------------------
import FWCore.ParameterSet.VarParsing as opts
import glob
import sys

options = opts.VarParsing('analysis')

options.register( 'sample',
    '',
    opts.VarParsing.multiplicity.list,
    opts.VarParsing.varType.string,
    'EDM Files to process'
    )

options.register( 'output',
    'edm_MassReco.root',
    opts.VarParsing.multiplicity.singleton,
    opts.VarParsing.varType.string,
    'Output EDM filename'
    )

options.register( 'sampledir',
    '',
    opts.VarParsing.multiplicity.list,
    opts.VarParsing.varType.string,
    'Directory(s) to edm files'
)

options.setDefault('maxEvents',100)

options.parseArguments()

if not options.sampledir and not options.sample :
    print "Error! No sample specified!"
    sys.exit(1);
elif options.sampledir and options.sample:
    print "Warning! Input specified, ignoring sampledir"
elif options.sampledir and not options.sample:
    print "Processing all files in (", options.sampledir,")..."
    for directory in options.sampledir:
        directory.strip();
        for edm_file in glob.glob( directory + "/*.root" ):
            options.sample.append( 'file:'+edm_file );

#-------------------------------------------------------------------------------
#   Defining process and cmsRun outputs
#-------------------------------------------------------------------------------
process = cms.Process("HitFitCompare")
process.load("Configuration.EventContent.EventContent_cff")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.MessageLogger.cerr.FwkReport.reportEvery = 1
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(options.maxEvents) )
process.source = cms.Source("PoolSource",
    fileNames = cms.untracked.vstring(options.sample)
    )

process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )
process.options.allowUnscheduled = cms.untracked.bool(True)

process.ChiSq6jet2b = cms.EDProducer(
    "ChiSqMassReco",
    metsrc      = cms.InputTag( "slimmedMETs" ),
    muonsrc     = cms.InputTag( "skimmedPatMuons" ),
    electronsrc = cms.InputTag( "skimmedPatElectrons" ),
    jetsrc      = cms.InputTag( "skimmedPatJets" ),
    ReqBJet     = cms.untracked.int32(2),
)

process.FakeResult = cms.EDProducer(
    "FakeMassReco",
    recosrc = cms.InputTag("ChiSq6jet2b","ChiSquareResult"),
    swap    = cms.int32( 3 )
)

#-------------------------------------------------------------------------------
#   Defining output Module
#-------------------------------------------------------------------------------
process.edmOut = cms.OutputModule(
    "PoolOutputModule",
    fileName = cms.untracked.string( options.output ),
    outputCommands = cms.untracked.vstring(
        "drop *",
        "keep RecoResult_*_*_*",
        ),
    )

# process.myfilterpath = cms.Path(process.tstarMassReco)
process.endPath = cms.EndPath( process.edmOut )


text:
<?php
namespace SilverStripe\SecurityReport;

use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\Security\Group;
use SilverStripe\Security\Permission;
use SilverStripe\Security\LoginAttempt;
use SilverStripe\Subsites\Model\Subsite;

/**
 * Extends the {@see Member} class with additional descriptions for elements.
 * See {@see UserSecurityReport} for usage.
 */
class MemberReportExtension extends DataExtension
{
    /**
     * Set cast of additional fields
     *
     * @var array
     * @config
     */
    private static $casting = array(
        'GroupsDescription' => 'Text',
        'PermissionsDescription' => 'Text'
    );

    /**
     * Retrieves the most recent successful LoginAttempt
     *
     * @return DBDatetime|string
     */
    public function getLastLoggedIn()
    {
        $lastTime = LoginAttempt::get()
            ->filter([
                'MemberID' => $this->owner->ID,
                'Status' => 'Success',
            ])
            ->sort('Created', 'DESC')
            ->first();

        if ($lastTime) {
            return $lastTime->dbObject('Created')->format(DBDatetime::ISO_DATETIME);
        }
        return _t(__CLASS__ . '.NEVER', 'Never');
    }

    /**
     * Builds a comma separated list of member group names for a given Member.
     *
     * @return string
     */
    public function getGroupsDescription()
    {
        if (class_exists(Subsite::class)) {
            Subsite::disable_subsite_filter(true);
        }

        // Get the member's groups, if any
        $groups = $this->owner->Groups();
        if ($groups->Count()) {
            // Collect the group names
            $groupNames = array();
            foreach ($groups as $group) {
                /** @var Group $group */
                $groupNames[] = html_entity_decode($group->getTreeTitle());
            }
            // return a csv string of the group names, sans-markup
            $result = preg_replace("#</?[^>]>#", '', implode(', ', $groupNames));
        } else {
            // If no groups then return a status label
            $result = _t(__CLASS__ . '.NOGROUPS', 'Not in a Security Group');
        }

        if (class_exists(Subsite::class)) {
            Subsite::disable_subsite_filter(false);
        }
        return $result;
    }

    /**
     * Builds a comma separated list of human-readbale permissions for a given Member.
     *
     * @return string
     */
    public function getPermissionsDescription()
    {
        if (class_exists(Subsite::class)) {
            Subsite::disable_subsite_filter(true);
        }

        $permissionsUsr = Permission::permissions_for_member($this->owner->ID);
        $permissionsSrc = Permission::get_codes(true);
        sort($permissionsUsr);

        $permissionNames = array();
        foreach ($permissionsUsr as $code) {
            $code = strtoupper($code);
            foreach ($permissionsSrc as $k => $v) {
                if (isset($v[$code])) {
                    $name = empty($v[$code]['name'])
                        ? _t(__CLASS__ . '.UNKNOWN', 'Unknown')
                        : $v[$code]['name'];
                    $permissionNames[] = $name;
                }
            }
        }

        $result = $permissionNames
            ? implode(', ', $permissionNames)
            : _t(__CLASS__ . '.NOPERMISSIONS', 'No Permissions');

        if (class_exists(Subsite::class)) {
            Subsite::disable_subsite_filter(false);
        }
        return $result;
    }
}


text:
#define VER_MAJOR_PRODUCTVER 6
#define VER_MINOR_PRODUCTVER 0

#define VER_PRODUCTVERSION VER_MAJOR_PRODUCTVER,VER_MINOR_PRODUCTVER,VER_PRODUCTBUILD,VER_PRODUCTBUILD_QFE
#define VER_PRODUCTVERSION_W (0x0600)
#define VER_PRODUCTVERSION_DW (0x06000000 | VER_PRODUCTBUILD)

#define VER_PRODUCTBETA_STR ""
#define VER_PRODUCTVERSION_STRING "6.00"


text:
var express = require('express'),
    http = require('http'),
    bcrypt = require("bcrypt"),

    // Setup the audio stream decoder, system audio speaker,
    // and the passthrough stream for the audio passed from spotify
    Lame = require('lame'),
    lame = new Lame.Decoder(),
    Speaker = require('speaker'),
    spkr = new Speaker(),

    // Initialize the spotify search engine and the spotify-web
    // interface that will pull track info and streams
    spotify = require('spotify-web'),
    search_spotify = require('spotify'),

    // Load the config file with app settings
    config = require("./config"),

     // Initialize sqlite and create our db if it doesnt exist
    sqlite = require("sqlite3"),
    sqlite3 = require("sqlite3").verbose(),
    db = new sqlite3.Database(__dirname+'/db/hawkeyetv.db'),

    // Other libs
    _ = require("underscore"),
    exec = require('child_process').exec,
    Twit = require('twit'),

    app = express(),
    server = http.createServer(app).listen( process.env.PORT || config.port );

    // Initialize sqlite and create our db if it doesnt exist
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database(__dirname+'/db/hawkeyetv.db');
var Twit = require('twit');
var feed = require("feed-read");
var FB = require("fb");

var io = require('socket.io').listen(server);
var views = ['chrome','youtube','settings', 'music', 'facebook', 'twitter', 'news', 'home'];
var ss, stream, omx, ms;
var playback = false;

var passport = require('passport')
    , TwitterStrategy = require('passport-twitter').Strategy
    , FacebookStrategy = require('passport-facebook').Strategy;

    passport.use(new TwitterStrategy({
        consumerKey: config.tw_consumerKey,
        consumerSecret: config.tw_consumerSecret,
        callbackURL: "twitter/callback"
    },
    function(token, tokenSecret, profile, done) {

        db.run("UPDATE profiles SET tw_token = ?, tw_secret =? WHERE id = ?", [ token, tokenSecret, "1" ], function(err){
            if(err) {
                console.log("Failed to load TW oauth token in the database");
            }
        });
        done(null);
    }
));

passport.use(new FacebookStrategy({
    clientID: config.fb_clientID,
    clientSecret: config.fb_clientSecret,
    callbackURL: "/auth/facebook/callback"
},
    function(accessToken, refreshToken, profile, done) {
        console.log("Facebook Token: ", accessToken);
        db.run("UPDATE profiles SET fb_token = ?, fb_refresh =? WHERE id = ?", [ accessToken, refreshToken, "1" ], function(err){
            if(err) {
                console.log("Failed to load FB oauth token in the database");
            }
        });
        done(null);
    }
));

 //Socket.io Server
 io.set('log level', 1);
 io.sockets.on('connection', function (socket) {

    socket.on("screen", function(data) {
        socket.type = "screen";
        ss = socket;
        console.log("Screen ready...");
    });

    socket.on("remote", function(data) {
        socket.type = "remote";
        ms = socket;
        console.log("Remote ready...");
    });

    socket.on("control", function(data) {
        if (views.indexOf(data.action) > -1) {
            console.log("Render: ", data.action );
            ss.emit('controlling', data.action);
        }
    });
    socket.on("change-bg", function(data) {

        ss.emit("on-change-bg",data);

    });

    socket.on("refresh", function(data) {
        ss.emit('refresh-control', data);
    });

    socket.on("modal-control", function(data) {
        console.log("modal action: ",data.action);
        console.log("modal data: ",data.data);
        ss.emit('search-bar-control', data);
    });

    socket.on("swipe", function(data) {
        console.log("direction: ",data.direction);
        console.log("distance: ",data.distance);
        ss.emit('swipe-control', data);
    });

    socket.on("toggle-youtube", function(data) {
        ss.emit('youtube-toggle-control', data);
    });

    socket.on("play-youtube", function(data) {
        console.log(data.id);
        var id = data.id,
            url = "http://www.youtube.com/watch?v="+id;

        exec('youtube-dl -i -g --cookies /dev/shm/youtube_cookie.txt ' + url,
            function (error, stdout, stderr) {
                if (error !== null) {
                    console.log('exec error: ' + error);
                } if (stdout != null) {
                  if (omx != null) {
                    console.log("OMX - not NULL");
                      omx.quit();
                      omx = null;
                  }
                  omx = require('omxcontrol');
                  omx.start(stdout.trim());
                  ms.emit('youtube-ctl-btn');
                }
            });
    });

    socket.on("youtube-playback", function(data) {
      if (omx != null) {
        omx.pause();
      }
    });

    socket.on("youtube-stop", function(data) {
      if (omx != null) {
        omx.quit();
        omx = null;
      }
    });

    socket.on("get-rss-feed", function(data) {
        console.log("RSS FEED:",data);

        feed(data, function(err, articles) {
          if (err) throw err;
          ss.emit('rss-control',articles);
          // Each article has the following properties:
          //
          //   * "title"     - The article title (String).
          //   * "author"    - The author's name (String).
          //   * "link"      - The original article link (String).
          //   * "content"   - The HTML content of the article (String).
          //   * "published" - The date that the article was published (Date).
          //   * "feed"      - {name, source, link}
          //
        });
    });

    socket.on("get-facebook-status",function(data){

         db.get("SELECT * FROM profiles WHERE id = ?", [ "1" ], function(err, user){

             var token = user.fb_token;
             var secret = user.fb_refresh;

             if(typeof ms != "undefined"){
                 if(token === null){

                      ms.emit('sent-facebook-status',"logged_out");
                 }
                 else{
                      ms.emit('sent-facebook-status',"logged_in");
                  }
             }
         });
     });
    socket.on("get-twitter-status",function(data){

            db.get("SELECT * FROM profiles WHERE id = ?", [ "1" ], function(err, user){

                console.log("tw-token");
                console.log(user.tw_token);

                var token = user.tw_token;
                var secret = user.tw_secret;

                if(typeof ms != "undefined"){
                    if(token === null){

                         ms.emit('sent-twitter-status',"logged_out");
                    }
                    else{
                         ms.emit('sent-twitter-status',"logged_in");
                     }
                }
            });
        });

     socket.on("log-out-facebook",function(data){

         db.run("UPDATE profiles SET fb_token = ?, fb_refresh =? WHERE id = ?", [ null, null, "1" ], function(err){
             if(err) {
                 console.log("Failed to load TW oauth token in the database");
             }
         });
         ss.emit('log-out-facebook');
         if(typeof ms != "undefined"){
             ms.emit('sent-facebook-status-status',"logged_out");
         }
     });

     socket.on("log-out-twitter",function(data){
         db.run("UPDATE profiles SET tw_token = ?, tw_secret =? WHERE id = ?", [ null, null, "1" ], function(err){
             if(err) {
                 console.log("Failed to load TW oauth token in the database");
             }
         });
         ss.emit('log-out-twitter');
         if(typeof ms != "undefined"){
             ms.emit('sent-twitter-status',"logged_out");
         }
     });

    socket.on("log-in-facebook", function(data) {
            console.log("log in fb");
            ss.emit('ss-log-in-facebook', data);
    });

    socket.on("on-click-facebook", function(data) {
      db.get("SELECT * FROM profiles WHERE id = ?", [ "1" ], function(err, user){
        var token = user.fb_token;
        var secret = user.fb_refresh;

        if(token === null){
          ms.emit('facebook-login');
        } else{
            FB.setAccessToken(token);
            FB.api('/me/home', function(r) {
              ss.emit('sent-facebook-feed',r);
            })
          }
      });
    });

    socket.on("spotify-search", function(data) {
      console.log("Spotify - Search: ", data);
      search_spotify.search({ type: 'track', query: data.query }, function(err, data) {
        if ( err ) {
            console.log('Error occurred: ' + err);
            return;
        } else if ( data.info.num_results == 0 ) {
          ss.broadcast.emit('spotify-null');
        } else {
          tracks = {};
          loop = 5;
          if (data.info.num_results < 6) {
            console.log(data.info.num_results);
            loop = data.info.num_results;
          }
          // NEED to allow results of different sizes
          for (i = 0; i < loop; i++){
            key = i;
            min = parseInt(data.tracks[i].length / 60) % 60;
            sec = Math.floor(data.tracks[i].length % 60);
            tracks[key] = { name: data.tracks[i].name,
              artist: data.tracks[i].artists[0].name,
              href: data.tracks[i].href,
              time: min + ":" + (sec < 10 ? "0"+sec : sec)
            }
          }
          tracks['size'] = loop;
          ss.broadcast.emit('spotify-results', tracks);
        }
        });
    });

    socket.on("spotify-play", function(data) {
      if (stream != null) {
        if (stream._readableState.flowing) {
          console.log("Spotify - Second Play");
          stopSpotify();
        }
        console.log("HERE");
        stream = null;
        spotifyPlay(data);
        ss.broadcast.emit('spotify-reset');
      } else {
        console.log("Spotify - First Play");
        spotifyPlay(data);
      }
    });
    socket.on("spotify-pause", function(data) {
      if (stream != null ){
        if (stream._readableState.flowing) {
          stopSpotify();
          stream.pause();
        } else if (stream._readableState.pipesCount == 0) {
            stopSpotify();
            stream.pause();
        }
      }
    });
    socket.on("spotify-resume", function(data) {
      if (stream != null ){
        if (!stream._readableState.flowing) {
          console.log("Spotify - Resume");
          stream.resume();
          stream
            .pipe(lame)
            .pipe(spkr);
        }
      }
    });

    socket.on("on-click-twitter", function(data) {

        // we need to check if they have a token and token secret
        //if they do have those,  we create an object out of it. We should do this on server start
        //When the user clicks on the twitter button, and there is no object, we redirect them to login
        //if there is an object, we send them data.

        db.get("SELECT * FROM profiles WHERE id = ?", [ "1" ], function(err, user){
            if(user.tw_token === null){
                 ms.emit('twitter-login');
            }
            else{
                var T = new Twit({
                    consumer_key:         config.tw_consumerKey,
                    consumer_secret:      config.tw_consumerSecret,
                    access_token:         user.tw_token,
                    access_token_secret:  user.tw_secret
                });
                T.get('statuses/home_timeline', function (err, reply) {
                       console.log("reply is: ", reply);
                        ss.emit('sent-twitter-feed', reply);
                });
             }
        });
    });
 });

function spotifyPlay(data) {
  spotify.login(config.spotify_name, config.spotify_pass, function (err, spotify) {
    if (err) throw err;
    // first get a "Track" instance from the track URI
    spotify.get(data.track, function (err, track) {
      if (err) throw err;
      stream = track.play();
      stream
        .pipe(lame)
        .pipe(spkr)
        .on('finish', function () {
          spotify.disconnect();
        });
    });
  });
}

function stopSpotify() {
  console.log("Spotify - Stop");
  if ( stream != null ) {
    stream.unpipe(lame);
  }
  if ( lame != null) {
    lame.unpipe(spkr.end());
  }
  spkr, lame = null;
  lame = new Lame.Decoder()
  spkr = new Speaker();
}

// Create our profiles table if it doesn't exist
db.run("CREATE TABLE IF NOT EXISTS profiles (id INTEGER PRIMARY KEY, zipcode TEXT, news TEXT, theme TEXT, tw_token TEXT, tw_secret TEXT, fb_token TEXT, fb_refresh TEXT )");

// Allow node to be run with proxy passing
app.enable('trust proxy');

// Logging config
app.configure('local', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
    app.use(express.errorHandler());
});

// Compression (gzip)
app.use( express.compress() );
app.use( express.methodOverride() );
app.use( express.bodyParser() );            // Needed to parse POST data sent as JSON payload

// Cookie config
//
app.use( express.cookieParser( config.cookieSecret ) );           // populates req.signedCookies
 app.use( express.cookieSession( config.sessionSecret ) );         // populates req.session, needed for CSRF

// We need serverside view templating to initially set the CSRF token in the <head> metadata
// Otherwise, the html could just be served statically from the public directory
app.set('view engine', 'html');
app.set('views', __dirname + '/views' );
app.engine('html', require('hbs').__express);

app.use(express.static(__dirname+'/public'));

app.use( app.router );

app.get("/", function(req, res){
    res.render('index');
});

db.serialize(function(){
    db.get("SELECT * FROM profiles WHERE id = ?", [ "1" ], function(err, profile){
        if(profile){
            console.log("DB has first record");
        } else {
            db.run("INSERT INTO profiles (zipcode, news, theme) VALUES (?,?,?)",
                [ "52242", "disabled", "default"], function(err){
                if(err){
                    console.log(err);
                }
            });
        }
    });
});

app.post("/api/auth/open", function(req, res){
    db.get("SELECT * FROM profiles WHERE id = ?", [ req.body.id ], function(err, profile){
    if(profile){
        res.json({ profile: profile });
    } else {
        res.json({ error: "Default profile" });
    }
    });
});

app.post("/api/auth/update", function(req, res){
    db.serialize(function(){
        db.run("UPDATE profiles SET zipcode = ?, news = ?, theme = ? WHERE id = ?",
            [ req.body.zipcode, req.body.news, req.body.theme, req.body.id ], function(err){
            if(err) {
                console.log("Updating the user failed");
            } else {
                db.get("SELECT * FROM profiles WHERE id = ?", [ req.body.id ], function(err, profile){
                    if(profile){
                        res.json({ profile: profile });
                    } else {
                        res.json({ error: "Default profile" });
                    }
                });
            }
        });
    });
});

app.post("/api/auth/search", function(req, res){
    search_spotify.search({ type: 'track', query: 'under pressure' }, function(err, data) {
    if ( err ) {
        console.log('Error occurred: ' + err);
        return;
    }
        uri = data.tracks[0].href;
        console.log(data.tracks[0].href);
    });
});

app.post("/api/auth/play", function(){
    spotify.login("X", "X", function (err, spotify) {
      if (err) throw err;
      // first get a "Track" instance from the track URI
      spotify.get(uri, function (err, track) {
        if (err) throw err;
        stream = track.play();
        stream
          .pipe(lame)
          .pipe(spkr)
          .on('finish', function () {
            spotify.disconnect();
          });
      });
    });
});

app.get('/auth/twitter', passport.authenticate('twitter'));

app.get('/auth/twitter/callback',
  passport.authenticate('twitter', { successRedirect: '/',
                                     failureRedirect: '/' }));

app.get('/auth/facebook', passport.authenticate('facebook',{scope: 'read_stream'}));

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { successRedirect: '/',
                                     failureRedirect: '/' }));

// Close the db connection on process exit
// (should already happen, but to be safe)
process.on("exit", function(){
    db.close();
});

console.log("STARTUP:: Express server listening on port::", server.address().port, ", environment:: ", app.settings.env);


text:
@interface AuthInfo : NSObject
@property (nonatomic, assign) BOOL view;
@property (nonatomic, assign) BOOL set;
@property (nonatomic, assign) BOOL control;
@end


text:
package tutorial.javaConfig;

import tutorial.dependencyInjection.IAnimal;
import tutorial.dependencyInjection.impl.Dog;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by leituo56 on 6/10/14.
 */

@Configuration
public class AppConfig {
    @Bean (name = "animal_javaConfig")
    public IAnimal animalJavaConfig(){
        return new Dog();
    }
}


text:
using FileBrowser.FormControls;
using FileBrowser.Forms;
using FileBrowser.Models;
using FileBrowser.Models.Language;
using FileBrowser.Models.Themes;
using FileBrowser.Persistence.Repositories;
using FileBrowser.Properties;
using FileBrowser.Utils;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;

namespace FileBrowser
{

    /// <summary>
    /// The main entry point of the application.
    /// </summary>
    public partial class MainForm : Form, ILocalizable, IThemeable
    {

        private RepositoryController repositoryController;
        private DependencyController dependencyController;

        private DirectoryTreeView DirectoryTreeView;

        private ICollection<Folder> musicDirectories;
        private ICollection<string> extensions;
        private ICollection<string> filteredExtensions;

        /// <summary>
        /// Default Constructor
        /// </summary>
        public MainForm(RepositoryController repositoryController, DependencyController dependencyController)
        {
            InitializeComponent();
            this.repositoryController = repositoryController;
            this.dependencyController = dependencyController;
        }

        /* EVENTS RELATED TO THE WHOLE FORM*/
        #region MAINFORM EVENTS
        /// <summary>
        ///  Occurs when MainForm has loaded. Initializes everything needed to load the DirectoryTreeView
        /// </summary>
        /// <seealso cref="DirectoryTreeView"/>
        /// <remarks>This method should never be called by the User, but by <see cref="MainForm"/> itself</remarks>
        /// <param name="e">EventArgs</param>
        protected override void OnLoad(EventArgs e)
        {

            filteredExtensions = new List<string>();
            musicDirectories = repositoryController.FolderRepository.GetFolders();
            extensions = repositoryController.ExtensionRepository.GetExtensions();
            Icon = Properties.Resources.Icon;
            //Treeview specific UI
            DirectoryTreeView = new DirectoryTreeView(repositoryController, dependencyController);

            PanelContent.Controls.Add(DirectoryTreeView);
            PanelContent.Controls.SetChildIndex(DirectoryTreeView, 0);
            DirectoryTreeView.Anchor = AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top;
            DirectoryTreeView.BorderStyle = BorderStyle.None;
            DirectoryTreeView.Dock = DockStyle.Fill;

            DirectoryTreeView.NodeMouseClick += DirectoryTreeViews_NodeMouseClick;
            DirectoryTreeView.NodeMouseDoubleClick += DirectoryTreeViews_NodeMouseDoubleClick;

            UpdateSizeAndLocation();
            UpdateExtensionMenu();
            UpdateTheme();
            UpdateText();

            DirectoryTreeView.Generate(Settings.Default.Expand);
            base.OnLoad(e);
        }

        private void UpdateExtensionMenu()
        {
            FlowLayoutPanelExtensions.Controls.Clear();
            foreach (string ext in extensions)
            {
                CheckBox checkBoxExtension = new CheckBox
                {
                    Text = ext,
                    AutoSize = true,
                };

                checkBoxExtension.CheckedChanged += CheckBoxExtension_CheckedChanged;
                FlowLayoutPanelExtensions.Controls.Add(checkBoxExtension);
            }
        }

        private void CheckBoxExtension_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox checkBoxExtension = (CheckBox)sender;
            if (checkBoxExtension.Checked)
            {
                filteredExtensions.Add(checkBoxExtension.Text);
            }
            else
            {
                filteredExtensions.Remove(checkBoxExtension.Text);
            }

            DirectoryTreeView.Search(TextBoxSearch.Text, filteredExtensions);
            //   DirectoryTreeView.FilterExtensions(filteredExtensions);
        }

        /// <summary>
        /// Sets the saved size and location of the form
        /// </summary>
        public void UpdateSizeAndLocation()
        {
            if (!FormUtils.IsOnScreen(this))
            {
                Location = Settings.Default.WindowLocation;
            }
            Size = Settings.Default.WindowSize;
            Location = Settings.Default.WindowLocation;
        }

        public void UpdateTheme()
        {

            MenuButtonCollapseAll.ForeColor = dependencyController.ThemeManager.ColorTheme.DefaultText;
            MenuButtonShowAll.ForeColor = dependencyController.ThemeManager.ColorTheme.DefaultText;
            LabelSearch.ForeColor = dependencyController.ThemeManager.ColorTheme.DefaultText;
            foreach (CheckBox checkBoxExtension in FlowLayoutPanelExtensions.Controls)
            {
                checkBoxExtension.ForeColor = dependencyController.ThemeManager.ColorTheme.DefaultText;
            }

            PanelMainMenu.ForeColor = dependencyController.ThemeManager.ColorTheme.ForeGroundMenu;
            PanelMainMenu.BackColor = dependencyController.ThemeManager.ColorTheme.BackGroundMenu;
            PanelContent.BackColor = dependencyController.ThemeManager.ColorTheme.BackGroundTree;

            DirectoryTreeView.UpdateTheme();
        }

        public void UpdateText()
        {

            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(dependencyController.LanguageManager.GetPreferredLanguageCode());
            TitleBuilder titleBuilder = new TitleBuilder();
            Text = titleBuilder.BuildPrimaryTitle();
            MenuButtonGuide.Text = Resources.Strings.MenuHelp;
            MenuButtonRefresh.Text = Resources.Strings.MenuRefresh;
            MenuButtonSettings.Text = Resources.Strings.MenuSettings;
            LabelSearch.Text = Resources.Strings.Search;
            MenuButtonCollapseAll.Text = Resources.Strings.CollapseAll;
            MenuButtonShowAll.Text = Resources.Strings.ShowAll;
            MenuButtonAbout.Text = Resources.Strings.MenuAbout;
            DirectoryTreeView.UpdateText();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            Settings.Default.WindowLocation = Location;

            if (WindowState == FormWindowState.Normal)
            {
                Settings.Default.WindowSize = Size;
            }
            else
            {
                Settings.Default.WindowSize = RestoreBounds.Size;
            }

            Settings.Default.Save();
            base.OnFormClosing(e);
        }

        #endregion

        /* EVENTS RELATED THE THE MENU */
        #region MENU EVENTS

        /// <summary>
        /// Refreshes the TreeView
        /// <seealso cref="DirectoryTreeView"/>
        /// </summary>
        private void MenuButtonRefresh_Click(object sender, EventArgs e)
        {
            musicDirectories = repositoryController.FolderRepository.GetFolders();
            extensions = repositoryController.ExtensionRepository.GetExtensions();

            DirectoryTreeView.Generate(Settings.Default.Expand);
            UpdateExtensionMenu();
        }

        /// <summary>
        /// Open the settings view
        /// <seealso cref="SettingsForm"/>
        /// </summary>
        private void ButtonSettings_Click(object sender, EventArgs e)
        {

            SettingsForm settingsForm = new SettingsForm(repositoryController, dependencyController);
            settingsForm.LanguageChanged += SettingsForm_LanguageChanged;
            settingsForm.ColorChanged += SettingsForm_ColorChanged;

            FormUtils.OpenForm(settingsForm, Location);

        }

        /// <summary>
        /// Occurs when a color is changed in the SettingsForm
        /// <seealso cref="SettingsForm"/>
        /// </summary>
        private void SettingsForm_ColorChanged(object sender, EventArgs e)
        {
            UpdateTheme();
        }

        /// <summary>
        /// Occurs when the language is changed in the SettingsForm
        /// <seealso cref="SettingsForm"/>
        /// </summary>
        private void SettingsForm_LanguageChanged(object sender, EventArgs e)
        {
            UpdateText();
        }

        /// <summary>
        /// Opens the help view
        /// <seealso cref="HelpForm"/>
        /// </summary>
        private void MenuButtonGuide_Click(object sender, EventArgs e)
        {
            FormUtils.OpenForm(new HelpForm(), Location);
        }

        /// <summary>
        /// Opens the about view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuButtonAbout_Click(object sender, EventArgs e)
        {
            FormUtils.OpenForm(new AboutForm(), Location);
        }
        #endregion

        /* EVENTS RELATED TO THE TREEVIEW */
        #region TREE

        /// <summary>
        /// Occurs when a doubleclick occured in the TreeView
        /// <seealso cref="DirectoryTreeView.DoubleClicked(TreeNode)"/>
        /// </summary>
        private void DirectoryTreeViews_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                DirectoryTreeView.DoubleClicked(e.Node);
            }

        }

        /// <summary>
        /// Occurs when right clicking inside the treeview.
        /// <seealso cref="DirectoryTreeView.RightClicked(TreeNode)"/>
        /// </summary>
        private void DirectoryTreeViews_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                DirectoryTreeView.RightClicked(e.Node);
            }

        }

        /// <summary>
        /// Occurs when Enter is pressed while focused on TextBoxSearch and searches The DirectoryTreeView
        /// </summary>
        private void TextBoxSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)
            {
                return;
            }
            e.SuppressKeyPress = true;
            DirectoryTreeView.Search(TextBoxSearch.Text, filteredExtensions);
        }

        /// <summary>
        /// Occurs when the search input has changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBoxSearch_TextChanged(object sender, EventArgs e)
        {
            string input = TextBoxSearch.Text;
            if (string.IsNullOrWhiteSpace(input) || string.IsNullOrEmpty(input))
            {
                DirectoryTreeView.Search(null, filteredExtensions);
            }
        }

        /// <summary>
        /// Collapes the whole TreeView
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuButtonCollapseAll_Click(object sender, EventArgs e)
        {
            DirectoryTreeView.BeginUpdate();
            DirectoryTreeView.CollapseAll();
            DirectoryTreeView.EndUpdate();
        }

        /// <summary>
        /// Expands the whole treeview
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuButtonShowAll_Click(object sender, EventArgs e)
        {
            DirectoryTreeView.BeginUpdate();
            DirectoryTreeView.ExpandAll();
            DirectoryTreeView.Nodes[0].EnsureVisible(); // scroll to top
            DirectoryTreeView.EndUpdate();
        }

        #endregion

        private void ButtonClearSearch_Click(object sender, EventArgs e)
        {
            TextBoxSearch.Clear();
        }
    }
}


text:
FOUNDATION_EXPORT double CmsKitVersionNumber;
FOUNDATION_EXPORT const unsigned char CmsKitVersionString[];


text:
.class public final Lo/WX;
.super Ljava/lang/Object;
.source ""

# static fields
.field public static final ʻ:Ljava/lang/String; = "1.0.1"

.field public static final ˊ:Z = false

.field public static final ˋ:Ljava/lang/String; = "com.starbucks.cee"

.field public static final ˎ:Ljava/lang/String; = "release"

.field public static final ˏ:Ljava/lang/String; = "prodapi"

.field public static final ᐝ:I = 0x1b

# direct methods
.method public constructor <init>()V
    .locals 0

    .line 6
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
package ftcbootstrap.components.operations.motors;

import com.qualcomm.robotcore.hardware.DcMotor;

import ftcbootstrap.ActiveOpMode;
import ftcbootstrap.components.OpModeComponent;
import ftcbootstrap.components.utils.DriveDirection;
import ftcbootstrap.components.utils.MotorDirection;

/**
 * Operation to assist with Tank Driving will using an encoder
 */
public class TankDriveToEncoder extends OpModeComponent {

    private MotorToEncoder leftMotorToEncoder;
    private MotorToEncoder rightMotorEncoder;

    /**
     * Constructor for operation
     * Telemetry enabled by default.
     * @param opMode
     * @param leftMotor DcMotor
     * @param rightMotor DcMotor
     */
    public TankDriveToEncoder(ActiveOpMode opMode,
                              DcMotor leftMotor,
                              DcMotor rightMotor) {

        super(opMode);
        leftMotorToEncoder =  new MotorToEncoder(opMode, leftMotor );
        leftMotorToEncoder.setName("left motor");
        rightMotorEncoder = new MotorToEncoder( opMode, rightMotor );
        leftMotorToEncoder.setName("right motor");

    }

    @Override
    public void setOpModeLogLevel(int logLevel) {
        super.setOpModeLogLevel(logLevel);

        leftMotorToEncoder.setOpModeLogLevel(logLevel);
        rightMotorEncoder.setOpModeLogLevel(logLevel);

    }

    /**
     *
     * @param power
     * @param encoderDistance
     * @param driveDirection  {@link DriveDirection}
     * @param runMode  {@Link DcMotor.RunMode}
     * @return boolean target reached
     * @throws InterruptedException
     */
    public boolean runToTarget(double power, int encoderDistance, DriveDirection driveDirection, DcMotor.RunMode runMode) throws InterruptedException {

        boolean targetReached = false;

        MotorDirection motorDirection = TankDrive.leftMotorDirectionOn(driveDirection);
        if (driveDirection == DriveDirection.PIVOT_FORWARD_LEFT || driveDirection == DriveDirection.PIVOT_BACKWARD_RIGHT) {
            leftMotorToEncoder.stop();
        }
        else {
            targetReached =  leftMotorToEncoder.runToTarget(power, encoderDistance, motorDirection, runMode);
        }

        //stop the other motor if this target is reached
        if ( targetReached) {

            addTelemetry("left target reached.  Stopping right  left pos: " ,
                    leftMotorToEncoder.motorCurrentPosition() + " right pos: "  + rightMotorEncoder.motorCurrentPosition());

            rightMotorEncoder.stop();
            return true;
        }

        motorDirection = TankDrive.rightMotorDirectionOn(driveDirection);
        if (driveDirection == DriveDirection.PIVOT_FORWARD_RIGHT || driveDirection == DriveDirection.PIVOT_BACKWARD_LEFT) {
            rightMotorEncoder.stop();
        }
        else {
            targetReached = rightMotorEncoder.runToTarget(power, encoderDistance, motorDirection, runMode);
        }

        //stop the other motor if this target is reached
        if ( targetReached) {
            leftMotorToEncoder.stop();
            return true;
        }

        return false;

    }

    /**
     * Check if the operation is running.   Do this before calling runToTarget()
     * @return boolean
     */
    public boolean isDriving() {
        return leftMotorToEncoder.isRunning() || rightMotorEncoder.isRunning();
    }

    /**
     * stop the motors
     */
    public void stop()  throws InterruptedException {

        leftMotorToEncoder.stop();
        rightMotorEncoder.stop();

    }

    /**
     * check if current encoder position is close to target
     * @return boolean
     */
    public boolean targetReached() {

        return leftMotorToEncoder.targetReached() || rightMotorEncoder.targetReached();
    }

}


text:
Threadable.DoerSelectorItemController = Ember.ObjectController.extend({
  needs: ['doerSelector', 'conversation'],

  doers: Ember.computed.alias('controllers.doerSelector.doers'),

  isDoer: function() {
    var doers = this.get('doers');
    if (doers.length < 1) return false;
    return !! doers.findBy('id', this.get('id'));
  }.property('doers.@each', 'id'),

  changeType: function() {
    var persistedDoerIds = [];
    var persistedDoers = this.get('controllers.conversation.doers');

    if(persistedDoers) {
      persistedDoerIds = persistedDoers.map(function(doer){
        return doer.get('id');
      });
    }

    var doerHere = this.get('isDoer');
    var doerSaved = persistedDoerIds.indexOf(this.get('id')) !== -1;

    if (doerHere == doerSaved) return null;
    if (doerSaved) return 'removed';
    return 'added';
  }.property('id', 'isDoer', 'controllers.conversation.doers.@each'),

  isChanged: function() {
    return !!this.get('changeType');
  }.property('changeType'),

  isAdded: function() {
    return this.get('changeType') == 'added';
  }.property('changeType'),

  actions: {
    toggleDoer: function() {
      var doer  = this.get('model');
      var doers = this.get('doers');
      if(this.get('isDoer') ){
        this.get('controllers.doerSelector').set('doers', doers.rejectBy('id', doer.get('id')));
      } else {
        doers.pushObject(doer);
      }
      this.get('controllers.conversation').send('toggleDoerSelector');
      Ember.run(function() {
        var container = $('.conversation-show:first');
        var reply = container.find('.reply');
        var newScrollTop = container.scrollTop() + reply.position().top;
        $(".conversation-show").animate({scrollTop: newScrollTop}, 250);
      });
    }
  }
});


text:
package com.tutsplus.googlefit;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.FitnessActivities;
import com.google.android.gms.fitness.data.DataPoint;
import com.google.android.gms.fitness.data.DataSet;
import com.google.android.gms.fitness.data.DataSource;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.data.Session;
import com.google.android.gms.fitness.request.DataDeleteRequest;
import com.google.android.gms.fitness.request.SessionInsertRequest;
import com.google.android.gms.fitness.request.SessionReadRequest;
import com.google.android.gms.fitness.result.SessionReadResult;
import com.google.android.gms.fitness.result.SessionStopResult;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    //The name used for inserting and reading must match in order to receive results
    private final String SESSION_NAME = "session name";

    private GoogleApiClient mGoogleApiClient = null;
    private Session mSession;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Fitness.SESSIONS_API)
                .addApi(Fitness.HISTORY_API)
                .addScope(new Scope(Scopes.FITNESS_LOCATION_READ_WRITE))
                .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
                .addConnectionCallbacks(this)
                .enableAutoManage(this, 0, this)
                .build();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.btn_start_session)
    public void startSession() {
        mSession = new Session.Builder()
                .setName(SESSION_NAME)
                .setIdentifier(getString(R.string.app_name) + " " + System.currentTimeMillis())
                .setDescription("Yoga Session Description")
                .setStartTime(Calendar.getInstance().getTimeInMillis(), TimeUnit.MILLISECONDS)
                .setActivity(FitnessActivities.YOGA)
                .build();

        PendingResult<Status> pendingResult =
                Fitness.SessionsApi.startSession(mGoogleApiClient, mSession);

        pendingResult.setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        if (status.isSuccess()) {
                            Log.i("Tuts+", "Successfully started session");
                        } else {
                            Log.i("Tuts+", "Failed to start session: " + status.getStatusMessage());
                        }
                    }
                }
        );
    }

    @OnClick(R.id.btn_stop_session)
    public void stopSession() {

        PendingResult<SessionStopResult> pendingResult =
                Fitness.SessionsApi.stopSession(mGoogleApiClient, mSession.getIdentifier());

        pendingResult.setResultCallback(new ResultCallback<SessionStopResult>() {
            @Override
            public void onResult(SessionStopResult sessionStopResult) {
                if( sessionStopResult.getStatus().isSuccess() ) {
                    Log.i("Tuts+", "Successfully stopped session");
                    if( sessionStopResult.getSessions() != null && !sessionStopResult.getSessions().isEmpty() ) {
                        Log.i("Tuts+", "Session name: " + sessionStopResult.getSessions().get(0).getName());
                        Log.i("Tuts+", "Session start: " + sessionStopResult.getSessions().get(0).getStartTime(TimeUnit.MILLISECONDS));
                        Log.i("Tuts+", "Session end: " + sessionStopResult.getSessions().get(0).getEndTime(TimeUnit.MILLISECONDS));
                    }
                } else {
                    Log.i("Tuts+", "Failed to stop session: " + sessionStopResult.getStatus().getStatusMessage());
                }
            }

        });
    }

    @OnClick(R.id.btn_insert_segment)
    public void insertSegment() {
        if( !mGoogleApiClient.isConnected() ) {
            Toast.makeText(this, "Not connected to Google", Toast.LENGTH_SHORT).show();
            return;
        }

        Calendar calendar = Calendar.getInstance();
        Date now = new Date();
        calendar.setTime(now);

        long endTime = calendar.getTimeInMillis();
        calendar.add(Calendar.MINUTE, -15);
        long walkEndTime = calendar.getTimeInMillis();
        calendar.add(Calendar.MINUTE, -5);
        long walkStartTime = calendar.getTimeInMillis();
        calendar.add(Calendar.MINUTE, -15);
        long startTime = calendar.getTimeInMillis();

        float firstRunSpeed = 15;
        float walkSpeed = 5;
        float secondRunSpeed = 13;

        DataSource speedSegmentDataSource = new DataSource.Builder()
                .setAppPackageName(this.getPackageName())
                .setDataType(DataType.TYPE_SPEED)
                .setName("Tuts+ speed dataset")
                .setType(DataSource.TYPE_RAW)
                .build();

        DataSource activitySegmentDataSource = new DataSource.Builder()
                .setAppPackageName(this.getPackageName())
                .setDataType(DataType.TYPE_ACTIVITY_SEGMENT)
                .setName("Tuts+ activity segments dataset")
                .setType(DataSource.TYPE_RAW)
                .build();

        DataSet speedDataSet = DataSet.create(speedSegmentDataSource);
        DataSet activityDataSet = DataSet.create(activitySegmentDataSource);

        //Create speed data point for first run segment
        DataPoint firstRunSpeedDataPoint = speedDataSet.createDataPoint()
                .setTimeInterval(startTime, walkStartTime, TimeUnit.MILLISECONDS);
        firstRunSpeedDataPoint.getValue(Field.FIELD_SPEED).setFloat(firstRunSpeed);
        speedDataSet.add(firstRunSpeedDataPoint);

        //Create speed data point for walking segment
        DataPoint walkingSpeedDataPoint = speedDataSet.createDataPoint()
                .setTimeInterval(walkStartTime, walkEndTime, TimeUnit.MILLISECONDS);
        walkingSpeedDataPoint.getValue(Field.FIELD_SPEED).setFloat(walkSpeed);
        speedDataSet.add(walkingSpeedDataPoint);

        //Create speed data point for second run segment
        DataPoint secondRunSpeedDataPoint = speedDataSet.createDataPoint()
                .setTimeInterval(walkEndTime, endTime, TimeUnit.MILLISECONDS);
        secondRunSpeedDataPoint.getValue(Field.FIELD_SPEED).setFloat(secondRunSpeed);
        speedDataSet.add(secondRunSpeedDataPoint);

        //Create activity data point for first run segment
        DataPoint firstRunActivityDataPoint = activityDataSet.createDataPoint()
                .setTimeInterval(startTime, walkStartTime, TimeUnit.MILLISECONDS);
        firstRunActivityDataPoint.getValue(Field.FIELD_ACTIVITY).setActivity(FitnessActivities.RUNNING);
        activityDataSet.add(firstRunActivityDataPoint);

        //Create activity data point for walking segment
        DataPoint walkingActivityDataPoint = activityDataSet.createDataPoint()
                .setTimeInterval(walkStartTime, walkEndTime, TimeUnit.MILLISECONDS);
        walkingActivityDataPoint.getValue(Field.FIELD_ACTIVITY).setActivity(FitnessActivities.WALKING);
        activityDataSet.add(walkingActivityDataPoint);

        //Create activity data point for second run segment
        DataPoint secondRunActivityDataPoint = activityDataSet.createDataPoint()
                .setTimeInterval(walkEndTime, endTime, TimeUnit.MILLISECONDS);
        secondRunActivityDataPoint.getValue(Field.FIELD_ACTIVITY).setActivity(FitnessActivities.RUNNING);
        activityDataSet.add(secondRunActivityDataPoint);

        Session session = new Session.Builder()
                .setName(SESSION_NAME)
                .setIdentifier(getString(R.string.app_name) + " " + System.currentTimeMillis())
                .setDescription("Running in Segments")
                .setStartTime(startTime, TimeUnit.MILLISECONDS)
                .setEndTime(endTime, TimeUnit.MILLISECONDS)
                .setActivity(FitnessActivities.RUNNING)
                .build();

        SessionInsertRequest insertRequest = new SessionInsertRequest.Builder()
                .setSession(session)
                .addDataSet(speedDataSet)
                .addDataSet(activityDataSet)
                .build();

        PendingResult<Status> pendingResult =
                Fitness.SessionsApi.insertSession(mGoogleApiClient, insertRequest);

        pendingResult.setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                if( status.isSuccess() ) {
                    Log.i("Tuts+", "successfully inserted running session");
                } else {
                    Log.i("Tuts+", "Failed to insert running session: " + status.getStatusMessage());
                }
            }
        });

    }

    @OnClick(R.id.btn_read_session)
    public void readSession() {
        if( !mGoogleApiClient.isConnected() ) {
            Toast.makeText(this, "Not connected to Google", Toast.LENGTH_SHORT).show();
            return;
        }

        Calendar cal = Calendar.getInstance();
        Date now = new Date();
        cal.setTime(now);
        long endTime = cal.getTimeInMillis();
        cal.add(Calendar.MONTH, -1);
        long startTime = cal.getTimeInMillis();

        SessionReadRequest readRequest = new SessionReadRequest.Builder()
                .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
                .read(DataType.TYPE_SPEED)
                .setSessionName(SESSION_NAME)
                .build();

        PendingResult<SessionReadResult> sessionReadResult =
                Fitness.SessionsApi.readSession(mGoogleApiClient, readRequest);

        sessionReadResult.setResultCallback(new ResultCallback<SessionReadResult>() {
            @Override
            public void onResult(SessionReadResult sessionReadResult) {
                if (sessionReadResult.getStatus().isSuccess()) {
                    Log.i("Tuts+", "Successfully read session data");
                    for (Session session : sessionReadResult.getSessions()) {
                        Log.i("Tuts+", "Session name: " + session.getName());
                        for (DataSet dataSet : sessionReadResult.getDataSet(session)) {
                            for (DataPoint dataPoint : dataSet.getDataPoints()) {
                                Log.i("Tuts+", "Speed: " + dataPoint.getValue(Field.FIELD_SPEED));
                            }
                        }
                    }
                } else {
                    Log.i("Tuts+", "Failed to read session data");
                }
            }
        });
    }

    @OnClick(R.id.btn_delete_session)
    public void deleteSessions() {
        Calendar calendar = Calendar.getInstance();
        Date now = new Date();
        calendar.setTime(now);
        long endTime = calendar.getTimeInMillis();
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        long startTime = calendar.getTimeInMillis();

        DataDeleteRequest request = new DataDeleteRequest.Builder()
                .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
                .addDataType(DataType.TYPE_SPEED)
                .deleteAllSessions()
                .build();

        PendingResult<Status> deleteRequest = Fitness.HistoryApi.deleteData(mGoogleApiClient, request);
        deleteRequest.setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(@NonNull Status status) {
                if( status.isSuccess() ) {
                    Log.i("Tuts+", "Successfully deleted sessions");
                } else {
                    Log.i("Tuts+", "Failed to delete sessions");
                }
            }
        });
    }

    @Override
    public void onConnected(Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}


text:
package com.ibm.watson.discovery.v1.model;

import com.ibm.cloud.sdk.core.service.model.GenericModel;
import java.util.List;

/** Object containing an array of available configurations. */
public class ListConfigurationsResponse extends GenericModel {

  protected List<Configuration> configurations;

  /**
   * Gets the configurations.
   *
   * <p>An array of configurations that are available for the service instance.
   *
   * @return the configurations
   */
  public List<Configuration> getConfigurations() {
    return configurations;
  }
}


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

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/spinner_item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:singleLine="true"
        android:textColor="@android:color/white"
        android:textAppearance="@style/TextAppearance.AppCompat.Title"
        />

    <ImageView
        android:contentDescription="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/spinner_item_text"
        android:layout_toEndOf="@+id/spinner_item_text"
        android:paddingTop="6dp"
        android:paddingLeft="8dp"
        android:src="@android:drawable/arrow_down_float" />

</RelativeLayout>


text:
import * as os from 'os';
import * as path from 'vs/base/common/path';
import * as pfs from 'vs/base/node/pfs';

// This is required, since parseInt("7-preview") will return 7.
const IntRegex: RegExp = /^\d+$/;

const PwshMsixRegex: RegExp = /^Microsoft.PowerShell_.*/;
const PwshPreviewMsixRegex: RegExp = /^Microsoft.PowerShellPreview_.*/;

const enum Arch {
	x64,
	x86,
	ARM
}

let processArch: Arch;
switch (process.arch) {
	case 'ia32':
	case 'x32':
		processArch = Arch.x86;
		break;
	case 'arm':
	case 'arm64':
		processArch = Arch.ARM;
		break;
	default:
		processArch = Arch.x64;
		break;
}

/*
Currently, here are the values for these environment variables on their respective archs:

On x86 process on x86:
PROCESSOR_ARCHITECTURE is X86
PROCESSOR_ARCHITEW6432 is undefined

On x86 process on x64:
PROCESSOR_ARCHITECTURE is X86
PROCESSOR_ARCHITEW6432 is AMD64

On x64 process on x64:
PROCESSOR_ARCHITECTURE is AMD64
PROCESSOR_ARCHITEW6432 is undefined

On ARM process on ARM:
PROCESSOR_ARCHITECTURE is ARM64
PROCESSOR_ARCHITEW6432 is undefined

On x86 process on ARM:
PROCESSOR_ARCHITECTURE is X86
PROCESSOR_ARCHITEW6432 is ARM64

On x64 process on ARM:
PROCESSOR_ARCHITECTURE is ARM64
PROCESSOR_ARCHITEW6432 is undefined
*/
let osArch: Arch;
if (process.env['PROCESSOR_ARCHITEW6432']) {
	osArch = process.env['PROCESSOR_ARCHITEW6432'] === 'ARM64'
		? Arch.ARM
		: Arch.x64;
} else if (process.env['PROCESSOR_ARCHITECTURE'] === 'ARM64') {
	osArch = Arch.ARM;
} else if (process.env['PROCESSOR_ARCHITECTURE'] === 'X86') {
	osArch = Arch.x86;
} else {
	osArch = Arch.x64;
}

export interface IPowerShellExeDetails {
	readonly displayName: string;
	readonly exePath: string;
}

export interface IPossiblePowerShellExe extends IPowerShellExeDetails {
	exists(): Promise<boolean>;
}

class PossiblePowerShellExe implements IPossiblePowerShellExe {
	constructor(
		public readonly exePath: string,
		public readonly displayName: string,
		private knownToExist?: boolean) { }

	public async exists(): Promise<boolean> {
		if (this.knownToExist === undefined) {
			this.knownToExist = await pfs.SymlinkSupport.existsFile(this.exePath);
		}
		return this.knownToExist;
	}
}

function getProgramFilesPath(
	{ useAlternateBitness = false }: { useAlternateBitness?: boolean } = {}): string | null {

	if (!useAlternateBitness) {
		// Just use the native system bitness
		return process.env.ProgramFiles || null;
	}

	// We might be a 64-bit process looking for 32-bit program files
	if (processArch === Arch.x64) {
		return process.env['ProgramFiles(x86)'] || null;
	}

	// We might be a 32-bit process looking for 64-bit program files
	if (osArch === Arch.x64) {
		return process.env.ProgramW6432 || null;
	}

	// We're a 32-bit process on 32-bit Windows, there is no other Program Files dir
	return null;
}

async function findPSCoreWindowsInstallation(
	{ useAlternateBitness = false, findPreview = false }:
		{ useAlternateBitness?: boolean; findPreview?: boolean } = {}): Promise<IPossiblePowerShellExe | null> {

	const programFilesPath = getProgramFilesPath({ useAlternateBitness });
	if (!programFilesPath) {
		return null;
	}

	const powerShellInstallBaseDir = path.join(programFilesPath, 'PowerShell');

	// Ensure the base directory exists
	if (!await pfs.SymlinkSupport.existsDirectory(powerShellInstallBaseDir)) {
		return null;
	}

	let highestSeenVersion: number = -1;
	let pwshExePath: string | null = null;
	for (const item of await pfs.Promises.readdir(powerShellInstallBaseDir)) {

		let currentVersion: number = -1;
		if (findPreview) {
			// We are looking for something like "7-preview"

			// Preview dirs all have dashes in them
			const dashIndex = item.indexOf('-');
			if (dashIndex < 0) {
				continue;
			}

			// Verify that the part before the dash is an integer
			// and that the part after the dash is "preview"
			const intPart: string = item.substring(0, dashIndex);
			if (!IntRegex.test(intPart) || item.substring(dashIndex + 1) !== 'preview') {
				continue;
			}

			currentVersion = parseInt(intPart, 10);
		} else {
			// Search for a directory like "6" or "7"
			if (!IntRegex.test(item)) {
				continue;
			}

			currentVersion = parseInt(item, 10);
		}

		// Ensure we haven't already seen a higher version
		if (currentVersion <= highestSeenVersion) {
			continue;
		}

		// Now look for the file
		const exePath = path.join(powerShellInstallBaseDir, item, 'pwsh.exe');
		if (!await pfs.SymlinkSupport.existsFile(exePath)) {
			continue;
		}

		pwshExePath = exePath;
		highestSeenVersion = currentVersion;
	}

	if (!pwshExePath) {
		return null;
	}

	const bitness: string = programFilesPath.includes('x86') ? ' (x86)' : '';
	const preview: string = findPreview ? ' Preview' : '';

	return new PossiblePowerShellExe(pwshExePath, `PowerShell${preview}${bitness}`, true);
}

async function findPSCoreMsix({ findPreview }: { findPreview?: boolean } = {}): Promise<IPossiblePowerShellExe | null> {
	// We can't proceed if there's no LOCALAPPDATA path
	if (!process.env.LOCALAPPDATA) {
		return null;
	}

	// Find the base directory for MSIX application exe shortcuts
	const msixAppDir = path.join(process.env.LOCALAPPDATA, 'Microsoft', 'WindowsApps');

	if (!await pfs.SymlinkSupport.existsDirectory(msixAppDir)) {
		return null;
	}

	// Define whether we're looking for the preview or the stable
	const { pwshMsixDirRegex, pwshMsixName } = findPreview
		? { pwshMsixDirRegex: PwshPreviewMsixRegex, pwshMsixName: 'PowerShell Preview (Store)' }
		: { pwshMsixDirRegex: PwshMsixRegex, pwshMsixName: 'PowerShell (Store)' };

	// We should find only one such application, so return on the first one
	for (const subdir of await pfs.Promises.readdir(msixAppDir)) {
		if (pwshMsixDirRegex.test(subdir)) {
			const pwshMsixPath = path.join(msixAppDir, subdir, 'pwsh.exe');
			return new PossiblePowerShellExe(pwshMsixPath, pwshMsixName);
		}
	}

	// If we find nothing, return null
	return null;
}

function findPSCoreDotnetGlobalTool(): IPossiblePowerShellExe {
	const dotnetGlobalToolExePath: string = path.join(os.homedir(), '.dotnet', 'tools', 'pwsh.exe');

	return new PossiblePowerShellExe(dotnetGlobalToolExePath, '.NET Core PowerShell Global Tool');
}

function findWinPS(): IPossiblePowerShellExe | null {
	const winPSPath = path.join(
		process.env.windir!,
		processArch === Arch.x86 && osArch !== Arch.x86 ? 'SysNative' : 'System32',
		'WindowsPowerShell', 'v1.0', 'powershell.exe');

	return new PossiblePowerShellExe(winPSPath, 'Windows PowerShell', true);
}

/**
 * Iterates through all the possible well-known PowerShell installations on a machine.
 * Returned values may not exist, but come with an .exists property
 * which will check whether the executable exists.
 */
async function* enumerateDefaultPowerShellInstallations(): AsyncIterable<IPossiblePowerShellExe> {
	// Find PSCore stable first
	let pwshExe = await findPSCoreWindowsInstallation();
	if (pwshExe) {
		yield pwshExe;
	}

	// Windows may have a 32-bit pwsh.exe
	pwshExe = await findPSCoreWindowsInstallation({ useAlternateBitness: true });
	if (pwshExe) {
		yield pwshExe;
	}

	// Also look for the MSIX/UWP installation
	pwshExe = await findPSCoreMsix();
	if (pwshExe) {
		yield pwshExe;
	}

	// Look for the .NET global tool
	// Some older versions of PowerShell have a bug in this where startup will fail,
	// but this is fixed in newer versions
	pwshExe = findPSCoreDotnetGlobalTool();
	if (pwshExe) {
		yield pwshExe;
	}

	// Look for PSCore preview
	pwshExe = await findPSCoreWindowsInstallation({ findPreview: true });
	if (pwshExe) {
		yield pwshExe;
	}

	// Find a preview MSIX
	pwshExe = await findPSCoreMsix({ findPreview: true });
	if (pwshExe) {
		yield pwshExe;
	}

	// Look for pwsh-preview with the opposite bitness
	pwshExe = await findPSCoreWindowsInstallation({ useAlternateBitness: true, findPreview: true });
	if (pwshExe) {
		yield pwshExe;
	}

	// Finally, get Windows PowerShell
	pwshExe = findWinPS();
	if (pwshExe) {
		yield pwshExe;
	}
}

/**
 * Iterates through PowerShell installations on the machine according
 * to configuration passed in through the constructor.
 * PowerShell items returned by this object are verified
 * to exist on the filesystem.
 */
export async function* enumeratePowerShellInstallations(): AsyncIterable<IPowerShellExeDetails> {
	// Get the default PowerShell installations first
	for await (const defaultPwsh of enumerateDefaultPowerShellInstallations()) {
		if (await defaultPwsh.exists()) {
			yield defaultPwsh;
		}
	}
}

/**
* Returns the first available PowerShell executable found in the search order.
*/
export async function getFirstAvailablePowerShellInstallation(): Promise<IPowerShellExeDetails | null> {
	for await (const pwsh of enumeratePowerShellInstallations()) {
		return pwsh;
	}
	return null;
}


text:
namespace Affecto.Logging
{
    public enum LogEventLevel
    {
        Verbose,
        Debug,
        Information,
        Warning,
        Error,
        Critical
    }
}


text:
package algorithms.graphs;

import algorithms.util.PairInt;
import algorithms.util.SimpleLinkedListNode;
import java.util.Arrays;
import java.util.Iterator;

/**
 * miscellaneous graph methods.
 *
 * TODO: consider a method to remap vertex keys for input graphs that start
 * counting at 1 instead of 0 (they need vertex 0 removed and all vertex
 * numbers and vertex numbers in edges decreased by 1.
 *
 * @author nichole
 */
public class GraphUtil {

    /**
     * create an adjacency list from the given graph knowing that the vertexes
     * present are numbered 0 through number of vertexes-1.
     * Note that even if more than one edge is present in the direction from
     * vertex u to vertex v, only one is present in the adjacency list for that
     * directional edge in the returned adjacency list.
     * runtime complexity is O(|V| + |E|).
     * @param g
     * @return
     */
    public static SimpleLinkedListNode[] createAdjacencyList(
        NewmanGMLParser.GMLGraph g) {

        int nV = g.nodeIdLabelMap.size();

        SimpleLinkedListNode[] out = createAdjacencyList(g, nV);

        return out;
    }

    /**
     * create an adjacency list from a graph which may be missing vertex information
     * and might not be numbered from 0 to |V|-1.
     * runtime complexity is O((|V|*log_2(|V|( * |E|) which is longer
     * due to a needed sort.
     * Note that even if more than one edge is present in the direction from
     * vertex u to vertex v, only one is present in the adjacency list for that
     * directional edge in the returned adjacency list.
     * @param g
     * @return
     */
    public static SimpleLinkedListNode[] createAdjacencyList2(
        NewmanGMLParser.GMLGraph g) {

        int[] vs = g.nodeIdLabelMap.keys();
        Arrays.sort(vs, 0, vs.length);
        int nV = vs[vs.length - 1] + 1;

        SimpleLinkedListNode[] out = createAdjacencyList(g, nV);

        return out;
    }

    private static SimpleLinkedListNode[] createAdjacencyList(
        NewmanGMLParser.GMLGraph g, final int nVertexes) {

        SimpleLinkedListNode[] out = new SimpleLinkedListNode[nVertexes];
        for (int v = 0; v < nVertexes; ++v) {
            out[v] = new SimpleLinkedListNode();
        }

        //Entry<PairInt, TFloatList>entry;
        PairInt uv;
        //TFloatList wList;
        //Iterator<Entry<PairInt, TFloatList>> iter = g.edgeWeightMap.entrySet().iterator();
        Iterator<PairInt> iter = g.edgeWeightMap.keySet().iterator();
        while (iter.hasNext()) {
            //entry = iter.next();
            //uv = entry.getKey();
            //wList = entry.getValue();
            uv = iter.next();
            out[uv.getX()].insert(uv.getY());
        }

        return out;
    }
}