text:
/**
 * @fileOverview Initialize webserver services, express, routes, etc
 */
var http = require('http');

var Promise = require('bluebird');
var express = require('express');
var bodyParser = require('body-parser');

var srcCrude = null;

var expressApp = module.exports = {};

/** @type {?express} The express instance */
expressApp.app = null;

/** @type {http} The http instance */
expressApp.http = null;

/** @type {app.core.SessionStore} Instance of Session Store */
expressApp.sessionStore = null;

/**
 * DI the crude package.
 *
 * @param {crude} crude The crude package.
 */
expressApp.setCrude = function (crude) {
  srcCrude = crude;
};

/**
 * Kick off the webserver...
 *
 * @return {Promise} a promise.
 */
expressApp.init = function() {
  return new Promise(function(resolve, reject) {
    if (expressApp.app !== null) {
      expressApp.http.close(function (err) {
        if (err) {
          reject(err);
        } else {
          expressApp.initExpress()
            .return(null)
            .then(resolve, reject);
        }
      });
    } else {
      expressApp.initExpress()
        .return(null)
        .then(resolve, reject);
    }
  });
};

expressApp.initExpress = Promise.method(function() {

  var app = expressApp.app = express();

  var port = 3100;

  // Setup express
  app.set('port', port);
  app.set('view engine', 'jade');

  app.use(bodyParser.json());

  // initialize webserver
  expressApp.initWebserver(app);

  return Promise.all([
    expressApp.startWebserver(app),
  ]);
});

/**
 * Init the webserver.
 *
 * @param {Express} app the Express instance.
 */
expressApp.initWebserver = function(app) {
  expressApp.http = http.createServer(app);
};

/**
 * Start the webserver.
 *
 * @param {Express} app the Express instance.
 * @return {Promise} A promise.
 */
expressApp.startWebserver = function(app) {
  return new Promise(function(resolve, reject) {
    expressApp.http.on('clientError', function(err) {
      console.warn('startWebserver() :: Client Error. Exception:', err);
    });
    expressApp.http.on('error', function(err) {
      console.error('startWebserver() :: Failed to start web server. Exception:', err);
      reject(err);
    });

    expressApp.http.listen(app.get('port'), function(){
      resolve();
    });
  });
};


text:
#ifndef _CONF_H_
#define _CONF_H_

#define RING_SIZE 1024
#define MAX_PKT_QUOTA 64

#define RX_DESC_PER_QUEUE   128
#define TX_DESC_PER_QUEUE   512

#define MBUF_DATA_SIZE     RTE_MBUF_DEFAULT_BUF_SIZE
#define MBUF_PER_POOL 8192

#define QUOTA_WATERMARK_MEMZONE_NAME "qw_global_vars"

#endif /* _CONF_H_ */

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<!--

    Copyright (C) 2010-2011 LShift Ltd.

    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.

-->

<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="net.lshift.diffa.kernel.differencing">
  <class name="PendingDifferenceEvent" table="pending_diffs">
    <id name="oid">
      <generator class="native">
        <param name="sequence">pending_diffs_sequence</param>
      </generator>
    </id>
    <component name="objId">
      <property name="id" type="string" column="entity_id" index="pdiff_domain_idx" />
      <component name="pair">
        <property name="domain" type="string" column="domain" index="pdiff_domain_idx" />
        <property name="key" type="string" column="pair" index="pdiff_domain_idx" />
      </component>
    </component>
    <property name="detectedAt" type="org.jadira.usertype.dateandtime.joda.PersistentDateTime" column="detected_at" not-null="true" />
    <property name="lastSeen" type="org.jadira.usertype.dateandtime.joda.PersistentDateTime" column="last_seen" not-null="true" />
    <property name="upstreamVsn" type="string" column="upstream_vsn" />
    <property name="downstreamVsn" type="string" column="downstream_vsn" />
  </class>

  <class name="ReportedDifferenceEvent" table="diffs">
    <id name="seqId">
      <column name="seq_id" index="seq_id_domain_idx"/>
      <generator class="native">
        <param name="sequence">diffs_sequence</param>
      </generator>
    </id>
    <component name="objId">
      <property name="id" type="string" column="entity_id" index="rdiff_domain_idx" />
      <component name="pair">
        <property name="domain" type="string" column="domain" index="rdiff_domain_idx, seq_id_domain_idx" />
        <property name="key" type="string" column="pair" index="rdiff_domain_idx" />
      </component>
    </component>
    <property name="isMatch" type="boolean" column="is_match" index="rdiff_ismatched" />
    <property name="detectedAt" type="org.jadira.usertype.dateandtime.joda.PersistentDateTime" column="detected_at" not-null="true" index="diff_detection" />
    <property name="lastSeen" type="org.jadira.usertype.dateandtime.joda.PersistentDateTime" column="last_seen" not-null="true" index="diff_last_seen" />
    <property name="upstreamVsn" type="string" column="upstream_vsn" />
    <property name="downstreamVsn" type="string" column="downstream_vsn" />
    <property name="ignored" type="boolean" column="ignored" />
  </class>

  <class name="StoreCheckpoint" table="store_checkpoints">
    <composite-id mapped="true">
      <key-many-to-one name="pair" class="net.lshift.diffa.kernel.config.DiffaPair" lazy="false">
        <column name="pair" />
        <column name="domain" />
      </key-many-to-one>
    </composite-id>
    <property name="latestVersion" type="long" column="latest_version" not-null="true"/>
  </class>

  <query name="storeCheckpointByPairAndDomain">
    select c from StoreCheckpoint c where c.pair.domain.name = :domain_name and c.pair.key = :pair_key
  </query>

  <query name="removeDomainCheckpoints">
    delete from StoreCheckpoint where domain = :domain_name
  </query>

  <query name="removeDomainDiffs">
    delete from ReportedDifferenceEvent where objId.pair.domain = :domain
  </query>
  <query name="removeDomainPendingDiffs">
    delete from PendingDifferenceEvent where objId.pair.domain = :domain
  </query>

  <query name="expireMatches"><![CDATA[
    delete from ReportedDifferenceEvent where lastSeen < :cutoff and isMatch = true
  ]]></query>

  <query name="removeDiffsByPairAndDomain">
    delete from ReportedDifferenceEvent where objId.pair.key = :pairKey and objId.pair.domain = :domain
  </query>
  <query name="removePendingDiffsByPairAndDomain">
    delete from PendingDifferenceEvent where objId.pair.key = :pairKey and objId.pair.domain = :domain
  </query>

  <query name="pendingByDomainIdAndVersionID">
    select e from PendingDifferenceEvent e where
      e.objId.pair.domain = :domain and e.objId.pair.key = :pair and e.objId.id = :objId
  </query>
  <query name="eventByDomainAndVersionID">
    select e from ReportedDifferenceEvent e where
      e.objId.pair.domain = :domain and e.objId.pair.key = :pair and e.objId.id = :objId
  </query>

  <query name="eventByDomainAndSeqId">
    select e from ReportedDifferenceEvent e where
      e.objId.pair.domain = :domain and e.seqId = :seqId
  </query>
  <query name="eventsSinceByDomain">
    select e from ReportedDifferenceEvent e where
      e.objId.pair.domain = :domain and e.seqId > :seqId
  </query>
  <query name="maxSeqIdByDomain">
    select max(e.seqId) from ReportedDifferenceEvent e where
      e.objId.pair.domain = :domain
  </query>
  <query name="unmatchedEventsInIntervalByDomain"><![CDATA[
    select e from ReportedDifferenceEvent e where
      e.objId.pair.domain = :domain and
      e.detectedAt >= :start and e.detectedAt < :end and
      e.isMatch = false and
      e.ignored = false
  ]]></query>
  <query name="unmatchedEventsByDomainAndPair"><![CDATA[
    select e from ReportedDifferenceEvent e where
      e.objId.pair.domain = :domain and e.objId.pair.key = :pair and
      e.isMatch = false and
      e.ignored = false
  ]]></query>
  <query name="unmatchedEventsInIntervalByDomainAndPair"><![CDATA[
    select e from ReportedDifferenceEvent e where
      e.objId.pair.domain = :domain and e.objId.pair.key = :pair and
      e.detectedAt >= :start and e.detectedAt < :end and
      e.isMatch = false and
      e.ignored = false
  ]]></query>
  <query name="unmatchedEventsInIntervalByDomainAndPairWithIgnored"><![CDATA[
    select e from ReportedDifferenceEvent e where
      e.objId.pair.domain = :domain and e.objId.pair.key = :pair and
      e.detectedAt >= :start and e.detectedAt < :end and
      e.isMatch = false
      order by e.seqId asc
  ]]></query>
  <query name="unmatchedEventsOlderThanCutoffByDomainAndPair"><![CDATA[
    select e from ReportedDifferenceEvent e where
      e.objId.pair.domain = :domain and e.objId.pair.key = :pair and
      e.isMatch = false and
      e.lastSeen < :cutoff
  ]]></query>
</hibernate-mapping>


text:
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
const ValidationErrorTypes = {
  PRESENCE: 'PRESENCE',
  PATTERN: 'PATTERN',
  RANGE: 'RANGE',
  CUSTOM: 'CUSTOM',
};

export function validateMinMax(value, min, max, field, t) {
  let error;

  switch (true) {
    case value !== '' && min !== false && max !== false && (value < min || value > max):
      error = {
        type: ValidationErrorTypes.RANGE,
        message: t('editor.editorControlPane.widget.range', {
          fieldLabel: field.get('label', field.get('name')),
          minValue: min,
          maxValue: max,
        }),
      };
      break;
    case value !== '' && min !== false && value < min:
      error = {
        type: ValidationErrorTypes.RANGE,
        message: t('editor.editorControlPane.widget.min', {
          fieldLabel: field.get('label', field.get('name')),
          minValue: min,
        }),
      };
      break;
    case value !== '' && max !== false && value > max:
      error = {
        type: ValidationErrorTypes.RANGE,
        message: t('editor.editorControlPane.widget.max', {
          fieldLabel: field.get('label', field.get('name')),
          maxValue: max,
        }),
      };
      break;
    default:
      error = null;
      break;
  }

  return error;
}

export default class NumberControl extends React.Component {
  static propTypes = {
    field: ImmutablePropTypes.map.isRequired,
    onChange: PropTypes.func.isRequired,
    classNameWrapper: PropTypes.string.isRequired,
    setActiveStyle: PropTypes.func.isRequired,
    setInactiveStyle: PropTypes.func.isRequired,
    value: PropTypes.node,
    forID: PropTypes.string,
    valueType: PropTypes.string,
    step: PropTypes.number,
    min: PropTypes.number,
    max: PropTypes.number,
    t: PropTypes.func.isRequired,
  };

  static defaultProps = {
    value: '',
  };

  handleChange = e => {
    const valueType = this.props.field.get('value_type');
    const { onChange } = this.props;
    const value = valueType === 'float' ? parseFloat(e.target.value) : parseInt(e.target.value, 10);

    if (!isNaN(value)) {
      onChange(value);
    } else {
      onChange('');
    }
  };

  isValid = () => {
    const { field, value, t } = this.props;
    const hasPattern = !!field.get('pattern', false);
    const min = field.get('min', false);
    const max = field.get('max', false);

    // Pattern overrides min/max logic always:
    if (hasPattern) {
      return true;
    }

    const error = validateMinMax(value, min, max, field, t);
    return error ? { error } : true;
  };

  render() {
    const { field, value, classNameWrapper, forID, setActiveStyle, setInactiveStyle } = this.props;
    const min = field.get('min', '');
    const max = field.get('max', '');
    const step = field.get('step', field.get('value_type') === 'int' ? 1 : '');
    return (
      <input
        type="number"
        id={forID}
        className={classNameWrapper}
        onFocus={setActiveStyle}
        onBlur={setInactiveStyle}
        value={value || (value === 0 ? value : '')}
        step={step}
        min={min}
        max={max}
        onChange={this.handleChange}
      />
    );
  }
}


text:
module Enocean
  module Esp3
    class PacketFactory
      class << self
        def from_data(packet_type, data, optional_data = [])
          case packet_type
            when 0x01 then Radio.from_data(data, optional_data)
            when 0x02 then Response.from_data(data, optional_data)
            else BasePacket.from_data(packet_type, data, optional_data)
          end
        end
      end
    end

    class BasePacket
      attr_reader :data, :optional_data, :packet_type

      class << self
        def from_data(packet_type, data, optional_data)
          self.new(packet_type, data, optional_data)
        end
      end

      def initialize(packet_type, data, optional_data)
        @packet_type, @data, @optional_data = packet_type, data, optional_data
      end

      def header
        [@data.count, @optional_data.count, @packet_type].pack("nCC").unpack("C*")
      end

      # see Enocean Serial Protocol, section 1.6.1 Packet description
      def serialize
        [ 0x55 ] + self.header + [ crc8(header) ] + @data + @optional_data + [ crc8(@data + @optional_data) ]
      end

      def base_info
        s = "\nESP3 packet packet_type: 0x%02x (%s)\n" % [@packet_type, self.class]
        s += "Data length     : %d\n" % @data.length
        s += "Opt. data length: %d\n" % @optional_data.length
        s
      end

      def content
        ""
      end

      def to_s
        return base_info + content
      end
    end
  end
end


text:
import template from './appAdminNotes.html';
import controller from './appAdminNotes.controller';
import './appAdminNotes.styl';

let appAdminNotesComponent = {
  restrict: 'E',
  bindings:  { appId : '='},
  template,
  controller
};

export default appAdminNotesComponent;


text:
//-----------------------------------------------------------------------
// <copyright file="Tile.cs" company="Mapbox">
//     Copyright (c) 2016 Mapbox. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Mapbox.Map
{
	using System;
	using Mapbox.Platform;
	using System.Linq;
	using System.Collections.Generic;
	using System.Collections.ObjectModel;

	///
	///    A Map tile, a square with vector or raster data representing a geographic
	///    bounding box. More info <see href="https://en.wikipedia.org/wiki/Tiled_web_map">
	///    here </see>.
	///
	public abstract class Tile : IAsyncRequest
	{

		private CanonicalTileId _id;
		private List<Exception> _exceptions;
		private State _state = State.New;
		private IAsyncRequest _request;
		private Action _callback;

		///  Tile state.
		public enum State
		{
			///  New tile, not yet initialized.
			New,
			///  Loading data.
			Loading,
			///  Data loaded and parsed.
			Loaded,
			///  Data loading cancelled.
			Canceled
		}

		///  Gets the <see cref="T:Mapbox.Map.CanonicalTileId"/> identifier.
		/// <value> The canonical tile identifier. </value>
		public CanonicalTileId Id
		{
			get { return _id; }
			set { _id = value; }
		}

		/// Flag to indicate if the request was successful
		public bool HasError
		{
			get
			{
				return _exceptions == null ? false : _exceptions.Count > 0;
			}
		}

		///  Exceptions that might have occured during creation of the tile.
		public ReadOnlyCollection<Exception> Exceptions
		{
			get { return null == _exceptions ? null : _exceptions.AsReadOnly(); }
		}

		///  Messages of exceptions otherwise empty string.
		public string ExceptionsAsString
		{
			get
			{
				if (null == _exceptions || _exceptions.Count == 0) { return string.Empty; }
				return string.Join(Environment.NewLine, _exceptions.Select(e => e.Message).ToArray());
			}
		}

		///
		/// Sets the error message.
		///
		/// <param name="errorMessage"></param>
		internal void AddException(Exception ex)
		{
			if (null == _exceptions) { _exceptions = new List<Exception>(); }
			_exceptions.Add(ex);
		}

		///
		///     Gets the current state. When fully loaded, you must
		///     check if the data actually arrived and if the tile
		///     is accusing any error.
		///
		/// <value> The tile state. </value>
		public State CurrentState
		{
			get
			{
				return _state;
			}
		}

		public bool IsCompleted
		{
			get
			{
				return _state == State.Loaded;
			}
		}

		///
		///     Initializes the <see cref="T:Mapbox.Map.Tile"/> object. It will
		///     start a network request and fire the callback when completed.
		///
		/// <param name="param"> Initialization parameters. </param>
		/// <param name="callback"> The completion callback. </param>
		public void Initialize(Parameters param, Action callback)
		{
			Cancel();

			_state = State.Loading;
			_id = param.Id;
			_callback = callback;
			_request = param.Fs.Request(MakeTileResource(param.MapId).GetUrl(), HandleTileResponse, tileId: _id, mapId: param.MapId);
		}

		internal void Initialize(IFileSource fileSource, CanonicalTileId canonicalTileId, string mapId, Action p)
		{
			Cancel();

			_state = State.Loading;
			_id = canonicalTileId;
			_callback = p;
			_request = fileSource.Request(MakeTileResource(mapId).GetUrl(), HandleTileResponse, tileId: _id, mapId: mapId);
		}

		///
		///     Returns a <see cref="T:System.String"/> that represents the current
		///     <see cref="T:Mapbox.Map.Tile"/>.
		///
		/// <returns>
		///     A <see cref="T:System.String"/> that represents the current
		///     <see cref="T:Mapbox.Map.Tile"/>.
		/// </returns>
		public override string ToString()
		{
			return Id.ToString();
		}

		///
		///     Cancels the request for the <see cref="T:Mapbox.Map.Tile"/> object.
		///     It will stop a network request and set the tile's state to Canceled.
		///
		/// <example>
		///
		/// // Do not request tiles that we are already requesting
		///	// but at the same time exclude the ones we don't need
		///	// anymore, cancelling the network request.
		///	tiles.RemoveWhere((T tile) =>
		///	{
		///		if (cover.Remove(tile.Id))
		///		{
		///			return false;
		///		}
		///		else
		///		{
		///			tile.Cancel();
		///			NotifyNext(tile);
		///			return true;
		/// 	}
		///	});
		///
		/// </example>
		public void Cancel()
		{
			if (_request != null)
			{
				_request.Cancel();
				_request = null;
			}

			_state = State.Canceled;
		}

		// Get the tile resource (raster/vector/etc).
		internal abstract TileResource MakeTileResource(string mapid);

		// Decode the tile.
		internal abstract bool ParseTileData(byte[] data);

		// TODO: Currently the tile decoding is done on the main thread. We must implement
		// a Worker class to abstract this, so on platforms that support threads (like Unity
		// on the desktop, Android, etc) we can use worker threads and when building for
		// the browser, we keep it single-threaded.
		private void HandleTileResponse(Response response)
		{

			if (response.HasError)
			{
				response.Exceptions.ToList().ForEach(e => AddException(e));
			}
			else
			{
				// only try to parse if request was successful

				// current implementation doesn't need to check if parsing is successful:
				// * Mapbox.Map.VectorTile.ParseTileData() already adds any exception to the list
				// * Mapbox.Map.RasterTile.ParseTileData() doesn't do any parsing
				ParseTileData(response.Data);
			}

			// Cancelled is not the same as loaded!
			if (_state != State.Canceled)
			{
				_state = State.Loaded;
			}
			_callback();
		}

		///
		///    Parameters for initializing a Tile object.
		///
		/// <example>
		///
		/// var parameters = new Tile.Parameters();
		/// parameters.Fs = MapboxAccess.Instance;
		/// parameters.Id = new CanonicalTileId(_zoom, _tileCoorindateX, _tileCoordinateY);
		/// parameters.MapId = "mapbox.mapbox-streets-v7";
		///
		/// </example>
		public struct Parameters
		{
			///  The tile id.
			public CanonicalTileId Id;

			///
			///     The tileset map ID, usually in the format "user.mapid". Exceptionally,
			///     <see cref="T:Mapbox.Map.RasterTile"/> will take the full style URL
			///     from where the tile is composited from, like mapbox://styles/mapbox/streets-v9.
			///
			public string MapId;

			///  The data source abstraction.
			public IFileSource Fs;
		}

	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Round About - Page demo Template</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/round-about.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Page demo

                        About

                        Services

                        Contact

About Us
                    It's Nice to Meet You!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint, explicabo dolores ipsam aliquam inventore corrupti eveniet quisquam quod totam laudantium repudiandae obcaecati ea consectetur debitis velit facere nisi expedita vel?

Our Team

John Smith
                    Job Title

What does this team member to? Keep it short! This is also a great spot for social links!

John Smith
                    Job Title

What does this team member to? Keep it short! This is also a great spot for social links!

John Smith
                    Job Title

What does this team member to? Keep it short! This is also a great spot for social links!

John Smith
                    Job Title

What does this team member to? Keep it short! This is also a great spot for social links!

John Smith
                    Job Title

What does this team member to? Keep it short! This is also a great spot for social links!

John Smith
                    Job Title

What does this team member to? Keep it short! This is also a great spot for social links!

Copyright © Your Website 2014


text:
'use strict';

describe('Service: BookDataService', function () {

    var BookDataService;

    // load the application module
    beforeEach(module('bmApp'));

    // get a reference to the service
    beforeEach(inject(function (_BookDataService_) {
        BookDataService = _BookDataService_;
    }));

    describe('Public API', function() {
        it('should include a getBookByIsbn() function', function () {
            expect(BookDataService.getBookByIsbn).toBeDefined();
        });

        it('should include a getBooks() function', function () {
            expect(BookDataService.getBooks).toBeDefined();
        });

        it('should include a storeBook() function', function () {
            expect(BookDataService.storeBook).toBeDefined();
        });

        it('should include a updateBook() function', function () {
            expect(BookDataService.updateBook).toBeDefined();
        });

        it('should include a deleteBookByIsbn() function', function () {
            expect(BookDataService.deleteBookByIsbn).toBeDefined();
        });
    });

    describe('Public API usage', function() {
        describe('getBookByIsbn()', function() {
            it('should return the proper book object (valid isbn)', function() {
                var isbn = '978-3-86490-050-1',
                    book = BookDataService.getBookByIsbn(isbn);
                expect(book.title).toBe('CoffeeScript');
            });

            it('should return null (invalid isbn)', function() {
                var isbn = 'test',
                    book = BookDataService.getBookByIsbn(isbn);
                expect(book).toBeNull();
            });
        });

        describe('getBooks()', function() {
            it('should return a proper array of book objects', function() {
                var books = BookDataService.getBooks();
                expect(books.length).toBe(3);
            });
        });

        describe('storeBook()', function() {
            it('should properly store the passed book object', function() {
                var beforeCount = BookDataService.getBooks().length;

                // store an example book
                var book = storeExampleBook();

                expect(BookDataService.getBooks().length).toBe(beforeCount + 1);
                expect(BookDataService.getBookByIsbn(book.isbn)).not.toBeNull();
            });
        });

        describe('updateBook()', function() {
            it('should properly update the book object', function() {
                // store an example book
                var book = storeExampleBook();

                // change it
                book.abstract = 'TEST';

                // update the example book
                BookDataService.updateBook(book);

                expect(BookDataService.getBookByIsbn(book.isbn).abstract).toBe(book.abstract);
            });
        });

        describe('deleteBookByIsbn()', function() {
            it('should properly delete the book object with the passed isbn', function() {
                // store an example book
                var book = storeExampleBook();

                // delete the example book
                BookDataService.deleteBookByIsbn(book.isbn);

                expect(BookDataService.getBookByIsbn(book.isbn)).toBeNull();
            });
        });
    });

    // Helper functions
    var storeExampleBook = function() {
        var isbn = '978-3-86490-127-0',
            book = {
                title       : 'JavaScript effektiv',
                subtitle    : '68 Dinge, die ein guter JavaScript-Entwickler wissen sollte',
                isbn        : isbn,
                abstract    : 'Wollen Sie JavaScript wirklich beherrschen?',
                numPages    : 240,
                author      : 'David Herman',
                publisher   : {
                    name: 'dpunkt.verlag',
                    url : 'http://dpunkt.de/'
                }
            };

        BookDataService.storeBook(book);

        return book;
    };

});


text:
require File.dirname(__FILE__) + '/../abstract_unit'

MemCache = Struct.new(:MemCache, :address) unless Object.const_defined?(:MemCache)

class FragmentCacheStoreSettingTest < Test::Unit::TestCase
  def teardown
    ActionController::Base.fragment_cache_store = ActionController::Caching::Fragments::MemoryStore.new
  end

  def test_file_fragment_cache_store
    ActionController::Base.fragment_cache_store = :file_store, "/path/to/cache/directory"
    assert_kind_of(
      ActionController::Caching::Fragments::FileStore,
      ActionController::Base.fragment_cache_store
    )
    assert_equal "/path/to/cache/directory", ActionController::Base.fragment_cache_store.cache_path
  end

  def test_drb_fragment_cache_store
    ActionController::Base.fragment_cache_store = :drb_store, "druby://localhost:9192"
    assert_kind_of(
      ActionController::Caching::Fragments::DRbStore,
      ActionController::Base.fragment_cache_store
    )
    assert_equal "druby://localhost:9192", ActionController::Base.fragment_cache_store.address
  end

  if defined? CGI::Session::MemCacheStore
    def test_mem_cache_fragment_cache_store
      ActionController::Base.fragment_cache_store = :mem_cache_store, "localhost"
      assert_kind_of(
        ActionController::Caching::Fragments::MemCacheStore,
        ActionController::Base.fragment_cache_store
      )
      assert_equal %w(localhost), ActionController::Base.fragment_cache_store.addresses
    end
  end

  def test_object_assigned_fragment_cache_store
    ActionController::Base.fragment_cache_store = ActionController::Caching::Fragments::FileStore.new("/path/to/cache/directory")
    assert_kind_of(
      ActionController::Caching::Fragments::FileStore,
      ActionController::Base.fragment_cache_store
    )
    assert_equal "/path/to/cache/directory", ActionController::Base.fragment_cache_store.cache_path
  end
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class DocumentosExternosModel extends CI_Model{

	function __construct(){
		parent::__construct();
		$this->load->database();
		$this->load->library('table');
	}

	function addDocumentExterno($newDocumentData){
		if($this->db->insert('docs_externos',$newDocumentData)){
			return TRUE;
		}else{
			echo $this->db->error_message();
		}
	}

	public function getLastDocumentExternoID(){
		$this->db->select('MAX(id_doc_externo) as id_doc_externo');
		$this->db->from('docs_externos');
		$results = $this->db->get();
		$num_results = $results->num_rows();
		if($num_results > 0){
			return $results->result()[0]->id_doc_externo;
		}
	}

	public function getDocumentExt($attr, $target){
		$this->db->select('d.*, date_format(d.fecha_captura, \'%d-%m%-%Y\') as fecha_captura');
		$this->db->from('docs_externos d');
		if($this->session->userdata('permiso') != "A"){ //si es administrador no aplican estos filtros
			$this->db->join('rel_docs_externos_puestos rdep', 'd.id_doc_externo = rdep.id_doc_ext', 'inner');
			$this->db->join('usuarios u','u.id_puesto = rdep.id_puesto', 'inner');
			$this->db->where('u.usuario = \''.$this->session->userdata('usuario').'\'');
		}
		$this->db->where($attr."= '".$target."'");
		$results = $this->db->get();
		$num_results = $results->num_rows();
		if($num_results > 0){
			return $results;
		}else{
			return $num_results;
		}
	}

	public function asignarDocumentoExternoAPuesto($documento, $puesto){
		$datos['id_doc_ext'] = $documento;
		$datos['id_puesto'] = $puesto;
		$result = $this->db->insert('rel_docs_externos_puestos', $datos);
		if($result){
			return true;
		}
	}

	function searchDocumentExterno($target){
		//si es administrador que muestre toooodos los documentos.
		if($this->session->userdata('permiso') == "A"){
			$this->db->select("d.*, DATE_FORMAT(d.fecha_captura, '%d-%m-%Y') as fecha_creacion");
			$this->db->from('docs_externos d');
			if(is_numeric($target)){//si es numerico buscará por el id del documento
				$where = "d.activo = '1' AND (
					d.nombre_documento LIKE '%".$target."%'
					OR d.archivo LIKE '%".$target."%')";
				$this->db->where($where);
			}else{
				$where = "d.activo = '1' AND (
					d.nombre_documento LIKE '%".$target."%'
					OR d.archivo LIKE '%".$target."%')";
				$this->db->where($where);
			}
			echo $this->db->last_query();
		}else{
			//Si no es usuario administrador solo le mostrará a los que tenga permiso
			$this->db->select("d.*, DATE_FORMAT(d.fecha_captura, '%d-%m-%Y') as fecha_creacion");
			$this->db->from('docs_externos d');
			$this->db->join('rel_docs_externos_puestos rdep', 'd.id_doc_externo=rdep.id_doc_ext', 'inner');
			$this->db->join('usuarios u','u.id_puesto = rdep.id_puesto', 'inner');
			$this->db->where('u.usuario = \''.$this->session->userdata('usuario').'\'');
			if(is_numeric($target)){//si es numerico buscará por el id del documento
				$where = "d.activo = '1' AND (
					d.nombre_documento LIKE '%".$target."%'
					OR d.archivo LIKE '%".$target."%')";
				$this->db->where($where);
			}else{
				$where = "d.activo = '1' AND (
					d.nombre_documento LIKE '%".$target."%'
					OR d.archivo LIKE '%".$target."%')";
				$this->db->where($where);
			}
		}

		$resultados = $this->db->get();
		//echo $this->db->last_query();
		$num_results = $resultados->num_rows();
		if($num_results > 0){
			return $resultados;
		}else{
			return false;
		}
	}

	function searchUsersGrantsDocument($id_documento_ext){
		//Se ejecutará este query:
		$this->db->select("u.usuario, u.nombre, u.envio_correo, u.correo");
		$this->db->from("usuarios u");
		$this->db->join("rel_docs_externos_puestos rdep", "u.id_puesto = rdep.id_puesto", "inner");
		$this->db->join("docs_externos d", "rdep.id_doc_ext = d.id_doc_externo");
		$this->db->where("d.id_doc_externo =".$id_documento_ext);
		$resultados = $this->db->get();

		$num_results = $resultados->num_rows();
		if($num_results > 0){
			//$tmpl = array('table_open' => '<table border=1 id="documentos" cellpadding=2 cellspacing=1>');
			//$headers_table = array('Documento','ID Calidad', 'Revisión', 'Generado por', 'Tiempo de Retención', 'Responsable', 'Nom. Archivo');
			//$this->table->set_template($tmpl);
			//$this->table->set_heading($headers_table);
			//return $table = $this->table->generate($query);
			return $resultados;
		}else{
			return false;
		}
	}

	function deleteDocumentExt($id_doc_ext){
		$desactivar_doc = array('activo' => 0);
		$this->db->set($desactivar_doc);
		$this->db->where('id_doc_externo', $id_doc_ext);
		$query = $this->db->update('docs_externos');

		if($query){
			$resultado['state'] = true;
			$resultado['message'] = "Se ha eliminado el documento externo del SGC.";
			return $resultado;
		}else{
			$resultado['state'] = false;
			$resultado['message'] = $this->db->_error_message();
			return $resultado;
		}
	}
}
?>


text:
package com.algorithm.array;

/**
 * http://www.geeksforgeeks.org/maximum-of-all-subarrays-of-size-k/
 * Test cases
 * input containg neg and pos values
 * val of k is neg 0 or pos
 * val of k is larger than size of input
 * val of k is same as size of input
 */
import java.util.Deque;
import java.util.LinkedList;

public class MaximumOfSubarrayOfSizeK {

	public int[] maxSubArray(int input[], int k) {
		Deque<Integer> queue = new LinkedList<Integer>();
		int max[] = new int[input.length - k + 1];
		int maxVal = Integer.MIN_VALUE;
		// first find max of first k values and make it 0th element of max array
		for (int i = 0; i < k; i++) {
			if (maxVal < input[i]) {
				maxVal = input[i];
			}
			if (queue.isEmpty()) {
				queue.offerLast(i);
			} else {
				while (!queue.isEmpty() && input[queue.peekLast()] <= input[i]) {
					queue.pollLast();
				}
				queue.offerLast(i);
			}

		}
		max[0] = maxVal;
		int index = 1;
		// continue from k till end of the input array
		for (int i = k; i < input.length; i++) {
			// if index of peek is k distance from i then its no value to us.
			// throw it away
			if (i - k + 1 > queue.peekFirst()) {
				queue.pollFirst();
			}
			while (!queue.isEmpty() && input[queue.peekLast()] <= input[i]) {
				queue.pollLast();
			}
			queue.offerLast(i);
			// Only reason first element survived was because it was biggest
			// element.
			// make it the max value for this k
			max[index] = input[queue.peekFirst()];
			index++;
		}
		return max;
	}

	public static void main(String args[]) {
		int input[] = { 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 };
		MaximumOfSubarrayOfSizeK msa = new MaximumOfSubarrayOfSizeK();
		int max[] = msa.maxSubArray(input, 4);
		for (int i : max) {
			System.out.print(i + " ");
		}
	}
}


text:
package org.codelibs.elasticsearch.web.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.codelibs.core.beans.util.BeanUtil;
import org.codelibs.elasticsearch.web.entity.EsAccessResult;
import org.codelibs.robot.entity.AccessResult;
import org.codelibs.robot.entity.AccessResultImpl;
import org.codelibs.robot.service.DataService;
import org.codelibs.robot.util.AccessResultCallback;
import org.elasticsearch.action.index.IndexRequest.OpType;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

public class EsDataService extends AbstractRobotService implements DataService {

    public int scrollTimeout = 60000;

    public int scrollSize = 100;

    @PostConstruct
    public void init() {
        esClient.addOnConnectListener(() -> {
            createMapping("data");
        });
    }

    @Override
    public void store(final AccessResult accessResult) {
        super.insert(accessResult, OpType.CREATE);
    }

    @Override
    public void update(final AccessResult accessResult) {
        store(accessResult);
    }

    @Override
    public void update(final List<AccessResult> accessResultList) {
        insertAll(accessResultList, OpType.INDEX);
    }

    @Override
    public int getCount(final String sessionId) {
        return (int) esClient.prepareCount(index).setTypes(sessionId).execute().actionGet().getCount();
    }

    @Override
    public void delete(final String sessionId) {
        deleteBySessionId(sessionId);
    }

    @Override
    public AccessResult getAccessResult(final String sessionId, final String url) {
        return get(AccessResultImpl.class, sessionId, url);
    }

    @Override
    public List<AccessResult> getAccessResultList(final String url, final boolean hasData) {
        final SearchResponse response =
                esClient.prepareSearch(index).setTypes(type).setQuery(QueryBuilders.termQuery(URL, url)).execute().actionGet();
        final SearchHits hits = response.getHits();
        final List<AccessResult> accessResultList = new ArrayList<AccessResult>();
        if (hits.getTotalHits() != 0) {
            for (final SearchHit searchHit : hits.getHits()) {
                accessResultList.add(BeanUtil.copyMapToNewBean(searchHit.getSource(), EsAccessResult.class, option -> {
                    option.converter(new EsTimestampConverter(), timestampFields).excludeWhitespace();
                }));
            }
        }
        return accessResultList;
    }

    @Override
    public void iterate(final String sessionId, final AccessResultCallback callback) {
        SearchResponse response =
                esClient.prepareSearch(index)
                        .setTypes(type)
                        .setSearchType(SearchType.SCAN)
                        .setScroll(new TimeValue(scrollTimeout))
                        .setQuery(
                                QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.termFilter(SESSION_ID, sessionId)))
                        .setSize(scrollSize).execute().actionGet();
        while (true) {
            final SearchHits searchHits = response.getHits();
            for (final SearchHit searchHit : searchHits) {
                final AccessResult accessResult = BeanUtil.copyMapToNewBean(searchHit.getSource(), EsAccessResult.class, option -> {
                    option.converter(new EsTimestampConverter(), timestampFields).excludeWhitespace();
                });
                callback.iterate(accessResult);
            }

            if (searchHits.hits().length == 0) {
                break;
            }
            response = esClient.prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(scrollTimeout)).execute().actionGet();
        }
    }
}


text:
using System.Runtime.CompilerServices;

namespace System {
	[ScriptNamespace("ss")]
	[IncludeGenericArguments(false)]
	public class Lazy<T> {
		[InlineCode("new {$System.Lazy`1}(function() {{ return {T}.createInstance(); }})")]
		public Lazy() {
		}

		[InlineCode("new {$System.Lazy`1}(function() {{ return {T}.createInstance(); }})")]
		public Lazy(bool b) {
		}

		[AlternateSignature]
		public Lazy(Func<T> valueFactory) {
		}

		public Lazy(Func<T> valueFactory, bool b) {
		}

		[IntrinsicProperty]
		public bool IsValueCreated { get { return false; } }

		public T Value { [ScriptName("value")] get { return default(T); } }
	}
}


text:
class Redis
  class Store < self
    include Ttl, Interface

    def initialize(options = { })
      super
      _extend_marshalling options
      _extend_namespace   options
    end

    def self.rails3? #:nodoc:
      defined?(::Rails) && ::Rails::VERSION::MAJOR == 3
    end

    def self.rails31? #:nodoc:
      defined?(::Rails) && ::Rails::VERSION::MAJOR == 3 && ::Rails::VERSION::MINOR == 1
    end

    def reconnect
      @client.reconnect
    end

    def to_s
      "Redis Client connected to #{@client.host}:#{@client.port} against DB #{@client.db}"
    end

    private
      def _extend_marshalling(options)
        @marshalling = !(options[:marshalling] === false) # HACK - TODO delegate to Factory
        extend Marshalling if @marshalling
      end

      def _extend_namespace(options)
        @namespace = options[:namespace]
        extend Namespace if @namespace
      end
  end
end


text:
function UIWidget:setMargin(...)
  local params = {...}
  if #params == 1 then
    self:setMarginTop(params[1])
    self:setMarginRight(params[1])
    self:setMarginBottom(params[1])
    self:setMarginLeft(params[1])
  elseif #params == 2 then
    self:setMarginTop(params[1])
    self:setMarginRight(params[2])
    self:setMarginBottom(params[1])
    self:setMarginLeft(params[2])
  elseif #params == 4 then
    self:setMarginTop(params[1])
    self:setMarginRight(params[2])
    self:setMarginBottom(params[3])
    self:setMarginLeft(params[4])
  end
end


text:
package org.thingsboard.server.common.data.rule;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;

@Data
public class RuleChainImportResult {

    @JsonIgnore
    private TenantId tenantId;
    private RuleChainId ruleChainId;
    private String ruleChainName;
    @JsonInclude(JsonInclude.Include.NON_DEFAULT)
    private boolean updated;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String error;

}


text:
#include "tensorflow/compiler/mlir/lite/transforms/dilated_conv.h"

#include "mlir/Transforms/GreedyPatternRewriteDriver.h"  // from @llvm-project

namespace mlir {
namespace TFL {
namespace {

struct IdentifyDilatedConvPass
    : public PassWrapper<IdentifyDilatedConvPass, FunctionPass> {
  void runOnFunction() override;
};

void IdentifyDilatedConvPass::runOnFunction() {
  OwningRewritePatternList patterns;
  auto func = getFunction();

  patterns.insert<ConvertTFDilatedConvOp<TF::Conv2DOp>,
                  ConvertTFDilatedConvOp<TF::DepthwiseConv2dNativeOp>>(
      &getContext());
  applyPatternsAndFoldGreedily(func, std::move(patterns));
}
}  // namespace

static PassRegistration<IdentifyDilatedConvPass> pass(
    "tfl-identify-dilated-conv",
    "Identify and replace patterns for dilated convolution.");

}  // namespace TFL
}  // namespace mlir


text:
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace tusdotnet.test.Helpers
{
    /// <summary>
    /// The SlowMemoryStream adds a 100 ms delay on every ReadAsync.
    /// </summary>
    public class SlowMemoryStream : Stream
    {
        private readonly MemoryStream _stream;

        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="buffer">The buffer to read from</param>
        public SlowMemoryStream(byte[] buffer)
        {
            _stream = new MemoryStream(buffer);
        }

        public override bool CanRead => _stream.CanRead;

        public override bool CanSeek => _stream.CanSeek;

        public override bool CanWrite => false;

        public override long Length => _stream.Length;

        public override long Position
        {
            get { return _stream.Position; }
            set { _stream.Position = value; }
        }

        public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            await Task.Delay(100);

            // Note: Do not use the provided cancellation token but let the disk store cancel the read instead.
            return await _stream.ReadAsync(buffer, offset, count, CancellationToken.None);
        }

        public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException();

        public override int Read(byte[] buffer, int offset, int count) => throw new NotImplementedException();

        public override void SetLength(long value) => throw new NotImplementedException();

        public override void Flush() => throw new NotImplementedException();

        public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException();
    }
}


text:
<?php

namespace backend\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
use backend\models\AuthAssignment;
use yii\rbac\Item;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
class User extends \yii\db\ActiveRecord
{

    public  $password;
    public  $password_repeat;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    public function getRoles($id=false){
        if(!$id) {
            $id = (int)Yii::$app->request->get('id');
        }
        $roles = Role::find()->where(['=','type',Item::TYPE_ROLE])->asArray()->indexBy('name')->all();
        $res = [];
        $hisRoles = [];
        if($id > 0){
            $hisRoles = AuthAssignment::find()->where(['=','user_id', $id])->asArray()->indexBy('item_name')->all();
        }
        foreach($roles as $name=>$role){
            $res[$name]['role'] = $name;
            if($hisRoles[$name]){
                $res[$name]['checked'] = 1;
            }else{
                $res[$name]['checked'] = 0;
            }
        }
        return $res;
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'updated_at',
                'value' => time(),
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password_hash', 'email'], 'required'],
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['username'], 'unique'],
            [['email'], 'unique'],
            [['email'], 'email'],
            [['password_reset_token'], 'unique'],
            [['password', 'password_repeat'], 'string', 'min' => 6],
            ['password_repeat', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match" ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Логин',
            'auth_key' => 'Auth Key',
            'password_hash' => 'Пароль(hash)',
            'password_reset_token' => 'Password Reset Token',
            'email' => 'Email',
            'status' => 'Status(0-deleted, 10-active)',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'password_repeat' => 'Подтверждение нового пароля',
            'password' => 'Новый пароль',
        ];
    }
}


text:
rsy_local(){

    sudo chown -R lan:lan ~/
    (
    cd /media/lan/hitachi/netrunner
    ln -s ~/data/note/shell/bin ~/
    mkdir -p ~/.config/autostart;ln -s ~/bin/startup ~/.config/autostart/
    mkdir -p ~/.stardict/dic
    tar -xf /media/lan/hitachi/software/stardic/dic.tgz -C ~/.stardict/dic
    sudo sed -i 's/GRUB_CMDLINE_LINUX=""/GRUB_CMDLINE_LINUX="acpi_osi=Linux acpi_backlight=video"/' /etc/default/grub
    sudo sed -i '$i echo 50 >/sys/class/backlight/intel_backlight/brightness \nsu - lan -c "bash /home/lan/bin/startup"' /etc/rc.local

    sudo update-grub
    )
}
rsy_apt(){
    sudo add-apt-repository -y ppa:synapse-core/testing
    sudo apt-get update
    sudo apt-get install -y meld gitk pv zsh autojump vim nethogs  language-pack-gnome-zh-hans keepassx python-pip nodejs stardict curl  wget aria2 proxychains synapse ppa-purge elinks whois tree tmux ufw iftop tig okular guake silversearcher-ag exuberant-ctags nodejs-legacy amule
    sudo pip install shadowsocks
    sudo npm install -g coffee-script
    #sudo sed -i '/^socks4/d' /etc/proxychains.conf
    #sudo echo 'socks5 127.0.0.1 1080'>>/etc/proxychains.conf
    chsh -s /usr/bin/zsh

}

install_dev(){
    mkdir -p ~/program
    find /media/lan/hitachi/software/ -iname '*gz' -exec tar -xf {} -C ~/program/ \;
    # cat >> 没有权限
    sudo sed -i '30a JAVA_HOME=/home/lan/program/jdk1.7.0_03\nexport PATH=$JAVA_HOME/bin:$PATH' /etc/profile
    ln -sf ~/program/sublime_text_3/custom.desktop ~/Desktop/sublime.desktop
    sudo ln -sf ~/program/sublime_text_3/custom.desktop /usr/share/applications/sublime.desktop
}

link_rcs(){
    ln -sf ~/data/note/shell/rcs/.[!.]* ~/
    ln -sf ~/data/note/git/.gitconfig ~/
}

rsy_local &
rsy_apt
(
    cd ~/data
    git clone /media/lan/hitachi/repo/person.git
    sudo rm /etc/proxychains.conf
    ln -sf ~/data/note/gfw/proxychains.conf /etc/proxychains.conf
)

#install flash
tar -xf /media/lan/hitachi/software/flash/install_flash_player_11_linux.x86_64.tar.gz -C /tmp/
sudo cp /tmp/libflashplayer.so /usr/lib/mozilla/plugins
sudo cp -r /tmp/usr/* /usr

# This operation is too long and less important,place it at last
rsync -avzh --delete /media/lan/hitachi/book ~/data/
rsync -avhz /media/lan/hitachi/Music/* ~/Music/
rsync -avhz /media/lan/hitachi/netrunner/home/lan /home/
install_dev

#bash ~/data/note/google/earth.sh
#bash ~/data/note/ubuntu/clementine.sh
bash ~/data/note/ubuntu/fcitx/fcitx
sudo chown -R lan:lan ~/
# bash ~/data/note/google/chrome/install_chrome.sh


text:
#ifndef SimTK_SIMBODY_MOBILIZED_BODY_LINEORIENTATION_H_
#define SimTK_SIMBODY_MOBILIZED_BODY_LINEORIENTATION_H_

/** @file
Declares the MobilizedBody::LineOrientation class. **/

#include "simbody/internal/MobilizedBody.h"

namespace SimTK {

/** Two mobilities, representing unrestricted orientation for a body which is
inertialess along its own z axis. The generalized coordinates are the same
as for the general Ball (Spherical) mobilizer, but there are only
two generalized speeds. These are the x,y components of the angular velocity
of frame M in F, but expressed in \e M (the body or outboard frame).

LineOrientation and FreeLine are special "ball" and "free" mobilizers designed
to allow arbitrary orientations for "linear" bodies, such as a CO2 molecule
consisting only of point masses arranged along a straight line. Such bodies have
no inertia about the line and cause singularities in the equations of motion if
attached to Ball (Spherical) or Free mobilizers. Instead, use the
LineOrientation and LineFree mobilizers, making sure that the inertialess
direction is along the outboard body's z axis (that is, Mz). These mobilizers
introduce only two rotational mobilities (generalized speeds u), being incapable
of representing non-zero angular velocity of M in F about Mz. The generalized
speeds are in fact the wx and wy components of w_FM_M, that is, the x and y
components of the angular velocity of M in F expressed in M. However,
at least three generalized coordinates (q's) are required to represent the
orientation. By default we use four quaternions for unconditional stability.
Alternatively, you can request a 1-2-3 body fixed Euler angle sequence (that is,
about x, then new y, then new z) which will suffer a singularity when the y
rotation is 90 degrees since that aligns the first rotation axis (x) with the
last (z) which is the inertialess direction.

@see MobilizedBody::FreeLine, MobilizedBody::Ball **/
class SimTK_SIMBODY_EXPORT MobilizedBody::LineOrientation : public MobilizedBody {
public:
    /** Default constructor provides an empty handle that can be assigned to
    reference any %MobilizedBody::LineOrientation. **/
    LineOrientation() {}

    /** Create a %LineOrientation mobilizer between an existing parent (inboard)
    body P and a new child (outboard) body B created by copying the given
    \a bodyInfo into a privately-owned Body within the constructed
    %MobilizedBody object. Specify the mobilizer frames F fixed to parent P and
    M fixed to child B.
    @see MobilizedBody for a diagram and explanation of terminology. **/
    LineOrientation(MobilizedBody& parent, const Transform& X_PF,
                    const Body& bodyInfo,  const Transform& X_BM,
                    Direction=Forward);

    /** Abbreviated constructor you can use if the mobilizer frames are
    coincident with the parent and child body frames. **/
    LineOrientation(MobilizedBody& parent, const Body& bodyInfo,
                    Direction=Forward);

    LineOrientation& addBodyDecoration(const Transform& X_BD, const DecorativeGeometry& g) {
        (void)MobilizedBody::addBodyDecoration(X_BD,g); return *this;
    }
    LineOrientation& addOutboardDecoration(const Transform& X_MD,  const DecorativeGeometry& g) {
        (void)MobilizedBody::addOutboardDecoration(X_MD,g); return *this;
    }
    LineOrientation& addInboardDecoration (const Transform& X_FD, const DecorativeGeometry& g) {
        (void)MobilizedBody::addInboardDecoration(X_FD,g); return *this;
    }

    LineOrientation& setDefaultInboardFrame(const Transform& X_PF) {
        (void)MobilizedBody::setDefaultInboardFrame(X_PF); return *this;
    }

    LineOrientation& setDefaultOutboardFrame(const Transform& X_BM) {
        (void)MobilizedBody::setDefaultOutboardFrame(X_BM); return *this;
    }

    // This is just a nicer name for the generalized coordinate.
    LineOrientation& setDefaultRotation(const Rotation& R_FM) {
        return setDefaultQ(R_FM.convertRotationToQuaternion());
    }
    Rotation getDefaultRotation() const {return Rotation(getDefaultQ());}

    // Generic default state Topology methods.
    const Quaternion& getDefaultQ() const;
    LineOrientation& setDefaultQ(const Quaternion& q);

    const Vec4& getQ(const State&) const;
    const Vec4& getQDot(const State&) const;
    const Vec4& getQDotDot(const State&) const;
    const Vec2& getU(const State&) const;
    const Vec2& getUDot(const State&) const;

    void setQ(State&, const Vec4&) const;
    void setU(State&, const Vec2&) const;

    const Vec4& getMyPartQ(const State&, const Vector& qlike) const;
    const Vec2& getMyPartU(const State&, const Vector& ulike) const;

    Vec4& updMyPartQ(const State&, Vector& qlike) const;
    Vec2& updMyPartU(const State&, Vector& ulike) const;

    /** @cond **/ // hide from Doxygen
    SimTK_INSERT_DERIVED_HANDLE_DECLARATIONS(LineOrientation,
                                             LineOrientationImpl, MobilizedBody);
    /** @endcond **/
};

} // namespace SimTK

#endif // SimTK_SIMBODY_MOBILIZED_BODY_LINEORIENTATION_H_


text:
package wlt.fox.zhizhihuhu.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import wlt.fox.zhizhihuhu.R;
import wlt.fox.zhizhihuhu.bean.daily.DailyBean;
import wlt.fox.zhizhihuhu.bean.zhihu.LatestNews;
import wlt.fox.zhizhihuhu.ui.activity.WebActivity;
import wlt.fox.zhizhihuhu.view.TopStoriesViewPager;

/**
 * Created by wlt on 2016/9/20.
 * E-mail : autumnsassou@163.com
 */
public class DailyListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context mContext;
    DailyBean.ResponseBean response;

    private static final int TYPE_TOP = -1;

    private static final int TYPE_HEADLINE = -3;

    private int feed_position = 2;

    public DailyListAdapter(Context mContext, DailyBean.ResponseBean response) {
        this.mContext = mContext;
        this.response = response;
    }

    @Override
    public int getItemViewType(int position) {
        if(response.getBanners() != null) {//有banner
            if (position == 0) {
                return TYPE_TOP;
            } else if(response.getHeadline().getPost() != null) {//有头条
                if (position == 1) {
                    return TYPE_HEADLINE;
                } else {
                    //有banner和头条,所以正文的position从2开始
                    feed_position = 2;
                    return position;
                }
            } else {
                //有banner没头条
                feed_position = 1;
                return position;
            }
        } else {
            feed_position = 0;
            return position;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View rootView;
        if(viewType == TYPE_TOP) {
            rootView = View.inflate(parent.getContext(),
                    R.layout.item_zhihu_top_stories, null);
            return new TopStoriesViewHolder(rootView);
        } else if (viewType == TYPE_HEADLINE) {
            rootView = View.inflate(parent.getContext(),
                    R.layout.item_daily_headline, null);
            return new HeadlineViewHolder(rootView);
        } else {
            DailyBean.ResponseBean.FeedsBean feedsBean = response.getFeeds().get(viewType - feed_position);
            switch (feedsBean.getType()) {
                case 0: {
                    rootView = View.inflate(parent.getContext(),
                            R.layout.item_daily_feed_0, null);
                    return new Feed_0_ViewHolder(rootView);
                }
                case 1: {
                    rootView = View.inflate(parent.getContext(),
                            R.layout.item_daily_feed_1, null);
                    return new Feed_1_ViewHolder(rootView);
                }
                case 2: {
                    rootView = View.inflate(parent.getContext(),
                            R.layout.item_daily_feed_0, null);
                    return new Feed_0_ViewHolder(rootView);
                }
                default:
                    rootView = View.inflate(parent.getContext(),
                            R.layout.item_empty, null);
                    return new EmptyViewHolder(rootView);
            }
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof TopStoriesViewHolder) {
            TopStoriesViewHolder topStoriesViewHolder = (TopStoriesViewHolder) holder;
            topStoriesViewHolder.bindItem(response.getBanners());
        } else if (holder instanceof HeadlineViewHolder) {
            HeadlineViewHolder headlineViewHolder = (HeadlineViewHolder) holder;
            headlineViewHolder.bindItem(response.getHeadline());
        } else if (holder instanceof Feed_1_ViewHolder) {
            Feed_1_ViewHolder feed_1_viewHolder = (Feed_1_ViewHolder) holder;
            DailyBean.ResponseBean.FeedsBean feedsBean = response.getFeeds().get(position - feed_position);
            if (feedsBean.getType() == 1) {
                feed_1_viewHolder.bindItem(feedsBean);
            }
        } else if (holder instanceof Feed_0_ViewHolder) {
            Feed_0_ViewHolder feed_0_viewHolder = (Feed_0_ViewHolder) holder;
            DailyBean.ResponseBean.FeedsBean feedsBean = response.getFeeds().get(position - feed_position);
            if (feedsBean.getType() == 0) {
                feed_0_viewHolder.bindItem(feedsBean);
            } else if (feedsBean.getType() == 2) {
                feed_0_viewHolder.bindItem(feedsBean);
            }
        } else if (holder instanceof EmptyViewHolder) {

        }
    }

    @Override
    public int getItemCount() {
        int count = 0;
        if(response.getBanners() != null) count ++;
        if (response.getFeeds() != null) count = count + response.getFeeds().size();
        if(response.getHeadline().getPost() != null) count++;
        return count;
    }

    class TopStoriesViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.vp_top_stories)
        TopStoriesViewPager vp_top_stories;
        @BindView(R.id.tv_top_title)
        TextView tv_top_title;
        @BindView(R.id.tv_tag)
        TextView tv_tag;

        public TopStoriesViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            tv_tag.setVisibility(View.GONE);
        }

        public void bindItem(List<DailyBean.ResponseBean.BannersBean> banners) {
            List<LatestNews.TopStories> topList = new ArrayList<>();
            for (DailyBean.ResponseBean.BannersBean banner : banners) {
                LatestNews.TopStories t = new LatestNews.TopStories();
                t.setImage(banner.getImage());
                t.setTitle(banner.getPost().getTitle());
                t.setUrl(banner.getPost().getAppview());
                topList.add(t);
            }
            vp_top_stories.init(topList, tv_top_title, new TopStoriesViewPager.ViewPagerClickListenner() {
                @Override
                public void onClick(LatestNews.TopStories item) {
                    startWebActivity(item.getUrl());
                }
            });
        }
    }

    private void startWebActivity(String url) {
        Intent intent = WebActivity.newIntent(mContext, url);
        mContext.startActivity(intent);
    }

    class HeadlineViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.tv_headline_1)
        TextView tv_headline_1;
        @BindView(R.id.tv_headline_2)
        TextView tv_headline_2;
        @BindView(R.id.tv_headline_3)
        TextView tv_headline_3;
        @BindView(R.id.card)
        CardView card_headline;

        public HeadlineViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void bindItem(final DailyBean.ResponseBean.HeadlineBean headline) {
            ChangeCardViewColor.setCardViewBackgroundColor(card_headline);

            List<DailyBean.ResponseBean.HeadlineBean.ListBean> headLines = headline.getList();
            tv_headline_1.setText(headLines.get(0).getDescription());
            tv_headline_2.setText(headLines.get(1).getDescription());
            tv_headline_3.setText(headLines.get(2).getDescription());
            card_headline.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startWebActivity(headline.getPost().getAppview());
                }
            });
        }
    }

    class Feed_0_ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.iv_feed_0_icon)
        ImageView iv_feed_0_icon;
        @BindView(R.id.tv_feed_0_title)
        TextView tv_feed_0_title;
        @BindView(R.id.tv_feed_0_desc)
        TextView tv_feed_0_desc;
        @BindView(R.id.iv_feed_0_type)
        ImageView iv_feed_0_type;
        @BindView(R.id.tv_Feed_0_type)
        TextView tv_Feed_0_type;
        @BindView(R.id.card)
        CardView card_layout;

        public Feed_0_ViewHolder(View rootView) {
            super(rootView);
            ButterKnife.bind(this, itemView);
        }

        public void bindItem(final DailyBean.ResponseBean.FeedsBean feeds) {
            ChangeCardViewColor.setCardViewBackgroundColor(card_layout);

            tv_feed_0_title.setText(feeds.getPost().getTitle());
            tv_feed_0_desc.setText(feeds.getPost().getDescription());
            tv_Feed_0_type.setText(feeds.getPost().getCategory().getTitle());
            Glide.with(mContext).load(feeds.getImage()).centerCrop().into(iv_feed_0_icon);
            if (feeds.getType() == 0) {
                Glide.with(mContext).load(R.drawable.feed_0_icon).centerCrop().into(iv_feed_0_type);
                card_layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
            } else if (feeds.getType() == 2) {
                Glide.with(mContext).load(R.drawable.feed_1_icon).centerCrop().into(iv_feed_0_type);
                card_layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startWebActivity(feeds.getPost().getAppview());
                    }
                });
            }
        }
    }

    class Feed_1_ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.tv_feed_1_title)
        TextView tv_feed_1_title;
        @BindView(R.id.tv_feed_1_type)
        TextView tv_feed_1_type;
        @BindView(R.id.iv_feed_1_type_icon)
        ImageView iv_feed_1_type_icon;
        @BindView(R.id.iv_feed_1_icon)
        ImageView iv_feed_1_icon;
        @BindView(R.id.card)
        CardView card_feed_1;

        public Feed_1_ViewHolder(View rootView) {
            super(rootView);
            ButterKnife.bind(this, itemView);
        }

        public void bindItem(final DailyBean.ResponseBean.FeedsBean feeds) {
            ChangeCardViewColor.setCardViewBackgroundColor(card_feed_1);

            tv_feed_1_title.setText(feeds.getPost().getTitle());
            tv_feed_1_type.setText(feeds.getPost().getCategory().getTitle());
            Glide.with(mContext).load(feeds.getPost().getCategory().getImage_lab()).centerCrop().into(iv_feed_1_type_icon);
            Glide.with(mContext).load(feeds.getImage()).centerCrop().into(iv_feed_1_icon);

            card_feed_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startWebActivity(feeds.getPost().getAppview());
                }
            });
        }
    }

    private class EmptyViewHolder extends RecyclerView.ViewHolder {
        public EmptyViewHolder(View rootView) {
            super(rootView);
        }
    }
}


text:
require "helper"
require 'money'
require 'monetize'

describe BraintreeTransactionGateway do
  let(:gateway) { BraintreeTransactionGateway.new }

  context "disputed transactions" do
    let(:transaction_id) { "mw8kz36" }
    let(:expected_dispute) do
      BraintreeTransactionGateway::Dispute.new(
        transaction_id,
        Date.civil(2014, 5, 2),
        Money.us_dollar(15_00),
        Date.civil(2014, 5, 19),
        "open",
        "general"
      )
    end

    let(:braintree_transaction) do
      double(:transaction,
        id: transaction_id,
        status: "settled",
        disputes: [
          double(:dispute,
                 received_date: Date.civil(2014, 5, 2),
                 amount: "15.0".to_d,
                 currency_iso_code: "USD",
                 reply_by_date: Date.civil(2014, 5, 19),
                 status: "open",
                 reason: "general",
          ),
        ],
      )
    end

    describe "#disputes" do
      let(:from) { Date.civil 2014, 5, 1 }
      let(:to) { Date.civil 2014, 6, 1 }
      it "returns disputes in range" do
        allow(Braintree::Transaction)
          .to receive(:search).and_return([braintree_transaction])

        @result = gateway.disputes from, to
        expect(@result).to eq [expected_dispute]
      end
    end

    describe "#disputes_for_transaction" do
      it "returns disputes attached to a specific transaction" do
        allow(Braintree::Transaction)
          .to receive(:find).with(transaction_id)
          .and_return(braintree_transaction)

        @result = gateway.disputes_for_transaction transaction_id
        expect(@result).to eq [expected_dispute]
      end
    end
  end

  describe "#charge" do
    context "when successful" do
      before do
        use_cassette("charge-success") do
          @result = gateway.charge(successful_sale_options)
        end
      end

      it "is successful" do
        expect(@result.success?).to be_true
      end

      it "has a transaction_id" do
        expect(@result.transaction_id).to eq("7fhzzr")
      end
    end

    context "when unsuccessful" do
      before do
        use_cassette("charge-processor_declined") do
          @result = gateway.charge(unsuccessful_sale_options)
        end
      end

      it "is unsuccessful" do
        expect(@result.success?).to be_false
      end
    end

    context "with an invalid credit card" do
      before do
        use_cassette("charge-failed_validation") do
          @result = gateway.charge invalid_credit_card_sale_options
        end
      end

      it "is unsuccessful" do
        expect(@result.success?).to be_false
      end

      it "returns a code" do
        expect(@result.code).to eq("81717")
      end

      it "has a message" do
        message = "Credit card number is not an accepted test number."
        expect(@result.message).to eq(message)
      end
    end
  end

  describe "#refund_settled_at" do
    it "returns nil for a refund that has not settled yet" do
      use_cassette("refunded_at-incomplete") do
        refund_transaction_id = 'dq39dg'

        @result = gateway.refund_settled_at(refund_transaction_id)

        expect(@result).to be_nil
      end
    end

    it "returns when the refund settled for a refund that has settled" do
      use_cassette("refunded_at-complete") do
        refund_transaction_id = '3tgqq2'
        expected_time = Time.utc 2014, 2, 4, 8, 15, 10

        @result = gateway.refund_settled_at(refund_transaction_id)

        expect(@result).to eq expected_time
      end
    end

    it "raises TransactionMissing when the refund doesn't exist" do
      use_cassette("refunded_at-missing") do
        expect { gateway.refund_settled_at("garbage") }
          .to raise_error(BraintreeTransactionGateway::TransactionMissing)
      end
    end
  end

  describe "#escrow_status" do
    context "for an existing transaction" do
      before do
        use_cassette("escrow_status-held") do
          @result = gateway.escrow_status("5wb5g6")
        end
      end

      it "returns the status" do
        expect(@result).to eq("held")
      end
    end

    context "for a missing transaction" do
      it "raises an exception" do
        use_cassette("escrow_status-missing") do
          expect { gateway.escrow_status("garbage") }
            .to raise_error(BraintreeTransactionGateway::TransactionMissing)
        end
      end
    end
  end

  describe "#locate" do
    context "for an existing transaction" do
      context "successful transaction" do
        let(:order_id) { "test-abcd1234" }

        before do
          use_cassette("locate-success") do
            gateway.charge successful_sale_options order_id: order_id

            @result = gateway.locate order_id
          end
        end

        it "is successful" do
          expect(@result.success?).to be_true
        end

        it "has a transaction_id" do
          expect(@result.transaction_id).to eq("9gnfcw")
        end
      end

      context "failed transaction" do
        let(:order_id) { "test-deadbeef-2" }

        before do
          use_cassette("locate-failure") do
            gateway.charge unsuccessful_sale_options order_id: order_id

            @result = gateway.locate order_id
          end
        end

        it "is unsuccessful" do
          expect(@result.success?).to be_false
        end

        it "has a transaction_id" do
          expect(@result.transaction_id).to eq("hxwnhb")
        end
      end

      context "settled transaction" do
        before do
          use_cassette("locate-settled") do
            @result = gateway.locate "588a0cdc8a1b2f1043536c66d8ea2821"
          end
        end

        it "is successful" do
          expect(@result.success?).to be_true
        end

        it "has a transaction_id" do
          expect(@result.transaction_id).to eq("74j5km")
        end
      end
    end

    context "for an unknown transaction" do
      it "raises an exception" do
        use_cassette("locate-unknown") do
          expect { gateway.locate("chucktesta") }
            .to raise_error(BraintreeTransactionGateway::TransactionMissing)
        end
      end
    end
  end

  context "#release" do
    it "returns true with a successful transaction" do
      use_cassette("release-success") do
        expect(gateway.release("g8fyvr")).to be_true
      end
    end

    it "returns false with a non-held transaction" do
      use_cassette("release-failure") do
        expect(gateway.release("73fxwb")).to be_false
      end
    end

    it "returns false with a missing transaction" do
      use_cassette("release-missing") do
        expect(gateway.release("notarealid")).to be_false
      end
    end
  end

  describe "#refund" do
    it "returns a success result with a successful transaction" do
      use_cassette("refund-success") do
        result = gateway.refund "9tdbbw"

        expect(result.success?).to be_true
      end
    end

    it "returns an unsuccessful result with a missing transaction" do
      use_cassette("refund-missing") do
        result = gateway.refund "does-not-exist"

        expect(result.success?).to be_false
      end
    end

    it "returns an unsuccessful result with a failed transaction" do
      use_cassette("refund-failing") do
        result = gateway.refund "test-deadbeef-2"

        expect(result.success?).to be_false
      end
    end
  end

  private

  def successful_sale_options options = {}
    {
      amount: "100.0",
      service_fee_amount: "5.00",
      options: {
        hold_in_escrow: true,
        submit_for_settlement: true,
      },
      credit_card: {
        number: "4111111111111111",
        expiration_month: "05",
        expiration_year: "2014",
        cvv: "123",
      },
      merchant_account_id: "04arts_foundation_g3jkdb_troll",
    }.merge options
  end

  def unsuccessful_sale_options options = {}
    successful_sale_options.merge(
      amount: "2000",
    ).merge options
  end

  def invalid_credit_card_sale_options options = {}
    successful_sale_options.merge(
      credit_card: {
        number: "5444444444444445",
        expiration_month: "05",
        expiration_year: "2014",
        cvv: "123",
      },
    ).merge options
  end

  def use_cassette name, &block
    formatted_name = format "BraintreeTransactionGateway-%s", name

    VCR.use_cassette formatted_name, &block
  end
end


text:
=========
 Gotchas
=========

To begin, we should make something about SymPy clear.  SymPy is nothing more
than a Python library, like ``NumPy``, ``Django``, or even modules in the
Python standard library ``sys`` or ``re``.  What this means is that SymPy does
not add anything to the Python language.  Limitations that are inherent in the
Python language are also inherent in SymPy.  It also means that SymPy tries to
use Python idioms whenever possible, making programming with SymPy easy for
those already familiar with programming with Python.  As a simple example,
SymPy uses Python syntax to build expressions.  Implicit multiplication (like
``3x`` or ``3 x``) is not allowed in Python, and thus not allowed in SymPy.
To multiply ``3`` and ``x``, you must type ``3*x`` with the ``*``.

.. _tutorial-gotchas-symbols:

Symbols
=======

One consequence of this fact is that SymPy can be used in any environment
where Python is available.  We just import it, like we would any other
library:

    >>> from sympy import *

This imports all the functions and classes from SymPy into our interactive
Python session.  Now, suppose we start to do a computation.

    >>> x + 1
    Traceback (most recent call last):
    ...
    NameError: name 'x' is not defined

Oops! What happened here?  We tried to use the variable ``x``, but it tells us
that ``x`` is not defined.  In Python, variables have no meaning until they
are defined.  SymPy is no different.  Unlike many symbolic manipulation
systems you may have used, in SymPy, variables are not defined automatically.
Do define variables, we must use ``symbols``.

    >>> x = symbols('x')
    >>> x + 1
    x + 1

``symbols`` takes a string of variable names separated by spaces or commas,
and creates Symbols out of them.  We can then assign these to variable names.
Later, we will investigate some convenient ways we can work around this issue.
For now, let us just define the most common variable names, ``x``, ``y``, and
``z``, for use through the rest of this section

    >>> x, y, z = symbols('x y z')

As a final note, we note that the name of a Symbol and the name of the
variable it is assigned to need not have anything to do with one another.

    >>> a, b = symbols('b a')
    >>> a
    b
    >>> b
    a

Here we have done the very confusing thing of assigning a Symbol with the name
``a`` to the variable ``b``, and a Symbol of the name ``b`` to the variable
``a``.  Now the Python variable named ``a`` points to the SymPy Symbol named
``b``, and visa versa.  How confusing.  We could have also done something like

    >>> crazy = symbols('unrelated')
    >>> crazy + 1
    unrelated + 1

This also shows that Symbols can have names longer than one character if we
want.

Usually, the best practice is to assign Symbols to Python variables of the
same name, although there are exceptions:  Symbol names can contain characters
that are not allowed in Python variable names, or may just want to avoid
typing long names by assigning Symbols with long names to single letter Python
variables.

To avoid confusion, throughout this tutorial, Symbol names and Python variable
names will always coincide.  Furthermore, the word "Symbol" will refer to a
SymPy Symbol and the word "variable" will refer to a Python variable.

Finally, let us be sure we understand the difference between SymPy Symbols and
Python variables.  Consider the following::

  x = symbols('x')
  expr = x + 1
  x = 2
  print expr

What do you think the output of this code will be?  If you thought ``3``,
you're wrong.  Let's see what really happens

    >>> x = symbols('x')
    >>> expr = x + 1
    >>> x = 2
    >>> print expr
    x + 1

Changing ``x`` to ``2`` had no effect on ``expr``.  This is because ``x = 2``
changes the Python variable ``x`` to ``2``, but has no effect on the SymPy
Symbol ``x``, which was what we used in creating ``expr``.  When we created
``expr``, the Python variable ``x`` was a Symbol.  After we created, it, we
changed the Python variable ``x`` to 2.  But ``expr`` remains the same.  This
behavior is not unique to SymPy.  All Python programs work this way: if a
variable is changed, expressions that were already created with that variable
do not change automatically.  For example

    >>> x = 'abc'
    >>> expr = x + 'def'
    >>> expr
    'abcdef'
    >>> x = 'ABC'
    >>> expr
    'abcdef'

.. sidebar:: Quick Tip

   To change the value of a Symbol in an expression, use ``subs``

     >>> x = symbols('x')
     >>> expr = x + 1
     >>> expr.subs(x, 2)
     3

In this example, if we want to know what ``expr`` is with the new value of
``x``, we need to reevaluate the code that created ``expr``, namely, ``expr =
x + 1``.  This can be complicated if several lines created ``expr``.  One
advantage of using a symbolic computation system like SymPy is that we can
build a symbolic representation for ``expr``, and then substitute ``x`` with
values.  The correct way to do this in SymPy is to use ``subs``, which will be
discussed in more detail later.

    >>> x = symbols('x')
    >>> expr = x + 1
    >>> expr.subs(x, 2)
    3

.. TODO: Add link to basic operations section

.. _tutorial_gotchas_equals:

Equals signs
============

Another very important consequence of the fact that SymPy does not extend
Python syntax is that ``=`` does not represent equality in SymPy.  Rather it
is Python variable assignment.  This is hard-coded into the Python language,
and SymPy makes no attempts to change that.

You may think, however, that ``==``, which is used for equality testing in
Python, is used for SymPy as equality.  This is not quite correct either.  Let
us see what happens when we use ``==``.

    >>> x + 1 == 4
    False

Instead of treating ``x + 1 == 4`` symbolically, we just got ``False``.  In
SymPy, ``==`` represents exact symbolic equality testing.  This means that ``a
== b`` means that we are *asking* if `a = b`.  We always get a ``bool`` as the
result of ``==``.  There is a separate object, called ``Eq``, which can be
used to create symbolic equalities

    >>> Eq(x + 1, 4)
    x + 1 == 4

There is one additional caveat about ``==`` as well.  Suppose we want to know
if `(x + 1)^2 = x^2 + 2x + 1`.  We might try something like this:

    >>> (x + 1)**2 == x**2 + 2*x + 1
    False

We got ``False`` again. However, `(x + 1)^2` *does* equal `x^2 + 2x + 1`. What
is going on here?  Did we find a bug in SymPy, or is it just not powerful
enough to recognize this basic algebraic fact?

Recall from above that ``==`` represents *exact* symbolic equality testing.
"Exact" here means that two symbolic expressions will compare equal with
``==`` only if they are exactly equal symbolically.  Here, `(x + 1)^2` and
`x^2 + 2x + 1` are not the same symbolically. One is the power of an addition
of two terms, and the other is the addition of three terms.

It turns out that when using SymPy as a library, having ``==`` test for exact
symbolic equality is far more useful than having it represent symbolic
equality, or having it test for mathematical equality.  However, as a new
user, you will probably care more about the latter two.  We have already seen
an alternative to representing equalities symbolically, ``Eq``.  To test if
two things are equal, it is best to recall the basic fact that if `a = b`,
then `a - b = 0`.  Thus, the best way to check if `a = b` is to take `a - b`
and simplify it, and see if it goes to 0.  We will learn :ref:`later
<tutorial-simplify>` that the function to do this is called ``simplify``. This
method is not infallible---in fact, it can be `theoretically proven
<http://en.wikipedia.org/wiki/Richardson%27s_theorem>`_ that it is impossible
to determine if two symbolic expressions are identically equal in
general---but for most common expressions, it works quite well.

    >>> a = (x + 1)**2
    >>> b = x**2 + 2*x + 1
    >>> simplify(a - b)
    0
    >>> c = x**2 - 2*x + 1
    >>> simplify(a - c)
    4*x

Two Final Notes: ``^`` and ``/``
================================

You may have noticed that we have been using ``**`` for exponentiation instead
of the standard ``^``.  That's because SymPy follows Python's conventions.  In
Python, ``^`` represents logical exclusive or.  SymPy follows this convention:

     >>> True ^ False
     True
     >>> True ^ True
     False
     >>> x^y
     Or(And(Not(x), y), And(Not(y), x))

Finally, a small technical discussion on how SymPy works is in order.  When
you type something like ``x + 1``, the SymPy Symbol ``x`` is added to the
Python int ``1``.  Python's operator rules then allow SymPy to tell Python
that SymPy objects know how to be added to Python ints, and so ``1`` is
automatically converted to the SymPy Integer object.

This sort of operator magic happens automatically behind the scenes, and you
rarely need to even know that it is happening.  However, there is one
exception.  Whenever you combine a SymPy object and a SymPy object, or a SymPy
object and a Python object, you get a SymPy object, but whenever you combine
two Python objects, SymPy never comes into play, and so you get a Python
object.

    >>> type(Integer(1) + 1)
    <class 'sympy.core.numbers.Integer'>
    >>> type(1 + 1)
    <... 'int'>

This is usually not a big deal. Python ints work much the same as SymPy
Integers, but there is one important exception:  division.  In SymPy, the
division of two Integers gives a Rational:

    >>> Integer(1)/Integer(3)
    1/3
    >>> type(Integer(1)/Integer(3))
    <class 'sympy.core.numbers.Rational'>

But in Python ``/`` represents either integer division or floating point
division, depending on whether you are in Python 2 or Python 3, and depending
on whether or not you have run ``from __future__ import division``:

    >>> from __future__ import division
    >>> 1/2 #doctest: +SKIP
    0.5

To avoid this, we can construct the rational object explicitly

    >>> Rational(1, 2)
    1/2

This problem also comes up whenever we have a larger symbolic expression with
``int/int`` in it.  For example:

    >>> x + 1/2 #doctest: +SKIP
    x + 0.5

This happens because Python first evaluates ``1/2`` into ``0.5``, and then
that is cast into a SymPy type when it is added to ``x``.  Again, we can get
around this by explicitly creating a Rational:

    >>> x + Rational(1, 2)
    x + 1/2

There are several tips on avoiding this situation in the :ref:`gotchas`
document.

Further Reading
===============

For more discussion on the topics covered in this section, see :ref:`gotchas`.


text:
layout: page
title: Parsons 45th Anniversary
date: 2016-05-24
author: Stephen Flynn
tags: weekly links, java
status: published
summary: Nulla maximus purus ac libero.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 05/07/2017
  endDate: 05/09/2017
  ctyhocn: DALDRHX
  groupCode: P4A
published: true
---
Phasellus sit amet mauris mi. Aliquam fringilla dui sed justo venenatis aliquet. Integer felis odio, auctor eget odio vel, posuere luctus ante. Nulla interdum euismod fermentum. Mauris eget aliquet enim. Sed convallis eget elit sed posuere. Suspendisse condimentum arcu nulla, sed auctor lacus blandit in. Curabitur eget odio et elit euismod luctus. Vivamus mollis neque vel magna tincidunt posuere. Cras et erat ut turpis efficitur elementum. Phasellus nec risus ut sapien aliquet tempor a eget magna.
Aliquam sed dui pretium, varius arcu vel, posuere est. Vivamus sit amet eros pretium, suscipit urna ac, volutpat massa. Sed ac sapien pellentesque, consectetur eros nec, bibendum eros. Nullam dapibus pretium condimentum. Nunc ac lacus id magna commodo laoreet sit amet id erat. Nam vitae sagittis diam. Curabitur feugiat, lorem eu finibus bibendum, lectus justo egestas orci, non malesuada sapien leo vitae mi. Pellentesque ut dapibus massa.

* Duis consequat diam et nibh facilisis, eget ornare odio hendrerit
* In pulvinar mi ac elit fermentum, non gravida lacus laoreet
* Donec dignissim massa sit amet blandit finibus.

Etiam eros odio, venenatis nec placerat et, hendrerit a erat. Nunc lobortis nibh quis augue tincidunt, gravida condimentum nisl tempor. Proin nec orci ut nibh viverra tristique eu vitae dui. Proin auctor lacinia felis, quis aliquet turpis. Phasellus scelerisque libero malesuada lorem elementum, eu convallis augue elementum. Duis sagittis iaculis eros id posuere. Fusce ac nunc mauris. Nam vehicula est lectus, quis tempus quam rutrum eu. Donec consequat velit et lorem bibendum cursus. Curabitur sit amet dapibus magna, vel pellentesque leo.


text:
"""Modeule to test authentication in the application"""
import json

from tests.basetest import TestBase

class AuthTestCase(TestBase):
    """Test authentication namespace"""

    def test_registration(self):
        """Test if registration works correctly"""
        res = self.client.post(
            '/api/v1/auth/register',
            data=self.user_data
        )
        result = json.loads(res.data.decode())
        self.assertEqual(
            result['message'],
            'Registered successfully, please log in.'
        )

    def test_bad_username_registration(self):
        """
            Test if API rejects users with special characters in their username
        """
        bad_user = {
            'username': '@/*-ffg',
            'email': 'test@test.com',
            'password': 'test_password'
        }

        res = self.client.post(
            '/api/v1/auth/register',
            data=bad_user
        )
        result = json.loads(res.data.decode())
        self.assertIn('No special characters for users names', str(result))

    def test_bad_email_registration(self):
        """
            Test if API rejects users whose emails have improper format
        """
        bad_user = {
            'username': 'test',
            'email': 'testestcom',
            'password': 'test_password'
        }

        res = self.client.post(
            '/api/v1/auth/register',
            data=bad_user
        )
        result = json.loads(res.data.decode())
        self.assertEqual(
            result['message'],
            'Incorrect email format.'
        )

    def test_short_password_registration(self):
        """
            Test if API rejects users whose passwords are too short
        """
        bad_user = {
            'username': 'test',
            'email': 'test@test.com',
            'password': 'test'
        }

        res = self.client.post(
            '/api/v1/auth/register',
            data=bad_user
        )
        result = json.loads(res.data.decode())
        self.assertEqual(
            result['message'],
            'Password too short.'
        )

    def test_already_registered(self):
        """Test is users can't be registered more than once"""
        res = self.client.post(
            '/api/v1/auth/register',
            data=self.user_data
        )
        self.assertEqual(res.status_code, 201)
        second_res = self.client.post(
            '/api/v1/auth/register',
            data=self.user_data
        )
        result = json.loads(second_res.data.decode())
        self.assertIn(
            "Email or username already used. Try",
            result['message']
        )

    def test_user_login(self):
        """Test if a users can login"""
        res = self.client.post(
            '/api/v1/auth/register',
            data=self.user_data
        )
        self.assertEqual(res.status_code, 201)

        login_res = self.client.post(
            '/api/v1/auth/login',
            data=self.user_data_login
        )
        result = json.loads(login_res.data.decode())
        self.assertTrue(result['token'])

    def test_non_registered_user_login(self):
        """Test if users who are not registered can log in"""
        bad_user = {
            'email': 'bad.user@bad.com',
            'password': 'amabaddie'
        }

        login_res = self.client.post(
            '/api/v1/auth/login',
            data=bad_user
        )
        result = json.loads(login_res.data.decode())
        self.assertEqual(
            result['message'], "Invalid email or password, Please try again")

    def test_password_reset(self):
        """Method to test if API can reset a users password"""
        res = self.client.post(
            '/api/v1/auth/register',
            data=self.user_data
        )
        self.assertEqual(res.status_code, 201)

        login_res = self.client.post(
            '/api/v1/auth/login',
            data=self.user_data_login
        )
        self.assertEqual(login_res.status_code, 200)

        self.client.post(
            '/api/v1/auth/reset_password',
            data={'email': 'test@test.com'}
        )

        login_res2 = self.client.post(
            '/api/v1/auth/login',
            data=self.user_data_login
        )
        self.assertEqual(login_res2.status_code, 401)

    def test_password_reset_bad_email(self):
        """
        Method to test if API cannot reset a users
        password with abad email
        """
        self.client.post(
            '/api/v1/auth/register',
            data=self.user_data
        )

        reset_res = self.client.post(
            '/api/v1/auth/reset_password',
            data={'email': 'testest.com'}
        )
        self.assertEqual(reset_res.status_code, 400)

    def test_password_reset_non_existing_user(self):
        """
        Method to test if API cannot reset a users
        password with abad email
        """
        self.client.post(
            '/api/v1/auth/register',
            data=self.user_data
        )

        self.client.post(
            '/api/v1/auth/login',
            data=self.user_data_login
        )
        reset_res = self.client.post(
            '/api/v1/auth/reset_password',
            data={'email': 'tes@test.com'}
        )
        self.assertEqual(reset_res.status_code, 400)


text:
package com.google.api.ads.adwords.jaxws.v201506.cm;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Represents a Mobile Device Criterion.
 *
A criterion of this type can only be created using an ID. A criterion of this type can be either targeted or excluded.
 *             This is enabled for AdX.
 *
 *
 *
Java class for MobileDevice complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="MobileDevice">
 *   <complexContent>
 *     <extension base="{https://adwords.google.com/api/adwords/cm/v201506}Criterion">
 *       <sequence>
 *         <element name="deviceName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="manufacturerName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="deviceType" type="{https://adwords.google.com/api/adwords/cm/v201506}MobileDevice.DeviceType" minOccurs="0"/>
 *         <element name="operatingSystemName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MobileDevice", propOrder = {
    "deviceName",
    "manufacturerName",
    "deviceType",
    "operatingSystemName"
})
public class MobileDevice
    extends Criterion
{

    protected String deviceName;
    protected String manufacturerName;
    @XmlSchemaType(name = "string")
    protected MobileDeviceDeviceType deviceType;
    protected String operatingSystemName;

    /**
     * Gets the value of the deviceName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDeviceName() {
        return deviceName;
    }

    /**
     * Sets the value of the deviceName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDeviceName(String value) {
        this.deviceName = value;
    }

    /**
     * Gets the value of the manufacturerName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getManufacturerName() {
        return manufacturerName;
    }

    /**
     * Sets the value of the manufacturerName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setManufacturerName(String value) {
        this.manufacturerName = value;
    }

    /**
     * Gets the value of the deviceType property.
     *
     * @return
     *     possible object is
     *     {@link MobileDeviceDeviceType }
     *
     */
    public MobileDeviceDeviceType getDeviceType() {
        return deviceType;
    }

    /**
     * Sets the value of the deviceType property.
     *
     * @param value
     *     allowed object is
     *     {@link MobileDeviceDeviceType }
     *
     */
    public void setDeviceType(MobileDeviceDeviceType value) {
        this.deviceType = value;
    }

    /**
     * Gets the value of the operatingSystemName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getOperatingSystemName() {
        return operatingSystemName;
    }

    /**
     * Sets the value of the operatingSystemName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setOperatingSystemName(String value) {
        this.operatingSystemName = value;
    }

}


text:
/**
 * This worker will register itself with worker manager and
 * report its ID.  The parent will then connect directly to this worker
 * and execute work.
 */

this.endpointLogLevel = 'debug';
importScripts('../build/endpoint.demo.js');
var endpoint = this.endpoint;

var _this = this;
var api = {
    doWork: function(id) {
        return 'worked ' + id;
    },
    terminate: function() {
        setTimeout(function() {
            endpoint.getConfiguration().getLink('default-worker').close();
            _this.close();
        }, 250);
    }
};

var adapter = endpoint.registerAdapter(endpoint.getInstanceId(), '1.0', api);

// Tell parent about us
var parentFacade = endpoint.createFacade('worker-register-api', '1.0', { neighborhood: 'group' });
parentFacade.on('ready', function() {
    parentFacade.getApi().registerWorker(endpoint.getInstanceId())
        .then(function() {
            parentFacade.close();
        });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#FF5722</color>
    <color name="colorPrimaryDark">#E64A19</color>
    <color name="colorBlue">#0192ff</color>
    <color name="colorAccent">@color/colorPrimary</color>
</resources>