text:
EXPCL_PANDAEGG void init_libpandaegg();

#endif


text:
module StudioGame
	require_relative 'player'

	class ClumsyPlayer < Player
		attr_reader :boost

		def initialize(name, health=100, boost=10)
			super(name, health)
			@boost = boost
		end

		def found_treasure(treasure)
			damaged_treasure = Treasure.new(treasure.name, treasure.points/2.0)
			super(damaged_treasure)
		end

		def w00t
			@boost.times { super }
		end
	end

	if __FILE__ == $0
		clumsy = ClumsyPlayer.new("klutz")

		hammer = Treasure.new(:hammer, 50)
		clumsy.found_treasure(hammer)
		clumsy.found_treasure(hammer)
		clumsy.found_treasure(hammer)

		crowbar = Treasure.new(:crowbar, 400)
		clumsy.found_treasure(crowbar)

		clumsy.each_found_treasure do |treasure|
			puts "#{treasure.points} total #{treasure.name} points."
		end
		puts "#{clumsy.points} grand total points"

		puts clumsy.w00t
	end
end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.spark.sql.catalyst.expressions

import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.catalyst.trees.CurrentOrigin.withOrigin
import org.apache.spark.sql.catalyst.trees.Origin
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.{Decimal, DecimalType, LongType}

class DecimalExpressionSuite extends SparkFunSuite with ExpressionEvalHelper {

  test("UnscaledValue") {
    val d1 = Decimal("10.1")
    checkEvaluation(UnscaledValue(Literal(d1)), 101L)
    val d2 = Decimal(101, 3, 1)
    checkEvaluation(UnscaledValue(Literal(d2)), 101L)
    checkEvaluation(UnscaledValue(Literal.create(null, DecimalType(2, 1))), null)
  }

  test("MakeDecimal") {
    withSQLConf(SQLConf.ANSI_ENABLED.key -> "false") {
      checkEvaluation(MakeDecimal(Literal(101L), 3, 1), Decimal("10.1"))
      checkEvaluation(MakeDecimal(Literal.create(null, LongType), 3, 1), null)
      val overflowExpr = MakeDecimal(Literal.create(1000L, LongType), 3, 1)
      checkEvaluation(overflowExpr, null)
      checkEvaluationWithMutableProjection(overflowExpr, null)
      evaluateWithoutCodegen(overflowExpr, null)
      checkEvaluationWithUnsafeProjection(overflowExpr, null)
    }
    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
      checkEvaluation(MakeDecimal(Literal(101L), 3, 1), Decimal("10.1"))
      checkEvaluation(MakeDecimal(Literal.create(null, LongType), 3, 1), null)
      val overflowExpr = MakeDecimal(Literal.create(1000L, LongType), 3, 1)
      intercept[ArithmeticException](checkEvaluationWithMutableProjection(overflowExpr, null))
      intercept[ArithmeticException](evaluateWithoutCodegen(overflowExpr, null))
      intercept[ArithmeticException](checkEvaluationWithUnsafeProjection(overflowExpr, null))
    }
  }

  test("CheckOverflow") {
    val d1 = Decimal("10.1")
    checkEvaluation(CheckOverflow(Literal(d1), DecimalType(4, 0), true), Decimal("10"))
    checkEvaluation(CheckOverflow(Literal(d1), DecimalType(4, 1), true), d1)
    checkEvaluation(CheckOverflow(Literal(d1), DecimalType(4, 2), true), d1)
    checkEvaluation(CheckOverflow(Literal(d1), DecimalType(4, 3), true), null)
    intercept[ArithmeticException](CheckOverflow(Literal(d1), DecimalType(4, 3), false).eval())
    intercept[ArithmeticException](checkEvaluationWithMutableProjection(
      CheckOverflow(Literal(d1), DecimalType(4, 3), false), null))

    val d2 = Decimal(101, 3, 1)
    checkEvaluation(CheckOverflow(Literal(d2), DecimalType(4, 0), true), Decimal("10"))
    checkEvaluation(CheckOverflow(Literal(d2), DecimalType(4, 1), true), d2)
    checkEvaluation(CheckOverflow(Literal(d2), DecimalType(4, 2), true), d2)
    checkEvaluation(CheckOverflow(Literal(d2), DecimalType(4, 3), true), null)
    intercept[ArithmeticException](CheckOverflow(Literal(d2), DecimalType(4, 3), false).eval())
    intercept[ArithmeticException](checkEvaluationWithMutableProjection(
      CheckOverflow(Literal(d2), DecimalType(4, 3), false), null))

    checkEvaluation(CheckOverflow(
      Literal.create(null, DecimalType(2, 1)), DecimalType(3, 2), true), null)
    checkEvaluation(CheckOverflow(
      Literal.create(null, DecimalType(2, 1)), DecimalType(3, 2), false), null)
  }

  test("SPARK-39208: CheckOverflow & CheckOverflowInSum support query context in runtime errors") {
    val d = Decimal(101, 3, 1)
    val query = "select cast(d as decimal(4, 3)) from t"
    val origin = Origin(
      startIndex = Some(7),
      stopIndex = Some(30),
      sqlText = Some(query))

    val expr1 = withOrigin(origin) {
      CheckOverflow(Literal(d), DecimalType(4, 3), false)
    }
    checkExceptionInExpression[ArithmeticException](expr1, query)

    val expr2 = CheckOverflowInSum(Literal(d), DecimalType(4, 3), false, queryContext = query)
    checkExceptionInExpression[ArithmeticException](expr2, query)
  }
}


text:
package exporter

import (
	"bytes"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
	"go.skia.org/infra/go/skerr"
	"go.skia.org/skia/bazel/exporter/interfaces/mocks"
)

const workspaceTestWorkspaceDir = "/path/to/workspace"

// This input test data (in textproto format) started as output of
// a bazel cquery call - like:
//
//	bazel cquery --noimplicit_deps 'kind("rule", deps(//:skia_public))' --output textproto > out.txt
//
// and then hand edited to create a small valid query result with specific
// files, copts, and other cc_library/cc_binary rule attributes.
const workspaceTestTextProto = `results {
	target {
		type: RULE
		rule {
		  name: "//src/libs:sum"
		  rule_class: "cc_library"
		  location: "/path/to/workspace/src/libs/BUILD.bazel:8:11"
		  attribute {
			name: "copts"
			type: STRING_LIST
			string_list_value: "-O2"
			explicitly_specified: true
			nodep: false
		  }
		  attribute {
			name: "defines"
			type: STRING_LIST
			string_list_value: "SUMDEF"
			explicitly_specified: false
			nodep: false
		  }
		  attribute {
			name: "includes"
			type: STRING_LIST
			string_list_value: "."
			explicitly_specified: false
			nodep: false
		  }
		  attribute {
			name: "linkopts"
			type: STRING_LIST
			string_list_value: "-L/library/dir"
			explicitly_specified: false
			nodep: false
		  }
		  attribute {
			name: "name"
			type: STRING
			string_value: "sum"
			explicitly_specified: true
			nodep: false
		  }
		  attribute {
			  name: "srcs"
			  type: LABEL_LIST
			  string_list_value: "//src/libs:sum.cpp"
			  explicitly_specified: true
			  nodep: false
		  }
		  attribute {
			name: "hdrs"
			type: LABEL_LIST
			string_list_value: "//src/libs:sum.h"
			explicitly_specified: true
			nodep: false
		  }
		  attribute {
			name: "visibility"
			type: STRING_LIST
			string_list_value: "//visibility:public"
			explicitly_specified: true
			nodep: true
		  }
		}
	  },
	}
	results {
	  target {
	  type: RULE
	  rule {
		name: "//src/apps:hello"
		rule_class: "cc_binary"
		location: "/path/to/workspace/src/apps/BUILD.bazel:8:11"
		attribute {
		  name: "copts"
		  type: STRING_LIST
		  string_list_value: "-O1"
		  explicitly_specified: true
		  nodep: false
		}
		attribute {
		  name: "defines"
		  type: STRING_LIST
		  string_list_value: "APPDEF"
		  explicitly_specified: false
		  nodep: false
		}
		attribute {
		  name: "linkopts"
		  type: STRING_LIST
		  string_list_value: "-L/app/dir"
		  explicitly_specified: false
		  nodep: false
		}
		attribute {
		  name: "name"
		  type: STRING
		  string_value: "hello"
		  explicitly_specified: true
		  nodep: false
		}
		attribute {
			name: "srcs"
			type: LABEL_LIST
			string_list_value: "//src/apps:hello-world.cpp"
			explicitly_specified: true
			nodep: false
		}
		attribute {
			name: "deps"
			type: LABEL_LIST
			string_list_value: "//src/libs:sum"
			explicitly_specified: false
			nodep: false
		}
		attribute {
		  name: "visibility"
		  type: STRING_LIST
		  string_list_value: "//visibility:public"
		  explicitly_specified: true
		  nodep: true
		}
	  }
	}
  }`

// Return the workspace (cmakeWorkspace) for the test data.
//
// Note: this helper function makes no test assertions as the
// Export function is already tested.
func getTestWorkspace(t *testing.T) (cmakeWorkspace, error) {
	protoData, err := textProtoToProtobuf(workspaceTestTextProto)
	if err != nil {
		return cmakeWorkspace{}, skerr.Wrap(err)
	}

	// Export to CMake buffer.
	fs := mocks.NewFileSystem(t)
	fs.On("OpenFile", mock.Anything).Return(new(bytes.Buffer), nil).Once()
	e := NewCMakeExporter("projName", workspaceTestWorkspaceDir, "CMakeLists.txt", fs)
	qcmd := mocks.NewQueryCommand(t)
	qcmd.On("Read", mock.Anything).Return(protoData, nil)
	err = e.Export(qcmd)
	if err != nil {
		return cmakeWorkspace{}, skerr.Wrap(err)
	}

	return e.workspace, nil
}

func TestIsGetRule_ValidName_ReturnsRule(t *testing.T) {
	workspace, err := getTestWorkspace(t)
	require.NoError(t, err)

	r := workspace.getRule("//src/libs:sum")
	require.NotNil(t, r)
	assert.Equal(t, "//src/libs:sum", r.getName())
}

func TestIsGetRule_InvalidName_ReturnsNil(t *testing.T) {
	workspace, err := getTestWorkspace(t)
	require.NoError(t, err)

	r := workspace.getRule("//non/existent:rule")
	assert.Nil(t, r)
}

func TestCreateRule_ValidBazelRule_NotNil(t *testing.T) {
	workspace, err := getTestWorkspace(t)
	require.NoError(t, err)

	// Get the rule from the existing workspace (since we can't make one)
	cmakeRule := workspace.getRule("//src/libs:sum")
	require.NotNil(t, cmakeRule)

	otherWorkspace := newCMakeWorkspace()
	require.NotNil(t, otherWorkspace)
	otherCMakeRule := otherWorkspace.createRule(cmakeRule.rule)
	require.NotNil(t, otherCMakeRule)
}

func TestIsRuleWritten_NotWritten_ReturnsFalse(t *testing.T) {
	var state writeState
	assert.False(t, state.isRuleWritten("//unwritten:rule"))
}

func TestIsRuleWritten_Written_ReturnsTrue(t *testing.T) {
	var state writeState
	state.setRuleWritten("//written:rule")
	assert.True(t, state.isRuleWritten("//written:rule"))
}


text:
class CreateBarbers < ActiveRecord::Migration
  def change
	create_table :Barbers do |i|
		i.text :Barber
		i.timestamps
	end
	Barbers.create :Barber => "Guss Fring"
	Barbers.create :Barber => "Walter Wite"
	Barbers.create :Barber => "Jessie Pinkman"
  end
end


text:
require 'spec_helper'

describe 'User' do
  before(:example) do
    @user = CyberCoach::User.new
  end

  it 'should instantiate itself with preset attributes' do
    uri = '/pants/'
    id = 1
    username = 'pants'
    email = 'fancy@pants.com'
    password = 'fancy'
    real_name = 'Fancy Pants'
    privacy_level = CyberCoach::PrivacyLevel::OWNER
    pants = 'yes'
    @user = CyberCoach::User.new(
      uri: uri,
      id: id,
      username: username,
      email: email,
      password: password,
      real_name: real_name,
      privacy_level: privacy_level,
      pants: pants
    )
    expect(@user.uri).to be(uri)
    expect(@user.id).to be(id)
    expect(@user.username).to be(username)
    expect(@user.email).to be(email)
    expect(@user.password).to be(password)
    expect(@user.real_name).to be(real_name)
    expect(@user.privacy_level).to be(privacy_level)
    expect { @user.pants }.to raise_error(NoMethodError)
  end

  it 'should raise an error if it does not exist' do
    @user.username = 'gnirloff'
    expect { @user.read }.to raise_error(CyberCoach::HttpError)
  end

  it 'should read all' do
    users = CyberCoach::User.read_all
    expect(users.resources.size).to eq(5)
    expect(users.next).not_to be_nil
    expect { users.previous }.to raise_error(CyberCoach::ResourcePage::NoPreviousPageError)
  end

  it 'should get the authentication options' do
    @user = UserHelper.make(8)
    @user.create
    expect(@user.authentication).to eq(
                                      basic_auth: {
                                        username: @user.username,
                                        password: @user.password
                                      }
                                    )
  end

  describe 'crud' do
    before(:example) do
      @user = UserHelper.make(8)
      ResourceHelper.safe_delete(@user)
    end

    after(:example) do
      ResourceHelper.safe_delete(@user)
    end

    it 'should create itself without nilling the password' do
      old_uri = @user.uri
      old_password = @user.password
      @user.create
      expect(@user.uri).to eq(old_uri)
      expect(@user.password).to eq(old_password)
    end

    it 'should read itself without nilling the password' do
      old_password = @user.password
      @user.create
      @user.read
      # users do not have an id
      expect(@user.id).to be_nil
      expect(@user.uri).not_to be_nil
      expect(@user.username).not_to be_nil
      expect(@user.email).not_to be_nil
      expect(@user.password).to eq(old_password)
      expect(@user.privacy_level).not_to be_nil
      expect(@user.real_name).not_to be_nil
      expect(@user.date_created).not_to be_nil
    end

    it 'should update itself without nilling the password' do
      @user.create
      old_password = @user.password
      old_real_name = @user.real_name
      new_real_name = 'habakuck'
      @user.real_name = new_real_name
      @user.update
      expect(@user.password).to eq(old_password)
      expect(@user.real_name).not_to eq(old_real_name)
      expect(@user.real_name).to eq(new_real_name)
    end

    it 'should delete itself' do
      @user.create
      @user.delete
      expect { @user.read }.to raise_error(CyberCoach::HttpError)
    end
  end

  describe 'invalidation' do
    before(:example) do
      @user = UserHelper.make(8)
      ResourceHelper.safe_delete(@user)
    end

    after(:example) do
      ResourceHelper.safe_delete(@user)
    end

    it 'should not invalidate when creating' do
      password = @user.password
      @user.password = 'notThePassword'
      expect(@user.password).not_to eq(password)
      expect { @user.create({}, false) }.not_to raise_error
      @user.password = password
    end

    it 'should not invalidate when reading' do
      @user.create
      password = @user.password
      @user.password = 'notThePassword'
      expect(@user.password).not_to eq(password)
      expect { @user.read({}, false) }.not_to raise_error
      @user.password = password
    end

    it 'should not invalidate when updating' do
      @user.create
      password = @user.password
      @user.password = 'notThePassword'
      expect(@user.password).not_to eq(password)
      expect { @user.update({}, false) }.not_to raise_error
      @user.password = password
    end

    it 'should not invalidate when deleting' do
      @user.create
      password = @user.password
      @user.password = 'notThePassword'
      expect(@user.password).not_to eq(password)
      expect { @user.delete({}, false) }.not_to raise_error
      @user.password = password
    end
  end
end


text:
package be.kwakeroni.scratch.test;

import be.kwakeroni.parameters.basic.client.model.Ranged;
import be.kwakeroni.parameters.basic.client.model.Simple;
import be.kwakeroni.parameters.basic.client.query.EntryQuery;
import be.kwakeroni.parameters.basic.client.query.RangedQuery;
import be.kwakeroni.parameters.basic.client.query.ValueQuery;
import be.kwakeroni.parameters.basic.type.Range;
import be.kwakeroni.parameters.client.api.model.Entry;
import be.kwakeroni.parameters.client.api.model.Parameter;
import be.kwakeroni.parameters.client.api.model.ParameterGroup;
import be.kwakeroni.parameters.client.api.query.Query;
import be.kwakeroni.parameters.types.api.ParameterType;
import be.kwakeroni.scratch.EntryAssert;
import be.kwakeroni.scratch.env.Environment;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public abstract class RangedGroupTestSupport<V extends Comparable<? super V>, ET extends Ranged<V, Simple>> extends GroupTestSupport<ET> {

    private final Logger LOG = LoggerFactory.getLogger(this.getClass());
    private final RangeTestParameter<V> values;
    private final ParameterType<V> rangeValueType;

    protected RangedGroupTestSupport(Environment environment,
                                     ParameterGroup<ET> group,
                                     RangeTestParameter<V> rangeParameter,
                                     TestParameter<?>... otherParameters) {
        super(environment, group, ExtArrays.prepend(rangeParameter, otherParameters));
        this.values = rangeParameter;
        this.rangeValueType = rangeParameter.rangeValueType;
    }

    protected Query<ET, ?> valueQuery(V value, int paramIndex) {
        return new RangedQuery<>(value, rangeValueType, new ValueQuery<>(parameter(paramIndex)));
    }

    protected Query<ET, Entry> entryQuery(V value) {
        return new RangedQuery<>(value, rangeValueType, new EntryQuery());
    }

    protected static <T extends Comparable<? super T>>
    RangeTestParameter<T> rangeParam(Parameter<Range<T>> parameter, ParameterType<T> rangeValueType,
                                     T lowerValue, T originalLowValue, T originalMidValue1, T originalMidValue2, T originalHighValue,
                                     T otherLowValue, T otherMidValue, T otherHighValue, T higherValue) {
        return new RangeTestParameter<T>(parameter, rangeValueType,
                lowerValue, originalLowValue, originalMidValue1, originalMidValue2, originalHighValue,
                otherLowValue, otherMidValue, otherHighValue, higherValue);
    }

    @DisplayName("Changing a parameter value")
    @Test
    public void testWriteRangedValue() {
        Query<ET, ?> query = valueQuery(this.values.originalMidValue1, 1);

        assertThat(get(query)).isEqualTo(originalValue(1));

        set(query, otherValue(1));

        assertThat(get(query)).isEqualTo(otherValue(1));
    }

    @Test
    @DisplayName("Changing an entry")
    public void testWriteRangedEntry() {
        Query<ET, Entry> query = entryQuery(this.values.originalMidValue1);

        EntryAssert.assertThat(get(query)).hasParameters(this.parameters).withValues(this.originalValues);

        set(query, entry(this.otherValues));

        assertThat(optGet(query)).isEmpty();
        EntryAssert.assertThat(get(entryQuery(this.values.otherMidValue)))
                .hasParameters(this.parameters).withValues(this.otherValues);
    }

    @Test
    @DisplayName("Adding an entry")
    public void testAddRangedEntry() {
        assertThat(optGet(entryQuery(this.values.otherMidValue))).isEmpty();

        addEntry(entry(this.otherValues));

        EntryAssert.assertThat(get(entryQuery(this.values.otherMidValue)))
                .hasParameters(this.parameters)
                .withValues(this.otherValues);
    }

    @Test
    @DisplayName("Does not allow adding an overlapping range")
    public void testAddOverlappingRange() {
        assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1));
        assertThat(optGet(valueQuery(this.values.otherMidValue, 1))).isEmpty();

        assertThatThrownBy(() ->
                addEntry(entry(ExtArrays.replace(this.originalValues, 0, Range.of(this.values.lowerValue, this.values.originalMidValue2))))
        ).isInstanceOf(IllegalStateException.class)
                .satisfies(throwable -> LOG.error(throwable.toString()))
                .hasMessageContaining(parameter(0).getName());

        assertThatThrownBy(() ->
                addEntry(entry(ExtArrays.replace(this.originalValues, 0, Range.of(this.values.originalMidValue2, this.values.otherMidValue))))
        ).isInstanceOf(IllegalStateException.class)
                .satisfies(throwable -> LOG.error(throwable.toString()))
                .hasMessageContaining(parameter(0).getName());

        assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1));
        assertThat(optGet(valueQuery(this.values.otherMidValue, 1))).isEmpty();
    }

    @Test
    @DisplayName("Does not allow adding a fully-contained range")
    public void testAddFullyContainedOverlappingRange() {
        assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1));
        assertThat(get(valueQuery(this.values.originalMidValue2, 1))).isEqualTo(originalValue(1));

        assertThatThrownBy(() ->
                addEntry(entry(ExtArrays.replace(this.originalValues, 0, Range.of(this.values.originalMidValue1, this.values.originalMidValue2))))
        ).isInstanceOf(IllegalStateException.class)
                .satisfies(throwable -> LOG.error(throwable.toString()))
                .hasMessageContaining(parameter(0).getName());

        assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1));
        assertThat(get(valueQuery(this.values.originalMidValue2, 1))).isEqualTo(originalValue(1));
    }

    @Test
    @DisplayName("Adding an entry preceding another entry")
    public void testAddAdjoiningRangeBefore() {
        assertThat(optGet(valueQuery(this.values.lowerValue, 1))).isEmpty();
        assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1));

        addEntry(entry(ExtArrays.replace(this.otherValues, 0, Range.of(this.values.lowerValue, this.values.originalLowValue))));

        assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1));
        assertThat(get(valueQuery(this.values.lowerValue, 1))).isEqualTo(otherValue(1));
    }

    @Test
    @DisplayName("Adding an entry following another entry")
    public void testAddAdjoiningRangeAfter() {
        assertThat(optGet(valueQuery(this.values.otherMidValue, 1))).isEmpty();
        assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1));

        addEntry(entry(ExtArrays.replace(this.otherValues, 0, Range.of(this.values.originalHighValue, this.values.higherValue))));

        assertThat(get(valueQuery(this.values.originalMidValue1, 1))).isEqualTo(originalValue(1));
        assertThat(get(valueQuery(this.values.otherMidValue, 1))).isEqualTo(otherValue(1));
    }

}


text:
### アプリケーションの設定
pom.xml
```
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
```

application.properties
```
spring.mail.host=XXX
spring.mail.port=25
spring.mail.username=XXX
spring.mail.password=XXX
```

### Java
```java
@Autowired
private MailSender sender;

public void hoge() {
    SimpleMailMessage msg = new SimpleMailMessage();

    msg.setFrom("from@example.com");
    msg.setTo("to@exapmle.com");
    msg.setSubject("タイトル");
    msg.setText("本文");

    sender.send(msg);
}
```


text:
title: "Friday Hacks #143, November 3"
date: 2017-10-31 00:09:44.471653
author: Herbert
url: /2017/11/friday-hacks-143
---

Hey everyone! This week, we have E-Liang, a freshman, talking about his project Jarvis, which is a personal assistant. We also have Angad, a data scientist at Twitter Singapore talking about its stack. See you there!

{{< friday_hack_header venue="SR3, Town Plaza, University Town, NUS" date="November 3" >}}

### Building Jarvis

#### Talk Description:

This talk describes how I built my own personal assistant, inspired by Star Trek's LCARS and Iron Man's Jarvis. I will talk about my design and implementation of such a system, some technical challenges I faced and some pointers for anyone seeking to build their own Jarvis.

#### Speaker Profile

E-Liang is a freshman Computer Science undergraduate student at NUS. He taught himself programming 8 years ago and has been hacking on projects ever since.

### Data Engineering at Twitter

#### Talk Description:

With hundreds of petabytes of data at Twitter, every data scientist and engineer writes production quality data processing jobs. Here, we will dive into how we work with this data to produce insights for decisions across the company.

#### Speaker Profile

Angad Singh is a data scientist at Twitter Singapore. He graduated from NUS Computer Engineering, and he was the president of NUSHackers in 2010-11.


text:
<!DOCTYPE html>

<link rel="author" title="David Grogan" href="dgrogan@chromium.org">
<link rel="help" href="https://drafts.csswg.org/css-box-3/#padding-physical" title="Percentages line">
<meta name="assert" content="item's padding is resolved against parent's size, not item's" />

If the item's % padding is calculated correctly, there is a blue square on the left and an orange square on the right, both 50x50.

<x-flexbox>
  <x-item>

  </x-item>
</x-flexbox>


text:
class SectionsController < ApplicationController
  before_action :authenticate_teacher!

  def index
  end

  def show
    @ungraded_assignments = assignments.select{ |assignment| !assignment.fully_graded? }
  end

  def create
    @section = Section.new(section_params)
    if @section.save
      redirect_to root_path
      flash[:notice] = 'Section successfully created!'
    else
      render :new
    end
  end

  def new
    @section = Section.new
  end

  def edit
  end

  def update
    if section_params[:file]
      parser = CsvParsingService.new(section_params[:file].tempfile, section)
      if parser.run
        redirect_to section_path(section)
      end
    else
      if section.update(section_params)
        redirect_to section_path
        flash[:notice] = 'Section successfully updated!'
      else
        render :edit
      end
    end
  end

  def destroy
    if section.destroy
      redirect_to root_path
    end
  end

private
  def sections
    @sections ||= current_teacher.sections.decorate
  end
  helper_method :sections

  def section
    @section ||= current_teacher.sections.find(params[:id]).decorate
  end
  helper_method :section

  def seats
    @seats ||= section.seats.decorate
  end
  helper_method :seats

  def assignments
    @assignments ||= section.assignments.decorate
  end
  helper_method :assignments

  def section_params
    params.require(:section).permit(:term_id, :course_id, :academic_year_start, :academic_year_end, :period, :teacher_id, :file)
  end
end


text:
package org.bergefall.iobase.server;

import java.util.List;

import org.bergefall.iobase.blp.BusinessLogicPipline;
import org.bergefall.protocol.metatrader.MetaTraderProtos.MetaTraderMessage;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class MetaTraderTcpServerHandlerBase extends SimpleChannelInboundHandler<MetaTraderMessage> {

	private List<BusinessLogicPipline> businessPipelines;

	public MetaTraderTcpServerHandlerBase(List<BusinessLogicPipline> blp) {
		super();
		businessPipelines = blp;
	}

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, MetaTraderMessage msg)
      throws Exception {
	  for (BusinessLogicPipline pipeline : businessPipelines) {
		  pipeline.enqueue(msg);
	  }
  }

  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) {
      ctx.flush();
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
      cause.printStackTrace();
      ctx.close();
  }

}


text:
class CreateSearchLogs < ActiveRecord::Migration[5.2]
  def change
    create_table :search_logs do |t|
      t.references :user
      t.references :short_link
      t.timestamps
    end
  end
end


text:
package handler

import (
	"github.com/gorilla/sessions"
	"github.com/seka/bbs-sample/database"
)

// Option ...
type Option struct {
	CookieStore sessions.Store
	DB          database.Database
}


text:
namespace {

const char* const kNetworkProxyTypeKey = "network.proxy.type";
const char* const kHTTPProxyKey = "network.proxy.http";
const char* const kHTTPProxyPortKey = "network.proxy.http_port";
const char* const kSSLProxyKey = "network.proxy.ssl";
const char* const kSSLProxyPortKey = "network.proxy.ssl_port";
const char* const kFTPProxyKey = "network.proxy.ftp";
const char* const kFTPProxyPortKey = "network.proxy.ftp_port";
const char* const kGopherProxyKey = "network.proxy.gopher";
const char* const kGopherProxyPortKey = "network.proxy.gopher_port";
const char* const kSOCKSHostKey = "network.proxy.socks";
const char* const kSOCKSHostPortKey = "network.proxy.socks_port";
const char* const kSOCKSVersionKey = "network.proxy.socks_version";
const char* const kAutoconfigURL = "network.proxy.autoconfig_url";
const char* const kNoProxyListKey = "network.proxy.no_proxies_on";
const char* const kPrefFileName = "prefs.js";

FirefoxProxySettings::ProxyConfig IntToProxyConfig(int type) {
  switch (type) {
    case 1:
      return FirefoxProxySettings::MANUAL;
    case 2:
      return FirefoxProxySettings::AUTO_FROM_URL;
    case 4:
      return FirefoxProxySettings::AUTO_DETECT;
    case 5:
      return FirefoxProxySettings::SYSTEM;
    default:
      LOG(ERROR) << "Unknown Firefox proxy config type: " << type;
      return FirefoxProxySettings::NO_PROXY;
  }
}

FirefoxProxySettings::SOCKSVersion IntToSOCKSVersion(int type) {
  switch (type) {
    case 4:
      return FirefoxProxySettings::V4;
    case 5:
      return FirefoxProxySettings::V5;
    default:
      LOG(ERROR) << "Unknown Firefox proxy config type: " << type;
      return FirefoxProxySettings::UNKNONW;
  }
}

// Parses the prefs found in the file |pref_file| and puts the key/value pairs
// in |prefs|. Keys are strings, and values can be strings, booleans or
// integers.  Returns true if it succeeded, false otherwise (in which case
// |prefs| is not filled).
// Note: for strings, only valid UTF-8 string values are supported. If a
// key/pair is not valid UTF-8, it is ignored and will not appear in |prefs|.
bool ParsePrefFile(const base::FilePath& pref_file,
                   base::DictionaryValue* prefs) {
  // The string that is before a pref key.
  const std::string kUserPrefString = "user_pref(\"";
  std::string contents;
  if (!base::ReadFileToString(pref_file, &contents))
    return false;

  std::vector<std::string> lines;
  Tokenize(contents, "\n", &lines);

  for (std::vector<std::string>::const_iterator iter = lines.begin();
       iter != lines.end(); ++iter) {
    const std::string& line = *iter;
    size_t start_key = line.find(kUserPrefString);
    if (start_key == std::string::npos)
      continue;  // Could be a comment or a blank line.
    start_key += kUserPrefString.length();
    size_t stop_key = line.find('"', start_key);
    if (stop_key == std::string::npos) {
      LOG(ERROR) << "Invalid key found in Firefox pref file '" <<
          pref_file.value() << "' line is '" << line << "'.";
      continue;
    }
    std::string key = line.substr(start_key, stop_key - start_key);
    size_t start_value = line.find(',', stop_key + 1);
    if (start_value == std::string::npos) {
      LOG(ERROR) << "Invalid value found in Firefox pref file '" <<
          pref_file.value() << "' line is '" << line << "'.";
      continue;
    }
    size_t stop_value = line.find(");", start_value + 1);
    if (stop_value == std::string::npos) {
      LOG(ERROR) << "Invalid value found in Firefox pref file '" <<
          pref_file.value() << "' line is '" << line << "'.";
      continue;
    }
    std::string value = line.substr(start_value + 1,
                                    stop_value - start_value - 1);
    base::TrimWhitespace(value, base::TRIM_ALL, &value);
    // Value could be a boolean.
    bool is_value_true = LowerCaseEqualsASCII(value, "true");
    if (is_value_true || LowerCaseEqualsASCII(value, "false")) {
      prefs->SetBoolean(key, is_value_true);
      continue;
    }

    // Value could be a string.
    if (value.size() >= 2U &&
        value[0] == '"' && value[value.size() - 1] == '"') {
      value = value.substr(1, value.size() - 2);
      // ValueString only accept valid UTF-8.  Simply ignore that entry if it is
      // not UTF-8.
      if (IsStringUTF8(value))
        prefs->SetString(key, value);
      else
        VLOG(1) << "Non UTF8 value for key " << key << ", ignored.";
      continue;
    }

    // Or value could be an integer.
    int int_value = 0;
    if (base::StringToInt(value, &int_value)) {
      prefs->SetInteger(key, int_value);
      continue;
    }

    LOG(ERROR) << "Invalid value found in Firefox pref file '"
               << pref_file.value() << "' value is '" << value << "'.";
  }
  return true;
}

}  // namespace

FirefoxProxySettings::FirefoxProxySettings() {
  Reset();
}

FirefoxProxySettings::~FirefoxProxySettings() {
}

void FirefoxProxySettings::Reset() {
  config_type_ = NO_PROXY;
  http_proxy_.clear();
  http_proxy_port_ = 0;
  ssl_proxy_.clear();
  ssl_proxy_port_ = 0;
  ftp_proxy_.clear();
  ftp_proxy_port_ = 0;
  gopher_proxy_.clear();
  gopher_proxy_port_ = 0;
  socks_host_.clear();
  socks_port_ = 0;
  socks_version_ = UNKNONW;
  proxy_bypass_list_.clear();
  autoconfig_url_.clear();
}

// static
bool FirefoxProxySettings::GetSettings(FirefoxProxySettings* settings) {
  DCHECK(settings);
  settings->Reset();

  base::FilePath profile_path = GetFirefoxProfilePath();
  if (profile_path.empty())
    return false;
  base::FilePath pref_file = profile_path.AppendASCII(kPrefFileName);
  return GetSettingsFromFile(pref_file, settings);
}

bool FirefoxProxySettings::ToProxyConfig(net::ProxyConfig* config) {
  switch (config_type()) {
    case NO_PROXY:
      *config = net::ProxyConfig::CreateDirect();
      return true;
    case AUTO_DETECT:
      *config = net::ProxyConfig::CreateAutoDetect();
      return true;
    case AUTO_FROM_URL:
      *config = net::ProxyConfig::CreateFromCustomPacURL(
          GURL(autoconfig_url()));
      return true;
    case SYSTEM:
      // Can't convert this directly to a ProxyConfig.
      return false;
    case MANUAL:
      // Handled outside of the switch (since it is a lot of code.)
      break;
    default:
      NOTREACHED();
      return false;
  }

  // The rest of this funciton is for handling the MANUAL case.
  DCHECK_EQ(MANUAL, config_type());

  *config = net::ProxyConfig();
  config->proxy_rules().type =
      net::ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME;

  if (!http_proxy().empty()) {
    config->proxy_rules().proxies_for_http.SetSingleProxyServer(
        net::ProxyServer(
            net::ProxyServer::SCHEME_HTTP,
            net::HostPortPair(http_proxy(), http_proxy_port())));
  }

  if (!ftp_proxy().empty()) {
    config->proxy_rules().proxies_for_ftp.SetSingleProxyServer(
        net::ProxyServer(
            net::ProxyServer::SCHEME_HTTP,
            net::HostPortPair(ftp_proxy(), ftp_proxy_port())));
  }

  if (!ssl_proxy().empty()) {
    config->proxy_rules().proxies_for_https.SetSingleProxyServer(
        net::ProxyServer(
            net::ProxyServer::SCHEME_HTTP,
            net::HostPortPair(ssl_proxy(), ssl_proxy_port())));
  }

  if (!socks_host().empty()) {
    net::ProxyServer::Scheme proxy_scheme = V5 == socks_version() ?
        net::ProxyServer::SCHEME_SOCKS5 : net::ProxyServer::SCHEME_SOCKS4;

    config->proxy_rules().fallback_proxies.SetSingleProxyServer(
        net::ProxyServer(
            proxy_scheme,
            net::HostPortPair(socks_host(), socks_port())));
  }

  config->proxy_rules().bypass_rules.ParseFromStringUsingSuffixMatching(
      JoinString(proxy_bypass_list_, ';'));

  return true;
}

// static
bool FirefoxProxySettings::GetSettingsFromFile(const base::FilePath& pref_file,
                                               FirefoxProxySettings* settings) {
  base::DictionaryValue dictionary;
  if (!ParsePrefFile(pref_file, &dictionary))
    return false;

  int proxy_type = 0;
  if (!dictionary.GetInteger(kNetworkProxyTypeKey, &proxy_type))
    return true;  // No type means no proxy.

  settings->config_type_ = IntToProxyConfig(proxy_type);
  if (settings->config_type_ == AUTO_FROM_URL) {
    if (!dictionary.GetStringASCII(kAutoconfigURL,
                                   &(settings->autoconfig_url_))) {
      LOG(ERROR) << "Failed to retrieve Firefox proxy autoconfig URL";
    }
    return true;
  }

  if (settings->config_type_ == MANUAL) {
    if (!dictionary.GetStringASCII(kHTTPProxyKey, &(settings->http_proxy_)))
      LOG(ERROR) << "Failed to retrieve Firefox proxy HTTP host";
    if (!dictionary.GetInteger(kHTTPProxyPortKey,
                               &(settings->http_proxy_port_))) {
      LOG(ERROR) << "Failed to retrieve Firefox proxy HTTP port";
    }
    if (!dictionary.GetStringASCII(kSSLProxyKey, &(settings->ssl_proxy_)))
      LOG(ERROR) << "Failed to retrieve Firefox proxy SSL host";
    if (!dictionary.GetInteger(kSSLProxyPortKey, &(settings->ssl_proxy_port_)))
      LOG(ERROR) << "Failed to retrieve Firefox proxy SSL port";
    if (!dictionary.GetStringASCII(kFTPProxyKey, &(settings->ftp_proxy_)))
      LOG(ERROR) << "Failed to retrieve Firefox proxy FTP host";
    if (!dictionary.GetInteger(kFTPProxyPortKey, &(settings->ftp_proxy_port_)))
      LOG(ERROR) << "Failed to retrieve Firefox proxy SSL port";
    if (!dictionary.GetStringASCII(kGopherProxyKey, &(settings->gopher_proxy_)))
      LOG(ERROR) << "Failed to retrieve Firefox proxy gopher host";
    if (!dictionary.GetInteger(kGopherProxyPortKey,
                               &(settings->gopher_proxy_port_))) {
      LOG(ERROR) << "Failed to retrieve Firefox proxy gopher port";
    }
    if (!dictionary.GetStringASCII(kSOCKSHostKey, &(settings->socks_host_)))
      LOG(ERROR) << "Failed to retrieve Firefox SOCKS host";
    if (!dictionary.GetInteger(kSOCKSHostPortKey, &(settings->socks_port_)))
      LOG(ERROR) << "Failed to retrieve Firefox SOCKS port";
    int socks_version;
    if (dictionary.GetInteger(kSOCKSVersionKey, &socks_version))
      settings->socks_version_ = IntToSOCKSVersion(socks_version);

    std::string proxy_bypass;
    if (dictionary.GetStringASCII(kNoProxyListKey, &proxy_bypass) &&
        !proxy_bypass.empty()) {
      base::StringTokenizer string_tok(proxy_bypass, ",");
      while (string_tok.GetNext()) {
        std::string token = string_tok.token();
        base::TrimWhitespaceASCII(token, base::TRIM_ALL, &token);
        if (!token.empty())
          settings->proxy_bypass_list_.push_back(token);
      }
    }
  }
  return true;
}


text:
package shared

import (
	"bytes"
	"encoding/binary"
	"io"
)

// BufferedReaderFlags is an enum to configure a buffered reader
type BufferedReaderFlags byte

const (
	// BufferedReaderFlagDelimiter enables reading for a delimiter. This flag is
	// ignored if an MLE flag is set.
	BufferedReaderFlagDelimiter = BufferedReaderFlags(0)

	// BufferedReaderFlagMLE enables reading if length encoded messages.
	// Runlength is read as ASCII (to uint64) until the first byte (ASCII char)
	// of the delimiter string.
	// Only one MLE flag is supported at a time.
	BufferedReaderFlagMLE = BufferedReaderFlags(1)

	// BufferedReaderFlagMLE8 enables reading if length encoded messages.
	// Runlength is read as binary (to uint8).
	// Only one MLE flag is supported at a time.
	BufferedReaderFlagMLE8 = BufferedReaderFlags(2)

	// BufferedReaderFlagMLE16 enables reading if length encoded messages.
	// Runlength is read as binary (to uint16).
	// Only one MLE flag is supported at a time.
	BufferedReaderFlagMLE16 = BufferedReaderFlags(3)

	// BufferedReaderFlagMLE32 enables reading if length encoded messages.
	// Runlength is read as binary (to uint32).
	// Only one MLE flag is supported at a time.
	BufferedReaderFlagMLE32 = BufferedReaderFlags(4)

	// BufferedReaderFlagMLE64 enables reading if length encoded messages.
	// Runlength is read as binary (to uint64).
	// Only one MLE flag is supported at a time.
	BufferedReaderFlagMLE64 = BufferedReaderFlags(5)

	// BufferedReaderFlagMLEFixed enables reading messages with a fixed length.
	// Only one MLE flag is supported at a time.
	BufferedReaderFlagMLEFixed = BufferedReaderFlags(6)

	// BufferedReaderFlagMaskMLE is a bitmask to mask out everything but MLE flags
	BufferedReaderFlagMaskMLE = BufferedReaderFlags(7)

	// BufferedReaderFlagBigEndian sets binary reading to big endian encoding.
	BufferedReaderFlagBigEndian = BufferedReaderFlags(8)

	// BufferedReaderFlagEverything will keep MLE and/or delimiters when
	// building a message.
	BufferedReaderFlagEverything = BufferedReaderFlags(16)
)

type bufferError string

func (b bufferError) Error() string {
	return string(b)
}

// BufferReadCallback defines the function signature for callbacks passed to
// ReadAll.
type BufferReadCallback func(msg []byte, sequence uint64)

// BufferDataInvalid is returned when a parsing encounters an error
var BufferDataInvalid = bufferError("Invalid data")

// BufferedReader is a helper struct to read from any io.Reader into a byte
// slice. The data can arrive "in pieces" and will be assembled.
// A data "piece" is considered complete if a delimiter or a certain runlength
// has been reached. The latter has to be enabled by flag and will disable the
// default behavior, which is looking for a delimiter string.
// In addition to that every data "piece" will receive an incrementing sequence
// number.
type BufferedReader struct {
	data       []byte
	delimiter  []byte
	parse      func() ([]byte, int)
	sequence   uint64
	paramMLE   int
	growSize   int
	end        int
	encoding   binary.ByteOrder
	flags      BufferedReaderFlags
	incomplete bool
}

// NewBufferedReader creates a new buffered reader that reads messages from a
// continuous stream of bytes.
// Messages can be separated from the stream by using common methods such as
// fixed size, encoded message length or delimiter string.
// The internal buffer is grown statically (by its original size) if necessary.
// bufferSize defines the initial size / grow size of the buffer
// flags configures the parsing method
// offsetOrLength sets either the runlength offset or fixed message size
// delimiter defines the delimiter used for textual message parsing
func NewBufferedReader(bufferSize int, flags BufferedReaderFlags, offsetOrLength int, delimiter string) *BufferedReader {
	buffer := BufferedReader{
		data:       make([]byte, bufferSize),
		delimiter:  []byte(delimiter),
		paramMLE:   offsetOrLength,
		encoding:   binary.LittleEndian,
		sequence:   0,
		end:        0,
		flags:      flags,
		growSize:   bufferSize,
		incomplete: true,
	}

	if flags&BufferedReaderFlagBigEndian != 0 {
		buffer.encoding = binary.BigEndian
	}

	if flags&BufferedReaderFlagMaskMLE == 0 {
		buffer.parse = buffer.parseDelimiter
	} else {
		switch flags & BufferedReaderFlagMaskMLE {
		default:
			buffer.parse = buffer.parseMLEText
		case BufferedReaderFlagMLE8:
			buffer.parse = buffer.parseMLE8
		case BufferedReaderFlagMLE16:
			buffer.parse = buffer.parseMLE16
		case BufferedReaderFlagMLE32:
			buffer.parse = buffer.parseMLE32
		case BufferedReaderFlagMLE64:
			buffer.parse = buffer.parseMLE64
		case BufferedReaderFlagMLEFixed:
			buffer.parse = buffer.parseMLEFixed
		}
	}

	return &buffer
}

// Reset clears the buffer by resetting its internal state
func (buffer *BufferedReader) Reset(sequence uint64) {
	buffer.sequence = sequence
	buffer.end = 0
	buffer.incomplete = true
}

// general message extraction part of all parser methods
func (buffer *BufferedReader) extractMessage(messageLen int, msgStartIdx int) ([]byte, int) {
	nextMsgIdx := msgStartIdx + messageLen
	if nextMsgIdx > buffer.end {
		return nil, 0 // ### return, incomplete ###
	}
	if buffer.flags&BufferedReaderFlagEverything != 0 {
		msgStartIdx = 0
	}
	return buffer.data[msgStartIdx:nextMsgIdx], nextMsgIdx
}

// messages have a fixed size
func (buffer *BufferedReader) parseMLEFixed() ([]byte, int) {
	return buffer.extractMessage(buffer.paramMLE, 0)
}

// messages are separated by a delimiter string
func (buffer *BufferedReader) parseDelimiter() ([]byte, int) {
	delimiterIdx := bytes.Index(buffer.data[:buffer.end], buffer.delimiter)
	if delimiterIdx == -1 {
		return nil, 0 // ### return, incomplete ###
	}

	messageLen := delimiterIdx
	if buffer.flags&BufferedReaderFlagEverything != 0 {
		messageLen += len(buffer.delimiter)
	}

	data, nextMsgIdx := buffer.extractMessage(messageLen, 0)

	if data != nil && buffer.flags&BufferedReaderFlagEverything == 0 {
		nextMsgIdx += len(buffer.delimiter)
	}
	return data, nextMsgIdx
}

// messages are separeated length encoded by ASCII number and (an optional)
// delimiter.
func (buffer *BufferedReader) parseMLEText() ([]byte, int) {
	messageLen, msgStartIdx := Btoi(buffer.data[buffer.paramMLE:buffer.end])
	if msgStartIdx == 0 {
		return nil, -1 // ### return, malformed ###
	}

	msgStartIdx += buffer.paramMLE
	// Read delimiter if necessary (check if valid runlength)
	if delimiterLen := len(buffer.delimiter); delimiterLen > 0 {
		msgStartIdx += delimiterLen
		if msgStartIdx >= buffer.end {
			return nil, 0 // ### return, incomplete ###
		}
		if !bytes.Equal(buffer.data[msgStartIdx-delimiterLen:msgStartIdx], buffer.delimiter) {
			return nil, -1 // ### return, malformed ###
		}
	}

	return buffer.extractMessage(int(messageLen), msgStartIdx)
}

// messages are separated binary length encoded
func (buffer *BufferedReader) parseMLE8() ([]byte, int) {
	var messageLen uint8
	reader := bytes.NewReader(buffer.data[buffer.paramMLE:buffer.end])
	err := binary.Read(reader, buffer.encoding, &messageLen)
	if err != nil {
		return nil, -1 // ### return, malformed ###
	}
	return buffer.extractMessage(int(messageLen), buffer.paramMLE+1)
}

// messages are separated binary length encoded
func (buffer *BufferedReader) parseMLE16() ([]byte, int) {
	var messageLen uint16
	reader := bytes.NewReader(buffer.data[buffer.paramMLE:buffer.end])
	err := binary.Read(reader, buffer.encoding, &messageLen)
	if err != nil {
		return nil, -1 // ### return, malformed ###
	}
	return buffer.extractMessage(int(messageLen), buffer.paramMLE+2)
}

// messages are separated binary length encoded
func (buffer *BufferedReader) parseMLE32() ([]byte, int) {
	var messageLen uint32
	reader := bytes.NewReader(buffer.data[buffer.paramMLE:buffer.end])
	err := binary.Read(reader, buffer.encoding, &messageLen)
	if err != nil {
		return nil, -1 // ### return, malformed ###
	}
	return buffer.extractMessage(int(messageLen), buffer.paramMLE+4)
}

// messages are separated binary length encoded
func (buffer *BufferedReader) parseMLE64() ([]byte, int) {
	var messageLen uint64
	reader := bytes.NewReader(buffer.data[buffer.paramMLE:buffer.end])
	err := binary.Read(reader, buffer.encoding, &messageLen)
	if err != nil {
		return nil, -1 // ### return, malformed ###
	}
	return buffer.extractMessage(int(messageLen), buffer.paramMLE+8)
}

// ReadAll calls ReadOne as long as there are messages in the stream.
// Messages will be send to the given write callback.
// If callback is nil, data will be read and discarded.
func (buffer *BufferedReader) ReadAll(reader io.Reader, callback BufferReadCallback) error {
	for {
		data, seq, more, err := buffer.ReadOne(reader)
		if data != nil && callback != nil {
			callback(data, seq)
		}

		if err != nil {
			return err // ### return, error ###
		}

		if !more {
			return nil // ### return, done ###
		}
	}
}

// ReadOne reads the next message from the given stream (if possible) and
// generates a sequence number for this message.
// The more return parameter is set to true if there are still messages or parts
// of messages in the stream. Data and seq is only set if a complete message
// could be parsed.
// Errors are returned if reading from the stream failed or the parser
// encountered an error.
func (buffer *BufferedReader) ReadOne(reader io.Reader) (data []byte, seq uint64, more bool, err error) {
	if buffer.incomplete {
		bytesRead, err := reader.Read(buffer.data[buffer.end:])

		if err != nil && err != io.EOF {
			return nil, 0, buffer.end > 0, err // ### return, error reading ###
		}

		if bytesRead == 0 {
			return nil, 0, buffer.end > 0, err // ### return, no data ###
		}

		buffer.end += bytesRead
		buffer.incomplete = false
	}

	msgData, nextMsgIdx := buffer.parse()

	if nextMsgIdx == -1 {
		buffer.end = 0
		buffer.incomplete = true
		return nil, 0, true, BufferDataInvalid // ### return, invalid data ###
	}

	if msgData == nil {
		// Check if buffer needs to be resized
		if len(buffer.data) == buffer.end {
			temp := buffer.data
			buffer.data = make([]byte, len(buffer.data)+buffer.growSize)
			copy(buffer.data, temp)
		}
		buffer.incomplete = true
		return nil, 0, true, err // ### return, incomplete ###
	}

	msgDataCopy := make([]byte, len(msgData))
	copy(msgDataCopy, msgData)

	if nextMsgIdx < buffer.end {
		copy(buffer.data, buffer.data[nextMsgIdx:buffer.end])
		buffer.end -= nextMsgIdx
	} else {
		buffer.end = 0
		buffer.incomplete = true
	}

	seqNum := buffer.sequence
	buffer.sequence++
	return msgDataCopy, seqNum, buffer.end > 0, err
}


text:
require 'rails_helper'

describe UsersController do
  it "redirects to home page upon save" do
    post :create, {user: {user_name:"test123", password:"test123"}}
    response.should redirect_to root_url
  end
end


text:
import { css } from 'glamor'
import React from 'react'
import View, { IViewProps } from '../View'

const style = css({
  borderTop: '1px solid #e7ecee',
  '> *': {
    padding: '10px 13px',
    textAlign: 'center',
  },
  '> :not(:last-child)': {
    borderRight: '1px solid #e7ecee',
  },
})

const CardFooter = (props: IViewProps) => (
  <View
    alignH="space-around"
    alignV="center"
    direction="row"
    {...style}
    {...props}
  />
)

export default CardFooter


text:
import sympy as sp

from means.core import ODEProblem
from means.approximation.approximation_baseclass import ApproximationBaseClass
from means.util.moment_counters import generate_n_and_k_counters

from dmu_over_dt import generate_dmu_over_dt
from eq_central_moments import eq_central_moments
from raw_to_central import raw_to_central
from means.util.sympyhelpers import substitute_all, quick_solve

from closure_gamma import GammaClosure
from closure_log_normal import LogNormalClosure
from closure_normal import NormalClosure
from closure_scalar import ScalarClosure

def mea_approximation(model, max_order, closure='scalar', *closure_args, **closure_kwargs):
    r"""
    A wrapper around :class:`~means.approximation.mea.moment_expansion_approximation.MomentExpansionApproximation`.
    It performs moment expansion approximation (MEA) up to a given order of moment.
    See :class:`~means.approximation.mea.moment_expansion_approximation.MomentExpansionApproximation` for details
    about the options.

    :return: an ODE problem which can be further used in inference and simulation.
    :rtype: :class:`~means.core.problems.ODEProblem`
    """
    mea = MomentExpansionApproximation(model, max_order, closure=closure, *closure_args, **closure_kwargs)
    return mea.run()

class MomentExpansionApproximation(ApproximationBaseClass):
    r"""
    A class to perform moment expansion approximation as described in [Ale2013]_ up to a given order of moment.
    In addition, it allows to close the Taylor expansion by using parametric values for last order central moments.

    """
    def __init__(self, model, max_order, closure='scalar', *closure_args, **closure_kwargs):

        r"""
        :param model: The model to be approximated
        :type model: :class:`~means.core.model.Model`

        :param max_order: the highest order of central moments in the resulting ODEs
        :param closure: a string describing the type of closure to use. Currently, the supported closures are:

            `'scalar'`
                higher order central moments are set to zero.
                See :class:`~means.approximation.mea.closure_scalar.ScalarClosure`.
            `'normal'`
                uses normal distribution to compute last order central moments.
                See :class:`~means.approximation.mea.closure_normal.NormalClosure`.
            `'log-normal'`
                uses log-normal distribution.
                See :class:`~means.approximation.mea.closure_log_normal.LogNormalClosure`.
            `'gamma'`
                *EXPERIMENTAL*,
                uses gamma distribution.
                See :class:`~means.approximation.mea.closure_gamma.GammaClosure`.

        :type closure: string
        :param closure_args: arguments to be passed to the closure
        :param closure_kwargs: keyword arguments to be passed to the closure
        """
        super(MomentExpansionApproximation, self).__init__(model)

        max_order = int(max_order)
        if max_order < 1:
            raise ValueError("`max_order` can only be POSITIVE, {0!r} given".format(max_order))

        self.__max_order = max_order

        # A dictionary of "option -> closure". this allows a generic handling for closure without having to add
        # if-else and exceptions when implementing new closures. One only needs to add the new closure class to the dict
        supported_closures = {"log-normal": LogNormalClosure,
                             "scalar": ScalarClosure,
                             "normal": NormalClosure,
                             "gamma": GammaClosure}

        # We initialise the closure for this approximation
        try:
            # our closure is an instance of the class queried in the dictionary
            ClosureClass = supported_closures[closure]
            self.__closure = ClosureClass(self.__max_order, *closure_args, **closure_kwargs)
        except KeyError:
            error_str = "The closure type '{0}' is not supported.\n\
                         Supported values for closure:\
                         {1}"
            raise KeyError(error_str.format(closure, supported_closures))

    @property
    def closure(self):
        return self.__closure

    def run(self):
        r"""
        Overrides the default run() method.
        Performs the complete analysis on the model specified during initialisation.

        :return: an ODE problem which can be further used in inference and simulation.
        :rtype: :class:`~means.core.problems.ODEProblem`
        """
        max_order = self.__max_order
        stoichiometry_matrix = self.model.stoichiometry_matrix
        propensities = self.model.propensities
        species = self.model.species
        # compute n_counter and k_counter; the "n" and "k" vectors in equations, respectively.
        n_counter, k_counter = generate_n_and_k_counters(max_order, species)
        # dmu_over_dt has row per species and one col per element of n_counter (eq. 6)
        dmu_over_dt = generate_dmu_over_dt(species, propensities, n_counter, stoichiometry_matrix)
        # Calculate expressions to use in central moments equations (eq. 9)
        central_moments_exprs = eq_central_moments(n_counter, k_counter, dmu_over_dt, species, propensities, stoichiometry_matrix, max_order)
        # Expresses central moments in terms of raw moments (and central moments) (eq. 8)
        central_from_raw_exprs = raw_to_central(n_counter, species, k_counter)
        # Substitute raw moment, in central_moments, with expressions depending only on central moments
        central_moments_exprs = self._substitute_raw_with_central(central_moments_exprs, central_from_raw_exprs, n_counter, k_counter)
        # Get final right hand side expressions for each moment in a vector
        mfk = self._generate_mass_fluctuation_kinetics(central_moments_exprs, dmu_over_dt, n_counter)
        # Applies moment expansion closure, that is replaces last order central moments by parametric expressions
        mfk = self.closure.close(mfk, central_from_raw_exprs, n_counter, k_counter)
        # These are the left hand sign symbols referring to the mfk
        prob_lhs = self._generate_problem_left_hand_side(n_counter, k_counter)
        # Finally, we build the problem
        out_problem = ODEProblem("MEA", prob_lhs, mfk, sp.Matrix(self.model.parameters))
        return out_problem

    def _generate_problem_left_hand_side(self, n_counter, k_counter):
        """
        Generate the left hand side of the ODEs. This is simply the
        symbols for the corresponding moments.
        Note that, in principle, they are in of course fact the
        time derivative of the moments.

        :param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments
        :type n_counter: list[:class:`~means.core.descriptors.Moment`]
        :param k_counter: a list of :class:`~means.core.descriptors.Moment`\s representing raw moments
        :type k_counter: list[:class:`~means.core.descriptors.Moment`]
        :return: a list of the problem left hand sides
        :rtype: list[:class:`sympy.Symbol`]
        """

        # concatenate the symbols for first order raw moments (means)
        prob_moments_over_dt = [k for k in k_counter if k.order == 1]
        # and the higher order central moments (variances, covariances,...)
        prob_moments_over_dt += [n for n in n_counter if self.__max_order >= n.order > 1]

        return prob_moments_over_dt

    def _generate_mass_fluctuation_kinetics(self, central_moments, dmu_over_dt, n_counter):
        """
        Generate the Mass Fluctuation Kinetics (i.e. the right hand side of the ODEs)

        :param central_moments: The matrix of central moment expressions
        :param dmu_over_dt:
        :param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments
        :type n_counter: list[:class:`~means.core.descriptors.Moment`]
        :return: the MFK as a matrix
        :rtype: :class:`sympy.Matrix`
        """

        # symbols for central moments
        central_moments_symbols = sp.Matrix([n.symbol for n in n_counter])

        # rhs for the first order raw moment
        mfk = [e for e in dmu_over_dt * central_moments_symbols]
        # rhs for the higher order raw moments
        mfk += [(sp.Matrix(cm).T * central_moments_symbols)[0] for cm in central_moments.tolist()]

        mfk = sp.Matrix(mfk)

        return mfk

    def _substitute_raw_with_central(self, central_moments_exprs, central_from_raw_exprs, n_counter, k_counter):
        r"""
        Takes the expressions for central moments, and substitute the symbols representing raw moments,
        by equivalent expressions in terms of central moment

        :param central_moments_exprs: a matrix of expressions for central moments.
        :param central_from_raw_exprs: central moment expressed in terms of raw moments
        :param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments
        :type n_counter: list[:class:`~means.core.descriptors.Moment`]
        :param k_counter: a list of :class:`~means.core.descriptors.Moment`\s representing raw moments
        :type k_counter: list[:class:`~means.core.descriptors.Moment`]

        :return: expressions for central moments without raw moment
        """
        positiv_raw_moms_symbs = [raw.symbol for raw in k_counter if raw.order > 1]
        # The symbols for the corresponding central moment
        central_symbols= [central.symbol for central in n_counter if central.order > 1]
        # Now we state (central_symbols == central_from_raw_exprs)
        eq_to_solve = [cfr - cs for (cs, cfr) in zip(central_symbols, central_from_raw_exprs)]

        # And we solve this for the symbol of the corresponding raw moment. This gives an expression
        # of the symbol for raw moment in terms of central moments and lower order raw moment
        solved_xs = sp.Matrix([quick_solve(eq,raw) for (eq, raw) in zip(eq_to_solve, positiv_raw_moms_symbs)])

        # now we want to express raw moments only in terms od central moments and means
        # for instance if we have: :math:`x_1 = 1; x_2 = 2 +x_1 and  x_3 = x_2*x_1`, we should give:
        # :math:`x_1 = 1; x_2 = 2+1 and  x_3 = 1*(2+1)`
        # To achieve this, we recursively apply substitution as many times as the highest order (minus one)
        max_order = max([p.order for p in k_counter])

        for i in range(max_order - 1):
            substitution_pairs = zip(positiv_raw_moms_symbs, solved_xs)
            solved_xs = substitute_all(solved_xs, substitution_pairs)

        # we finally build substitution pairs to replace all raw moments
        substitution_pairs = zip(positiv_raw_moms_symbs, solved_xs)

        # apply this substitution to all elements of the central moment expressions matrix
        out_exprs = substitute_all(central_moments_exprs, substitution_pairs)

        return out_exprs


text:
@interface BYListBar : UIScrollView

@property (nonatomic,copy) void(^arrowChange)();
@property (nonatomic,copy) void(^listBarItemClickBlock)(NSString *itemName , NSInteger itemIndex);

@property (nonatomic,strong) NSMutableArray *visibleItemList;

-(void)operationFromBlock:(animateType)type itemName:(NSString *)itemName index:(int)index;
-(void)itemClickByScrollerWithIndex:(NSInteger)index;

@end


text: Projeto 06 de POO


text:
#ifndef LILY_API_VALUE_H
# define LILY_API_VALUE_H

# include <stdint.h>

/* This file contains the structures and API needed by foreign functions to
   communicate with Lily. */

typedef struct lily_vm_state_ lily_vm_state;

typedef struct lily_dynamic_val_    lily_dynamic_val;
typedef struct lily_file_val_       lily_file_val;
typedef struct lily_foreign_val_    lily_foreign_val;
typedef struct lily_function_val_   lily_function_val;
typedef struct lily_generic_val_    lily_generic_val;
typedef struct lily_hash_elem_      lily_hash_elem;
typedef struct lily_hash_val_       lily_hash_val;
typedef struct lily_instance_val_   lily_instance_val;
typedef struct lily_list_val_       lily_list_val;
typedef struct lily_string_val_     lily_string_val;
typedef struct lily_value_          lily_value;

#define lily_isa_boolean(v)    (v & VAL_IS_BOOLEAN)
#define lily_isa_bytestring(v) (v & VAL_IS_BYTESTRING)
#define lily_isa_double(v)     (v & VAL_IS_DOUBLE)
#define lily_isa_dynamic(v)    (v & VAL_IS_DYNAMIC)
#define lily_isa_enum(v)       (v & VAL_IS_ENUM)
#define lily_isa_file(v)       (v & VAL_IS_FILE)
#define lily_isa_foreign(v)    (v & VAL_IS_FOREIGN)
#define lily_isa_function(v)   (v & VAL_IS_FUNCTION)
#define lily_isa_hash(v)       (v & VAL_IS_HASH)
#define lily_isa_instance(v)   (v & VAL_IS_INSTANCE)
#define lily_isa_integer(v)    (v & VAL_IS_INTEGER)
#define lily_isa_list(v)       (v & VAL_IS_LIST)
#define lily_isa_string(v)     (v & VAL_IS_STRING)
#define lily_isa_tuple(v)      (v & VAL_IS_TUPLE)

#define DECLARE_SETTERS(name, ...) \
void lily_##name##_boolean(__VA_ARGS__, int); \
void lily_##name##_double(__VA_ARGS__, double); \
void lily_##name##_empty_variant(__VA_ARGS__, lily_instance_val *); \
void lily_##name##_file(__VA_ARGS__, lily_file_val *); \
void lily_##name##_foreign(__VA_ARGS__, lily_foreign_val *); \
void lily_##name##_filled_variant(__VA_ARGS__, lily_instance_val *); \
void lily_##name##_hash(__VA_ARGS__, lily_hash_val *); \
void lily_##name##_instance(__VA_ARGS__, lily_instance_val *); \
void lily_##name##_integer(__VA_ARGS__, int64_t); \
void lily_##name##_list(__VA_ARGS__, lily_list_val *); \
void lily_##name##_string(__VA_ARGS__, lily_string_val *); \
void lily_##name##_tuple(__VA_ARGS__, lily_list_val *); \
void lily_##name##_value(__VA_ARGS__, lily_value *); \

/* Operations for specific kinds of values. */
lily_value *lily_new_empty_value(void); /* Try to not use this. */

/* ByteString operations */
char *lily_bytestring_get_raw(lily_string_val *);
int lily_bytestring_length(lily_string_val *);

/* Dynamic operations */
lily_dynamic_val *lily_new_dynamic_val(void);
void lily_dynamic_set_value(lily_dynamic_val *, lily_value *);

/* File operations */
lily_file_val *lily_new_file_val(FILE *, const char *);

/* Instance operations */
lily_instance_val *lily_new_instance_val(void);
lily_value *lily_instance_get(lily_instance_val *, int);
DECLARE_SETTERS(instance_set, lily_instance_val *, int)

/* Hash operations (still a work-in-progress) */
lily_hash_val *lily_new_hash_val(void);

/* List operations */
/* Deprecated, use list_of_n instead. */
lily_list_val *lily_new_list_val(void);
lily_list_val *lily_new_list_of_n(int);
DECLARE_SETTERS(list_set, lily_list_val *, int)

/* String operations */
lily_value *lily_new_string(const char *);
lily_value *lily_new_string_take(char *);
lily_string_val *lily_new_raw_string(const char *);
lily_string_val *lily_new_raw_string_sized(const char *, int);
char *lily_string_get_raw(lily_string_val *);
int lily_string_length(lily_string_val *);

/* Enum operations */
/* Hardcoded ids here are temporary, and will be removed later. */
#define SOME_VARIANT_ID 0
#define NONE_VARIANT_ID 1

#define RIGHT_VARIANT_ID 0
#define LEFT_VARIANT_ID  1

lily_instance_val *lily_new_left(void);
lily_instance_val *lily_new_right(void);
lily_instance_val *lily_new_some(void);
lily_instance_val *lily_get_none(lily_vm_state *);

DECLARE_SETTERS(variant_set, lily_instance_val *, int)

/* Stack operations
   Note: Push operations are sourced from vm. */
lily_value *lily_pop_value(lily_vm_state *);
void lily_drop_value(lily_vm_state *);
DECLARE_SETTERS(push, lily_vm_state *)

DECLARE_SETTERS(return, lily_vm_state *)
void lily_return_tag_dynamic(lily_vm_state *, lily_dynamic_val *);
void lily_return_value_noref(lily_vm_state *, lily_value *);

/* Calling, and argument fetching */
void lily_vm_prepare_call(lily_vm_state *, lily_function_val *);
void lily_vm_exec_prepared_call(lily_vm_state *, int);

int                lily_arg_count(lily_vm_state *);

int                lily_arg_boolean(lily_vm_state *, int);
double             lily_arg_double(lily_vm_state *, int);
lily_file_val *    lily_arg_file(lily_vm_state *, int);
FILE *             lily_arg_file_raw(lily_vm_state *, int);
lily_function_val *lily_arg_function(lily_vm_state *, int);
lily_hash_val *    lily_arg_hash(lily_vm_state *, int);
lily_generic_val * lily_arg_generic(lily_vm_state *, int);
lily_instance_val *lily_arg_instance(lily_vm_state *, int);
int64_t            lily_arg_integer(lily_vm_state *, int);
lily_list_val *    lily_arg_list(lily_vm_state *, int);
lily_string_val *  lily_arg_string(lily_vm_state *, int);
char *             lily_arg_string_raw(lily_vm_state *, int);
lily_value *       lily_arg_value(lily_vm_state *, int);

/* Result operations */
void lily_result_return(lily_vm_state *);
lily_value *lily_result_get(lily_vm_state *);
int lily_result_get_boolean(lily_vm_state *);

/* General operations. Special care should be taken with these. */

void lily_deref(lily_value *);
void lily_assign_value(lily_value *, lily_value *);
void lily_assign_value_noref(lily_value *, lily_value *);
lily_value *lily_copy_value(lily_value *);
int lily_eq_value(struct lily_vm_state_ *, lily_value *, lily_value *);

#endif


text:
"""Generic class for Set/Get properties of GData Provisioning clients."""

__author__ = 'Gunjan Sharma <gunjansharma@google.com>'

import gdata.apps
import gdata.apps_property
import gdata.data

class AppsPropertyEntry(gdata.data.GDEntry):
  """Represents a  generic entry in object form."""

  property = [gdata.apps_property.AppsProperty]

  def _GetProperty(self, name):
    """Get the apps:property value with the given name.

    Args:
      name: string Name of the apps:property value to get.

    Returns:
      The apps:property value with the given name, or None if the name was
          invalid.
    """
    value = None
    for p in self.property:
      if p.name == name:
        value = p.value
        break
    return value

  def _SetProperty(self, name, value):
    """Set the apps:property value with the given name to the given value.

    Args:
      name: string Name of the apps:property value to set.
      value: string Value to give the apps:property value with the given name.
    """
    found = False
    for i in range(len(self.property)):
      if self.property[i].name == name:
        self.property[i].value = value
        found = True
        break
    if not found:
      self.property.append(
          gdata.apps_property.AppsProperty(name=name, value=value))


text:
// Code generated by go-swagger; DO NOT EDIT.

// Copyright Authors of Cilium
// SPDX-License-Identifier: Apache-2.0

package daemon

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"net/http"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/runtime/middleware"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
)

// NewGetHealthzParams creates a new GetHealthzParams object
// no default values defined in spec.
func NewGetHealthzParams() GetHealthzParams {

	return GetHealthzParams{}
}

// GetHealthzParams contains all the bound params for the get healthz operation
// typically these are obtained from a http.Request
//
// swagger:parameters GetHealthz
type GetHealthzParams struct {

	// HTTP Request Object
	HTTPRequest *http.Request `json:"-"`

	/*Brief will return a brief representation of the Cilium status.

	  In: header
	*/
	Brief *bool
}

// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewGetHealthzParams() beforehand.
func (o *GetHealthzParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
	var res []error

	o.HTTPRequest = r

	if err := o.bindBrief(r.Header[http.CanonicalHeaderKey("brief")], true, route.Formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

// bindBrief binds and validates parameter Brief from header.
func (o *GetHealthzParams) bindBrief(rawData []string, hasKey bool, formats strfmt.Registry) error {
	var raw string
	if len(rawData) > 0 {
		raw = rawData[len(rawData)-1]
	}

	// Required: false

	if raw == "" { // empty values pass all other validations
		return nil
	}

	value, err := swag.ConvertBool(raw)
	if err != nil {
		return errors.InvalidType("brief", "header", "bool", raw)
	}
	o.Brief = &value

	return nil
}


text:
import unittest
import nose.tools
import scipy.stats as stats

from ..tsp_generator import TSPGenerator

class TSPGeneratorTest(unittest.TestCase):

    def setUp(self):
        self._num_points = 1000

    def test_create_dataset(self):
        gen = TSPGenerator(self._num_points)
        data = gen.generate()

        nose.tools.assert_equal(data.shape, (self._num_points, 2))

        # check x axis is drawn from uniform distribution
        D, p_value = stats.kstest(data[:, 0], 'uniform', args=(0, 10))
        nose.tools.assert_greater(p_value, 0.05)

        # check y axis is drawn from uniform distribution
        D, p_value = stats.kstest(data[:, 1], 'uniform', args=(0, 10))
        nose.tools.assert_greater(p_value, 0.05)

    def test_create_dataset_with_bounds(self):
        # check lower bound param
        gen = TSPGenerator(self._num_points, low=5)
        data = gen.generate()

        nose.tools.assert_equal(data.shape, (self._num_points, 2))
        nose.tools.assert_equal(data[data < 5].size, 0)

        # check upper bound param
        gen = TSPGenerator(self._num_points, high=5)
        data = gen.generate()

        nose.tools.assert_equal(data.shape, (self._num_points, 2))
        nose.tools.assert_equal(data[data > 5].size, 0)

        # check both bounds together
        gen = TSPGenerator(self._num_points, low=5, high=15)
        data = gen.generate()

        nose.tools.assert_equal(data.shape, (self._num_points, 2))
        nose.tools.assert_equal(data[data < 5].size, 0)
        nose.tools.assert_equal(data[data > 15].size, 0)


text:
module RubyJmeter
  class ExtendedDSL < DSL
    def soapxmlrpc_request(params, &block)
      params[:method] ||= 'POST'

      super
    end
  end
end


text:
<?php

namespace Speedwork\Framework\Command;

use Speedwork\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\ProcessUtils;

/**
 * @author Sankar <sankar.suda@gmail.com>
 */
class ServeCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'serve';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Serve the application on the PHP development server';

    /**
     * Execute the console command.
     *
     * @throws \Exception
     */
    public function fire()
    {
        $base   = $this->app['path.base'];
        $public = $this->app['path.public'];
        chdir($public);

        $host   = $this->input->getOption('host');
        $port   = $this->input->getOption('port');
        $base   = ProcessUtils::escapeArgument($base);
        $binary = ProcessUtils::escapeArgument((new PhpExecutableFinder())->find(false));

        $this->info("Speedwork development server started on http://{$host}:{$port}/");

        passthru("{$binary} -S {$host}:{$port} {$base}/server.php");
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', 'localhost'],
            ['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8080],
        ];
    }
}


text:
cd "c:\github\twitch-desktop\src\client"
sass --watch scss/main.scss:css/main.css


text:
require 'fpm/cookery/log/output/null'
require 'cabin' # Via fpm.
require 'json'

module FPM
  module Cookery
    module Log
      @debug = false
      @output = FPM::Cookery::Log::Output::Null.new

      @channel = ::Cabin::Channel.get
      @channel.subscribe(self)
      @channel.level = :info

      class << self
        def enable_debug(value = true)
          @debug = value
        end

        def output(out)
          @output = out
        end

        def debug(message)
          @output.debug(message) if @debug
        end

        def info(message)
          @output.info(message)
        end

        def warn(message)
          @output.warn(message)
        end

        def error(message)
          @output.error(message)
        end

        def fatal(message)
          @output.fatal(message)
        end

        def puts(message)
          @output.puts(message)
        end

        def <<(event)
          level = event.fetch(:level, :info).downcase.to_sym

          event.delete(:level)

          data = event.clone

          data.delete(:message)
          data.delete(:timestamp)

          send(level, "[FPM] #{event[:message]} #{data.to_json}")
        end
      end
    end
  end
end


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_SSL_SECURITY_STATE_TAB_HELPER_H_
#define CHROME_BROWSER_SSL_SECURITY_STATE_TAB_HELPER_H_

#include <memory>

#include "base/callback.h"
#include "base/optional.h"
#include "components/security_state/core/security_state.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "third_party/blink/public/common/security/security_style.h"

namespace content {
class NavigationHandle;
class WebContents;
}  // namespace content

// Tab helper provides the page's security status. Also logs console warnings
// for private data on insecure pages.
class SecurityStateTabHelper
    : public content::WebContentsObserver,
      public content::WebContentsUserData<SecurityStateTabHelper> {
 public:
  ~SecurityStateTabHelper() override;

  // See security_state::GetSecurityLevel.
  security_state::SecurityLevel GetSecurityLevel();
  std::unique_ptr<security_state::VisibleSecurityState>
  GetVisibleSecurityState();

  // content::WebContentsObserver:
  void DidStartNavigation(
      content::NavigationHandle* navigation_handle) override;
  void DidFinishNavigation(
      content::NavigationHandle* navigation_handle) override;
  void DidChangeVisibleSecurityState() override;

  // Used by tests to specify a callback to be called when
  // GetVisibleSecurityState() is called.
  void set_get_security_level_callback_for_tests_(base::OnceClosure closure) {
    get_security_level_callback_for_tests_ = std::move(closure);
  }

 private:
  explicit SecurityStateTabHelper(content::WebContents* web_contents);
  friend class content::WebContentsUserData<SecurityStateTabHelper>;

  bool UsedPolicyInstalledCertificate() const;
  security_state::MaliciousContentStatus GetMaliciousContentStatus() const;

  // Caches the legacy TLS warning suppression status for the duration of a page
  // load (bound to a specific navigation ID) to ensure that we show consistent
  // security UI (e.g., security indicator and page info). This is because the
  // status depends on external state (a component loading from disk), which can
  // cause inconsistent state across a page load if it isn't cached.
  base::Optional<std::pair<int /* navigation entry ID */,
                           bool /* should_suppress_legacy_tls_warning */>>
      cached_should_suppress_legacy_tls_warning_;

  base::OnceClosure get_security_level_callback_for_tests_;

  WEB_CONTENTS_USER_DATA_KEY_DECL();

  DISALLOW_COPY_AND_ASSIGN(SecurityStateTabHelper);
};

#endif  // CHROME_BROWSER_SSL_SECURITY_STATE_TAB_HELPER_H_


text:
package io.featureflow.client;

import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import io.featureflow.client.model.Audience;
import io.featureflow.client.model.Condition;
import io.featureflow.client.model.Operator;
import io.featureflow.client.model.Rule;
import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by oliver on 21/11/16.
 */
public class RuleMatchesTest {

    @Test
    public void testRuleEquals() throws Exception {

        Rule rule = new Rule();

        Condition c1 = new Condition();
        c1.target = "name";
        c1.operator = Operator.equals;
        c1.values.add(new JsonPrimitive("oliver"));

        Audience a = new Audience();
        a.conditions = Arrays.asList(c1);
        rule.setAudience(a);

        FeatureflowUser user = new FeatureflowUser("oliver");
        Map<String, JsonElement> contextValues = new HashMap<>();
        contextValues.put("name", new JsonPrimitive("oliver"));
        user.withAttributes(contextValues);

        Assert.assertTrue(rule.matches(user));

    }

    @Test
    public void testMultipleConditionsMustAllMatch() throws Exception {

        Rule rule = new Rule();

        Condition c1 = new Condition();
        c1.target = "tier";
        c1.operator = Operator.equals;
        c1.values.add(new JsonPrimitive("gold"));

        Condition c2 = new Condition();
        c2.target = "name";
        c2.operator = Operator.equals;
        c2.values.add(new JsonPrimitive("oliver"));

        Audience a = new Audience();
        a.conditions = Arrays.asList(c1, c2);
        rule.setAudience(a);

        FeatureflowUser user = new FeatureflowUser("oliver");
        Map<String, JsonElement> contextValues = new HashMap<>();
        contextValues.put("name", new JsonPrimitive("oliver"));
        contextValues.put("tier", new JsonPrimitive("silver"));
        user.withAttributes(contextValues);

        Assert.assertTrue(!rule.matches(user));

    }

    @Test
    public void testRuleGreaterThan() throws Exception {
        Rule rule = new Rule();
        Condition c1 = new Condition();
        c1.target = "age";
        c1.operator = Operator.greaterThan;
        c1.values.add(new JsonPrimitive(25l));

        Audience a = new Audience();
        a.conditions = Arrays.asList(c1);
        rule.setAudience(a);

        FeatureflowUser user = new FeatureflowUser("oliver");
        Map<String, JsonElement> contextValues = new HashMap<>();
        contextValues.put("name", new JsonPrimitive("oliver"));
        contextValues.put("age", new JsonPrimitive(26l));

        user.withAttributes(contextValues);

        Assert.assertTrue(rule.matches(user));

    }

    @Test
    public void testRuleMatchesWithNullAudience() throws Exception {
        Rule rule = new Rule();
        Condition c1 = new Condition();
        c1.target = "age";
        c1.operator = Operator.greaterThan;
        c1.values.add(new JsonPrimitive(25l));

        FeatureflowUser user = new FeatureflowUser("oliver");
        Map<String, JsonElement> contextValues = new HashMap<>();
        contextValues.put("name", new JsonPrimitive("oliver"));
        contextValues.put("age", new JsonPrimitive(26l));

        user.withAttributes(contextValues);

        Assert.assertTrue(rule.matches(user));

    }

}


text:
import mongoose from 'mongoose';

const Schema = mongoose.Schema;

const FilterSchema = new Schema({
  id: String,
  name: String,
  displayName: String,
  range: [Number],
  values: [Number],
  step: Number,
  description: String
});

export default mongoose.model('Filter', FilterSchema);


text:
package fr.nacvolley.tournament.util;

import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;

import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.logging.Logger;

/**
 * Using CouchDb database
 */
public class Db {

    public static Db instance=new Db();

    public CouchDbConnector db;

    private Logger log = Logger.getLogger(Db.class.getName());

    private String dbUrl;

    private String dbName;
    public Db() {
        // 1. Register POJO
        try {
            InitialContext initCtx = new InitialContext();
            Context envCtx = (Context)initCtx.lookup("java:comp/env");
            dbUrl=(String)envCtx.lookup("dbUrl");
            dbName=(String)envCtx.lookup("dbName");
        }
        catch (Exception e) {
            this.log.severe("Cannot get context environment variables (dbName, dbUrl), check context XML file : " + e.getMessage());
            dbUrl="http://localhost:2001";
            dbName="tournament";
            this.log.warning("Using default dbUrl : "+dbUrl+", with default dbName : "+dbName);
        }

        try {
            HttpClient httpClient = new StdHttpClient.Builder()
                    .url(dbUrl)
                    .build();

            CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
            db = new StdCouchDbConnector(dbName, dbInstance);
            db.createDatabaseIfNotExists();
        }
        catch (Exception e) {
            System.err.println("Error when opening DB : "+e.getMessage());
        }
    }

}


text:
package org.innovateuk.ifs.competition.service;

import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.user.resource.UserResource;

import java.util.List;

public interface CompetitionSetupInnovationLeadRestService {

    RestResult<List<UserResource>> findAvailableInnovationLeadsNotAssignedToCompetition(long competitionId);

    RestResult<List<UserResource>> findInnovationLeadsAssignedToCompetition(long competitionId);

    RestResult<Void> addInnovationLead(long competitionId, long innovationLeadUserId);

    RestResult<Void> removeInnovationLead(long competitionId, long innovationLeadUserId);
}


text:
require 'spec_helper'

module CS
  module Collection
    describe SensorDataCollection do
      describe "process_batch" do
        it "should convert into multi data payload" do
          sdc = SensorDataCollection.new
          sdc.batch_size = 2

          current_batch = [
            EndPoint::SensorData.new(sensor_id: 1, value: 1),
            EndPoint::SensorData.new(sensor_id: 1, value: 2),
            EndPoint::SensorData.new(sensor_id: 2, value: 1),
            EndPoint::SensorData.new(sensor_id: 2, value: 2),
            EndPoint::SensorData.new(sensor_id: 1, value: 3),
            EndPoint::SensorData.new(sensor_id: 1, value: 4),
            EndPoint::SensorData.new(sensor_id: 2, value: 3),
            EndPoint::SensorData.new(sensor_id: 2, value: 4)
          ]

          sdc.process_batch(current_batch)
        end
      end
    end
  end
end


text:
<?php $b = base_url(); ?>

Regístrate en BeerBoss:

      <form  method="post" enctype="multipart/form-data" name="forma">

            Nombre de usuario:
            <input required type="text" name="Username">

            Sitio Web:
            <input required type="text" name="Web">

            Correo:
            <input required type="email" name="Correo">

            Password:
            <input required type="password" name="Pass">

            Repetir password:
            <input required type="password" name="rPass">

            Biografía
            <input required type="text" name="Bio">

            Avatar:
            <input type="file" name="userfile" value="Upload" id="userfile">
            <input type="hidden" name="imagen" id="imagen" value="0">

          Registrarse

      </form>


text:
package org.onosproject.net.meter;

import com.google.common.collect.ImmutableSet;
import org.onosproject.core.ApplicationId;
import org.onosproject.net.AbstractAnnotated;
import org.onosproject.net.Annotations;
import org.onosproject.net.DeviceId;

import java.util.Collection;
import java.util.Optional;

import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * A default implementation of a meter.
 */
public final class DefaultMeterRequest extends AbstractAnnotated implements MeterRequest {

    private final ApplicationId appId;
    private final Meter.Unit unit;
    private final boolean burst;
    private final Collection<Band> bands;
    private final DeviceId deviceId;
    private final Optional<MeterContext> context;
    private final Type op;
    private final MeterScope scope;
    private final Optional<Long> index;

    private DefaultMeterRequest(DeviceId deviceId, ApplicationId appId,
                                Meter.Unit unit, boolean burst,
                                Collection<Band> bands, MeterContext context,
                                Type op, MeterScope scope, Optional<Long> index,
                                Annotations... annotations) {
        super(annotations);
        this.deviceId = deviceId;
        this.appId = appId;
        this.unit = unit;
        this.burst = burst;
        this.bands = bands;
        this.context = Optional.ofNullable(context);
        this.op = op;
        this.scope = scope;
        this.index = index;
    }

    @Override
    public DeviceId deviceId() {
        return deviceId;
    }

    @Override
    public ApplicationId appId() {
        return appId;
    }

    @Override
    public Meter.Unit unit() {
        return unit;
    }

    @Override
    public boolean isBurst() {
        return burst;
    }

    @Override
    public Collection<Band> bands() {
        return bands;
    }

    @Override
    public Optional<MeterContext> context() {
        return context;
    }

    @Override
    public MeterScope scope() {
        return scope;
    }

    @Override
    public Optional<Long> index() {
        return index;
    }

    public static Builder builder() {
        return new Builder();
    }

    @Override
    public String toString() {
        return toStringHelper(this)
                .add("device", deviceId)
                .add("appId", appId.name())
                .add("unit", unit)
                .add("isBurst", burst)
                .add("bands", bands)
                .add("scope", scope)
                .add("desired index", index.orElse(null))
                .add("annotations", annotations())
                .toString();
    }

    public static final class Builder implements MeterRequest.Builder {
        // Relevant only for delete
        private static final Band DUMMY_BAND = new DefaultBand(Band.Type.DROP, 0L, 0L, (short) 0);

        private ApplicationId appId;
        private Meter.Unit unit = Meter.Unit.KB_PER_SEC;
        private boolean burst = false;
        private Collection<Band> bands;
        private DeviceId deviceId;
        private MeterContext context;
        private Annotations annotations;
        private MeterScope scope = MeterScope.globalScope();
        private Optional<Long> desiredIndex = Optional.empty();

        @Override
        public MeterRequest.Builder forDevice(DeviceId deviceId) {
            this.deviceId = deviceId;
            return this;
        }

        @Override
        public MeterRequest.Builder fromApp(ApplicationId appId) {
            this.appId = appId;
            return this;
        }

        @Override
        public MeterRequest.Builder withUnit(Meter.Unit unit) {
            this.unit = unit;
            return this;
        }

        @Override
        public MeterRequest.Builder burst() {
            this.burst = true;
            return this;
        }

        @Override
        public MeterRequest.Builder withBands(Collection<Band> bands) {
            this.bands = ImmutableSet.copyOf(bands);
            return this;
        }

        @Override
        public MeterRequest.Builder withContext(MeterContext context) {
            this.context = context;
            return this;
        }

        @Override
        public MeterRequest.Builder withAnnotations(Annotations annotations) {
            this.annotations = annotations;
            return this;
        }

        @Override
        public MeterRequest.Builder withScope(MeterScope scope) {
            this.scope = scope;
            return this;
        }

        @Override
        public MeterRequest.Builder withIndex(Long index) {
            this.desiredIndex = Optional.ofNullable(index);
            return this;
        }

        @Override
        public MeterRequest add() {
            validate();
            return new DefaultMeterRequest(deviceId, appId, unit, burst, bands, context,
                                           Type.ADD, scope, desiredIndex, annotations);
        }

        @Override
        public MeterRequest remove() {
            // Allow to create the removal request without specifying bands
            if (bands == null || bands.isEmpty()) {
                bands = ImmutableSet.of(DUMMY_BAND);
            }

            validate();
            return new DefaultMeterRequest(deviceId, appId, unit, burst, bands, context,
                                           Type.REMOVE, scope, desiredIndex, annotations);
        }

        private void validate() {
            checkNotNull(deviceId, "Must specify a device");
            checkNotNull(bands, "Must have bands.");
            checkArgument(!bands.isEmpty(), "Must have at least one band.");
            checkNotNull(appId, "Must have an application id");
            if (desiredIndex.isPresent()) {
                checkArgument(desiredIndex.get() >= 0, "Desired index cannot be negative");
            }
        }

    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('nomi', '0078_auto_20170619_0725'),
    ]

    operations = [
        migrations.AddField(
            model_name='nomination',
            name='result_approvals',
            field=models.ManyToManyField(blank=True, related_name='result_approvals', to='nomi.Post'),
        ),
        migrations.AlterField(
            model_name='nomination',
            name='status',
            field=models.CharField(choices=[('Nomination created', 'Nomination created'), ('Nomination out', 'Nomination out'), ('Interview period', 'Interview period'), ('Sent for ratification', 'Sent for ratification'), ('Work done', 'Work done')], default='Nomination created', max_length=50),
        ),
    ]


text:
package p2p

import (
	"crypto/md5"
	"encoding/json"
	"errors"
	"fmt"
	"net/url"
	"sync"
	"time"

	"github.com/go-openapi/strfmt"
	"github.com/semi-technologies/weaviate/entities/schema"
	genesis_client "github.com/semi-technologies/weaviate/genesis/client"
	client_ops "github.com/semi-technologies/weaviate/genesis/client/operations"
	genesismodels "github.com/semi-technologies/weaviate/genesis/models"
	libnetwork "github.com/semi-technologies/weaviate/usecases/network"
	"github.com/semi-technologies/weaviate/usecases/network/common/peers"
	p2pschema "github.com/semi-technologies/weaviate/usecases/network/p2p/schema"
	"github.com/sirupsen/logrus"
)

const (
	NETWORK_STATE_BOOTSTRAPPING = "network bootstrapping"
	NETWORK_STATE_FAILED        = "network failed"
	NETWORK_STATE_HEALTHY       = "network healthy"
)

// ErrPeerNotFound because it was either never registered
// or was registered, but timed out in the meantime
var ErrPeerNotFound = errors.New("Peer does not exist or has been removed after being inactive")

// The real network implementation. Se also `fake_network.go`
type network struct {
	sync.Mutex

	// Peer ID assigned by genesis server
	peerID    strfmt.UUID
	peerName  string
	publicURL strfmt.URI

	state           string
	genesisURL      strfmt.URI
	logger          logrus.FieldLogger
	client          genesis_client.WeaviateGenesisServer
	peers           peers.Peers
	callbacks       []libnetwork.PeerUpdateCallback
	schemaGetter    libnetwork.SchemaGetter
	downloadChanged downloadChangedFn
}

type downloadChangedFn func(peers.Peers) peers.Peers

// BootstrapNetwork with HTTP p2p functionality
func BootstrapNetwork(logger logrus.FieldLogger, genesisURL strfmt.URI, publicURL strfmt.URI, peerName string) (libnetwork.Network, error) {
	if genesisURL == "" {
		return nil, fmt.Errorf("No genesis URL provided in network configuration")
	}

	genesisURI, err := url.Parse(string(genesisURL))
	if err != nil {
		return nil, fmt.Errorf("Could not parse genesis URL '%v'", genesisURL)
	}

	if publicURL == "" {
		return nil, fmt.Errorf("No public URL provided in network configuration")
	}

	_, err = url.Parse(string(publicURL))
	if err != nil {
		return nil, fmt.Errorf("Could not parse public URL '%v'", publicURL)
	}

	if peerName == "" {
		return nil, fmt.Errorf("No peer name specified in network configuration")
	}

	transportConfig := genesis_client.TransportConfig{
		Host:     genesisURI.Host,
		BasePath: genesisURI.Path,
		Schemes:  []string{genesisURI.Scheme},
	}

	client := genesis_client.NewHTTPClientWithConfig(nil, &transportConfig)

	n := network{
		publicURL:       publicURL,
		peerName:        peerName,
		state:           NETWORK_STATE_BOOTSTRAPPING,
		genesisURL:      genesisURL,
		logger:          logger,
		client:          *client,
		peers:           make([]peers.Peer, 0),
		downloadChanged: p2pschema.DownloadChanged,
	}

	// Bootstrap the network in the background.
	go n.bootstrap()

	return &n, nil
}

func (n *network) bootstrap() {
	time.Sleep(10) //TODO: Use channel close to listen for when complete configuration is done.
	n.logger.WithField("action", "network_bootstrap").Debug("network bootstrapping beginning")

	newPeer := genesismodels.PeerUpdate{
		PeerName: n.peerName,
		PeerURI:  n.publicURL,
	}

	params := client_ops.NewGenesisPeersRegisterParams()
	params.Body = &newPeer
	response, err := n.client.Operations.GenesisPeersRegister(params)
	if err != nil {
		n.logger.
			WithField("action", "network_bootstrap").
			WithError(err).
			Error("could not register peer in network")
		n.state = NETWORK_STATE_FAILED
	} else {
		n.state = NETWORK_STATE_HEALTHY
		n.peerID = response.Payload.Peer.ID
		n.logger.
			WithField("action", "network_bootstrap").
			WithField("peer_id", n.peerID).
			Info("registered at genesis server")
	}

	go n.keepPinging()
}

func (n *network) IsReady() bool {
	return false
}

func (n *network) GetStatus() string {
	return n.state
}

func (n *network) ListPeers() (peers.Peers, error) {
	return n.peers, nil
}

func (n *network) GetPeerByName(name string) (peers.Peer, error) {
	for _, peer := range n.peers {
		if peer.Name == name {
			return peer, nil
		}
	}

	return peers.Peer{}, ErrPeerNotFound
}

func (n *network) keepPinging() {
	for {
		time.Sleep(30 * time.Second)
		n.ping()
	}
}

func (n *network) ping() {
	n.logger.WithField("action", "network_ping").Debug("pinging genesis server")

	if n.schemaGetter == nil {
		n.logger.
			WithField("action", "network_ping").
			WithError(errors.New("no schema getter present")).
			Error("cannot ping gensis server")
		return
	}

	currentSchema := n.schemaGetter.GetSchemaSkipAuth()

	n.Lock()
	params := client_ops.NewGenesisPeersPingParams()
	params.PeerID = n.peerID
	hash, err := schemaHash(currentSchema)
	if err != nil {
		n.logger.
			WithField("action", "network_ping").
			WithError(err).
			Error("cannot ping gensis server")
		return
	}

	params.Body = &genesismodels.PeerPing{
		SchemaHash: hash,
	}
	n.Unlock()
	_, err = n.client.Operations.GenesisPeersPing(params)
	if err != nil {
		n.logger.
			WithField("action", "network_ping").
			WithError(err).
			Error("cannot ping gensis server")
	}
}

// GetNetworkResolver for now simply returns itself
// because the network is not fully plugable yet.
// Once we have made the network pluggable, then this would
// be a method on the connector which returns the actual
// plugged in Network
func (n *network) GetNetworkResolver() libnetwork.Network {
	return n
}

func (n *network) RegisterSchemaGetter(schemaGetter libnetwork.SchemaGetter) {
	n.schemaGetter = schemaGetter
}

func schemaHash(s schema.Schema) (string, error) {
	schemaBytes, err := json.Marshal(s)
	if err != nil {
		return "", fmt.Errorf("couldnt convert schema to json before hashing: %s", err)
	}

	hash := md5.New()
	fmt.Fprintf(hash, "%s", schemaBytes)
	return fmt.Sprintf("%x", hash.Sum(nil)), nil
}