text:
package scala.meta.tests.metacp

import java.nio.file._
import org.scalatest.FunSuite
import org.scalatest.tagobjects.Slow
import scala.collection.JavaConverters._
import scala.meta.cli._
import scala.meta.io._
import scala.meta.metacp.Settings
import scala.meta.testkit.DiffAssertions
import scala.meta.tests._
import scala.meta.tests.cli.CliSuite

class MetacpErrorSuite extends FunSuite with DiffAssertions {

  private val tmp = AbsolutePath(Files.createTempDirectory("metacp"))
  tmp.toFile.deleteOnExit()
  private val settings = Settings().withOut(tmp)

  test("missing symbol 1", Slow) {
    val (result, out, err) = CliSuite.withReporter { reporter =>
      val scalametaSettings = settings.withClasspath(
        Library(
          "org.scalameta",
          "scalameta_2.12",
          "3.2.0",
          // Scalameta has public signatures that reference scala-reflect APIs even if scala-reflect not
          // declared as a provided dependency in pom.xml.
          provided = Nil
        ).classpath()
      )
      Metacp.process(scalametaSettings, reporter)
    }
    assert(result.classpath.isEmpty)
    assert(out.nonEmpty)
    assertNoDiffOrPrintExpected(
      err.replaceAll("(missing symbol: .*?) .*", "$1"),
      """|missing symbol: java
         |missing symbol: scala.reflect.macros.whitebox
         |missing symbol: scala.reflect.macros.blackbox
         |missing symbol: scala.reflect.macros.Aliases
         |missing symbol: scala.reflect.api
         |missing symbol: scala.reflect.macros.Universe
         |NOTE. To fix 'missing symbol' errors please provide a complete --classpath or --dependency-classpath. The provided classpath or classpaths should include the Scala library as well as JDK jars such as rt.jar.
      """.stripMargin
    )
  }

  test("missing symbol 2") {
    val tmp = Files.createTempDirectory("a_")
    tmp.toFile.deleteOnExit()
    val aclassFrom = Paths.get(BuildInfo.databaseClasspath).resolve("A.class")
    val aclassTo = tmp.resolve("A.class")
    Files.copy(aclassFrom, aclassTo)

    val (result, out, err) = CliSuite.withReporter { reporter =>
      val classpath = Classpath(AbsolutePath(tmp))
      Metacp.process(settings.withClasspath(classpath), reporter)
    }
    assert(result.classpath.isEmpty)
    assertNoDiffOrPrintExpected(
      out,
      s"""|{
          |  "status": {
          |    "$tmp": ""
          |  },
          |  "scalaLibrarySynthetics": ""
          |}
          |""".stripMargin
    )
    assertNoDiffOrPrintExpected(
      err,
      s"""|missing symbol: scala in $tmp
          |NOTE. To fix 'missing symbol' errors please provide a complete --classpath or --dependency-classpath. The provided classpath or classpaths should include the Scala library as well as JDK jars such as rt.jar.
      """.stripMargin
    )
  }

  test("missing symbol 3") {
    val output = Files.createTempDirectory("metacp")
    output.toFile.deleteOnExit()
    val resources = Paths.get("tests", "jvm", "src", "test", "resources")
    val manifest = resources.resolve("manifest.jar")
    val settings = Settings()
      .withOut(AbsolutePath(output))
      .withClasspath(Classpath(AbsolutePath(manifest)))

    assert(!Files.list(output).iterator.hasNext)
    val (result, out, err) = CliSuite.withReporter { reporter =>
      Metacp.process(settings, reporter)
    }
    assert(result.classpath.isEmpty)
    assertNoDiffOrPrintExpected(
      out,
      s"""|{
          |  "status": {
          |    "${AbsolutePath(manifest)}": ""
          |  },
          |  "scalaLibrarySynthetics": ""
          |}
          |""".stripMargin
    )
    assertNoDiffOrPrintExpected(
      err,
      s"""|missing symbol: scala in ${AbsolutePath(manifest)}
          |NOTE. To fix 'missing symbol' errors please provide a complete --classpath or --dependency-classpath. The provided classpath or classpaths should include the Scala library as well as JDK jars such as rt.jar.
      """.stripMargin
    )
    // TODO(olafurpg) fix this assertion before merging PR!
    // assert(!Files.list(output).iterator.hasNext)
  }

  test("missing symbol 4") {
    val input = Files.createTempDirectory("a_")
    input.toFile.deleteOnExit()
    val aclassFrom = Paths.get(BuildInfo.databaseClasspath).resolve("A.class")
    val aclassTo = input.resolve("A.class")
    Files.copy(aclassFrom, aclassTo)

    val output = Files.createTempDirectory("out_")
    output.toFile.deleteOnExit()
    val settings = Settings()
      .withOut(AbsolutePath(output))
      .withClasspath(Classpath(AbsolutePath(input)))
      .withStubBrokenSignatures(true)
      .withLogBrokenSignatures(true)

    val (result, out, err) = CliSuite.withReporter { reporter =>
      Metacp.process(settings, reporter)
    }
    assert(result.isSuccess)
    assertNoDiffOrPrintExpected(
      err,
      s"""|broken signature for _empty_/A#: missing symbol: scala
          |broken signature for _empty_/A#b().: missing symbol: <empty>.B
      """.stripMargin
    )
  }
}


text:
require 'core/spec_helper'

describe ZendeskAPI::DataResource do
  specify "singular resource name" do
    expect(ZendeskAPI::Ticket.singular_resource_name).to eq("ticket")
    expect(ZendeskAPI::TicketField.singular_resource_name).to eq("ticket_field")
  end

  specify "resource name" do
    expect(ZendeskAPI::Ticket.resource_name).to eq("tickets")
    expect(ZendeskAPI::TicketField.resource_name).to eq("ticket_fields")
    expect(ZendeskAPI::Category.resource_name).to eq("categories")
  end

  context "association" do
    subject { ZendeskAPI::TestResource.new(client, :id => 1) }
    let(:options) { {} }

    before(:each) do
      ZendeskAPI::TestResource.has :nil, options.merge(:class => ZendeskAPI::NilDataResource)
    end

    it "should try and find non-existent object" do
      stub_json_request(:get, %r{test_resources/1/nil}, json(:nil_data_resource => {}))

      expect(subject.nil).to be_instance_of(ZendeskAPI::NilDataResource)
    end

    context "inline => true" do
      let(:options) { { :inline => true } }

      it "should not try and find non-existent object" do
        subject.nil
      end
    end
  end

  context "user" do
    context "with first order attributes" do
      subject { ZendeskAPI::TestResource.new(client) }
      before(:each) { subject.attributes[:priority] = "normal" }

      it "should be able to access underlying attributes" do
        expect(subject.priority).to eq("normal")
      end

      it "should be able to change underlying attributes" do
        expect { subject.priority = "urgent" }.to_not raise_error
      end

      it "should be able to iterate over underlying attributes" do
        expect do
          subject.map do |k, v|
            [k.to_sym, v]
          end
        end.to_not raise_error
      end
    end

    context "with second order attributes" do
      subject { ZendeskAPI::TestResource.new(client) }
      before(:each) { subject.priority = "normal" }

      it "should be able to change underlying attributes" do
        expect(subject.priority).to eq("normal")
      end

      it "should be able to change underlying attributes" do
        expect { subject.priority = "urgent" }.to_not raise_error
      end

      it "should be able to iterate over underlying attributes" do
        expect do
          subject.map do |k, v|
            [k.to_sym, v]
          end
        end.to_not raise_error
      end
    end
  end

  context "has" do
    before(:each) { ZendeskAPI::TestResource.has ZendeskAPI::TestResource }

    context "class methods" do
      subject { ZendeskAPI::TestResource }

      it "should define a method with the same name" do
        expect(subject.instance_methods.map(&:to_s)).to include("test_resource")
      end

      context "with explicit class name" do
        before(:all) { ZendeskAPI::TestResource.has :baz, :class => ZendeskAPI::TestResource }

        it "should define a method with the same name" do
          expect(subject.instance_methods.map(&:to_s)).to include("baz")
        end
      end
    end

    context "instance method" do
      context "with no side-loading" do
        subject { ZendeskAPI::TestResource.new(client, :id => 1, :test_resource_id => 1) }
        before(:each) { stub_json_request(:get, %r{test_resources/\d+}, json(:test_resource => {})) }

        it "should attempt to grab the resource from the host" do
          expect(subject.test_resource).to be_instance_of(ZendeskAPI::TestResource)
        end

        it "should pass the path on to the resource" do
          expect(subject.test_resource.path).to eq("test_resources")
        end

        context "with a client error" do
          before(:each) { stub_request(:get, %r{test_resources/\d+}).to_return(:status => 500) }

          it "should handle it properly" do
            expect { silence_logger { expect(subject.test_resource).to be_nil } }.to_not raise_error
          end
        end

        context "with an explicit path set" do
          before(:each) do
            ZendeskAPI::TestResource.has ZendeskAPI::TestResource, :path => "blergh"
            stub_json_request(:get, %r{blergh/\d+}, json(:test_resource => {}))
          end

          it "should call the right path" do
            expect(subject.test_resource).to be_instance_of(ZendeskAPI::TestResource)
          end
        end
      end

      context "with side-loading of resource" do
        let(:test_resource) { { :message => "FOO_OBJ" } }
        subject { ZendeskAPI::TestResource.new(client, :test_resource => test_resource).test_resource }

        it "should load the correct instance" do
          expect(subject).to be_instance_of(ZendeskAPI::TestResource)
        end

        it "should load foo from the hash" do
          expect(subject.message).to eq("FOO_OBJ")
        end
      end

      context "with side-loading of id" do
        subject { ZendeskAPI::TestResource.new(client, :test_resource_id => 1) }
        before(:each) do
          stub_json_request(:get, %r{test_resources/1}, json("test_resource" => {}))
        end

        it "should find foo_id and load it from the api" do
          subject.test_resource
        end

        it "should handle nil response from find api" do
          expect(ZendeskAPI::TestResource).to receive(:find).twice.and_return(nil)
          expect(subject.test_resource).to be_nil
          subject.test_resource
        end
      end
    end
  end

  context "has_many" do
    before(:each) { ZendeskAPI::TestResource.has_many ZendeskAPI::TestResource }

    context "class methods" do
      subject { ZendeskAPI::TestResource }

      it "should define a method with the same name" do
        expect(subject.instance_methods.map(&:to_s)).to include("test_resources")
      end

      context "with explicit class name" do
        before(:each) { ZendeskAPI::TestResource.has_many :cats, :class => ZendeskAPI::TestResource }

        it "should define a method with the same name" do
          expect(subject.instance_methods.map(&:to_s)).to include("cats")
        end
      end
    end

    context "instance method" do
      context "with no side-loading" do
        subject { ZendeskAPI::TestResource.new(client, :id => 1) }

        it "should not attempt to grab the resource from the host" do
          expect(subject.test_resources).to be_instance_of(ZendeskAPI::Collection)
        end

        it "should pass the path on to the resource" do
          expect(subject.test_resources.path).to eq("test_resources/1/test_resources")
        end

        context "with an explicit path set" do
          before(:each) do
            ZendeskAPI::TestResource.has_many ZendeskAPI::TestResource, :path => "blargh"
          end

          it "should call the right path" do
            expect(subject.test_resources.path).to eq("test_resources/1/blargh")
          end
        end
      end

      context "with side-loading of resource" do
        let(:test_resources) { [{ :message => "FOO_OBJ" }] }
        subject { ZendeskAPI::TestResource.new(client, :test_resources => test_resources).test_resources.first }

        it "should properly create instance" do
          expect(subject.message).to eq("FOO_OBJ")
        end

        it "should map bars onto TestResource class" do
          expect(subject).to be_instance_of(ZendeskAPI::TestResource)
        end
      end

      context "with side-loading of id" do
        let(:test_resource_ids) { [1, 2, 3] }
        subject { ZendeskAPI::TestResource.new(client, :test_resource_ids => test_resource_ids) }

        it "should find foo_id and load it from the api" do
          expect(ZendeskAPI::TestResource).to receive(:find).with(client, kind_of(Hash)).exactly(test_resource_ids.length).times
          subject.test_resources
        end

        it "should handle nil response from find api" do
          expect(ZendeskAPI::TestResource).to receive(:find).with(client, kind_of(Hash)).exactly(test_resource_ids.length).times.and_return(nil)
          expect(subject.test_resources).to be_empty
          subject.test_resources # Test expectations
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { replace } from 'connected-react-router';
import { RootState } from '../reducers';

import Page from './Page';
import LoginOrRegisterContainer from '../containers/LoginOrRegister';

const LoginOrRegister = () => {
  const { authenticated } = useSelector((state: RootState) => state.user);
  const dispatch = useDispatch();

  /*
   * Redirect to '/' if is already logged in.
   */
  useEffect(() => {
    if (authenticated) {
      dispatch(replace({ pathname: '/' }));
    }
  }, []);

  const pageTitle = () => {
    return 'LoginOrRegister | reactGo';
  };

  const pageMeta = () => {
    return [
      { name: 'description', content: 'A reactGo example of a login or register page' },
    ];
  };

  const pageLink = () => {
    return [];
  };

  const getMetaData = () => ({
    title: pageTitle(),
    meta: pageMeta(),
    link: pageLink(),
  });

  return (
    <Page {...getMetaData()}>
      <LoginOrRegisterContainer />
    </Page>
  );
};

export default LoginOrRegister;


text:
import {GivenAnswer} from "./givenAnswers.model";
export class GameResult{
    _id : string;
    quizId : string;
    givenAnswers : {[questionNo : number] : GivenAnswer[]} = {};
}


text:
@implementation ChannelsDataSource

- (id)initWithAudioSystem:(AudioSystem*)newAudioSystem
{
    [newAudioSystem retain];

    audioSystem = newAudioSystem;

    return self;
}

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

- (int)numberOfRowsInTableView:(NSTableView*)tableView
{
    return 16;
}

- (id)tableView:(NSTableView*)tableView objectValueForTableColumn:(NSTableColumn*)column row:(int)rowIndex
{
    if ([[column identifier] isEqualToString:@"channel"]) {
        return [NSString stringWithFormat:@"%d", rowIndex+1];
    }
    else {
        return [audioSystem nameOfInstrument:[audioSystem currentInstrumentOnChannel:rowIndex]];
    }
}

@end


text:
#ifdef _WIN32
#if defined _DEBUG
#pragma comment(lib,"WidgetFactoryd.lib")
#else
#pragma comment(lib,"WidgetFactory.lib")
#endif
#endif


text:
[![Build Status](https://travis-ci.org/PhoenixMachina/SapphireORM.svg?branch=master)](https://travis-ci.org/PhoenixMachina/SapphireORM)
[![Licence MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)

A Julia ORM.

How to add it to your project :

```
Pkg.clone("https://github.com/PhoenixMachina/SapphireORM.git")
```

# Using it
Here's how to call the constructor :
```
Sapphire(username, password, dbname, option, host, driver)
```


text:
require "spec_helper"

require "fetchable"

describe Fetchable do
  subject(:fetchable) {
    double(:fetchable, :[] => fetched_object).extend(Fetchable)
  }

  let(:fetched_object) { double(:fetched_object) }
  let(:fetch_key)      { double(:fetch_key) }

  describe "#fetch" do
    it "delegates to the fetchable's finder method" do
      fetchable.fetch(fetch_key)

      expect(fetchable).to have_received(:[]).with(fetch_key)
    end

    context "when entry for key exists" do
      it "does not execute the block" do
        expect {
          fetchable.fetch(fetch_key) { raise "This block must not run" }
        }.not_to raise_error
      end

      it "returns the entry from the fetchable" do
        expect(fetchable.fetch(fetch_key)).to be fetched_object
      end
    end

    context "when the enrty for the key comes back false" do
      let(:fetched_object) { false }

      it "does not execute the block" do
        expect {
          fetchable.fetch(fetch_key) { raise "This block must not run" }
        }.not_to raise_error
      end

      it "returns the entry from the fetchable" do
        expect(fetchable.fetch(fetch_key)).to be fetched_object
      end
    end

    context "when entry for key does not exist" do
      let(:fetched_object) { nil }

      context "when a default argument is given" do
        let(:default) { double(:default) }

        it "returns the default" do
          expect(fetchable.fetch(fetch_key, default)).to be default
        end

        context "when default argument is nil" do
          it "returns nil" do
            expect(fetchable.fetch(fetch_key, nil)).to be nil
          end
        end

        context "when default argument is false" do
          it "returns false" do
            expect(fetchable.fetch(fetch_key, false)).to be false
          end
        end
      end

      context "when a block is given" do
        let(:spy) { double(:spy, :block_was_called => block_return_value) }
        let(:block) { lambda { |key| spy.block_was_called(key) } }
        let(:block_return_value) { double(:block_return_value) }

        it "returns the result of block" do
          expect(fetchable.fetch(fetch_key, &block)).to be block_return_value
        end

        it "yields the key to the block" do
          fetchable.fetch(fetch_key, &block)
          expect(spy).to have_received(:block_was_called).with(fetch_key)
        end
      end

      context "no default or block given" do
        it "raises record not found" do
          expect{ fetchable.fetch(fetch_key) }.to raise_error(KeyError, "key not found #{fetch_key}")
        end
      end
    end

    context "when both block and default argument is given" do
      it "raises ArgumentError" do
        expect{ fetchable.fetch(fetch_key, nil) {} }.to raise_error(ArgumentError)
      end
    end
  end
end


text:
/*
 * ELF types, defined in the "enum Elf_Type" API.
 *
 * The members of the list form a 2-tuple: (name, C-type-suffix).
 * + name is an Elf_Type symbol without the ELF_T_ prefix.
 * + C-type-suffix is the suffix for Elf32_ and Elf64_ type names.
 */

/*
 * DEFINE_STRUCT(NAME,MEMBERLIST...)
 *
 * Map a type name to its members.
 *
 * Each member-list element comprises of pairs of (field name, type),
 * in the sequence used in the file representation of NAME.
 *
 * Each member list element comprises a pair containing a field name
 * and a basic type.  Basic types include IDENT, HALF, WORD, LWORD,
 * ADDR{32,64}, OFF{32,64}, SWORD, XWORD, SXWORD.
 *
 * The last element of a member list is the null element: _,_.
 */

/*-
 * Copyright (c) 2006,2008-2011 Joseph Koshy
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS `AS IS' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <libelf.h>

#include "_libelf.h"

ELFTC_VCSID("$Id: libelf_fsize.m4 2225 2011-11-26 18:55:54Z jkoshy $");

/* WARNING: GENERATED FROM libelf_fsize.m4. */

/*
 * Create an array of file sizes from the elf_type definitions
 */

struct fsize {
	size_t fsz32;
	size_t fsz64;
};

static struct fsize fsize[ELF_T_NUM] = {
[ELF_T_ADDR] = { .fsz32 = sizeof(Elf32_Addr), .fsz64 = sizeof(Elf64_Addr) },

[ELF_T_BYTE] = { .fsz32 = 1, .fsz64 = 1 },

[ELF_T_CAP] = { .fsz32 = sizeof(Elf32_Word)+sizeof(Elf32_Word)+0, .fsz64 = sizeof(Elf64_Xword)+sizeof(Elf64_Xword)+0 },

[ELF_T_DYN] = { .fsz32 = sizeof(Elf32_Sword)+sizeof(Elf32_Word)+0, .fsz64 = sizeof(Elf64_Sxword)+sizeof(Elf64_Xword)+0 },

[ELF_T_EHDR] = { .fsz32 = EI_NIDENT+sizeof(Elf32_Half)+sizeof(Elf32_Half)+sizeof(Elf32_Word)+sizeof(Elf32_Addr)+sizeof(Elf32_Off)+sizeof(Elf32_Off)+sizeof(Elf32_Word)+sizeof(Elf32_Half)+sizeof(Elf32_Half)+sizeof(Elf32_Half)+sizeof(Elf32_Half)+sizeof(Elf32_Half)+sizeof(Elf32_Half)+0, .fsz64 = EI_NIDENT+sizeof(Elf64_Half)+sizeof(Elf64_Half)+sizeof(Elf64_Word)+sizeof(Elf64_Addr)+sizeof(Elf64_Off)+sizeof(Elf64_Off)+sizeof(Elf64_Word)+sizeof(Elf64_Half)+sizeof(Elf64_Half)+sizeof(Elf64_Half)+sizeof(Elf64_Half)+sizeof(Elf64_Half)+sizeof(Elf64_Half)+0 },

[ELF_T_GNUHASH] = { .fsz32 = 1, .fsz64 = 1 },

[ELF_T_HALF] = { .fsz32 = sizeof(Elf32_Half), .fsz64 = sizeof(Elf64_Half) },

[ELF_T_LWORD] = { .fsz32 = sizeof(Elf32_Lword), .fsz64 = sizeof(Elf64_Lword) },

[ELF_T_MOVE] = { .fsz32 = sizeof(Elf32_Lword)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Half)+sizeof(Elf32_Half)+0, .fsz64 = sizeof(Elf64_Lword)+sizeof(Elf64_Xword)+sizeof(Elf64_Xword)+sizeof(Elf64_Half)+sizeof(Elf64_Half)+0 },

[ELF_T_MOVEP] = { .fsz32 = 0, .fsz64 = 0 },

[ELF_T_NOTE] = { .fsz32 = 1, .fsz64 = 1 },

[ELF_T_OFF] = { .fsz32 = sizeof(Elf32_Off), .fsz64 = sizeof(Elf64_Off) },

[ELF_T_PHDR] = { .fsz32 = sizeof(Elf32_Word)+sizeof(Elf32_Off)+sizeof(Elf32_Addr)+sizeof(Elf32_Addr)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+0, .fsz64 = sizeof(Elf64_Word)+sizeof(Elf64_Word)+sizeof(Elf64_Off)+sizeof(Elf64_Addr)+sizeof(Elf64_Addr)+sizeof(Elf64_Xword)+sizeof(Elf64_Xword)+sizeof(Elf64_Xword)+0 },

[ELF_T_REL] = { .fsz32 = sizeof(Elf32_Addr)+sizeof(Elf32_Word)+0, .fsz64 = sizeof(Elf64_Addr)+sizeof(Elf64_Xword)+0 },

[ELF_T_RELA] = { .fsz32 = sizeof(Elf32_Addr)+sizeof(Elf32_Word)+sizeof(Elf32_Sword)+0, .fsz64 = sizeof(Elf64_Addr)+sizeof(Elf64_Xword)+sizeof(Elf64_Sxword)+0 },

[ELF_T_SHDR] = { .fsz32 = sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Addr)+sizeof(Elf32_Off)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+0, .fsz64 = sizeof(Elf64_Word)+sizeof(Elf64_Word)+sizeof(Elf64_Xword)+sizeof(Elf64_Addr)+sizeof(Elf64_Off)+sizeof(Elf64_Xword)+sizeof(Elf64_Word)+sizeof(Elf64_Word)+sizeof(Elf64_Xword)+sizeof(Elf64_Xword)+0 },

[ELF_T_SWORD] = { .fsz32 = sizeof(Elf32_Sword), .fsz64 = sizeof(Elf64_Sword) },

[ELF_T_SXWORD] = { .fsz32 = 0, .fsz64 = sizeof(Elf64_Sxword) },

[ELF_T_SYMINFO] = { .fsz32 = sizeof(Elf32_Half)+sizeof(Elf32_Half)+0, .fsz64 = sizeof(Elf64_Half)+sizeof(Elf64_Half)+0 },

[ELF_T_SYM] = { .fsz32 = sizeof(Elf32_Word)+sizeof(Elf32_Addr)+sizeof(Elf32_Word)+1+1+sizeof(Elf32_Half)+0, .fsz64 = sizeof(Elf64_Word)+1+1+sizeof(Elf64_Half)+sizeof(Elf64_Addr)+sizeof(Elf64_Xword)+0 },

[ELF_T_VDEF] = { .fsz32 = 1, .fsz64 = 1 },

[ELF_T_VNEED] = { .fsz32 = 1, .fsz64 = 1 },

[ELF_T_WORD] = { .fsz32 = sizeof(Elf32_Word), .fsz64 = sizeof(Elf64_Word) },

[ELF_T_XWORD] = { .fsz32 = 0, .fsz64 = sizeof(Elf64_Xword) },

};

size_t
_libelf_fsize(Elf_Type t, int ec, unsigned int v, size_t c)
{
	size_t sz;

	sz = 0;
	if (v != EV_CURRENT)
		LIBELF_SET_ERROR(VERSION, 0);
	else if ((int) t < ELF_T_FIRST || t > ELF_T_LAST)
		LIBELF_SET_ERROR(ARGUMENT, 0);
	else {
		sz = ec == ELFCLASS64 ? fsize[t].fsz64 : fsize[t].fsz32;
		if (sz == 0)
			LIBELF_SET_ERROR(UNIMPL, 0);
	}

	return (sz*c);
}


text:
package com.google.idea.testing.cidr;

import com.google.common.collect.ImmutableSet;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.UserDataHolderBase;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.cidr.lang.CLanguageKind;
import com.jetbrains.cidr.lang.OCFileTypeHelpers;
import com.jetbrains.cidr.lang.OCLanguageKind;
import com.jetbrains.cidr.lang.toolchains.CidrFileSeparators;
import com.jetbrains.cidr.lang.workspace.OCCompilerSettings;
import com.jetbrains.cidr.lang.workspace.OCLanguageKindCalculator;
import com.jetbrains.cidr.lang.workspace.OCResolveConfiguration;
import com.jetbrains.cidr.lang.workspace.OCResolveConfigurationImpl;
import com.jetbrains.cidr.lang.workspace.OCVariant;
import com.jetbrains.cidr.lang.workspace.headerRoots.HeadersSearchRoot;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.jetbrains.annotations.NotNull;

/** Stub {@link OCResolveConfiguration} for testing. */
public abstract class StubOCResolveConfigurationBase extends UserDataHolderBase
    implements OCResolveConfiguration {

  private final Project project;
  private final StubOCCompilerSettings compilerSettings;

  StubOCResolveConfigurationBase(Project project) {
    this.project = project;
    this.compilerSettings = new StubOCCompilerSettings(project);
  }

  public void setLibraryIncludeRoots(List<HeadersSearchRoot> searchRoots) {
    compilerSettings.setLibraryIncludeRoots(searchRoots);
  }

  @Override
  public Project getProject() {
    return project;
  }

  @Override
  public String getUniqueId() {
    return getName();
  }

  @Override
  public String getName() {
    return "Stub Resolve Configuration";
  }

  @Nullable
  @Override
  public OCVariant getVariant() {
    return null;
  }

  @Override
  public String getDisplayName() {
    return getName();
  }

  @Override
  public Collection<VirtualFile> getSources() {
    return Collections.emptyList();
  }

  @Override
  public Collection<String> getSourceUrls() {
    return Collections.emptyList();
  }

  @Nullable
  @Override
  public OCLanguageKind getDeclaredLanguageKind(VirtualFile sourceOrHeaderFile) {
    String fileName = sourceOrHeaderFile.getName();
    if (OCFileTypeHelpers.isSourceFile(fileName)) {
      return getLanguageKind(sourceOrHeaderFile);
    }
    return getMaximumLanguageKind();
  }

  @Nullable
  @Override
  public OCLanguageKind getDeclaredLanguageKind(String sourceFileUrl) {
    return null;
  }

  private OCLanguageKind getMaximumLanguageKind() {
    return CLanguageKind.CPP;
  }

  @Override
  public Set<OCLanguageKind> getEnabledLanguageKinds() {
    return ImmutableSet.of(CLanguageKind.C, CLanguageKind.CPP);
  }

  @Override
  public Stream<OCCompilerSettings> getAllCompilerSettings() {
    return Stream.of();
  }

  private OCLanguageKind getLanguageKind(VirtualFile sourceFile) {
    OCLanguageKind kind = OCLanguageKindCalculator.tryFileTypeAndExtension(project, sourceFile);
    return kind != null ? kind : getMaximumLanguageKind();
  }

  @Override
  public OCCompilerSettings getCompilerSettings(
      OCLanguageKind ocLanguageKind, @Nullable VirtualFile virtualFile) {
    return compilerSettings;
  }

  @Override
  public OCCompilerSettings getCompilerSettings(OCLanguageKind languageKind, String sourceFileUrl) {
    return compilerSettings;
  }

  @Override
  public int compareTo(OCResolveConfiguration o) {
    return OCResolveConfigurationImpl.compareConfigurations(this, o);
  }

  @Override
  public CidrFileSeparators getFileSeparators() {
    return CidrFileSeparators.UNIX;
  }

  @Override
  public boolean hasSourceFile(@NotNull VirtualFile virtualFile) {
    return false;
  }
}


text: #CopyDeletePaste.py


text:
rm core
./tester
gdb tester core


text:
package sourcecoded.quantum.item;

import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import sourcecoded.core.crafting.ICraftableItem;
import sourcecoded.quantum.api.vacuum.VacuumRegistry;
import sourcecoded.quantum.crafting.vacuum.VacuumEntropicStar;

public class ItemEntropicStar extends ItemQuantum implements ICraftableItem {

    public ItemEntropicStar() {
        this.setTextureName("star/starAll");
        this.setUnlocalizedName("itemEntropicStar");
        setMaxDamage(0);
        setMaxStackSize(8);
    }

    public boolean hasEffect(ItemStack itemStack, int pass) {
        return true;
    }

    @Override
    public IRecipe[] getRecipes(Item item) {
        VacuumRegistry.addRecipe(new VacuumEntropicStar());
        return new IRecipe[0];
    }
}


text:
title: Homemade Chilly Chicken Pizza
date: 2015-03-14 17:49:00 Z
permalink: "/homemade-chilly-chicken-pizza/"
categories:
- Non Vegetarian
id: 59
author: admin
layout: post
guid: http://cookingteach.com/homemade-chilly-chicken-pizza/
---

[![](http://2.bp.blogspot.com/-qHrH_q1GaT0/VQRmpUQJvQI/AAAAAAAAAJE/k510oclAc-U/s1600/2.jpg)](http://2.bp.blogspot.com/-qHrH_q1GaT0/VQRmpUQJvQI/AAAAAAAAAJE/k510oclAc-U/s1600/2.jpg)

## Homemade Chilly Chicken Pizza

**Chilly Chicken Pizza** is really very crispy and tasty.Its very special for all **non veg [pizza](http://en.wikipedia.org/wiki/Pizza "Pizza")** lovers.Its very **easy** to make.You can make it at home and enjoy it.In this am using a **topping** of [chilli chicken](http://en.wikipedia.org/wiki/Chilli_chicken "Chilli chicken") for make it tasty.

## _Ingredients:_

*   2 ready-made pizza basses
*   150 gm pizza cheese (grated)

### [Marinate](http://en.wikipedia.org/wiki/Marination "Marination") For 30 Minutes

*   1 boneless chicken breast (150 gm) cut into 1/4″ pieces
*   1/2 onion finely chopped
*   1/2 capsicum finely chopped
*   1 tbsp red chilli paste
*   1 tbsp [soya sauce](http://en.wikipedia.org/wiki/Soy_sauce "Soy sauce")
*   1 tbsp vinegar
*   a pinch of ajinomoto (optional)
*   1/2 tbsp cornflour
*   1/2 tbsp salt
*   1/2 tbsp [black pepper](http://en.wikipedia.org/wiki/Black_pepper "Black pepper")
*   1 tbsp oregano
*   1 tbsp oil
*   4 flakes garlic finely chopped
*   1/2 cup ready made [tomato puree](http://en.wikipedia.org/wiki/Tomato_pur%C3%A9e "Tomato purée")
*   3 tbsp [tomato ketchup](http://en.wikipedia.org/wiki/Ketchup "Ketchup")

## _Method:_

*   In a dish **marinate** chicken with all ingredients for **1/2 hour** or even more.
*   **Cover chicken** and microwave it for 3 minutes.
*   **Brush** the bottom of the **pizza base** with oil and place bottom side up on the greased **tawa** placed on a high rack.
*   **Grill** for 3-4 minutes till golden and crispy.
*   To assemble, **place** pizza on a **wire rack** or greased tawa.
*   **Sprinkle** some **cheese.**
*   **Spread** chilli chicken.
*   **Sprinkle** the remaining **cheese**.
*   **Grill** again for 4 minutes.


text:
using testing::_;
using testing::Invoke;
using testing::NotNull;

namespace chromeos {

namespace tether {

namespace {

// Used to verify the KeepAliveOperation notifies the observer when appropriate.
class MockOperationObserver : public KeepAliveOperation::Observer {
 public:
  MockOperationObserver() = default;
  ~MockOperationObserver() = default;

  MOCK_METHOD2(OnOperationFinishedRaw,
               void(multidevice::RemoteDeviceRef, DeviceStatus*));

  void OnOperationFinished(multidevice::RemoteDeviceRef remote_device,
                           std::unique_ptr<DeviceStatus> device_status) {
    OnOperationFinishedRaw(remote_device, device_status.get());
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(MockOperationObserver);
};

}  // namespace

class KeepAliveOperationTest : public testing::Test {
 protected:
  KeepAliveOperationTest()
      : local_device_(multidevice::RemoteDeviceRefBuilder()
                          .SetPublicKey("local device")
                          .Build()),
        remote_device_(multidevice::CreateRemoteDeviceRefListForTest(1)[0]) {}

  void SetUp() override {
    fake_device_sync_client_ =
        std::make_unique<device_sync::FakeDeviceSyncClient>();
    fake_device_sync_client_->set_local_device_metadata(local_device_);
    fake_secure_channel_client_ =
        std::make_unique<secure_channel::FakeSecureChannelClient>();

    operation_ = ConstructOperation();
    operation_->Initialize();

    ConnectAuthenticatedChannelForDevice(remote_device_);
  }

  std::unique_ptr<KeepAliveOperation> ConstructOperation() {
    auto connection_attempt =
        std::make_unique<secure_channel::FakeConnectionAttempt>();
    connection_attempt_ = connection_attempt.get();
    fake_secure_channel_client_->set_next_listen_connection_attempt(
        remote_device_, local_device_, std::move(connection_attempt));

    auto operation = base::WrapUnique(
        new KeepAliveOperation(remote_device_, fake_device_sync_client_.get(),
                               fake_secure_channel_client_.get()));
    operation->AddObserver(&mock_observer_);

    // Prepare the disconnection timeout timer to be made for the remote device.
    auto test_timer_factory = std::make_unique<TestTimerFactory>();
    test_timer_factory->set_device_id_for_next_timer(
        remote_device_.GetDeviceId());
    operation->SetTimerFactoryForTest(std::move(test_timer_factory));

    test_clock_.SetNow(base::Time::UnixEpoch());
    operation->SetClockForTest(&test_clock_);

    return operation;
  }

  void ConnectAuthenticatedChannelForDevice(
      multidevice::RemoteDeviceRef remote_device) {
    auto fake_client_channel =
        std::make_unique<secure_channel::FakeClientChannel>();
    connection_attempt_->NotifyConnection(std::move(fake_client_channel));
  }

  const multidevice::RemoteDeviceRef local_device_;
  const multidevice::RemoteDeviceRef remote_device_;

  secure_channel::FakeConnectionAttempt* connection_attempt_;
  std::unique_ptr<device_sync::FakeDeviceSyncClient> fake_device_sync_client_;
  std::unique_ptr<secure_channel::FakeSecureChannelClient>
      fake_secure_channel_client_;

  std::unique_ptr<KeepAliveOperation> operation_;

  base::SimpleTestClock test_clock_;
  MockOperationObserver mock_observer_;
  base::HistogramTester histogram_tester_;

 private:
  DISALLOW_COPY_AND_ASSIGN(KeepAliveOperationTest);
};

// Tests that the KeepAliveTickle message is sent to the remote device once the
// communication channel is connected and authenticated.
TEST_F(KeepAliveOperationTest, KeepAliveTickleSentOnceAuthenticated) {
  std::unique_ptr<KeepAliveOperation> operation = ConstructOperation();
  operation->Initialize();

  // Create the client channel for the remote device.
  auto fake_client_channel =
      std::make_unique<secure_channel::FakeClientChannel>();

  // No requests as a result of creating the client channel.
  auto& sent_messages = fake_client_channel->sent_messages();
  EXPECT_EQ(0u, sent_messages.size());

  // Connect and authenticate the client channel.
  connection_attempt_->NotifyConnection(std::move(fake_client_channel));

  // Verify the KeepAliveTickle message is sent.
  auto message_wrapper = std::make_unique<MessageWrapper>(KeepAliveTickle());
  std::string expected_payload = message_wrapper->ToRawMessage();
  EXPECT_EQ(1u, sent_messages.size());
  EXPECT_EQ(expected_payload, sent_messages[0].first);
}

// Tests that observers are notified when the operation has completed, signified
// by the OnMessageReceived handler being called.
TEST_F(KeepAliveOperationTest, NotifiesObserversOnResponse) {
  DeviceStatus test_status = CreateDeviceStatusWithFakeFields();

  // Verify that the observer is called with the correct parameters.
  EXPECT_CALL(mock_observer_, OnOperationFinishedRaw(remote_device_, NotNull()))
      .WillOnce(Invoke([this, &test_status](multidevice::RemoteDeviceRef device,
                                            DeviceStatus* status) {
        EXPECT_EQ(remote_device_, device);
        EXPECT_EQ(test_status.SerializeAsString(), status->SerializeAsString());
      }));

  KeepAliveTickleResponse response;
  response.mutable_device_status()->CopyFrom(test_status);
  std::unique_ptr<MessageWrapper> message(new MessageWrapper(response));
  operation_->OnMessageReceived(std::move(message), remote_device_);
}

TEST_F(KeepAliveOperationTest, RecordsResponseDuration) {
  static constexpr base::TimeDelta kKeepAliveTickleResponseTime =
      base::TimeDelta::FromSeconds(3);

  EXPECT_CALL(mock_observer_, OnOperationFinishedRaw(remote_device_, _));

  // Advance the clock in order to verify a non-zero response duration is
  // recorded and verified (below).
  test_clock_.Advance(kKeepAliveTickleResponseTime);

  std::unique_ptr<MessageWrapper> message(
      new MessageWrapper(KeepAliveTickleResponse()));
  operation_->OnMessageReceived(std::move(message), remote_device_);

  histogram_tester_.ExpectTimeBucketCount(
      "InstantTethering.Performance.KeepAliveTickleResponseDuration",
      kKeepAliveTickleResponseTime, 1);
}

}  // namespace tether

}  // namespace chromeos


text:
#import <Foundation/Foundation.h>

#import <FBControlCore/FBControlCore.h>

@class DVTiOSDevice;
@class FBDeviceSet;
@class FBProductBundle;
@class FBTestRunnerConfiguration;
@protocol FBDeviceOperator;
@protocol FBControlCoreLogger;

NS_ASSUME_NONNULL_BEGIN

/**
 Class that wraps DVTAbstractiOSDevice and it's device operator that can perform actions on it.
 */
@interface FBDevice : NSObject <FBiOSTarget>

/**
 The Device Set to which the Device Belongs.
 */
@property (nonatomic, weak, readonly) FBDeviceSet *set;

/**
 The Logger to Log events with.
 */
@property (nonatomic, strong, readonly) id<FBControlCoreLogger> logger;

/**
 The DVTDevice, corresponding to the reciever.
 */
@property (nonatomic, nullable, strong, readonly) DVTiOSDevice *dvtDevice;

/**
 Device operator used to control device
 */
@property (nonatomic, nullable, strong, readonly) id<FBDeviceOperator> deviceOperator;

/**
 Device's name
 */
@property (nonatomic, copy, readonly) NSString *name;

/**
 Device's model name
 */
@property (nonatomic, copy, readonly) NSString *modelName;

/**
 Device's system Version
 */
@property (nonatomic, copy, readonly) NSString *systemVersion;

/**
 Architectures suported by device
 */
@property (nonatomic, copy, readonly) NSSet *supportedArchitectures;

/**
 Starts test manager daemon service

 @return AMDServiceConnection if the operation succeeds, otherwise NULL.
 */
- (CFTypeRef)startTestManagerServiceWithError:(NSError **)error;

@end

NS_ASSUME_NONNULL_END


text:
/*
 */

#include  <unistd.h>
#include  <stdio.h>
#include  <fcntl.h>

#include  "group.h"			/*  VNMR include file */
#include  "symtab.h"                    /*  VNMR include file */
#include  "variables.h"
#include  "config.h"

/*  This file is modified from vconfig.c  */

#ifndef VMS
#include  <sys/file.h>
#define F_OK            0       /* does file exist */
#define X_OK            1       /* is it executable by caller */
#define W_OK            2       /* writable by caller */
#define R_OK            4       /* readable by caller */
#endif

#define  SYSTEMDIR   (1<<0)
#define  CONPARFILE  (1<<1)
#define  STDPARFILE  (1<<2)
#define  TESTSFILE   (1<<3)

#define  MAXPATHL    128

/*  This define lets the program developer work with an arbitrary CONPAR
    file.  Since CONPAR would now be defined by the programmer, defining
    this symbol causes the program to assume you are debugging.  Thus
    you can access interactive mode without all the permission tests.
    Use the `display' argument to access display mode.			*/

/*  Global structures of builtin type.  */

int	interact_flag;
int	bg_flag;
int	fileStatus;
int	makestdparlink;
int	maketestslink;
int	display_flag;
char	systemdir[ MAXPATHL ] = "";
char	userdir[ MAXPATHL ] = "";	/* vfilesys.c (follow_link) */
				      /* requires the userdir array */

/*  Store the name of the CONPAR file here.	*/

char      conparfil[ MAXPATHL ];
char      conFile[ MAXPATHL ];

struct _hw_config   console_data;

char	*cwb_file;

extern char RevID[];
extern char RevDate[];
extern char CDNT[];

#ifndef VMS
	extern char	*getenv();
#else
	extern char	*vms_getenv();
#endif

/************************************************************************/

#ifndef VMS

/*  These programs might get called when VNMR config exits.
    The public program is configExit.

    configExit is called from the GUI programs.  It does not
    itself call exit, but returns to the GUI and assumes the
    GUI calls the exit program.

    Unlike the GUI version (configExit_sunview, etc.), this
    program assumes the current data should be written out.	*/

putSysGlobalVals( fnptr )
char *fnptr;
{
	int	r;

	r = P_save(SYSTEMGLOBAL, fnptr);
	if (r != 0)
	  fprintf( stderr,
		"failed to write system global parameters to %s\n", fnptr
	  );
}

int
makelink( link_name )
char *link_name;
{
	char	base_path[ MAXPATHL ], link_path[ MAXPATHL ], h1freq_str[ 14 ];
	int	result;
	double	h1freq_val;

	result = P_getreal( SYSTEMGLOBAL, "h1freq", &h1freq_val, 1 );
	if (result != 0) {
		fprintf( stderr, "cannot access `h1freq' parameter\n" );
		return( -1 );
	}

/*  Use %.3d format convertor to guarantee at least
    3 non-blank characters in the resulting string.	*/

	sprintf( &h1freq_str[ 0 ], "%.3d", (int) (h1freq_val+0.001) );

	strcpy( &base_path[ 0 ], &systemdir[ 0 ] );
	strcat( &base_path[ 0 ], "/par" );
	strcat( &base_path[ 0 ], &h1freq_str[ 0 ] );
	strcat( &base_path[ 0 ], "/" );
	strcat( &base_path[ 0 ], link_name );

/*  Verify the base path exists before proceeding...  */

	if (access( &base_path[0], F_OK) != 0) {
		fprintf( stderr, "entry %s doesn't exist\n", &base_path[ 0 ] );
		return( -1 );
	}

	strcpy( &link_path[ 0 ], &systemdir[ 0 ] );
	strcat( &link_path[ 0 ], "/" );
	strcat( &link_path[ 0 ], link_name );

/*  Only unlink if the link is present.  */

	if (access( &link_path[ 0 ], F_OK ) == 0)
	  if (unlink( &link_path[ 0 ])) {
		perror("unlink failure in VNMR config");
		fprintf( stderr, "failed to unlink %s\n", &link_path[ 0 ] );
		return( -1 );
	  }

	if (symlink( &base_path[ 0 ], &link_path[ 0 ] )) {
		perror("link failure in config");
		fprintf( stderr,
	    "Failed to link %s to %s", &link_path[ 0  ], &base_path[ 0 ]
		);
		return( -1 );
	}

	return( 0 );
}

#endif

/************************************************************************/

static int
process_args( argc, argv)
int argc;
char *argv[];
{
	int	iter;

	display_flag = 0;
	bg_flag = 0;
	cwb_file = NULL;
	if (argc < 2)
	  return( 0 );

	iter = 0;						/* Start at 1 */
	while (++iter < argc ) {
		if (strcmp( argv[ iter ], "display" ) == 0 ||
		    strcmp( argv[ iter ], "print" ) == 0)
		  display_flag = 1;
		else if (strcmp( argv[ iter ], "-background") == 0 ||
		    strcmp( argv[ iter ], "-bg") == 0)
		  	bg_flag = 1;
		else if (strcmp( argv[ iter ], "cwbf" ) == 0)
		{
                    iter++;
                    if (argc <= iter) {
                        fprintf( stderr, "Console writeback file requires a file name\n");
			return(-1);
		    }
		    if (cwb_file) {
                	free( cwb_file );
                	cwb_file = NULL;
        	    }
		    if ((int)strlen(argv[iter]) > 0)
		    {
			cwb_file = (char *) malloc(strlen(argv[iter]) + 1);
			if (cwb_file != NULL)
			    strcpy(cwb_file, argv[iter]);
		    }
		}
	}

	return( 0 );
}

#ifndef VMS

/*  VNMR config can run interactively only if some conditions are met:
	    write access to the VNMR system directory
	    write access to the CONPAR file
	    write access to the link "stdpar" in the VNMR system directory
	    write access to the link "tests" in the VNMR system directory
*/

static int
check_interactive_access( report_flag, cmd_name )
int report_flag;
char  *cmd_name;
{
	int	retval;
	char	conparlink[ MAXPATHL ];
	int	ival;

	retval = 0;
	if (access(&systemdir[ 0 ], W_OK) != 0) {
		if (report_flag)
		  fprintf( stderr,
    "cannot run %s interactively, no write access to %s\n",
     cmd_name, &systemdir[ 0 ]
		  );
		fileStatus |= SYSTEMDIR;
		retval = -1;
	}

	if (access( &conparfil[ 0 ], W_OK) != 0) {
		if (report_flag)
		  fprintf( stderr,
    "cannot run %s interactively, no write access to %s\n",
     cmd_name, &conparfil[ 0 ]
		  );
		fileStatus |= CONPARFILE;
		retval = -1;
	}

	return( retval );
}

#endif

int
main( argc, argv )
int argc;
char *argv[];
{
	int		ival, report_flag;
	char		*quick_ptr;

#ifndef VMS
	quick_ptr = getenv( "vnmrsystem" );
#else
	quick_ptr = vms_getenv( "vnmrsystem" );
#endif

	process_args(argc, argv);
	if (bg_flag)
	{
	    freopen("/dev/null","a", stdout);
            freopen("/dev/null","a", stderr);
	}
	if (quick_ptr == NULL)
	{
	    fprintf( stderr, "Error: env 'vnmrsystem' is not set. \n");
	    exit( 1 );
	}

	if (strlen( quick_ptr ) >= MAXPATHL-30) {
		fprintf( stderr,
	    "error starting VNMR CONFIG, value for 'vnmrsystem' is too long\n"
		);
		exit( 1 );
	}
	strcpy( &systemdir[ 0 ], quick_ptr );
	read_console_data();
        interact_flag = 1;
	report_flag = 0;

#ifdef CONPAR_FILE
	strcpy( &conparfil[ 0 ], CONPAR_FILE );
#else
#ifndef VMS
	makestdparlink = 131071;		/* Normally these links are */
	maketestslink = 131071; 		/* to be made if the command */
						/* is used interactively. */
	strcpy( &conparfil[ 0 ], &systemdir[ 0 ] );
	strcat( &conparfil[ 0 ], "/conpar" );

        ival = check_interactive_access( report_flag, "VNMR config" );
	if (ival != 0)
	    interact_flag = 0;
#else
	strcpy( &conparfil[ 0 ], &systemdir[ 0 ] );
	strcat( &conparfil[ 0 ], "conpar" );

	interact_flag = 0;		/* No interactive mode on VMS */
#endif
#endif
	getSysVals( &conparfil[ 0 ] );

/* ---  print revision ID and Date, Compiled within revdate.c --- */
        P_setstring( SYSTEMGLOBAL, "rev", &RevID[ 0 ], 1);
        P_setstring( SYSTEMGLOBAL, "revdate", &RevDate[ 0 ], 1);
	if (display_flag)
	{
	    disp_conpar(stdout);
	    if (!bg_flag)
		return;
	}

	if (bg_flag)
	{
	    if (interact_flag)
	    {
		restore_console_data();
		vconfigSaveExit();
	    }
	}
	else
	{
	   makeVconfigPanels( argc, argv );
	   vconfigLoop();
	}
}

extern symbol   **getTreeRoot();
extern varInfo   *rfindVar();
extern varInfo   *RcreateVar();

int
config_setreal( name, value, index )
char *name;
double value;
int index;
{
        symbol  **root;
        varInfo *v;

        if (root = getTreeRoot(getRoot( SYSTEMGLOBAL )))
          if (v = rfindVar( name, root )) {
                if (assignReal( value, v, index ))
                  return( 0 );
                else
                  return( -99 );
          }

/*  Create the real number parameter if it does not exist.  */

          else {
                v = RcreateVar( name, root, T_REAL );
                if (assignReal( value, v, index ))
                  return( 0 );
                else
                  return( -99 );
          }
        else
          return( -1 );                 /* No such tree (should not happen) */
}

int config_setstring( name, value, index )
char *name;
char *value;
int index;
{
        symbol  **root;
        varInfo *v;

        if (root = getTreeRoot(getRoot( SYSTEMGLOBAL )))
          if (v = rfindVar( name, root )) {
                if (assignString( value, v, index ))
                  return( 0 );
                else
                  return( -99 );
          }

/*  Create the string parameter if it does not exist.  */

          else {
                v = RcreateVar( name, root, T_STRING );
                if (assignString( value, v, index ))
                  return( 0 );
                else
                  return( -99 );
          }
        else
          return( -1 );                 /* No such tree (should not happen) */
}


text:
<?php
declare(strict_types = 1);

namespace DrdPlus\Person\Exceptions;

interface Logic extends Exception
{

}


text:
import NodeDefender

def system_status(mac_address, payload):
    operation, status = payload['stat'].split(',')
    if operation == '0' and status == '0':
        pass
    elif operation == '1' and status == '0':
        pass
    elif operation == '2' and status == '0':
        pass
    elif operation == '3':                      # Node Excluded
        if status == '0':                       # Operation successful
            NodeDefender.mqtt.command.icpe.zwave.node.list(mac_address)
    elif operation == '4' and status == '0':
        pass
    elif operation == '5':                      # Node removed
        if status == '0':                       # Operation successful
            NodeDefender.mqtt.command.icpe.zwave.node.list(mac_address)
    elif operation == '6' and status == '0':
        pass
    elif operation == '7' and status == '0':
        pass
    elif operation == '8' and status == '0':
        pass
    elif operation == '9' and status == '0':
        pass
    elif operation == '10' and status == '0':
        pass
    elif operation == '11' and status == '0':
        pass
    elif operation == '13' and status == '0':
        pass
    elif operation == '14' and status == '0':
        pass
    elif operation == '15' and status == '0':
        pass
    elif operation == '50' and status == '0':
        pass
    elif operation == '51' and status == '0':
        pass

    home_id = payload['netid']
    controller_id = payload['controllerid']

    automatic_polling = bool(eval(payload['aopoll']))
    always_reporting = bool(eval(payload['awrpt']))
    general_wakeup = payload['acwkup']
    forward_unsolicited = bool(eval(payload['unsolicit']))
    #auto_reboot = bool(eval(payload['armask']))
    auto_isolate = bool(eval(payload['autoisolate']))
    battery_warning = bool(eval(payload['bnlevel']))
    health_check_interval = payload['hcinterval']
    NodeDefender.db.icpe.update_redis(mac_address,
                                 home_id = home_id,
                                 controller_id = controller_id,
                                 automatic_polling = automatic_polling,
                                 always_reporting = always_reporting,
                                 general_wakeup = general_wakeup,
                                 forward_unsolicited = forward_unsolicited,
                                 #auto_reboot = auto_reboot,
                                 auto_isolate = auto_isolate,
                                 battery_warning = battery_warning,
                                 health_check_interval = health_check_interval)
    return True


text:
package com.shishuo.cms.plugin;

import javax.annotation.PostConstruct;

public interface Plugin {

	@PostConstruct
	public void init() throws Exception;
}


text:
'use strict';

/**
 * Module dependencies.
 */
var config = require('../config'),
	express = require('express'),
	morgan = require('morgan'),
	bodyParser = require('body-parser'),
	favicon = require('serve-favicon'),
	compress = require('compression'),
	methodOverride = require('method-override'),
	cookieParser = require('cookie-parser'),
	helmet = require('helmet'),
	flash = require('connect-flash'),
	consolidate = require('consolidate'),
	path = require('path');

/**
 * Initialize local variables
 */
module.exports.initLocalVariables = function (app) {
	// Setting application local variables
	app.locals.title = config.app.title;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.jsFiles = config.files.client.js;
	app.locals.cssFiles = config.files.client.css;

	// Passing the request url to environment locals
	app.use(function (req, res, next) {
		res.locals.host = req.protocol + '://' + req.hostname;
		res.locals.url = req.protocol + '://' + req.headers.host + req.originalUrl;
		next();
	});
};

/**
 * Initialize application middleware
 */
module.exports.initMiddleware = function (app) {
	// Showing stack errors
	app.set('showStackError', true);

	// Enable jsonp
	app.enable('jsonp callback');

	// Should be placed before express.static
	app.use(compress({
		filter: function (req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		level: 9
	}));

	// Initialize favicon middleware
	app.use(favicon('./modules/core/client/img/brand/favicon.ico'));

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		app.use(morgan('dev'));

		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded({
		extended: true
	}));
	app.use(bodyParser.json());
	app.use(methodOverride());

	// Add the cookie parser and flash middleware
	app.use(cookieParser());
	app.use(flash());
};

/**
 * Configure view engine
 */
module.exports.initViewEngine = function(app) {
	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './');
};

/**
 * Invoke modules server configuration
 */
module.exports.initModulesConfiguration = function(app) {
	config.files.server.configs.forEach(function (configPath) {
		require(path.resolve(configPath))(app);
	});
};

/**
 * Configure Helmet headers configuration
 */
module.exports.initHelmetHeaders = function (app) {
	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.xssFilter());
	app.use(helmet.nosniff());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');
};

/**
 * Configure the modules static routes
 */
module.exports.initModulesClientRoutes = function (app) {
	// Setting the app router and static folder
	app.use('/', express.static(path.resolve('./public')));

	// Globbing static routing
	config.folders.client.forEach(function (staticPath) {
		app.use(staticPath.replace('/client', ''), express.static(path.resolve('./' + staticPath)));
	});
};

/**
 * Configure the modules server routes
 */
module.exports.initModulesServerRoutes = function (app) {
	// Globbing routing files
	config.files.server.routes.forEach(function (routePath) {
		require(path.resolve(routePath))(app);
	});
};

/**
 * Configure error handling
 */
module.exports.initErrorRoutes = function (app) {
	// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
	app.use(function (err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);

		// Redirect to error page
		res.redirect('/server-error');
	});

	// Assume 404 since no middleware responded
	app.use(function (req, res) {
		// Redirect to not found page
		res.redirect('/not-found');
	});
};

/**
 * Initialize the Express application
 */
module.exports.init = function() {
	// Initialize express app
	var app = express();

	// Initialize local variables
	this.initLocalVariables(app);

	// Initialize Express middleware
	this.initMiddleware(app);

	// Initialize Express view engine
	this.initViewEngine(app);

	// Initialize Modules configuration
	this.initModulesConfiguration(app);

	// Initialize Helmet security headers
	this.initHelmetHeaders(app);

	// Initialize modules static client routes
	this.initModulesClientRoutes(app);

	// Initialize modules server routes
	this.initModulesServerRoutes(app);

	// Initialize error routes
	this.initErrorRoutes(app);

	return app;
};


text:
#include "writer/verilog/axi/axi_port.h"

#include "iroha/i_design.h"
#include "iroha/resource_params.h"
#include "writer/verilog/axi/axi_controller.h"
#include "writer/verilog/module.h"
#include "writer/verilog/port.h"
#include "writer/verilog/port_set.h"
#include "writer/verilog/table.h"
#include "writer/verilog/shared_memory.h"
#include "writer/verilog/shared_memory_accessor.h"
#include "writer/verilog/wire/wire_set.h"

namespace iroha {
namespace writer {
namespace verilog {
namespace axi {

AxiPort::AxiPort(const IResource &res, const Table &table)
  : Resource(res, table) {
  reset_polarity_ = tab_.GetModule()->GetResetPolarity();
}

void AxiPort::OutputSRAMConnection(ostream &os) {
  const string &clk = tab_.GetPortSet()->GetClk();
  const string &rst = tab_.GetPortSet()->GetReset();
  const IResource *mem = res_.GetParentResource();
  string rn = SharedMemory::GetName(*mem);
  int idx = 0;
  int excl = 0;
  const IResource *accessor;
  string addr, wdata, rdata, wen;
  if (IsExclusiveAccessor()) {
    idx = 1;
    excl = 1;
    accessor = nullptr;
    // Directly connected to port 1 (of 0 and 1).
    addr = SharedMemory::MemoryAddrPin(*mem, idx, accessor);
    wdata = SharedMemory::MemoryWdataPin(*mem, idx, accessor);
    rdata = SharedMemory::MemoryRdataPin(*mem, idx);
    wen = SharedMemory::MemoryWenPin(*mem, idx, accessor);
  } else {
    accessor = &res_;
    // Connection via WireSet.
    addr = SharedMemoryAccessor::AddrSrc(res_);
    wdata = SharedMemoryAccessor::WDataSrc(res_);
    wen = SharedMemoryAccessor::WEnSrc(res_);
    rdata = wire::Names::AccessorWire(rn, &res_, "rdata");
  }
  os << ".clk("<< clk << "), "
     << "." << AxiController::ResetName(reset_polarity_)
     << "(" << rst << "), "
     << ".sram_addr(" << addr << "), "
     << ".sram_wdata(" << wdata << "), "
     << ".sram_rdata(" << rdata << "), "
     << ".sram_wen(" << wen << "), "
     << ".sram_EXCLUSIVE(1'b" << excl << ")";
  if (excl) {
    os << ", .sram_req(/*not connected*/), .sram_ack(1'b1)";
  } else {
    os << ", .sram_req(" << wire::Names::AccessorWire(rn, &res_, "req")
       << "), .sram_ack(" << wire::Names::AccessorWire(rn, &res_, "ack")
       << ")";
  }
}

PortConfig AxiPort::GetPortConfig(const IResource &res) {
  PortConfig cfg;
  cfg.prefix = res.GetParams()->GetPortNamePrefix();
  cfg.axi_addr_width = res.GetParams()->GetAddrWidth();
  const IResource *mem_res = res.GetParentResource();
  IArray *array = mem_res->GetArray();
  cfg.sram_addr_width = array->GetAddressWidth();
  cfg.data_width = array->GetDataType().GetWidth();
  return cfg;
}

string AxiPort::PortSuffix() {
  const ITable *tab = res_.GetTable();
  return Util::Itoa(tab->GetId()) + "_" + Util::Itoa(res_.GetId());
}

string AxiPort::AddrPort() {
  return "axi_addr" + PortSuffix();
}

string AxiPort::WenPort() {
  return "axi_wen" + PortSuffix();
}

string AxiPort::ReqPort() {
  return "axi_req" + PortSuffix();
}

string AxiPort::AckPort() {
  return "axi_ack" + PortSuffix();
}

bool AxiPort::IsExclusiveAccessor() {
  auto *params = res_.GetParams();
  if (params->GetSramPortIndex() == "0") {
    return false;
  }
  return true;
}

}  // namespace axi
}  // namespace verilog
}  // namespace writer
}  // namespace iroha


text:
---
uid: SolidEdgeDraft.TableColumn.Header
summary:
remarks:
---


text:
"""--------------------------------------------------------------------------------------------#\
Vineet Nair Code for tree based clustering
-----------------------------------------------------------------------------------------------"""
import os
import random
#from numpy import *
import hclusttest
import hcluster

#Synthetic Graph consisting of 1000 nodes and 100000 edges
numnodes = 1000
numedges = 100000

#create a list of nodes
nodelist = []
for i in range(numnodes):
        nodelist.append(i)
n = len(nodelist)

#creating list of edges
#Creating a synthetic graph
edgelist= []
for j in range(numedges):
    edgelist.append(random.sample(nodelist, 2))

#sort the edgelist
edgelist.sort()

featurematrix = []
temp = edgelist[0][0]
#print(edgelist[0])

#Generating the sparse matrix
fmline = []
for index , item in enumerate(edgelist):
    newtemp = item[0]
    if(newtemp != temp):
        temp = newtemp
        featurematrix.append(fmline)
        fmline = []
        fmline.append(item[1])
    else:
        fmline.append(item[1])

#print(featurematrix)
#print(len(featurematrix))

"""
Building feature matrix from the edge list
extract feature vector for each node
"""
#tree = hclusttest.hcluster(featurematrix)
tree = hcluster.hcluster(featurematrix)


text:
package edu.ucla.nesl.datacollector;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;
import edu.ucla.nesl.datacollector.service.DataService;
import edu.ucla.nesl.datacollector.service.SyncService;
import edu.ucla.nesl.datacollector.tools.ZipUtils;
import edu.ucla.nesl.flowengine.SensorType;

public class DataArchive {

	public static final String archiveDir = "data_archive";

	private static final String ONGOING_PREFIX = "ongoing_";
	public static final String READY_FILE_EXT = ".ready";
	public static final String ZIP_FILE_EXT = ".zip";

	private static final long FILE_SIZE_LIMIT = 1024 * 1024 * 1024 * 5; // bytes
	private static final long FILE_AGE_LIMIT = 1000 * 60 * 10; // ms
	//private static final long FILE_AGE_LIMIT = 1000 * 10; // ms

	private static final String DATE_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS";
	private static final String SQL_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";

	private static final int INIT_STRING_CAPACITY = 1024;

	private String extPath = Environment.getExternalStorageDirectory().getPath() + "/" + archiveDir;
	private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
	private SimpleDateFormat sqlDateFormat = new SimpleDateFormat(SQL_DATE_FORMAT);

	private Map<String, File> fileMap = new HashMap<String, File>();
	private Map<String, Writer> writerMap = new HashMap<String, Writer>();

	private DataArchiveHandler mHandler;
	private Looper mLooper;

	private Context context;

	private StringBuilder mStringBuilder;
	private char[] mCharBuffer;

	final class DataArchiveHandler extends Handler {
		public DataArchiveHandler(Looper looper) {
			super(looper);
		}
	}

	public DataArchive(Context context) {
		this.context = context;

		HandlerThread thread = new HandlerThread(this.getClass().getName());
		thread.start();
		mLooper = thread.getLooper();
		mHandler = new DataArchiveHandler(mLooper);
		mStringBuilder = new StringBuilder(INIT_STRING_CAPACITY);
		mCharBuffer = new char[INIT_STRING_CAPACITY];

		if (!isExternalStorageWritable()) {
			return;
		}

		File file = new File(extPath);
		if (!file.exists()) {
			file.mkdirs();
		} else if (!file.isDirectory()) {
			file.delete();
			file.mkdirs();
		}

		loadDataFiles();
	}

	class OngoingCsvFileFilter implements FileFilter {
		private static final String REGEX_PREFIX = "^" + ONGOING_PREFIX;
		private static final String REGEX_POSTFIX = ".*\\.csv$";
		private final String regex;

		public OngoingCsvFileFilter() {
			regex = REGEX_PREFIX + REGEX_POSTFIX;
		}

		public OngoingCsvFileFilter(String sensor) {
			regex = REGEX_PREFIX + sensor + REGEX_POSTFIX;
		}

		@Override
		public boolean accept(File file) {
			if (file.getName().matches(regex)) {
				return true;
			}
			return false;
		}
	}

	private void loadDataFiles() {

		// Load ongoing files.
		File dir = new File(extPath);
		File[] files = dir.listFiles(new OngoingCsvFileFilter());
		Arrays.sort(files, Collections.reverseOrder());
		for (File csvFile : files) {
			String name = csvFile.getName().split("_")[1];
			if (fileMap.get(name) != null) {
				continue;
			} else {
				fileMap.put(name, csvFile);
				try {
					writerMap.put(name, new BufferedWriter(new FileWriter(csvFile.getAbsolutePath(), true)));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		// Check if ongoing files are too old or too big
		long timestamp = System.currentTimeMillis();
		List<String> toDeleteNames = new ArrayList<String>();
		for (Map.Entry<String, File> entry : fileMap.entrySet()) {
			String name = entry.getKey();
			File csvFile = entry.getValue();
			try {
				if (isFileTooOld(csvFile, timestamp) || csvFile.length() > FILE_SIZE_LIMIT) {
					Writer writer = writerMap.get(name);
					try {
						writer.close();
					} catch (IOException e) {
						e.printStackTrace();
					}

					// Rename the file
					File renamedFile = new File(csvFile.getAbsolutePath().replace(ONGOING_PREFIX, ""));
					csvFile.renameTo(renamedFile);

					// Start zipping.
					mHandler.post(new ZipRunnable(renamedFile.getAbsolutePath()));

					toDeleteNames.add(name);
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		for (String name : toDeleteNames) {
			fileMap.remove(name);
			writerMap.remove(name);
		}
	}

	public void close() {
		mLooper.quit();

		for (Writer writer : writerMap.values()) {
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void storeData(Bundle bundle) {

		if (!isExternalStorageWritable()) {
			return;
		}

		String name = bundle.getString(DataService.BUNDLE_NAME);
		long timestamp = bundle.getLong(DataService.BUNDLE_TIMESTAMP);

		Writer bw = getWriterForData(name, timestamp);

		if (bw == null) {
			return;
		}

		StringBuilder sb = convertBundleDataToString(bundle);

		if (sb == null) {
			return;
		}

		if (mCharBuffer.length != sb.capacity()) {
			Log.e(Const.TAG, "buffer length mismatch: " + mCharBuffer.length + ", " + sb.capacity());
			mCharBuffer = new char[sb.capacity()];
		}

		int length = sb.length();
		sb.getChars(0, length, mCharBuffer, 0);

		try {
			bw.write(mCharBuffer, 0, length);
			bw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private StringBuilder convertBundleDataToString(Bundle bundle) {
		String name = bundle.getString(DataService.BUNDLE_NAME);
		long timestamp = bundle.getLong(DataService.BUNDLE_TIMESTAMP);
		String timeStr = sqlDateFormat.format(new Date(timestamp));
		String type = bundle.getString(DataService.BUNDLE_TYPE);

		mStringBuilder.setLength(0);
		if (name.equals(SensorType.PHONE_ACCELEROMETER_NAME)
				|| name.equals(SensorType.PHONE_GPS_NAME)) {
			double[] data = bundle.getDoubleArray(DataService.BUNDLE_DATA);
			mStringBuilder.append(timeStr);
			for (double v : data) {
				mStringBuilder.append(", ").append(v);
			}
			mStringBuilder.append("\n");
			return mStringBuilder;
		} else if (type.equals("String")) {
			String data = bundle.getString(DataService.BUNDLE_DATA);
			mStringBuilder.append(timeStr).append(", ").append(data).append("\n");
			return mStringBuilder;
		} else if (type.equals("int")) {
			int data = bundle.getInt(DataService.BUNDLE_DATA);
			mStringBuilder.append(timeStr).append(", ").append(data).append("\n");
			return mStringBuilder;
		} else if (type.equals("double")) {
			double data = bundle.getDouble(DataService.BUNDLE_DATA);
			mStringBuilder.append(timeStr).append(", ").append(data).append("\n");
			return mStringBuilder;
		} else if (type.equals("double[]")) {
			double[] data = bundle.getDoubleArray(DataService.BUNDLE_DATA);
			long ts = timestamp;
			int sampleInterval = determineSampleInterval(name);
			for (double v : data) {
				mStringBuilder.append(sqlDateFormat.format(new Date(ts))).append(", ").append(v).append("\n");
				ts += sampleInterval;
			}
			return mStringBuilder;
		} else if (type.equals("int[]")) {
			int[] data = bundle.getIntArray(DataService.BUNDLE_DATA);
			long ts = timestamp;
			int sampleInterval = determineSampleInterval(name);
			for (int v : data) {
				mStringBuilder.append(sqlDateFormat.format(new Date(ts))).append(", ").append(v).append("\n");
				ts += sampleInterval;
			}
			return mStringBuilder;
		} else {
			Log.e(Const.TAG, "Unknown type: " + type);
		}

		return null;
	}

	private int determineSampleInterval(String name) {
		if (name.equals(SensorType.ECG_NAME)) {
			return SensorType.ECG_SAMPLE_INTERVAL;
		} else if (name.equals(SensorType.RIP_NAME)) {
			return SensorType.RIP_SAMPLE_INTERVAL;
		}
		return 1;
	}

	private Writer getWriterForData(String name, long timestamp) {

		File file = fileMap.get(name);

		if (file != null) {
			try {
				if (file.length() > FILE_SIZE_LIMIT || isFileTooOld(file, timestamp)) {
					Writer writer = writerMap.get(name);
					try {
						writer.close();
					} catch (IOException e) {
						e.printStackTrace();
					}

					// Rename the file
					File renamedFile = new File(file.getAbsolutePath().replace(ONGOING_PREFIX, ""));
					file.renameTo(renamedFile);

					// Start zipping.
					mHandler.post(new ZipRunnable(renamedFile.getAbsolutePath()));

					return createNewFile(name, timestamp);
				} else {
					return writerMap.get(name);
				}
			} catch (ParseException e) {
				e.printStackTrace();
				return null;
			}
		}

		return createNewFile(name, timestamp);
	}

	final class ZipRunnable implements Runnable {

		private String path;

		public ZipRunnable(String path) {
			this.path = path;
		}

		@Override
		public void run() {
			File file = new File(path);

			if (!file.exists()) {
				return;
			}

			if (file.length() <= 0) {
				file.delete();
			} else {
				try {
					String zipFileName = path + ZIP_FILE_EXT;
					ZipUtils.zip(new String[] { path }, zipFileName);
					file.delete();

					// Rename to mark it as ready.
					File oriZipFile = new File(zipFileName);
					File readyZipFile = new File(path + READY_FILE_EXT + ZIP_FILE_EXT);
					oriZipFile.renameTo(readyZipFile);

					// Notify SyncService
					Intent intent = new Intent(context, SyncService.class);
					context.startService(intent);

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private Writer createNewFile(String name, long timestamp) {
		String dateString = dateFormat.format(new Date(timestamp));
		File newFile = new File(extPath + "/" + ONGOING_PREFIX + name + "_" + dateString + ".csv");
		Writer writer;
		try {
			if (!newFile.exists()) {
				newFile.createNewFile();
			}
			writer = new BufferedWriter(new FileWriter(newFile.getAbsoluteFile(), true));
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		fileMap.put(name, newFile);
		writerMap.put(name, writer);
		return writer;
	}

	private boolean isFileTooOld(File file, long timestamp) throws ParseException {
		// ongoing_sensorname_2013-01-01-11-11-11-123.csv
		String time = file.getName().replace(".csv", "").split("_")[2];
		Date date = dateFormat.parse(time);
		long epoch = date.getTime();
		if (timestamp - epoch > FILE_AGE_LIMIT) {
			return true;
		}
		/*if (timestamp - epoch < 0) { // invalid future time, start new file.
			return true;
		}*/
		return false;
	}

	private boolean isExternalStorageWritable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		}
		return false;
	}

	public void finish(String sensor) {
		File dir = new File(extPath);
		File[] files = dir.listFiles(new OngoingCsvFileFilter(sensor));
		Arrays.sort(files);
		for (File csvFile : files) {
			String name = csvFile.getName().split("_")[1];
			if (fileMap.get(name) != null) {
				fileMap.remove(name);
			}
			if (writerMap.get(name) != null) {
				try {
					writerMap.get(name).close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				writerMap.remove(name);
			}

			// Rename the file
			File renamedFile = new File(csvFile.getAbsolutePath().replace(ONGOING_PREFIX, ""));
			csvFile.renameTo(renamedFile);

			// Start zipping.
			mHandler.post(new ZipRunnable(renamedFile.getAbsolutePath()));
		}
	}
}


text:
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void startScan();
    void addTableItem(unsigned int ip, unsigned short port, unsigned short protocol);
    void lockInput();   // disable the inputs when supvisor is running
    void freeInput();   // free the inputs after the supvisor stopped

private:
    // initialized in initialization list
    Ui::MainWindow *ui;
    unsigned int m_rowCount;
    Supervisor *m_supvisor;   // supervisor who control the procedure of scanning
    // initialized in function body
    QMenu *m_menu;
    QToolBar *m_toolBar;
    QAction *m_stopAction;
    QAction *m_startAction;
    QLabel *m_radar;
    QSpacerItem *m_spacer;
};

#endif // MAINWINDOW_H


text:
CSVGFeDiffuseLighting::
CSVGFeDiffuseLighting(CSVG &svg) :
 CSVGFeLighting(svg)
{
}

CSVGFeDiffuseLighting::
CSVGFeDiffuseLighting(const CSVGFeDiffuseLighting &fe) :
 CSVGFeLighting(fe)
{
}

CSVGFeDiffuseLighting *
CSVGFeDiffuseLighting::
dup() const
{
  return new CSVGFeDiffuseLighting(*this);
}

bool
CSVGFeDiffuseLighting::
processOption(const std::string &opt_name, const std::string &opt_value)
{
  double      r;
  std::string str;

  if      (svg_.stringOption(opt_name, opt_value, "in", str))
    filterIn_ = str;
  else if (svg_.stringOption(opt_name, opt_value, "result", str))
    filterOut_ = str;
  else if (svg_.stringOption(opt_name, opt_value, "lighting-color", str))
    lightingColor_ = Color(svg_.nameToColor(str));
  else if (svg_.realOption(opt_name, opt_value, "diffuseConstant", &r))
    diffuseConstant_ = r;
  else if (svg_.realOption(opt_name, opt_value, "surfaceScale", &r))
    surfaceScale_ = r;
  else
    return CSVGFilterBase::processOption(opt_name, opt_value);

  return true;
}

bool
CSVGFeDiffuseLighting::
drawElement()
{
  auto *inBuffer  = svg_.getBuffer(getFilterIn ());
  auto *outBuffer = svg_.getBuffer(getFilterOut());

  bool inDrawing = inBuffer->isDrawing();

  if (inDrawing) inBuffer->stopDraw();

  //---

  // get filtered object coords
  CBBox2D inBBox;

  getBufferSubRegion(inBuffer, inBBox);

  //---

  if (svg_.getDebugFilter()) {
    std::string objectBufferName = "_" + getUniqueName();

    auto *buffer = svg_.getBuffer(objectBufferName + "_in");

    buffer->setImageBuffer(inBuffer);
    buffer->setBBox       (inBBox);
  }

  //---

  filterImage(inBuffer, inBBox, outBuffer);

  outBuffer->setBBox(inBBox);

  //---

  if (svg_.getDebugFilter()) {
    std::string objectBufferName = "_" + getUniqueName();

    auto *buffer = svg_.getBuffer(objectBufferName + "_out");

    buffer->setImageBuffer(outBuffer);
    buffer->setBBox       (inBBox);
  }

  //---

  if (inDrawing) inBuffer->startDraw();

  return true;
}

void
CSVGFeDiffuseLighting::
print(std::ostream &os, bool hier) const
{
  if (hier) {
    os << "<feDiffuseLighting";

    printValues(os);

    if (hasChildren()) {
      os << ">" << std::endl;

      printChildren(os, hier);

      os << "</feDiffuseLighting>" << std::endl;
    }
    else
      os << "/>" << std::endl;
  }
  else
    os << "feDiffuseLighting ";
}

void
CSVGFeDiffuseLighting::
printValues(std::ostream &os, bool flat) const
{
  CSVGObject::printValues(os, flat);

  printNameValue(os, "in"             , filterIn_ );
  printNameValue(os, "result"         , filterOut_);
  printNameValue(os, "lighting-color" , lightingColor_);
  printNameValue(os, "diffuseConstant", diffuseConstant_);
  printNameValue(os, "surfaceScale"   , surfaceScale_);
}

std::ostream &
operator<<(std::ostream &os, const CSVGFeDiffuseLighting &fe)
{
  fe.print(os, false);

  return os;
}


text:
#include "linker.h"
#include "linker_translate_path.h"
#include "linker_utils.h"

#if defined(__LP64__)
#define APEX_LIB(apex, name) \
  { "/system/lib64/" name, "/apex/" apex "/lib64/" name }
#else
#define APEX_LIB(apex, name) \
  { "/system/lib/" name, "/apex/" apex "/lib/" name }
#endif

// Workaround for dlopen(/system/lib(64)/<soname>) when .so is in /apex. http://b/121248172
/**
 * Translate /system path to /apex path if needed
 * The workaround should work only when targetSdkVersion < Q.
 *
 * param out_name_to_apex pointing to /apex path
 * return true if translation is needed
 */
bool translateSystemPathToApexPath(const char* name, std::string* out_name_to_apex) {
  static constexpr const char* kPathTranslationQ[][2] = {
      APEX_LIB("com.android.i18n", "libicui18n.so"),
      APEX_LIB("com.android.i18n", "libicuuc.so")
  };

  if (name == nullptr) {
    return false;
  }

  auto comparator = [name](auto p) { return strcmp(name, p[0]) == 0; };

  if (get_application_target_sdk_version() < __ANDROID_API_Q__) {
    if (auto it =
            std::find_if(std::begin(kPathTranslationQ), std::end(kPathTranslationQ), comparator);
        it != std::end(kPathTranslationQ)) {
      *out_name_to_apex = (*it)[1];
      return true;
    }
  }

  return false;
}
// End Workaround for dlopen(/system/lib/<soname>) when .so is in /apex.


text:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import pymc3 as pm
from scipy.stats import mode, chisquare
from sklearn.metrics import confusion_matrix, accuracy_score
import lasagne
from utils import load_dataset
import theano
from utils import run_advi

sns.set_style('white')
sns.set_context('talk')

"""
In this file we build the Bayesian Convolutional NN to be trained on the MNIST data set
"""

class GaussWeights(object):
    """
    The priors act as regularizers here to try and keep the weights of the ANN small.
    It's mathematically equivalent to putting a L2 loss term that penalizes large weights into the objective function
    """
    def __init__(self):
        self.count = 0

    def __call__(self, shape):
        self.count += 1
        return pm.Normal('w%d' % self.count, mu=0, sd=.1,
                         testval=np.random.normal(size=shape).astype(np.float64),
                         shape=shape)

def build_ann_conv(init):
    """
    Build the Convolutional neural net to be trained with the ADVI algorithm
    :param init: can pass in a function init which has to return a Theano expression
    to be used as the weight and bias matrices
    :return:
    """
    network = lasagne.layers.InputLayer(shape=(None, 1, 28, 28),
                                        input_var=input_var)

    network = lasagne.layers.Conv2DLayer(
        network, num_filters=32, filter_size=(5, 5),
        nonlinearity=lasagne.nonlinearities.tanh,
        W=init)

    # Max-pooling layer of factor 2 in both dimensions:
    network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2))

    # Another convolution with 32 5x5 kernels, and another 2x2 pooling:
    network = lasagne.layers.Conv2DLayer(
        network, num_filters=32, filter_size=(5, 5),
        nonlinearity=lasagne.nonlinearities.tanh,
        W=init)

    network = lasagne.layers.MaxPool2DLayer(network,
                                            pool_size=(2, 2))

    n_hid2 = 256
    network = lasagne.layers.DenseLayer(
        network, num_units=n_hid2,
        nonlinearity=lasagne.nonlinearities.tanh,
        b=init,
        W=init
    )

    # Finally, we'll add the fully-connected output layer, of 10 softmax units:
    network = lasagne.layers.DenseLayer(
        network, num_units=10,
        nonlinearity=lasagne.nonlinearities.softmax,
        b=init,
        W=init
    )

    prediction = lasagne.layers.get_output(network)

    return pm.Categorical('out',
                          prediction,
                          observed=target_var)

if __name__ == "__main__":

    print("Loading data...")
    X_train, y_train, X_val, y_val, X_test, y_test = load_dataset()

    # Building a theano.shared variable
    input_var = theano.shared(X_train[:500, ...].astype(np.float64))
    target_var = theano.shared(y_train[:500, ...].astype(np.float64))

    with pm.Model() as neural_network_conv:
        likelihood = build_ann_conv(GaussWeights())
        v_params, trace, ppc, y_pred = run_advi(likelihood, X_train, y_train, input_var, X_test, y_test, target_var)

    print('Accuracy on test data = {}%'.format(accuracy_score(y_test, y_pred) * 100))

    miss_class = np.where(y_test != y_pred)[0]
    corr_class = np.where(y_test == y_pred)[0]

    preds = pd.DataFrame(ppc['out']).T

    chis = preds.apply(lambda x: chisquare(x).statistic, axis='columns')

    sns.distplot(chis.loc[miss_class].dropna(), label='Error')
    sns.distplot(chis.loc[corr_class].dropna(), label='Correct')
    plt.legend()
    sns.despine()
    plt.xlabel('Chi-Square statistic')
    plt.show()


text:
using FluentMvc.Configuration;
using FluentMvc.Constraints;
using NUnit.Framework;

namespace FluentMvc.Spec.Issues
{
    public class ExceptWhenNotCorrectlyApplied
    {
        [Test]
        public void should_create_not_constraint()
        {
            var whenDsl = Except.When<CustomContraint>();
            whenDsl.ConstraintRegistrations.Length.ShouldBeGreaterThan(0);
            whenDsl.ConstraintRegistrations[0].Prepare(new FluentMvcObjectFactory());
            whenDsl.ConstraintRegistrations[0].Constraint.ShouldBeOfType(typeof(NotConstraint));
        }
    }

    public class CustomContraint : IConstraint
    {
        public bool IsSatisfiedBy<T>(T selector) where T : RegistrySelector
        {
            return false;
        }
    }
}


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

<TITLE>
QueryRequest.Sorting (ATG Java API)
</TITLE>

<META NAME="date" CONTENT="2013-04-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

atg.search.routing.command.search

Class QueryRequest.Sorting

java.lang.Object
  atg.core.util.Enum
      atg.search.routing.command.search.QueryRequest.Sorting

All Implemented Interfaces:
java.io.Serializable, java.lang.Comparable

Enclosing class:
QueryRequest

public static class QueryRequest.Sorting
extends Enum

Enumeration type for answer sorting or grouping.
 See SearchPropertyEditors.

See Also:
Serialized Form

Nested Class Summary

static class
QueryRequest.Sorting.SortingEditor

Nested classes/interfaces inherited from class atg.core.util.Enum

Enum.EnumEditor, Enum.LocaleEnumEditor

Field Summary

static QueryRequest.Sorting
DOCUMENT

          Groups by document, meaning one document per answer group

static QueryRequest.Sorting
PROPERTY

          Groups by property, which can produce more than one document per answer group.

Fields inherited from class atg.core.util.Enum

CLASS_VERSION

Method Summary

static java.util.Iterator
getIterator()

static QueryRequest.Sorting
valueOf(java.lang.String pName)

Methods inherited from class atg.core.util.Enum

compareTo, getEnumClassInfo, getOrdinal, iterator, iterator, lookup, lookup, lookup, lookup, readResolve, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

DOCUMENT

public static final QueryRequest.Sorting DOCUMENT

Groups by document, meaning one document per answer group

PROPERTY

public static final QueryRequest.Sorting PROPERTY

Groups by property, which can produce more than one document per answer group.

Method Detail

valueOf

public static QueryRequest.Sorting valueOf(java.lang.String pName)

getIterator

public static java.util.Iterator getIterator()

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
#ifndef PWM_H_
#define PWM_H_
#include<string>
using std::string;

#define PWM_PATH "/sys/devices/ocp.3/"
#define PWM_PERIOD "period"
#define PWM_DUTY "duty"
#define PWM_POLARITY "polarity"
#define PWM_RUN "run"

namespace exploringBB {

class PWM {
public:
	enum POLARITY{ ACTIVE_HIGH=0, ACTIVE_LOW=1 };

private:
	string name, path;
	float analogFrequency;  //defaults to 100,000 Hz
	float analogMax;        //defaults to 3.3V

public:
	PWM(string pinName);

	virtual int setPeriod(unsigned int period_ns);
	virtual unsigned int getPeriod();
	virtual int setFrequency(float frequency_hz);
	virtual float getFrequency();
	virtual int setDutyCycle(unsigned int duration_ns);
	virtual int setDutyCycle(float percentage);
	virtual unsigned int getDutyCycle();
	virtual float getDutyCyclePercent();

	virtual int setPolarity(PWM::POLARITY);
	virtual void invertPolarity();
	virtual PWM::POLARITY getPolarity();

	virtual void setAnalogFrequency(float frequency_hz) { this->analogFrequency = frequency_hz; }
	virtual int calibrateAnalogMax(float analogMax); //must be between 3.2 and 3.4
	virtual int analogWrite(float voltage);

	virtual int run();
	virtual bool isRunning();
	virtual int stop();

	virtual ~PWM();
private:
	float period_nsToFrequency(unsigned int);
	unsigned int frequencyToPeriod_ns(float);
};

} /* namespace exploringBB */

#endif /* PWM_H_ */


text:
class RespondToSpecs
  def foo
  end
end

describe "Kernel#respond_to?" do
  before :each do
    @a = RespondToSpecs.new
  end

  it "returns false if a method exists, but is marked with a '$$stub' property" do
    `#{@a}.$foo.$$stub = true`
    @a.respond_to?(:foo).should be_false
  end
end


text:
import { SocketService } from './socket.service';
import { AppObservableObject } from '../../../../utils/base';

class MockSocketObservable extends AppObservableObject<any> {}

/**
 * Mock client SocketIO.
 */
class MockSocket {
    event: string;
    subject: MockSocketObservable = new MockSocketObservable();

    emit(event, data) {
        this.event = event;
        this.subject.setObject(data);
    }

    on(_event, fn) {
        this.subject.observable.subscribe(data => {
            fn(data);
        });
    }
}

/**
 * Test service that overrides the socket with a mocked version.
 */
export class TestSocketService extends SocketService {
    constructor() {
        super();
        this.socket = new MockSocket();
    }
}

describe('Realtime Service', () => {
    let service: TestSocketService;

    beforeEach(() => {
        service = new TestSocketService();
    });

    it('supports sending and receiving messages', (done) => {
        let receivedData = null;
        service.onData('message').subscribe(response => {
            receivedData = response;
        });

        const sentData = {data: 'foo'};
        service.send('message', sentData);

        expect(receivedData).toEqual(sentData);

        done();
    });
});