text:
"""Python module for generating .ninja files.

Note that this is emphatically not a required piece of Ninja; it's
just a helpful utility for build-file-generation systems that already
use Python.
"""

import textwrap
import re

def escape_spaces(word):
    return word.replace('$ ','$$ ').replace(' ','$ ')

class Writer(object):
    def __init__(self, output, width=78):
        self.output = output
        self.width = width

    def newline(self):
        self.output.write('\n')

    def comment(self, text):
        for line in textwrap.wrap(text, self.width - 2):
            self.output.write('# ' + line + '\n')

    def variable(self, key, value, indent=0):
        if value is None:
            return
        if isinstance(value, list):
            value = ' '.join(filter(None, value))  # Filter out empty strings.
        self._line('%s = %s' % (key, value), indent)

    def rule(self, name, command, description=None, depfile=None,
             generator=False, restat=False):
        self._line('rule %s' % name)
        self.variable('command', command, indent=1)
        if description:
            self.variable('description', description, indent=1)
        if depfile:
            self.variable('depfile', depfile, indent=1)
        if generator:
            self.variable('generator', '1', indent=1)
        if restat:
            self.variable('restat', '1', indent=1)

    def build(self, outputs, rule, inputs=None, implicit=None, order_only=None,
              variables=None):
        outputs = self._as_list(outputs)
        all_inputs = self._as_list(inputs)[:]
        out_outputs = map(escape_spaces, outputs)
        all_inputs = map(escape_spaces, all_inputs)

        if implicit:
            implicit = map(escape_spaces, self._as_list(implicit))
            all_inputs.append('|')
            all_inputs.extend(implicit)
        if order_only:
            order_only = map(escape_spaces, self._as_list(order_only))
            all_inputs.append('||')
            all_inputs.extend(order_only)

        self._line('build %s: %s %s' % (' '.join(out_outputs),
                                        rule,
                                        ' '.join(all_inputs)))

        if variables:
            for key, val in variables:
                self.variable(key, val, indent=1)

        return outputs

    def include(self, path):
        self._line('include %s' % path)

    def subninja(self, path):
        self._line('subninja %s' % path)

    def default(self, paths):
        self._line('default %s' % ' '.join(self._as_list(paths)))

    def _count_dollars_before_index(self, s, i):
      """Returns the number of '$' characters right in front of s[i]."""
      dollar_count = 0
      dollar_index = i - 1
      while dollar_index > 0 and s[dollar_index] == '$':
        dollar_count += 1
        dollar_index -= 1
      return dollar_count

    def _line(self, text, indent=0):
        """Write 'text' word-wrapped at self.width characters."""
        leading_space = '  ' * indent
        while len(text) > self.width:
            # The text is too wide; wrap if possible.

            # Find the rightmost space that would obey our width constraint and
            # that's not an escaped space.
            available_space = self.width - len(leading_space) - len(' $')
            space = available_space
            while True:
              space = text.rfind(' ', 0, space)
              if space < 0 or \
                 self._count_dollars_before_index(text, space) % 2 == 0:
                break

            if space < 0:
                # No such space; just use the first unescaped space we can find.
                space = available_space - 1
                while True:
                  space = text.find(' ', space + 1)
                  if space < 0 or \
                     self._count_dollars_before_index(text, space) % 2 == 0:
                    break
            if space < 0:
                # Give up on breaking.
                break

            self.output.write(leading_space + text[0:space] + ' $\n')
            text = text[space+1:]

            # Subsequent lines are continuations, so indent them.
            leading_space = '  ' * (indent+2)

        self.output.write(leading_space + text + '\n')

    def _as_list(self, input):
        if input is None:
            return []
        if isinstance(input, list):
            return input
        return [input]

def escape(string):
    """Escape a string such that it can be embedded into a Ninja file without
    further interpretation."""
    assert '\n' not in string, 'Ninja syntax does not allow newlines'
    # We only have one special metacharacter: '$'.
    return string.replace('$', '$$')


text:
package org.apache.commons.graph.spanning;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.apache.commons.graph.CommonsGraph.minimumSpanningTree;

import org.apache.commons.graph.Graph;
import org.apache.commons.graph.SpanningTree;
import org.apache.commons.graph.model.BaseLabeledVertex;
import org.apache.commons.graph.model.BaseLabeledWeightedEdge;
import org.apache.commons.graph.model.BaseWeightedEdge;
import org.apache.commons.graph.model.MutableSpanningTree;
import org.apache.commons.graph.model.UndirectedMutableGraph;
import org.apache.commons.graph.weight.primitive.DoubleWeightBaseOperations;
import org.junit.Test;

public final class PrimTestCase
{
    @Test( expected = NullPointerException.class )
    public void testNullGraph()
    {
        minimumSpanningTree( (Graph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>) null )
            .whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
            .fromArbitrarySource()
            .applyingPrimAlgorithm( new DoubleWeightBaseOperations() );
    }

    @Test( expected = NullPointerException.class )
    public void testNullVertex()
    {
        UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input =
            new UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>();

        minimumSpanningTree( input )
            .whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
            .fromSource( null )
            .applyingPrimAlgorithm( new DoubleWeightBaseOperations() );
    }

    @Test( expected = NullPointerException.class )
    public void testNullMonoid()
    {
        UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input = null;
        BaseLabeledVertex a = null;
        try
        {
            input = new UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>();
            a = new BaseLabeledVertex( "A" );
            input.addVertex( a );
        }
        catch ( NullPointerException e )
        {
            //try..catch need to avoid a possible test success even if a NPE is thorw during graph population
            fail( e.getMessage() );
        }

        minimumSpanningTree( input )
            .whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
            .fromSource( a )
            .applyingBoruvkaAlgorithm( null );
    }

    @Test( expected = IllegalStateException.class )
    public void testNotExistVertex()
    {
        UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input =
            new UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>();

        minimumSpanningTree( input )
            .whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
            .fromSource( new BaseLabeledVertex( "NOT EXIST" ) );
    }

    @Test( expected = IllegalStateException.class )
    public void testEmptyGraph()
    {
        UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input =
            new UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>();

        minimumSpanningTree( input )
            .whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
            .fromArbitrarySource()
            .applyingPrimAlgorithm( new DoubleWeightBaseOperations() );
    }

    /**
     * Test Graph and Prim's solution can be seen on these
     * slides
     */
    @Test
    public void verifyMinimumSpanningTree2()
    {
        UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input
            = new UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>();

        BaseLabeledVertex a = new BaseLabeledVertex( "a" );
        BaseLabeledVertex b = new BaseLabeledVertex( "b" );
        BaseLabeledVertex c = new BaseLabeledVertex( "c" );
        BaseLabeledVertex d = new BaseLabeledVertex( "d" );
        BaseLabeledVertex e = new BaseLabeledVertex( "e" );
        BaseLabeledVertex f = new BaseLabeledVertex( "f" );
        BaseLabeledVertex g = new BaseLabeledVertex( "g" );

        input.addVertex( a );
        input.addVertex( b );
        input.addVertex( c );
        input.addVertex( d );
        input.addVertex( e );
        input.addVertex( f );
        input.addVertex( g );

        input.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> b", 7D ), b );
        input.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> c", 14D ), c );
        input.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> d", 30D ), d );

        input.addEdge( b, new BaseLabeledWeightedEdge<Double>( "b <-> c", 21D ), c );

        input.addEdge( c, new BaseLabeledWeightedEdge<Double>( "c <-> d", 10D ), d );
        input.addEdge( c, new BaseLabeledWeightedEdge<Double>( "c <-> e", 1D ), e );

        input.addEdge( e, new BaseLabeledWeightedEdge<Double>( "e <-> f", 6D ), f );
        input.addEdge( e, new BaseLabeledWeightedEdge<Double>( "e <-> g", 9D ), g );

        input.addEdge( f, new BaseLabeledWeightedEdge<Double>( "f <-> g", 4D ), g );

        // expected

        MutableSpanningTree<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>, Double> expected =
            new MutableSpanningTree<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>, Double>( new DoubleWeightBaseOperations(), new BaseWeightedEdge<Double>() );

        for ( BaseLabeledVertex vertex : input.getVertices() )
        {
            expected.addVertex( vertex );
        }

        expected.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> b", 7D ), b );
        expected.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> c", 14D ), c );

        expected.addEdge( c, new BaseLabeledWeightedEdge<Double>( "c <-> d", 10D ), d );
        expected.addEdge( c, new BaseLabeledWeightedEdge<Double>( "c <-> e", 1D ), e );

        expected.addEdge( e, new BaseLabeledWeightedEdge<Double>( "e <-> f", 6D ), f );

        expected.addEdge( f, new BaseLabeledWeightedEdge<Double>( "f <-> g", 4D ), g );

        internalPrimAssertion( input, a, expected );
    }

    /**
     * Test Graph and Prim's solution can be seen on
     * Wikipedia
     */
    @Test
    public void verifyWikipediaMinimumSpanningTree()
    {
        UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input
            = new UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>>();

        BaseLabeledVertex a = new BaseLabeledVertex( "A" );
        BaseLabeledVertex b = new BaseLabeledVertex( "B" );
        BaseLabeledVertex c = new BaseLabeledVertex( "C" );
        BaseLabeledVertex d = new BaseLabeledVertex( "D" );
        BaseLabeledVertex e = new BaseLabeledVertex( "E" );
        BaseLabeledVertex f = new BaseLabeledVertex( "F" );
        BaseLabeledVertex g = new BaseLabeledVertex( "G" );

        input.addVertex( a );
        input.addVertex( b );
        input.addVertex( c );
        input.addVertex( d );
        input.addVertex( e );
        input.addVertex( f );
        input.addVertex( g );

        input.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> b", 7D ), b );
        input.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> d", 5D ), d );

        input.addEdge( b, new BaseLabeledWeightedEdge<Double>( "b <-> c", 8D ), c );
        input.addEdge( b, new BaseLabeledWeightedEdge<Double>( "b <-> d", 9D ), d );
        input.addEdge( b, new BaseLabeledWeightedEdge<Double>( "b <-> e", 7D ), e );

        input.addEdge( c, new BaseLabeledWeightedEdge<Double>( "c <-> e", 5D ), e );

        input.addEdge( d, new BaseLabeledWeightedEdge<Double>( "d <-> e", 15D ), e );
        input.addEdge( d, new BaseLabeledWeightedEdge<Double>( "d <-> f", 6D ), f );

        input.addEdge( e, new BaseLabeledWeightedEdge<Double>( "e <-> f", 8D ), f );
        input.addEdge( e, new BaseLabeledWeightedEdge<Double>( "e <-> g", 9D ), g );

        input.addEdge( f, new BaseLabeledWeightedEdge<Double>( "f <-> g", 11D ), g );

        // expected

        MutableSpanningTree<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>, Double> expected =
            new MutableSpanningTree<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>, Double>( new DoubleWeightBaseOperations(), new BaseWeightedEdge<Double>() );

        for ( BaseLabeledVertex vertex : input.getVertices() )
        {
            expected.addVertex( vertex );
        }

        expected.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> b", 7D ), b );
        expected.addEdge( a, new BaseLabeledWeightedEdge<Double>( "a <-> d", 5D ), d );
        expected.addEdge( b, new BaseLabeledWeightedEdge<Double>( "b <-> e", 7D ), e );
        expected.addEdge( c, new BaseLabeledWeightedEdge<Double>( "c <-> e", 5D ), e );
        expected.addEdge( d, new BaseLabeledWeightedEdge<Double>( "d <-> f", 6D ), f );
        expected.addEdge( e, new BaseLabeledWeightedEdge<Double>( "e <-> g", 9D ), g );

        internalPrimAssertion( input, d, expected );
    }

    private static void internalPrimAssertion( UndirectedMutableGraph<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>> input,
                                               BaseLabeledVertex source,
                                               MutableSpanningTree<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>, Double> expected )
    {
     // actual

        SpanningTree<BaseLabeledVertex, BaseLabeledWeightedEdge<Double>, Double> actual =
                        minimumSpanningTree( input )
                            .whereEdgesHaveWeights( new BaseWeightedEdge<Double>() )
                            .fromSource( source )
                            .applyingPrimAlgorithm( new DoubleWeightBaseOperations() );

        // assert!

        assertEquals( expected, actual );
    }

}

redpajama_set_name: RedPajamaGithub


text:
module Eribium
  module ViewHelpers
    module GravatarHelper

      def gravatar_url(user)
        email = case user
          when String
            user
          else
            user.respond_to?(:email) ? user.send(:email).to_s : ""
          end
        default_url = image_path("eribium/avatar.png")
        if email.present?
          gravatar_id = Digest::MD5.hexdigest(email.downcase)
          unless default_url =~ /^http(s)?:/
            default_url = request.base_url + default_url
          end
          gravatar_host = request.ssl? ? "https://secure.gravatar.com" : "http://gravatar.com"
          "#{gravatar_host}/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}"
        else
          default_url
        end
      end

    end
  end
end


text:
	${library_name}_${mount_tool_file_entry_type}_t *${mount_tool_file_entry_type_name} = NULL;
	const system_character_t *filename                                                  = NULL;
	static char *function                                                               = "mount_handle_get_file_entry_by_path";
	size_t filename_length                                                              = 0;
	size_t path_index                                                                   = 0;
	size_t path_length                                                                  = 0;
	int result                                                                          = 0;


text:
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
 * decaffeinate suggestions:
 * DS102: Remove unnecessary code created because of implicit returns
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */

import { expect } from 'chai'

import yayson from '../../src/yayson'
const { Adapter } = yayson()

describe('Adapter', function() {
  it('should get all object properties', function() {
    const attributes = Adapter.get({ name: 'Abraham' })
    return expect(attributes.name).to.eq('Abraham')
  })

  it('should get object property', function() {
    const name = Adapter.get({ name: 'Abraham' }, 'name')
    return expect(name).to.eq('Abraham')
  })

  return it('should get the id', function() {
    const id = Adapter.id({ id: 5 })
    return expect(id).to.eq('5')
  })
})


text:
require 'rails_helper'

describe Atmosphere::VirtualMachineFlavor do
  context 'supported architectures validation' do
    it "adds 'invalid architexture' error message" do
      fl = build(:virtual_machine_flavor,
          supported_architectures: 'invalid architecture'
        )
      saved = fl.save
      expect(saved).to be false
      expect(fl.errors.messages).to eq({
          supported_architectures: ['is not included in the list']
        })
    end
  end

  context 'architectures' do
    it 'supports both architectures' do
      flavor = build(:flavor, supported_architectures: 'i386_and_x86_64')

      expect(flavor.supports_architecture?('i386')).to be_truthy
      expect(flavor.supports_architecture?('x86_64')).to be_truthy
    end

    it 'supports only i386 architecture' do
      flavor = build(:flavor, supported_architectures: 'i386')

      expect(flavor.supports_architecture?('i386')).to be_truthy
      expect(flavor.supports_architecture?('x86_64')).to be_falsy
    end

    it 'supports only x architecture' do
      flavor = build(:flavor, supported_architectures: 'x86_64')

      expect(flavor.supports_architecture?('i386')).to be_falsy
      expect(flavor.supports_architecture?('x86_64')).to be_truthy
    end

    it 'finds all 386 flavors' do
      f32, _, f_both = flavor_archs_combination

      flavors = Atmosphere::VirtualMachineFlavor.with_arch('i386')

      expect(flavors.count).to eq 2
      expect(flavors).to include f32
      expect(flavors).to include f_both
    end

    it 'finds all 64 flavors' do
      _, f64, f_both = flavor_archs_combination

      flavors = Atmosphere::VirtualMachineFlavor.with_arch('x86_64')

      expect(flavors.count).to eq 2
      expect(flavors).to include f64
      expect(flavors).to include f_both
    end

    def flavor_archs_combination
      f32 = create(:flavor, supported_architectures: 'i386')
      f64 = create(:flavor, supported_architectures: 'x86_64')
      f_both = create(:flavor, supported_architectures: 'i386_and_x86_64')

      [f32, f64, f_both]
    end
  end

  context 'preferences' do
    it 'finds flavor with CPU specified' do
      flavor = to_smal_and_correct_flavor(cpu: 2)

      flavors = Atmosphere::VirtualMachineFlavor.with_prefs(cpu: 2)

      expect(flavors.count).to eq 1
      expect(flavors.first).to eq flavor
    end

    it 'finds flavor with Memory specified' do
      flavor = to_smal_and_correct_flavor(memory: 2)

      flavors = Atmosphere::VirtualMachineFlavor.with_prefs(memory: 2)

      expect(flavors.count).to eq 1
      expect(flavors.first).to eq flavor
    end

    it 'finds flavor with Memory specified' do
      flavor = to_smal_and_correct_flavor(hdd: 2)

      flavors = Atmosphere::VirtualMachineFlavor.with_prefs(hdd: 2)

      expect(flavors.count).to eq 1
      expect(flavors.first).to eq flavor
    end

    it 'finds flavor using complex query' do
      create(:flavor, cpu: 1, memory: 2, hdd: 2)
      create(:flavor, cpu: 2, memory: 1, hdd: 2)
      create(:flavor, cpu: 2, memory: 2, hdd: 1)
      flavor = create(:flavor, cpu: 2, memory: 2, hdd: 2)

      flavors = Atmosphere::VirtualMachineFlavor.with_prefs(cpu: 2, memory: 2, hdd: 2)

      expect(flavors.count).to eq 1
      expect(flavors.first).to eq flavor
    end

    def to_smal_and_correct_flavor(options)
      to_small = options.inject({}) do |hsh, entity|
        hsh[entity.first] = entity.last - 1
        hsh
      end

      create(:flavor, to_small)
      create(:flavor, options)
    end
  end

  context 'cost settings' do
    describe '#remove_hourly_cost_for' do
      let(:flavor) { create(:flavor) }
      let(:os_family) { Atmosphere::OSFamily.first }
      let(:at) { create(:appliance_type, os_family: os_family) }
      let(:vmt) { create(:virtual_machine_template, appliance_type: at) }

      it 'ignores removing nonexistent cost setting' do
        expect(Atmosphere::OSFamily.count).to eq 2
        expect{ flavor.remove_hourly_cost_for(os_family) }.
          not_to raise_error
        expect(flavor.remove_hourly_cost_for(os_family)).to eq nil
      end

      it 'removes set cost by destroying relation object' do
        flavor.set_hourly_cost_for(os_family, 100)
        expect(Atmosphere::FlavorOSFamily.count).to eq 1
        expect{ flavor.remove_hourly_cost_for(os_family) }.
          to change{ Atmosphere::FlavorOSFamily.count }.by(-1)
      end

      it 'prevents removing set cost that affects running VMs' do
        create(:virtual_machine,
               managed_by_atmosphere: true,
               virtual_machine_flavor: flavor,
               source_template: vmt)
        flavor.set_hourly_cost_for(os_family, 100)
        expect(Atmosphere::FlavorOSFamily.count).to eq 1
        expect{ flavor.remove_hourly_cost_for(os_family) }.
          to change{ Atmosphere::FlavorOSFamily.count }.by(0)
      end
    end

    describe 'destroy' do
      let(:flavor) { create(:flavor) }
      let(:os_family) { Atmosphere::OSFamily.first }

      it 'removes all pricing information together with a flavor' do
        flavor.set_hourly_cost_for(Atmosphere::OSFamily.first, 100)
        flavor.set_hourly_cost_for(Atmosphere::OSFamily.second, 500)
        expect(Atmosphere::FlavorOSFamily.count).to eq 2
        expect{ flavor.destroy }.
          to change { Atmosphere::FlavorOSFamily.count }.by(-2)
      end

      it 'should never perish when serving a running vm' do
        create(:virtual_machine,
               managed_by_atmosphere: true,
               virtual_machine_flavor: flavor)
        expect(flavor.virtual_machines.count).to eq 1
        expect{ flavor.destroy }.
          to change { Atmosphere::VirtualMachineFlavor.count }.by(0)
      end
    end
  end
end


text:
uwsgi-bonjour
=============

uWSGI plugin for OSX bonjour services integration

Installing it
=============

The plugin is 2.0 friendly, just run *(after having cloned it)*

```sh
uwsgi --build-plugin uwsgi-bonjour
```

Using it
========

The plugin currently exposes a single option `bonjour-register` allowing you to register new records
in the bonjour DNS service. You can register CNAME and A records.

Dynamically registering entries allows you to easily implement virtualhosting without messing with `/etc/hosts`. *(and more important the other people in your LAN will see them)*

Supposing you are working on the `darthvaderisbetterthanyoda` website, you may want to reach it via the `darthvaderisbetterthanyoda.local` domain without changing the name of your system:

```ini
[uwsgi]
plugins = bonjour
bonjour-register = name=darthvaderisbetterthanyoda.local,a=127.0.0.1
plugins = psgi
psgi = myapp.pl
master = true
http-socket = :8080
```

You can now directly connect to http://darthvaderisbetterthanyoda.local:8080/

The `bonjour-register` option can take the following parameters:

- `name` (required) the name you want to register

- `cname` create a CNAME record mapping to the specified hostname

- `a` (alias `ip`) create an A record mapping to the specified IPv4 address

- `unique` if set register the record as a unique bonjour entry (default is shared)

CNAME shortcut
==============

If you specify only a hostname as the `bonjour-register` argument, it will be registered as a CNAME for the local hostname.
If your hostname is called `deathstar.local` the following config:

```ini
[uwsgi]
plugins = bonjour
bonjour-register = darthvaderisbetterthanyoda.local
bonjour-register = hansolo.local
plugins = psgi
master = true
psgi = myapp.pl
http-socket = :8080
```

will create 2 CNAME records for darthvaderisbetterthanyoda.local and hansolo.local pointing to deathstar.local.

In same (rare) cases your local hostname could be messy and bonjour is not able to correctly use it. In such a case rely to non-shortcut setup, specifying the CNAME (or A) explicitly to a resolvable address.


text:
<!DOCTYPE html>

	<link rel="stylesheet" type="text/css" href="index.css"/>
	<link href='http://fonts.googleapis.com/css?family=Oswald:700' rel='stylesheet' type='text/css'>

<title>Dev's Webpage</title>

Dev Deol - Aspiring Web Developer

Hi Campers

Hi guys my name is Dev Deol and I'm an aspiring web developer just like the rest of you.  This summer I'm hoping to gain the knowledge to start a career in this field and hopefully make a few friends along the way.

My Links

Week1 Technical Blog

Cultural Blog

Week 2 Technical Blog

Week 3 Technical Blog

Week 3 Cultural Blog

Week 4 Technical Blog

Week 4 Cultural Blog

Week 5 Technical Blog

Week 5 Cultural Blog

Week 6 Technical Blog

Week 6 Cultural Blog

Week 7 Technical Blog

Week 7 Cultural Blog

Week 8 Technical Blog

Week 8 Cultural Blog

Week 9 Cultural Blog

See you in July


text:
module com.azure.resourcemanager.kubernetesconfiguration {
    requires transitive com.azure.core.management;

    exports com.azure.resourcemanager.kubernetesconfiguration;
    exports com.azure.resourcemanager.kubernetesconfiguration.fluent;
    exports com.azure.resourcemanager.kubernetesconfiguration.fluent.models;
    exports com.azure.resourcemanager.kubernetesconfiguration.models;

    opens com.azure.resourcemanager.kubernetesconfiguration.fluent.models to
        com.azure.core,
        com.fasterxml.jackson.databind;
    opens com.azure.resourcemanager.kubernetesconfiguration.models to
        com.azure.core,
        com.fasterxml.jackson.databind;
}


text:
/**
  @file
  @author Stefan Frings
*/

#ifndef HTTPREQUEST_H
#define HTTPREQUEST_H

#include <QByteArray>
#include <QHostAddress>
#include <QTcpSocket>
#include <QMap>
#include <QMultiMap>
#include <QSettings>
#include <QTemporaryFile>
#include <QUuid>
#include "httpglobal.h"

/**
  This object represents a single HTTP request. It reads the request
  from a TCP socket and provides getters for the individual parts
  of the request.

  The follwing config settings are required:

  maxRequestSize=16000
  maxMultiPartSize=1000000

  MaxRequestSize is the maximum size of a HTTP request. In case of
  multipart/form-data requests (also known as file-upload), the maximum
  size of the body must not exceed maxMultiPartSize.
  The body is always a little larger than the file itself.
*/

class DECLSPEC HttpRequest {
    Q_DISABLE_COPY(HttpRequest)
    friend class HttpSessionStore;

public:

    /** Values for getStatus() */
    enum RequestStatus {waitForRequest, waitForHeader, waitForBody, complete, abort};

    /**
      Constructor.
      @param settings Configuration settings
    */
    HttpRequest(QSettings* settings);

    /**
      Destructor.
    */
    virtual ~HttpRequest();

    /**
      Read the HTTP request from a socket.
      This method is called by the connection handler repeatedly
      until the status is RequestStatus::complete or RequestStatus::abort.
      @param socket Source of the data
    */
    void readFromSocket(QTcpSocket* socket);

    /**
      Get the status of this reqeust.
      @see RequestStatus
    */
    RequestStatus getStatus() const;

    /** Get the method of the HTTP request  (e.g. "GET") */
    QByteArray getMethod() const;

    /** Get the decoded path of the HTPP request (e.g. "/index.html") */
    QByteArray getPath() const;

    /** Get the raw path of the HTTP request (e.g. "/file%20with%20spaces.html") */
    const QByteArray& getRawPath() const;

    /** Get the version of the HTPP request (e.g. "HTTP/1.1") */
    QByteArray getVersion() const;

    /**
      Get the value of a HTTP request header.
      @param name Name of the header, not case-senitive.
      @return If the header occurs multiple times, only the last
      one is returned.
    */
    QByteArray getHeader(const QByteArray& name) const;

    /**
      Get the values of a HTTP request header.
      @param name Name of the header, not case-senitive.
    */
    QList<QByteArray> getHeaders(const QByteArray& name) const;

    /**
     * Get all HTTP request headers. Note that the header names
     * are returned in lower-case.
     */
    QMultiMap<QByteArray,QByteArray> getHeaderMap() const;

    /**
      Get the value of a HTTP request parameter.
      @param name Name of the parameter, case-sensitive.
      @return If the parameter occurs multiple times, only the last
      one is returned.
    */
    QByteArray getParameter(const QByteArray& name) const;

    /**
      Get the values of a HTTP request parameter.
      @param name Name of the parameter, case-sensitive.
    */
    QList<QByteArray> getParameters(const QByteArray& name) const;

    /** Get all HTTP request parameters. */
    QMultiMap<QByteArray,QByteArray> getParameterMap() const;

    /** Get the HTTP request body.  */
    QByteArray getBody() const;

    /**
      Decode an URL parameter.
      E.g. replace "%23" by '#' and replace '+' by ' '.
      @param source The url encoded strings
      @see QUrl::toPercentEncoding for the reverse direction
    */
    static QByteArray urlDecode(const QByteArray source);

    /**
      Get an uploaded file. The file is already open. It will
      be closed and deleted by the destructor of this HttpRequest
      object (after processing the request).

      For uploaded files, the method getParameters() returns
      the original fileName as provided by the calling web browser.
    */
    QTemporaryFile* getUploadedFile(const QByteArray fieldName) const;

    /**
      Get the value of a cookie.
      @param name Name of the cookie
    */
    QByteArray getCookie(const QByteArray& name) const;

    /** Get all cookies. */
    QMap<QByteArray,QByteArray>& getCookieMap();

    /**
      Get the address of the connected client.
      Note that multiple clients may have the same IP address, if they
      share an internet connection (which is very common).
     */
    QHostAddress getPeerAddress() const;

private:

    /** Request headers */
    QMultiMap<QByteArray,QByteArray> headers;

    /** Parameters of the request */
    QMultiMap<QByteArray,QByteArray> parameters;

    /** Uploaded files of the request, key is the field name. */
    QMap<QByteArray,QTemporaryFile*> uploadedFiles;

    /** Received cookies */
    QMap<QByteArray,QByteArray> cookies;

    /** Storage for raw body data */
    QByteArray bodyData;

    /** Request method */
    QByteArray method;

    /** Request path (in raw encoded format) */
    QByteArray path;

    /** Request protocol version */
    QByteArray version;

    /**
      Status of this request. For the state engine.
      @see RequestStatus
    */
    RequestStatus status;

    /** Address of the connected peer. */
    QHostAddress peerAddress;

    /** Maximum size of requests in bytes. */
    int maxSize;

    /** Maximum allowed size of multipart forms in bytes. */
    int maxMultiPartSize;

    /** Current size */
    int currentSize;

    /** Expected size of body */
    int expectedBodySize;

    /** Name of the current header, or empty if no header is being processed */
    QByteArray currentHeader;

    /** Boundary of multipart/form-data body. Empty if there is no such header */
    QByteArray boundary;

    /** Temp file, that is used to store the multipart/form-data body */
    QTemporaryFile tempFile;

    /** Parset he multipart body, that has been stored in the temp file. */
    void parseMultiPartFile();

    /** Sub-procedure of readFromSocket(), read the first line of a request. */
    void readRequest(QTcpSocket* socket);

    /** Sub-procedure of readFromSocket(), read header lines. */
    void readHeader(QTcpSocket* socket);

    /** Sub-procedure of readFromSocket(), read the request body. */
    void readBody(QTcpSocket* socket);

    /** Sub-procedure of readFromSocket(), extract and decode request parameters. */
    void decodeRequestParams();

    /** Sub-procedure of readFromSocket(), extract cookies from headers */
    void extractCookies();

    /** Buffer for collecting characters of request and header lines */
    QByteArray lineBuffer;

};

#endif // HTTPREQUEST_H


text:
layout: post
title:  "How Shall We Get Our Requests Granted?"
date:   2013-10-17 22:03:53
categories: newsletters
---

The unsurpassable promise of John 14:12-14 is brought up again in chapter 15. This time Jesus adds obedience to His commands as a condition for God's granting our requests. Some believers might surmise that

{% highlight ruby %}
def print_hi(name)
  puts "Hi, #{name}"
end
print_hi('Tom')
#=> prints 'Hi, Tom' to STDOUT.
{% endhighlight %}

Check out the [Jekyll docs][jekyll] for more info on how to get the most out of Jekyll. File all bugs/feature requests at [Jekyll's GitHub repo][jekyll-gh].

[jekyll-gh]: https://github.com/mojombo/jekyll
[jekyll]:    http://jekyllrb.com


text:
<?php
    error_reporting(E_ALL ^ E_NOTICE);
    define('DS', DIRECTORY_SEPARATOR);
    define('APP_ROOT', dirname(__FILE__) . DS);
    require(APP_ROOT . 'config.php');

    function error($msg)
    {
        header('Content-Type: text/plain; charset=utf8');
        die('Error: ' . (string)$msg);
    }

    $conn = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB);

    if ($conn->connect_errno) {
        error("Connect failed: " . $conn->connect_error);
    }

    $mod = strtolower($_GET['mod'] ?: 'main');
    // NEVER DO: require(APP_ROOT . 'mods/' . $mod);

    switch ($mod) {
        // read message
        case 'read': require(APP_ROOT . 'mods/read.php'); break;
        // new post form
        case 'new': require(APP_ROOT . 'templates/new.php'); break;
        // post new message
        case 'post': require(APP_ROOT . 'mods/post.php'); break;
        // something interesting
        case 'hack': require(APP_ROOT . 'templates/hack.php'); break;
        // password hash
        case 'hash': require(APP_ROOT . 'mods/hash.php'); break;
        // delete post
        case 'del': require(APP_ROOT . 'mods/del.php'); break;
        // home page
        case 'home': require(APP_ROOT . 'mods/home.php'); break;
        // home page
        default: header('Location: ' . $_SERVER['PHP_SELF'] . '?mod=home');
    }


text:
/**
 * A class to represent a node in the map
 */
package roadgraph;

import geography.GeographicPoint;

import java.util.HashSet;
import java.util.Set;

/**
 * @author UCSD MOOC development team
 *
 *         Class representing a vertex (or node) in our MapGraph
 *
 */
@SuppressWarnings("rawtypes")
class MapNode implements Comparable {
	/** The list of edges out of this node */
	private HashSet<MapEdge> edges;

	/** the latitude and longitude of this node */
	private GeographicPoint location;

	// WEEK 3 SOLUTIONS

	/** the predicted distance of this node (used in Week 3 algorithms) */
	private double distance;

	/** the actual distance of this node from start (used in Week 3 algorithms) */
	private double actualDistance;

	// END WEEK 3 SOLUTIONS

	MapNode(GeographicPoint loc) {
		location = loc;
		edges = new HashSet<MapEdge>();
		distance = 0.0;
		actualDistance = 0.0;
	}

	void addEdge(MapEdge edge) {
		edges.add(edge);
	}

	/** Return the neighbors of this MapNode */
	Set<MapNode> getNeighbors() {
		Set<MapNode> neighbors = new HashSet<MapNode>();
		for (MapEdge edge : edges) {
			neighbors.add(edge.getOtherNode(this));
		}
		return neighbors;
	}

	/** get the location of a node */
	GeographicPoint getLocation() {
		return location;
	}

	/** return the edges out of this node */
	Set<MapEdge> getEdges() {
		return edges;
	}

	/**
	 * Returns whether two nodes are equal. Nodes are considered equal if their locations are the same, even if their
	 * street list is different.
	 */
	public boolean equals(Object o) {
		if (!(o instanceof MapNode) || (o == null)) {
			return false;
		}
		MapNode node = (MapNode) o;
		return node.location.equals(this.location);
	}

	/**
	 * Because we compare nodes using their location, we also may use their location for HashCode.
	 *
	 * @return The HashCode for this node, which is the HashCode for the underlying point
	 */
	public int HashCode() {
		return location.hashCode();
	}

	/**
	 * ToString to print out a MapNode method
	 *
	 * @return the string representation of a MapNode
	 */
	public String toString() {
		String toReturn = "[NODE at location (" + location + ")";
		toReturn += " intersects streets: ";
		for (MapEdge e : edges) {
			toReturn += e.getRoadName() + ", ";
		}
		toReturn += "]";
		return toReturn;
	}

	// For debugging, output roadNames as a String.
	public String roadNamesAsString() {
		String toReturn = "(";
		for (MapEdge e : edges) {
			toReturn += e.getRoadName() + ", ";
		}
		toReturn += ")";
		return toReturn;
	}

	// WEEK 3 SOLUTIONS

	// get node distance (predicted)
	public double getDistance() {
		return this.distance;
	}

	// set node distance (predicted)
	public void setDistance(double distance) {
		this.distance = distance;
	}

	// get node distance (actual)
	public double getActualDistance() {
		return this.actualDistance;
	}

	// set node distance (actual)
	public void setActualDistance(double actualDistance) {
		this.actualDistance = actualDistance;
	}

	// Code to implement Comparable
	public int compareTo(Object o) {
		// convert to map node, may throw exception
		MapNode m = (MapNode) o;
		return ((Double) this.getDistance()).compareTo((Double) m.getDistance());
	}

	/**
	 * Find the closest from a set of neighbors
	 * @param startNode
	 *
	 * @param unVisitedneighbors
	 * @return closest neighbor
	 */
	public MapNode getClosestNeighbor(Set<MapNode> neighbors, MapNode startNode) {
		double minDistance = Double.POSITIVE_INFINITY;
		MapEdge shortestEdge = null;
		Set<MapEdge> edges = new HashSet<MapEdge>();

		// Get edges of selected neighbors and if no neighbors selected, get all edges
		if (neighbors == null ) {
			edges = getEdges();
		}
		else if (neighbors.isEmpty()){
			return startNode;
		}else {
			for (MapNode n : neighbors) {
				edges.add(new MapEdge("demo", this, n));
			}
		}

		// Find shortest edge
		for (MapEdge edge : edges) {
			if (edge.getLength() < minDistance) {
				shortestEdge = edge;
			}
		}
		return shortestEdge.getOtherNode(this);
	}

	/**
	 * Find the closest neighbor
	 *
	 * @return closest node
	 */
	public MapNode getClosestNeighbor() {
		double minDistance = Double.POSITIVE_INFINITY;
		MapEdge shortestEdge = null;

		// Find shortest edge
		for (MapEdge edge : getEdges()) {
			if (edge.getLength() < minDistance) {
				shortestEdge = edge;
			}
		}
		return shortestEdge.getOtherNode(this);
	}
}


text:
    <title>Example</title>
    <link type="text/css" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css"></link>
    <link type="text/css" rel="stylesheet" href="//raw.github.com/christianv/jquery-lifestream/master/css/lifestream.css"></link>
    <link type="text/css" rel="stylesheet" href="style/angular-lifestream.css"></link>

      <lifestream config="lifestreamConfig"></lifestream>


text:
package com.github.mauricio.async.db.mysql.binary.encoder

import io.netty.buffer.ByteBuf
import org.joda.time.LocalTime
import com.github.mauricio.async.db.mysql.column.ColumnTypes

object LocalTimeEncoder extends BinaryEncoder {
  def encode(value: Any, buffer: ByteBuf) {
    val time = value.asInstanceOf[LocalTime]

    val hasMillis = time.getMillisOfSecond != 0

    if ( hasMillis ) {
      buffer.writeByte(12)
    } else {
      buffer.writeByte(8)
    }

    if ( time.getMillisOfDay > 0 ) {
      buffer.writeByte(0)
    } else {
      buffer.writeByte(1)
    }

    buffer.writeInt(0)

    buffer.writeByte(time.getHourOfDay)
    buffer.writeByte(time.getMinuteOfHour)
    buffer.writeByte(time.getSecondOfMinute)

    if ( hasMillis ) {
      buffer.writeInt(time.getMillisOfSecond * 1000)
    }

  }

  def encodesTo: Int = ColumnTypes.FIELD_TYPE_TIME
}


text:
<?xml version="1.0"?>
<assembly>
    <id>plugin-agent-assembly</id>
    <includeBaseDirectory>false</includeBaseDirectory>
    <formats>
        <format>zip</format>
    </formats>
    <files>
        <file>
            <source>../ansible-runner-agent/teamcity-plugin.xml</source>
            <outputDirectory>/</outputDirectory>
        </file>
    </files>
    <moduleSets>
        <moduleSet>
            <useAllReactorProjects>true</useAllReactorProjects>
            <includes>
                <include>ee.elinyo.teamcity.plugins:ansible-runner-agent</include>
                <include>ee.elinyo.teamcity.plugins:ansible-runner-common</include>
            </includes>
            <binaries>
                <outputDirectory>lib</outputDirectory>
                <unpack>false</unpack>
                <dependencySets>
                    <dependencySet>
                        <includes>
                            <include>*</include>
                        </includes>
                    </dependencySet>
                </dependencySets>
            </binaries>
        </moduleSet>
    </moduleSets>
</assembly>


text:
/**************************************************************************/
/*!
    @file     main.c
    @author   K. Townsend (microBuilder.eu)

    @section LICENSE

    Software License Agreement (BSD License)

    Copyright (c) 2011, microBuilder SARL
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
    3. Neither the name of the copyright holders nor the
    names of its contributors may be used to endorse or promote products
    derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#include "projectconfig.h"
#include "sysinit.h"

#include "core/gpio/gpio.h"
#include "core/systick/systick.h"

#include "core/uart/uart.h"

#include "core/timer32/timer32.h"
#include "core/ssp/ssp.h"
#include "core/i2c/i2c.h"
#include "drivers/fatfs/diskio.h"
#include "drivers/fatfs/ff.h"

#include "ADXL375.h"

/**************************************************************************/
/*!
    Declarations
*/
/**************************************************************************/

uint8_t word[] = "hello there!";
UINT readBytes = 0;
bool uartHasData = false, frameFound = false;
uint8_t uartReadArr [CFG_UART_BUFSIZE] = {0};

// variables for fatfs operation
FRESULT res;
FIL fil;				/* File object */
DIR dir;				/* Pointer to the open directory object */
FILINFO fileInfo;		/* Pointer to file information to return */
static FATFS Fatfs[1];
UINT writtenBytes = 0;
uint32_t fileNameCounter = 0;
char fileName[] = {'0','0','0','0','l','u','c','h','.','d','a','t','\0'};

//vars for blinking
uint32_t currentSecond, lastSecond, uartDataReseivedSecond;
uint32_t cardWrittingErrorCount = 0;

/**************************************************************************/
/*!
    GYRO Declarations
*/
/**************************************************************************/

extern volatile uint32_t I2CMasterState;
extern volatile uint32_t I2CSlaveState;

extern volatile uint8_t I2CMasterBuffer[I2C_BUFSIZE];    // Master Mode
extern volatile uint8_t I2CSlaveBuffer[I2C_BUFSIZE];     // Master Mode

extern volatile uint32_t I2CReadLength;
extern volatile uint32_t I2CWriteLength;

extern volatile uint32_t RdIndex;
extern volatile uint32_t WrIndex;

extern volatile uint32_t _I2cMode;                       // I2CMASTER or I2CSLAVE

int ADXL375_FIFO_streamMode = 0x0FUL; // stream mode 16 samples

/**************************************************************************/
/*!
    Functions.
*/
/**************************************************************************/

//stop looping in case file operations error
//and turn on led
void checkRes(FRESULT *res)
{
  if (*res != FR_OK){
	  gpioSetValue(CFG_LED_PORT, CFG_LED_PIN, CFG_LED_ON);

	  // try to mount card again to continue writing
	do {
		*res = f_mount(0, &Fatfs[0]);
		systickDelay(1000);
	} while (*res != FR_OK);

  }
}

// Toggle led once per second in case normal UART reading and writing to SD
void blinking(uint32_t *current, uint32_t *last, uint32_t *uartDataReseived)
{
	*current = systickGetSecondsActive();
	if(*uartDataReseived > (*current - 10)) {
		if (*current != *last)
		{
		  *last = *current;
		  gpioSetValue(CFG_LED_PORT, CFG_LED_PIN, lastSecond % 2);
		}
	} else {
		//if last uart transmission was gather than 10 seconds ago
		//turn off led
		 gpioSetValue(CFG_LED_PORT, CFG_LED_PIN, CFG_LED_OFF);
	}

}

// int to char
void itoa(char *arr, uint32_t *num)
{
	int i = 3;
	do {
		arr[i--] = (*num % 10) + '0';
		*num /= 10;
	} while (*num);
}

//if frame found returns start index
//else returns -1
int findStartFrame(uint8_t *uartReadArr[], UINT *readBytes)
{
	uint8_t jj = 0;
	for(jj = 0; jj < (*readBytes - 1); jj++) {
		if((*uartReadArr[jj] == 0xff) && (uartReadArr[jj] == 0xff)) {
			return jj;
		}
	}
	return -1;
}

void writeArrayToCard(FIL fil, char fileName [], uint8_t arr [], UINT count)
{
	res = f_open (&fil, fileName, FA_READ | FA_WRITE | FA_OPEN_ALWAYS);
	checkRes(&res);
	res = f_lseek(&fil, (&fil)->fsize);
	checkRes(&res);
	res = f_write (&fil, arr, count, &writtenBytes);
	checkRes(&res);
	f_close(&fil);
}

void clearBuff() {
	int i = 0;
	for ( i = 0; i < I2C_BUFSIZE; i++ )
	{
		I2CMasterBuffer[i] = 0x00;
	}

	for ( i = 0; i < I2C_BUFSIZE; i++ )
	{
		I2CSlaveBuffer[i] = 0x00;
	}
}

/**************************************************************************/
/*!
    Main program entry point.
*/
/**************************************************************************/
int main(void)
{
  // Configure cpu and mandatory peripherals
  systemInit();
  res = f_mount(0, &Fatfs[0]);
  checkRes(&res);

  res = f_opendir (&dir,(XCHAR *)'/');
  checkRes(&res);

  fileNameCounter = 0;
  do {
	  res = f_readdir (&dir, &fileInfo);
	  checkRes(&res);
	  fileNameCounter++;
  } while((res == FR_OK) && (fileInfo.fname[0] != 0));

  itoa(&fileName, &fileNameCounter);

  currentSecond = lastSecond = uartDataReseivedSecond = 0;

  while (1)
  {
	//uartSend((uint8_t *)word, sizeof(word));
	uartHasData = uartRxBufferReadArray(uartReadArr, &readBytes);

		//if we still not found frame start
		//when found dont search again,
		//just write all from uart

//		if (uartHasData == true) {
//			writeArrayToCard(fil, fileName, &uartReadArr, &readBytes);
//			uartDataReseivedSecond = systickGetSecondsActive();
//	  	}

		clearBuff();

		//read device id to check ADXL375
		int tryReadGyroCount = 0;
		bool gyroOK = false;
		do {
			I2CWriteLength = 3;
			I2CReadLength = 0;
			I2CMasterBuffer[0] = SLAVE_ADDR;
			I2CMasterBuffer[1] = ADXL375_FIFO_CTL;
			I2CMasterBuffer[2] = 0x4FUL;//ADXL375_FIFO_streamMode;
			i2cEngine();
			clearBuff();

			do {
				I2CWriteLength = 2;
				I2CReadLength = 0;
				I2CMasterBuffer[0] = SLAVE_ADDR;
				I2CMasterBuffer[1] = ADXL375_FIFO_STATUS;
				i2cEngine();
				clearBuff();

				I2CWriteLength = 1;
				I2CReadLength = 1;
				I2CMasterBuffer[0] = SLAVE_ADDR | READ_WRITE;
				i2cEngine();

				systickDelay(100);
			} while(I2CSlaveBuffer[0] != 128);

			int jo = I2CSlaveBuffer[0];

			I2CWriteLength = 2;
			I2CReadLength = 0;
			I2CMasterBuffer[0] = SLAVE_ADDR;
			I2CMasterBuffer[1] = ADXL375_FIFO_CTL;
			i2cEngine();
			clearBuff();

			I2CWriteLength = 1;
			I2CReadLength = 16;
			I2CMasterBuffer[0] = SLAVE_ADDR | READ_WRITE;
			i2cEngine();

			jo = I2CSlaveBuffer[0];

		} while((I2CMasterState == 259) && (tryReadGyroCount <= 100));

		if(tryReadGyroCount < 100) {
			gyroOK = true;
		}

//		if ((uartHasData == true) && (frameFound == false)){
//
//			if(frameFound) {
//				writeArrayToCard(&fileName, &uartReadArr, &readBytes);
//				uartDataReseivedSecond = systickGetSecondsActive();
//			} else {
//				int frameFoundIndex = -1;
//				frameFoundIndex = findStartFrame(&uartReadArr, &readBytes);
//
//				if(frameFoundIndex >= 0) {
//					frameFound = true;
//				}
//			}
//		} else if ((uartHasData == true) && frameFound == true){
//			writeArrayToCard(&fileName, &uartReadArr, &readBytes);
//			uartDataReseivedSecond = systickGetSecondsActive();
//		}
//  	}

  	blinking(&currentSecond, &lastSecond, &uartDataReseivedSecond);
  }

  return 0;
}


text:
package meresti.linkviewer.rest.resources;

import meresti.linkviewer.core.entities.Relevance;
import org.springframework.hateoas.ResourceSupport;

public class ContentRoomLinkResource extends ResourceSupport {

    private LinkResource link;

    private Relevance relevance;

    private String relevanceRate;

    public LinkResource getLink() {
        return link;
    }

    public void setLink(final LinkResource link) {
        this.link = link;
    }

    public Relevance getRelevance() {
        return relevance;
    }

    public void setRelevance(final Relevance relevance) {
        this.relevance = relevance;
    }

    public String getRelevanceRate() {
        return relevanceRate;
    }

    public void setRelevanceRate(final String relevanceRate) {
        this.relevanceRate = relevanceRate;
    }
}


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql.Models;

namespace Microsoft.Azure.Management.Sql
{
    /// <summary>
    /// Represents all the operations for operating on Azure SQL Database
    /// Servers.  Contains operations to: Create, Retrieve, Update, and Delete
    /// servers.
    /// </summary>
    public partial interface IServerOperations
    {
        /// <summary>
        /// Creates a new Azure SQL Database server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the Resource Group to which the server belongs.
        /// </param>
        /// <param name='serverName'>
        /// The name of the Azure SQL Database Server on which the database is
        /// hosted.
        /// </param>
        /// <param name='parameters'>
        /// The required parameters for createing or updating a database.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Represents the response to a Get Azure Sql Database Server request.
        /// </returns>
        Task<ServerGetResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, ServerCreateOrUpdateParameters parameters, CancellationToken cancellationToken);

        /// <summary>
        /// Returns information about an Azure SQL Database Server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the Resource Group to which the server belongs.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server to delete.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken);

        /// <summary>
        /// Returns information about an Azure SQL Database Server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the Resource Group to which the server belongs.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server to retrieve.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Represents the response to a Get Azure Sql Database Server request.
        /// </returns>
        Task<ServerGetResponse> GetAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken);

        /// <summary>
        /// Returns information about an Azure SQL Database Server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the Resource Group to which the server belongs.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Represents the response to a Get Azure Sql Database Server request.
        /// </returns>
        Task<ServerListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken);

        /// <summary>
        /// Returns information about Azure SQL Database Server usage.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the Resource Group to which the server belongs.
        /// </param>
        /// <param name='serverName'>
        /// The name of the Azure SQL Database Server in which the Azure SQL
        /// Databases are hosted.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Represents the response to a List Azure Sql Database Server metrics
        /// request.
        /// </returns>
        Task<ServerMetricListResponse> ListUsagesAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken);
    }
}


text:
=head1 LICENSE

Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=head1 NAME

  Bio::EnsEMBL::Compara::PipeConfig::Example::WBParaSiteProteinTrees_conf

=head1 SYNOPSIS

    #1. update ensembl-hive, ensembl and ensembl-compara GIT repositories before each new release

    #2. you may need to update 'schema_version' in meta table to the current release number in ensembl-hive/sql/tables.sql

    #3. make sure that all default_options are set correctly

    #4. Run init_pipeline.pl script:
        init_pipeline.pl Bio::EnsEMBL::Compara::PipeConfig::Example::WBParaSiteProteinTrees_conf \
        -password <your_password> -mlss_id <your_current_PT_mlss_id> \
        -division <eg_division> -eg_release <egrelease>

    #5. Sync and loop the beekeeper.pl as shown in init_pipeline.pl's output

=head1 DESCRIPTION

    The PipeConfig example file for Ensembl Genomes group's version of
    ProteinTrees pipeline. This file is inherited from & customised further
    within the Ensembl Genomes infrastructure but this file serves as
    an example of the type of configuration we perform.

=head1 CONTACT

  Please contact Compara or Ensembl Genomes with questions/suggestions

=cut

package Bio::EnsEMBL::Compara::PipeConfig::Example::WBParaSiteProteinTrees_conf;

use strict;
use warnings;

use base ('Bio::EnsEMBL::Compara::PipeConfig::Example::EGProteinTrees_conf');

sub default_options {
    my ($self) = @_;

    return {
        %{$self->SUPER::default_options},   # inherit the EnsemblGenomes ones (especially all the paths and capacities)

    # parameters that are likely to change from execution to another:
        #mlss_id => 40043,
        #'do_not_reuse_list' => ['guillardia_theta'], # set this to empty or to the genome db names we should ignore

    # custom pipeline name, in case you don't like the default one
        'dbowner' => 'ensembl_compara',       # Used to prefix the database name (in HiveGeneric_conf)
        'pipeline_name' => $self->o('division').'_hom_'.$self->o('ps_release').'_'.$self->o('ensembl_release'),
        'division'  => 'wbparasite',

    # dependent parameters: updating 'work_dir' should be enough
        'base_dir'              =>  '/nfs/nobackup2/ensemblgenomes/wormbase/parasite/'.$self->o('ENV', 'USER').'/compara',
        # work_dir and exe_dir are defined in the base class

    # "Member" parameters:

    # blast parameters:

    # clustering parameters:

    # tree building parameters:
        'species_tree_input_file'   =>  '/nfs/panda/ensemblgenomes/wormbase/parasite/config/compara_guide_tree.wbparasite.tre',

    # homology_dnds parameters:

    # mapping parameters:

    # executable locations:

    # HMM specific parameters (set to 0 or undef if not in use)

    # hive_capacity values for some analyses:

    # hive priority for non-LOCAL health_check analysis:

    # connection parameters to various databases:

        # Uncomment and update the database locations

        # the production database itself (will be created)
        # it inherits most of the properties from HiveGeneric, we usually only need to redefine the host, but you may want to also redefine 'port'

        # the master database for synchronization of various ids (use undef if you don't have a master database)
        'master_db' => 'mysql://ensro@mysql-eg-pan-1.ebi.ac.uk:4276/ensembl_compara_master_parasite',

    ######## THESE ARE PASSED INTO LOAD_REGISTRY_FROM_DB SO PASS IN DB_VERSION
    ######## ALSO RAISE THE POINT ABOUT LOAD_FROM_MULTIPLE_DBs

    prod_1 => {
      -host   => 'mysql-ps-prod-1.ebi.ac.uk',
      -port   => 4450,
      -user   => 'ensro',
      -db_version => $self->o('ensembl_release')
    },

    staging_1 => {
      -host   => 'mysql-ps-staging-1.ebi.ac.uk',
      -port   => 4451,
      -user   => 'ensro',
      -db_version => $self->o('ensembl_release')
    },

    # NOTE: The databases referenced in the following arrays have to be hashes (not URLs)
    # Add the database entries for the current core databases and link 'curr_core_sources_locs' to them
    'curr_core_sources_locs' => [ $self->o('prod_1') ],

    # Add the database entries for the core databases of the previous release
    'prev_core_sources_locs'   => [ ],

    # Add the database location of the previous Compara release. Use "undef" if running the pipeline without reuse
    'prev_rel_db' => undef,

    };
}

sub resource_classes {
  my ($self) = @_;
  return {
         # Many classes are already defined there
         %{$self->SUPER::resource_classes},
         # But we could add some more here
  };
}

sub pipeline_analyses {
    my $self = shift;
    my $all_analyses = $self->SUPER::pipeline_analyses(@_);
    my %analyses_by_name = map {$_->{'-logic_name'} => $_} @$all_analyses;

    ## Extend this section to redefine the resource names of some analysis
    # e.g. $analyses_by_name{'hcluster_parse_output'}->{'-rc_name'} = '500Mb_job';

    return $all_analyses;
}

1;


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CBRemoteControl.Remote.Common
{
    class ScreenCommon
    {
        #region 方法
        public static byte[] GetScreen()
        {
            using (var screen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height))
            {
                var g = Graphics.FromImage(screen);
                g.CopyFromScreen(0, 0, 0, 0, screen.Size);
                //g.DrawString(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), new Font("黑体", 20f), new SolidBrush(Color.Red), 0, 0);
                return BitmapToByte(screen);
            }
        }
        #endregion

        #region 私有方法
        private static byte[] BitmapToByte(Bitmap bmp)
        {
            using (var ms = new MemoryStream())
            {
                bmp.Save(ms, ImageFormat.Jpeg);
                //bmp.Save(String.Format(@"z:\data\{0}.jpg", DateTime.Now.Ticks), ImageFormat.Jpeg);
                return ms.ToArray();
            }
        }
        #endregion
    }
}


text:
/*
	AudioDevice.cpp
	(c)2005 Palestar, Richard Lyle
*/

#define AUDIO_DLL
#include "Standard/Library.h"
#include "Audio/Sound.h"
#include "Audio/AudioDevice.h"
#include "Factory/FactoryTypes.h"

//----------------------------------------------------------------------------

IMPLEMENT_ABSTRACT_FACTORY( AudioDevice, Widget );
IMPLEMENT_ABSTRACT_FACTORY( AudioBuffer, Widget );

AudioDevice::AudioDevice()
{}

//----------------------------------------------------------------------------

static void LoadAudioLibs()
{
// Load all available audio devices
#ifdef _DEBUG
	static Library LIB_AUDIODS( ("AudioDSD.dll") );			// DirectSound
	static Library LIB_AUDIOPSX( ("AudioPSXD.dll") );		// PlayStation 2
	static Library LIB_AUDIOXB( ("AudioXBD.dll") );			// XBOX
#else
	static Library LIB_AUDIODS( ("AudioDS.dll") );			// DirectSound
	static Library LIB_AUDIOPSX( ("AudioPSX.dll") );			// PlayStation 2
	static Library LIB_AUDIOXB( ("AudioXB.dll") );			// XBOX
#endif
}

//----------------------------------------------------------------------------

AudioDevice * AudioDevice::create()
{
	LoadAudioLibs();
	if ( Factory::typeCount( classKey() ) > 0 )
		return WidgetCast<AudioDevice>(Factory::createWidget( Factory::type( classKey(), 0 ) ));

	return NULL;
}

AudioDevice * AudioDevice::create( const char * pClass )
{
	LoadAudioLibs();
	return WidgetCast<AudioDevice>(Factory::createNamedWidget( pClass ));
}

//----------------------------------------------------------------------------
// EOF


text:
#include "third_party/blink/renderer/core/css/css_style_declaration.h"

#include <algorithm>

#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_style_declaration.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/ascii_ctype.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"

namespace blink {

namespace {

// Check for a CSS prefix.
// Passed prefix is all lowercase.
// First character of the prefix within the property name may be upper or
// lowercase.
// Other characters in the prefix within the property name must be lowercase.
// The prefix within the property name must be followed by a capital letter.
bool HasCSSPropertyNamePrefix(const AtomicString& property_name,
                              const char* prefix) {
#if DCHECK_IS_ON()
  DCHECK(*prefix);
  for (const char* p = prefix; *p; ++p)
    DCHECK(IsASCIILower(*p));
  DCHECK(property_name.length());
#endif

  if (ToASCIILower(property_name[0]) != prefix[0])
    return false;

  unsigned length = property_name.length();
  for (unsigned i = 1; i < length; ++i) {
    if (!prefix[i])
      return IsASCIIUpper(property_name[i]);
    if (property_name[i] != prefix[i])
      return false;
  }
  return false;
}

CSSPropertyID ParseCSSPropertyID(const ExecutionContext* execution_context,
                                 const AtomicString& property_name) {
  unsigned length = property_name.length();
  if (!length)
    return CSSPropertyID::kInvalid;

  StringBuilder builder;
  builder.ReserveCapacity(length);

  unsigned i = 0;
  bool has_seen_dash = false;

  if (HasCSSPropertyNamePrefix(property_name, "webkit"))
    builder.Append('-');
  else if (IsASCIIUpper(property_name[0]))
    return CSSPropertyID::kInvalid;

  bool has_seen_upper = IsASCIIUpper(property_name[i]);

  builder.Append(ToASCIILower(property_name[i++]));

  for (; i < length; ++i) {
    UChar c = property_name[i];
    if (!IsASCIIUpper(c)) {
      if (c == '-')
        has_seen_dash = true;
      builder.Append(c);
    } else {
      has_seen_upper = true;
      builder.Append('-');
      builder.Append(ToASCIILower(c));
    }
  }

  // Reject names containing both dashes and upper-case characters, such as
  // "border-rightColor".
  if (has_seen_dash && has_seen_upper)
    return CSSPropertyID::kInvalid;

  String prop_name = builder.ReleaseString();
  return UnresolvedCSSPropertyID(execution_context, prop_name);
}

// When getting properties on CSSStyleDeclarations, the name used from
// Javascript and the actual name of the property are not the same, so
// we have to do the following translation. The translation turns upper
// case characters into lower case characters and inserts dashes to
// separate words.
//
// Example: 'backgroundPositionY' -> 'background-position-y'
//
// Also, certain prefixes such as 'css-' are stripped.
CSSPropertyID CssPropertyInfo(const ExecutionContext* execution_context,
                              const AtomicString& name) {
  typedef HashMap<String, CSSPropertyID> CSSPropertyIDMap;
  DEFINE_STATIC_LOCAL(CSSPropertyIDMap, map, ());
  CSSPropertyIDMap::iterator iter = map.find(name);
  if (iter != map.end())
    return iter->value;

  CSSPropertyID unresolved_property =
      ParseCSSPropertyID(execution_context, name);
  if (unresolved_property == CSSPropertyID::kVariable)
    unresolved_property = CSSPropertyID::kInvalid;
  map.insert(name, unresolved_property);
  DCHECK(!IsValidCSSPropertyID(unresolved_property) ||
         CSSProperty::Get(ResolveCSSPropertyID(unresolved_property))
             .IsWebExposed(execution_context));
  return unresolved_property;
}

}  // namespace

void CSSStyleDeclaration::Trace(Visitor* visitor) const {
  ExecutionContextClient::Trace(visitor);
  ScriptWrappable::Trace(visitor);
}

CSSStyleDeclaration::CSSStyleDeclaration(ExecutionContext* context)
    : ExecutionContextClient(context) {}

CSSStyleDeclaration::~CSSStyleDeclaration() = default;

void CSSStyleDeclaration::setCSSFloat(const ExecutionContext* execution_context,
                                      const String& value,
                                      ExceptionState& exception_state) {
  SetPropertyInternal(CSSPropertyID::kFloat, String(), value, false,
                      execution_context->GetSecureContextMode(),
                      exception_state);
}

String CSSStyleDeclaration::AnonymousNamedGetter(const AtomicString& name) {
  // Search the style declaration.
  CSSPropertyID unresolved_property =
      CssPropertyInfo(GetExecutionContext(), name);

  // Do not handle non-property names.
  if (!IsValidCSSPropertyID(unresolved_property))
    return String();

  return GetPropertyValueInternal(ResolveCSSPropertyID(unresolved_property));
}

NamedPropertySetterResult CSSStyleDeclaration::AnonymousNamedSetter(
    ScriptState* script_state,
    const AtomicString& name,
    const ScriptValue& value) {
  const ExecutionContext* execution_context =
      ExecutionContext::From(script_state);
  if (!execution_context)
    return NamedPropertySetterResult::kDidNotIntercept;
  CSSPropertyID unresolved_property = CssPropertyInfo(execution_context, name);
  if (!IsValidCSSPropertyID(unresolved_property))
    return NamedPropertySetterResult::kDidNotIntercept;
  // We create the ExceptionState manually due to performance issues: adding
  // [RaisesException] to the IDL causes the bindings layer to expensively
  // create a std::string to set the ExceptionState's |property_name| argument,
  // while we can use CSSProperty::GetPropertyName() here (see bug 829408).
  ExceptionState exception_state(
      script_state->GetIsolate(), ExceptionState::kSetterContext,
      "CSSStyleDeclaration",
      CSSProperty::Get(ResolveCSSPropertyID(unresolved_property))
          .GetPropertyName());
  // Perform a type conversion from ES value to
  // IDL [LegacyNullToEmptyString] DOMString only after we've confirmed that
  // the property name is a valid CSS attribute name (see bug 1310062).
  auto&& string_value =
      NativeValueTraits<IDLStringTreatNullAsEmptyString>::NativeValue(
          script_state->GetIsolate(), value.V8Value(), exception_state);
  if (UNLIKELY(exception_state.HadException()))
    return NamedPropertySetterResult::kIntercepted;
  SetPropertyInternal(unresolved_property, String(), string_value, false,
                      execution_context->GetSecureContextMode(),
                      exception_state);
  if (exception_state.HadException())
    return NamedPropertySetterResult::kIntercepted;
  return NamedPropertySetterResult::kIntercepted;
}

NamedPropertyDeleterResult CSSStyleDeclaration::AnonymousNamedDeleter(
    const AtomicString& name) {
  // Pretend to be deleted since web author can define their own property with
  // the same name.
  return NamedPropertyDeleterResult::kDeleted;
}

void CSSStyleDeclaration::NamedPropertyEnumerator(Vector<String>& names,
                                                  ExceptionState&) {
  typedef Vector<String, kNumCSSProperties - 1> PreAllocatedPropertyVector;
  DEFINE_STATIC_LOCAL(PreAllocatedPropertyVector, property_names, ());

  const ExecutionContext* execution_context = GetExecutionContext();

  if (property_names.empty()) {
    for (CSSPropertyID property_id : CSSPropertyIDList()) {
      const CSSProperty& property_class =
          CSSProperty::Get(ResolveCSSPropertyID(property_id));
      if (property_class.IsWebExposed(execution_context))
        property_names.push_back(property_class.GetJSPropertyName());
    }
    for (CSSPropertyID property_id : kCSSPropertyAliasList) {
      const CSSUnresolvedProperty* property_class =
          CSSUnresolvedProperty::GetAliasProperty(property_id);
      if (property_class->IsWebExposed(execution_context))
        property_names.push_back(property_class->GetJSPropertyName());
    }
    std::sort(property_names.begin(), property_names.end(),
              WTF::CodeUnitCompareLessThan);
  }
  names = property_names;
}

bool CSSStyleDeclaration::NamedPropertyQuery(const AtomicString& name,
                                             ExceptionState&) {
  return IsValidCSSPropertyID(CssPropertyInfo(GetExecutionContext(), name));
}

}  // namespace blink


text:
module PrimesMultiplicationTableGenerator
  VERSION = "0.0.1"
end


text:
package com.yang.yunfan.ui.news;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.yang.yunfan.R;
import com.yang.yunfan.model.News;
import com.yang.yunfan.utils.FrescoUtil;

import java.util.List;

/**
 * Created by yang on 2017/1/8.
 */

public class NewsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public static final String NETWORK_ERROR = "network_orror";

    private static final int VIEW_TYPE_NETWORK_ERROR = 0;
    private static final int VIEW_TYPE_ONE_IMAGE = 1;
    private static final int VIEW_TYPE_THREE_IMAGE = 2;

    private Context context;
    private List<News> datas;
    private OnItemClickListener onItemClickListener;

    public NewsListAdapter(Context context, List<News> datas) {
        this.context = context;
        this.datas = datas;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder vh = null;
        View view = null;
        switch (viewType){
            case VIEW_TYPE_NETWORK_ERROR:
                view = LayoutInflater.from(context).inflate(R.layout.layout_neterror_top, parent, false);
                vh = new NeterrorViewHolder(view);
                break;
            case VIEW_TYPE_ONE_IMAGE:
                view = LayoutInflater.from(context).inflate(R.layout.item_news_list_2, parent, false);
                vh = new ViewHolder(view);
                break;
            case VIEW_TYPE_THREE_IMAGE:
                view = LayoutInflater.from(context).inflate(R.layout.item_news_list, parent, false);
                vh = new ViewHolder(view);
                break;
        }
        return vh;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        int itemViewType = getItemViewType(position);
        if (itemViewType == VIEW_TYPE_NETWORK_ERROR){
            NeterrorViewHolder vh = (NeterrorViewHolder) holder;
            vh.llItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener != null){
                        onItemClickListener.onClickNeterorItem(v, position);
                    }
                }
            });
            return;
        }

        ViewHolder viewHolder = (ViewHolder) holder;
        News news = datas.get(position);
        viewHolder.tvTitle.setText(news.getTitle());
        FrescoUtil.setImageUri(viewHolder.sdv_1, news.getThumbnail_pic_s());
        if (itemViewType == VIEW_TYPE_THREE_IMAGE){
            FrescoUtil.setImageUri(viewHolder.sdv_2, news.getThumbnail_pic_s02());
            FrescoUtil.setImageUri(viewHolder.sdv_3, news.getThumbnail_pic_s03());
        }

        viewHolder.tvAuthor.setText(news.getAuthor_name());
        viewHolder.tvDate.setText(news.getDate());
        viewHolder.rlItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null){
                    onItemClickListener.onItemClick(v, position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    @Override
    public int getItemViewType(int position) {
        News news = datas.get(position);
        if (position == 0 && news != null && NETWORK_ERROR.equals(news.getCategory())){
            return VIEW_TYPE_NETWORK_ERROR;
        }

        if (TextUtils.isEmpty(news.getThumbnail_pic_s02()) || TextUtils.isEmpty(news.getThumbnail_pic_s03())){
            return VIEW_TYPE_ONE_IMAGE;
        }else {
            return VIEW_TYPE_THREE_IMAGE;
        }
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        RelativeLayout rlItem;
        TextView tvTitle;
        SimpleDraweeView sdv_1;
        SimpleDraweeView sdv_2;
        SimpleDraweeView sdv_3;
        TextView tvAuthor;
        TextView tvDate;

        public ViewHolder(View itemView) {
            super(itemView);
            rlItem = (RelativeLayout) itemView.findViewById(R.id.rl_item);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
            sdv_1 = (SimpleDraweeView) itemView.findViewById(R.id.sdv_1);
            sdv_2 = (SimpleDraweeView) itemView.findViewById(R.id.sdv_2);
            sdv_3 = (SimpleDraweeView) itemView.findViewById(R.id.sdv_3);
            tvAuthor = (TextView) itemView.findViewById(R.id.tv_author_name);
            tvDate = (TextView) itemView.findViewById(R.id.tv_date);
        }
    }
    public static class NeterrorViewHolder extends RecyclerView.ViewHolder{
        LinearLayout llItem;

        public NeterrorViewHolder(View itemView) {
            super(itemView);
            llItem = (LinearLayout) itemView.findViewById(R.id.ll_item);
        }
    }

    public interface OnItemClickListener{
        void onItemClick(View v, int position);

        void onClickNeterorItem(View v, int position);
    }

}


text:
module.exports = function (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      {
        pattern: 'js/morpheus-external-latest.min.js',
        watched: false
      },
      {
        pattern: 'js/morpheus-latest.min.js',
        watched: false
      },
      {
        pattern: 'jasmine/matchers/*.js',
        watched: false
      },
      {
        pattern: 'jasmine/spec/*.js',
        watched: false
      },
      {
        pattern: 'node_modules/whatwg-fetch/fetch.js',
        watched: false
      },
      {
        pattern: 'node_modules/promise-polyfill/promise.js',
        watched: false
      },
      {
        pattern: 'jasmine/test_files/*',
        included: false,
        served: true,
        watched: false,
        nocache: true
      }
    ],
    browserNoActivityTimeout: 100000,
    proxies: {
      '/test_files/': '/base/jasmine/test_files/'
    },

    // list of files to exclude
    exclude: ['jasmine/spec/marker_selection_test.js'],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {},

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  });
};


text:
<?php

namespace Econda\RecEngine\Config;

/**
 * Configuration classes for econda recommendation engine must implement this interface
 */
interface ConfigInterface
{
	/**
	 * Get econda cross sell accountid
	 * @return string
	 */
	public function getAccountId();
}