text:
require 'google/protobuf'

require 'google/api/annotations_pb'
require 'google/api/client_pb'
require 'google/api/field_behavior_pb'
require 'google/api/resource_pb'
require 'google/cloud/video/transcoder/v1/resources_pb'
require 'google/protobuf/empty_pb'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_file("google/cloud/video/transcoder/v1/services.proto", :syntax => :proto3) do
    add_message "google.cloud.video.transcoder.v1.CreateJobRequest" do
      optional :parent, :string, 1
      optional :job, :message, 2, "google.cloud.video.transcoder.v1.Job"
    end
    add_message "google.cloud.video.transcoder.v1.ListJobsRequest" do
      optional :parent, :string, 1
      optional :page_size, :int32, 2
      optional :page_token, :string, 3
      optional :filter, :string, 4
      optional :order_by, :string, 5
    end
    add_message "google.cloud.video.transcoder.v1.GetJobRequest" do
      optional :name, :string, 1
    end
    add_message "google.cloud.video.transcoder.v1.DeleteJobRequest" do
      optional :name, :string, 1
      optional :allow_missing, :bool, 2
    end
    add_message "google.cloud.video.transcoder.v1.ListJobsResponse" do
      repeated :jobs, :message, 1, "google.cloud.video.transcoder.v1.Job"
      optional :next_page_token, :string, 2
      repeated :unreachable, :string, 3
    end
    add_message "google.cloud.video.transcoder.v1.CreateJobTemplateRequest" do
      optional :parent, :string, 1
      optional :job_template, :message, 2, "google.cloud.video.transcoder.v1.JobTemplate"
      optional :job_template_id, :string, 3
    end
    add_message "google.cloud.video.transcoder.v1.ListJobTemplatesRequest" do
      optional :parent, :string, 1
      optional :page_size, :int32, 2
      optional :page_token, :string, 3
      optional :filter, :string, 4
      optional :order_by, :string, 5
    end
    add_message "google.cloud.video.transcoder.v1.GetJobTemplateRequest" do
      optional :name, :string, 1
    end
    add_message "google.cloud.video.transcoder.v1.DeleteJobTemplateRequest" do
      optional :name, :string, 1
      optional :allow_missing, :bool, 2
    end
    add_message "google.cloud.video.transcoder.v1.ListJobTemplatesResponse" do
      repeated :job_templates, :message, 1, "google.cloud.video.transcoder.v1.JobTemplate"
      optional :next_page_token, :string, 2
      repeated :unreachable, :string, 3
    end
  end
end

module Google
  module Cloud
    module Video
      module Transcoder
        module V1
          CreateJobRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.video.transcoder.v1.CreateJobRequest").msgclass
          ListJobsRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.video.transcoder.v1.ListJobsRequest").msgclass
          GetJobRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.video.transcoder.v1.GetJobRequest").msgclass
          DeleteJobRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.video.transcoder.v1.DeleteJobRequest").msgclass
          ListJobsResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.video.transcoder.v1.ListJobsResponse").msgclass
          CreateJobTemplateRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.video.transcoder.v1.CreateJobTemplateRequest").msgclass
          ListJobTemplatesRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.video.transcoder.v1.ListJobTemplatesRequest").msgclass
          GetJobTemplateRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.video.transcoder.v1.GetJobTemplateRequest").msgclass
          DeleteJobTemplateRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.video.transcoder.v1.DeleteJobTemplateRequest").msgclass
          ListJobTemplatesResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.video.transcoder.v1.ListJobTemplatesResponse").msgclass
        end
      end
    end
  end
end


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'my_test_gem'

redpajama_set_name: RedPajamaGithub


text:
$(document).ready(function () {

    initMaps();
});

function initMaps(){
 if ($('#map_canvas').length) {
            var latlng = new google.maps.LatLng(55.86725, -4.257231);
            var myOptions = {
                zoom: 10,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            var contentString = '
Standard Website
' +
             '123 Another Road
' +
             'City,
 Post Code
';

            var infowindow = new google.maps.InfoWindow({
                content: contentString
            });

            var marker = new google.maps.Marker({
                position: latlng,
                title: "Basic Website"
            });

            // To add the marker to the map, call setMap();
            marker.setMap(map);
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map, marker);
            });
        }

}

/* Rotating Panel */
var rotatingPanel = function () {

    var panels = [];

    $('.rotating-panel').each(function (i) {
        panels.push($(this));
    })

    if (panels.length > 0) {
        function StartTimer(position) {
            $(document).everyTime('4s', 'rotating-panel', function () { rotatingPanel.rotate(position); }, 0);
        }

        function StopTimer() {
            $(document).stopTime('rotating-panel');
        }

        StartTimer(2);

        $('#slidePager a').click(function (e) {
            //$('#slidePager a').removeClass("selected");
           // $(this).addClass("selected");

            var newPosition = $(this).attr('href').replace('?position=', '');
            rotatingPanel.rotate(newPosition);

            e.preventDefault();
        });
    }

    return {
        currentIndex: 0,
        rotate: function (direction) {
            StopTimer();
            direction = direction - 1;
            var oldIndex = this.currentIndex;

            if (direction < (panels.length) & direction >= 0) {
                this.currentIndex = direction;

                if (this.currentIndex < 0) {
                    this.currentIndex = (panels.length - 1);
                }
            }
            else {
                this.currentIndex++;

                if (this.currentIndex > (panels.length - 1)) {
                    this.currentIndex = 0;
                }
            }

            if (oldIndex != this.currentIndex) {
                $('#slidePager a').removeClass("selected");
                $('#slidePager a').eq(this.currentIndex).addClass("selected");

                panels[oldIndex].fadeOut(1000);
                panels[this.currentIndex].fadeIn(1000, function () { StartTimer(this.currentIndex + 1); });
            }
        }
    }
} ();


text:
"""autogenerated by genpy from skeleton_markers/recognitionActionActionFeedback.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct

import skeleton_markers.msg
import genpy
import actionlib_msgs.msg
import std_msgs.msg

class recognitionActionActionFeedback(genpy.Message):
  _md5sum = "aae20e09065c3809e8a8e87c4c8953fd"
  _type = "skeleton_markers/recognitionActionActionFeedback"
  _has_header = True #flag to mark the presence of a Header object
  _full_text = """# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======

Header header
actionlib_msgs/GoalStatus status
recognitionActionFeedback feedback

================================================================================
MSG: std_msgs/Header
# Standard metadata for higher-level stamped data types.
# This is generally used to communicate timestamped data
# in a particular coordinate frame.
#
# sequence ID: consecutively increasing ID
uint32 seq
#Two-integer timestamp that is expressed as:
# * stamp.secs: seconds (stamp_secs) since epoch
# * stamp.nsecs: nanoseconds since stamp_secs
# time-handling sugar is provided by the client library
time stamp
#Frame this data is associated with
# 0: no frame
# 1: global frame
string frame_id

================================================================================
MSG: actionlib_msgs/GoalStatus
GoalID goal_id
uint8 status
uint8 PENDING         = 0   # The goal has yet to be processed by the action server
uint8 ACTIVE          = 1   # The goal is currently being processed by the action server
uint8 PREEMPTED       = 2   # The goal received a cancel request after it started executing
                            #   and has since completed its execution (Terminal State)
uint8 SUCCEEDED       = 3   # The goal was achieved successfully by the action server (Terminal State)
uint8 ABORTED         = 4   # The goal was aborted during execution by the action server due
                            #    to some failure (Terminal State)
uint8 REJECTED        = 5   # The goal was rejected by the action server without being processed,
                            #    because the goal was unattainable or invalid (Terminal State)
uint8 PREEMPTING      = 6   # The goal received a cancel request after it started executing
                            #    and has not yet completed execution
uint8 RECALLING       = 7   # The goal received a cancel request before it started executing,
                            #    but the action server has not yet confirmed that the goal is canceled
uint8 RECALLED        = 8   # The goal received a cancel request before it started executing
                            #    and was successfully cancelled (Terminal State)
uint8 LOST            = 9   # An action client can determine that a goal is LOST. This should not be
                            #    sent over the wire by an action server

#Allow for the user to associate a string with GoalStatus for debugging
string text

================================================================================
MSG: actionlib_msgs/GoalID
# The stamp should store the time at which this goal was requested.
# It is used by an action server when it tries to preempt all
# goals that were requested before a certain time
time stamp

# The id provides a way to associate feedback and
# result message with specific goal requests. The id
# specified must be unique.
string id

================================================================================
MSG: skeleton_markers/recognitionActionFeedback
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======
# Define a feedback message

"""
  __slots__ = ['header','status','feedback']
  _slot_types = ['std_msgs/Header','actionlib_msgs/GoalStatus','skeleton_markers/recognitionActionFeedback']

  def __init__(self, *args, **kwds):
    """
    Constructor. Any message fields that are implicitly/explicitly
    set to None will be assigned a default value. The recommend
    use is keyword arguments as this is more robust to future message
    changes.  You cannot mix in-order arguments and keyword arguments.

    The available fields are:
       header,status,feedback

    :param args: complete set of field values, in .msg order
    :param kwds: use keyword arguments corresponding to message field names
    to set specific fields.
    """
    if args or kwds:
      super(recognitionActionActionFeedback, self).__init__(*args, **kwds)
      #message fields cannot be None, assign default values for those that are
      if self.header is None:
        self.header = std_msgs.msg.Header()
      if self.status is None:
        self.status = actionlib_msgs.msg.GoalStatus()
      if self.feedback is None:
        self.feedback = skeleton_markers.msg.recognitionActionFeedback()
    else:
      self.header = std_msgs.msg.Header()
      self.status = actionlib_msgs.msg.GoalStatus()
      self.feedback = skeleton_markers.msg.recognitionActionFeedback()

  def _get_types(self):
    """
    internal API method
    """
    return self._slot_types

  def serialize(self, buff):
    """
    serialize message into buffer
    :param buff: buffer, ``StringIO``
    """
    try:
      _x = self
      buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs))
      _x = self.header.frame_id
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      buff.write(struct.pack('<I%ss'%length, length, _x))
      _x = self
      buff.write(_struct_2I.pack(_x.status.goal_id.stamp.secs, _x.status.goal_id.stamp.nsecs))
      _x = self.status.goal_id.id
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      buff.write(struct.pack('<I%ss'%length, length, _x))
      buff.write(_struct_B.pack(self.status.status))
      _x = self.status.text
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      buff.write(struct.pack('<I%ss'%length, length, _x))
    except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
    except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))

  def deserialize(self, str):
    """
    unpack serialized message in str into this message instance
    :param str: byte array of serialized message, ``str``
    """
    try:
      if self.header is None:
        self.header = std_msgs.msg.Header()
      if self.status is None:
        self.status = actionlib_msgs.msg.GoalStatus()
      if self.feedback is None:
        self.feedback = skeleton_markers.msg.recognitionActionFeedback()
      end = 0
      _x = self
      start = end
      end += 12
      (_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.header.frame_id = str[start:end].decode('utf-8')
      else:
        self.header.frame_id = str[start:end]
      _x = self
      start = end
      end += 8
      (_x.status.goal_id.stamp.secs, _x.status.goal_id.stamp.nsecs,) = _struct_2I.unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.status.goal_id.id = str[start:end].decode('utf-8')
      else:
        self.status.goal_id.id = str[start:end]
      start = end
      end += 1
      (self.status.status,) = _struct_B.unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.status.text = str[start:end].decode('utf-8')
      else:
        self.status.text = str[start:end]
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

  def serialize_numpy(self, buff, numpy):
    """
    serialize message with numpy array types into buffer
    :param buff: buffer, ``StringIO``
    :param numpy: numpy python module
    """
    try:
      _x = self
      buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs))
      _x = self.header.frame_id
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      buff.write(struct.pack('<I%ss'%length, length, _x))
      _x = self
      buff.write(_struct_2I.pack(_x.status.goal_id.stamp.secs, _x.status.goal_id.stamp.nsecs))
      _x = self.status.goal_id.id
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      buff.write(struct.pack('<I%ss'%length, length, _x))
      buff.write(_struct_B.pack(self.status.status))
      _x = self.status.text
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      buff.write(struct.pack('<I%ss'%length, length, _x))
    except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
    except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))

  def deserialize_numpy(self, str, numpy):
    """
    unpack serialized message in str into this message instance using numpy for array types
    :param str: byte array of serialized message, ``str``
    :param numpy: numpy python module
    """
    try:
      if self.header is None:
        self.header = std_msgs.msg.Header()
      if self.status is None:
        self.status = actionlib_msgs.msg.GoalStatus()
      if self.feedback is None:
        self.feedback = skeleton_markers.msg.recognitionActionFeedback()
      end = 0
      _x = self
      start = end
      end += 12
      (_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.header.frame_id = str[start:end].decode('utf-8')
      else:
        self.header.frame_id = str[start:end]
      _x = self
      start = end
      end += 8
      (_x.status.goal_id.stamp.secs, _x.status.goal_id.stamp.nsecs,) = _struct_2I.unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.status.goal_id.id = str[start:end].decode('utf-8')
      else:
        self.status.goal_id.id = str[start:end]
      start = end
      end += 1
      (self.status.status,) = _struct_B.unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.status.text = str[start:end].decode('utf-8')
      else:
        self.status.text = str[start:end]
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

_struct_I = genpy.struct_I
_struct_3I = struct.Struct("<3I")
_struct_B = struct.Struct("<B")
_struct_2I = struct.Struct("<2I")


text:
#ifndef GLWIDGET_H
#define GLWIDGET_H

#include <QObject>
#include <QGLBuffer>
#include <QVarLengthArray>
#include <QtGui>
#include <QTimer>
#include <QCursor>
#include <QDataStream>

#include <boost/foreach.hpp>
 #include <QDebug>

#include <iostream>
#include <cassert>
#include <set>
#include <vector>

#include "gldata.h"
#include "p3.h"

namespace ocl
{

// #define PI 3.14159265

#define BUFFER_OFFSET(i) ((GLbyte *)NULL + (i))

class GLWidget : public QGLWidget {
    Q_OBJECT
    public:
        GLWidget( QWidget *parent=0, char *name=0 ) ;
        ~GLWidget() {}

        void initializeGL();
        /// add new GLData object and return pointer to it.

        GLData* addObject();
        QTimer* timer;
    signals:
        // a test/dummy signal, emitted when the user presses "c"
        void sig();

    protected:

        void resizeGL( int width, int height );
        void paintGL();
        void updateDir();
        void zoomView( int delta );
        void zoomView( const QPoint& newPos );
        void panView(const QPoint& newPos);
        void rotateView(const QPoint& newPos);
        void keyPressEvent( QKeyEvent *e ) {
            std::cout << e->key() << " pressed.\n";
            if ( e->key() == Qt::Key_C )
                emit sig();
            return;
        }
        void mouseMoveEvent( QMouseEvent *e ) {
            if (_leftButtonPressed ) {
               panView( e->pos() );
            } else if (_rightButtonPressed) {
                rotateView( e->pos() );
            }
            else if (_middleButtonPressed) {
                zoomView( e->pos() );
            }
        }
        void wheelEvent( QWheelEvent *e ) {
            //qDebug() << " mouseWheel delta= " << e->delta() << "\n";
            zoomView( e->delta() );
        }
        void mousePressEvent( QMouseEvent *e ) {
            //qDebug() << " mousePress : " << e->pos() << " button=" << e->button() << "\n";
            _oldMousePos = e->pos();
            if (e->button() == Qt::LeftButton) {
                setCursor(Qt::OpenHandCursor);
                _leftButtonPressed = true;
                //std::cout << " left button press\n";
            } else if (e->button() == Qt::RightButton) {
                setCursor(Qt::SizeAllCursor);
                _rightButtonPressed = true;
            }
            else if (e->button() == Qt::MiddleButton) {
                setCursor(Qt::SplitVCursor);
                _middleButtonPressed = true;
            }
        }
        void mouseReleaseEvent( QMouseEvent *e ) {
            //qDebug() << " mouseRelease : " << e->pos() << "\n";
            setCursor( Qt::ArrowCursor);
            _rightButtonPressed = false;
            _leftButtonPressed = false;
            _middleButtonPressed = false;
        }
        void timeOut() {
            updateGL();
        }

        // generate a VBO for each GLData object
        void genVBO() {
            BOOST_FOREACH(GLData* g, glObjects) {
                g->genVBO();
            }
        }

    protected slots:
        void timeOutSlot() { timeOut(); }

    private:
        /// camera position
        P3<float> _eye;
        /// camera up-vector
        P3<float> _up;
        /// camera look-at point
        P3<float> _center;
        /// rotation/pan y-axis
        P3<float> _diry;
        /// rotation/pan y-axis
        P3<float> _dirx;
        /// field of vision in y-dir
        float _fovy;
        /// position of near clipping plane
        float z_near;
        /// position of far clipping plane
        float z_far;

        /// these are the GLData objects which will be drawn in the OpenGL scene
        std::vector<GLData*> glObjects;

        QPoint _oldMousePos;
        int _width;
        int _height;
        bool _rightButtonPressed;
        bool _leftButtonPressed;
        bool _middleButtonPressed;
        QTime _lastFrameTime;
};

} // end ocl namespace

#endif


text:
<?php
/**
 * Test suite plugin session handler
 */

App::uses('CakeSessionHandlerInterface', 'Model/Datasource/Session');

class TestPluginSession implements CakeSessionHandlerInterface {

	public function open() {
		return true;
	}

	public function close() {
	}

	public function read($id) {
	}

	public function write($id, $data) {
	}

	public function destroy($id) {
	}

	public function gc($expires = null) {
	}

}


text:
{% extends 'forms/captcha.html' %}
{% block instructions %}

Sedikit lagi

Bantu kami melawan span dengan mengikuti arahan berikut:

{% endblock %}


text:
package org.osgi.test.cases.framework.secure.permissions.condition;

import java.util.Collection;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.condition.Condition;
import org.osgi.test.cases.framework.secure.permissions.util.PermissionsFilterException;
import org.osgi.test.cases.framework.secure.permissions.util.Util;

public class GetConditionActivator implements BundleActivator {

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext
	 * )
	 */
	public void start(BundleContext context) throws Exception {

		if (Util.debug)
			System.out.println("GETTER BUNDLE is going to start.");

		Collection<ServiceReference<Condition>> trueCondition = context
				.getServiceReferences(Condition.class,
						"(" + Condition.CONDITION_ID + "="
								+ Condition.CONDITION_ID_TRUE + ")");
		if (trueCondition.isEmpty()) {
			throw new PermissionsFilterException(
					"Fail to get ServiceReference of for true condition.");
		}
		else {
			if (Util.debug)
				System.out.println("Found true condition.");
		}

		Condition service = context.getService(trueCondition.iterator().next());
		if (service == null) {
			throw new PermissionsFilterException(
					"Fail to get service of true condition");
		}
		else {
			if (Util.debug)
				System.out.println("Got true condition service");
		}

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		// empty
	}

}


text:
module Azure::Compute::Mgmt::V2020_12_01
  module Models
    #
    # Describes a Virtual Machine run command.
    #
    class VirtualMachineRunCommandUpdate < UpdateResource

      include MsRestAzure

      # @return [VirtualMachineRunCommandScriptSource] The source of the run
      # command script.
      attr_accessor :source

      # @return [Array<RunCommandInputParameter>] The parameters used by the
      # script.
      attr_accessor :parameters

      # @return [Array<RunCommandInputParameter>] The parameters used by the
      # script.
      attr_accessor :protected_parameters

      # @return [Boolean] Optional. If set to true, provisioning will complete
      # as soon as the script starts and will not wait for script to complete.
      # Default value: false .
      attr_accessor :async_execution

      # @return [String] Specifies the user account on the VM when executing
      # the run command.
      attr_accessor :run_as_user

      # @return [String] Specifies the user account password on the VM when
      # executing the run command.
      attr_accessor :run_as_password

      # @return [Integer] The timeout in seconds to execute the run command.
      attr_accessor :timeout_in_seconds

      # @return [String] Specifies the Azure storage blob where script output
      # stream will be uploaded.
      attr_accessor :output_blob_uri

      # @return [String] Specifies the Azure storage blob where script error
      # stream will be uploaded.
      attr_accessor :error_blob_uri

      # @return [String] The provisioning state, which only appears in the
      # response.
      attr_accessor :provisioning_state

      # @return [VirtualMachineRunCommandInstanceView] The virtual machine run
      # command instance view.
      attr_accessor :instance_view

      #
      # Mapper for VirtualMachineRunCommandUpdate class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'VirtualMachineRunCommandUpdate',
          type: {
            name: 'Composite',
            class_name: 'VirtualMachineRunCommandUpdate',
            model_properties: {
              tags: {
                client_side_validation: true,
                required: false,
                serialized_name: 'tags',
                type: {
                  name: 'Dictionary',
                  value: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'StringElementType',
                      type: {
                        name: 'String'
                      }
                  }
                }
              },
              source: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.source',
                type: {
                  name: 'Composite',
                  class_name: 'VirtualMachineRunCommandScriptSource'
                }
              },
              parameters: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.parameters',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'RunCommandInputParameterElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'RunCommandInputParameter'
                      }
                  }
                }
              },
              protected_parameters: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.protectedParameters',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'RunCommandInputParameterElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'RunCommandInputParameter'
                      }
                  }
                }
              },
              async_execution: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.asyncExecution',
                default_value: false,
                type: {
                  name: 'Boolean'
                }
              },
              run_as_user: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.runAsUser',
                type: {
                  name: 'String'
                }
              },
              run_as_password: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.runAsPassword',
                type: {
                  name: 'String'
                }
              },
              timeout_in_seconds: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.timeoutInSeconds',
                type: {
                  name: 'Number'
                }
              },
              output_blob_uri: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.outputBlobUri',
                type: {
                  name: 'String'
                }
              },
              error_blob_uri: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.errorBlobUri',
                type: {
                  name: 'String'
                }
              },
              provisioning_state: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.provisioningState',
                type: {
                  name: 'String'
                }
              },
              instance_view: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.instanceView',
                type: {
                  name: 'Composite',
                  class_name: 'VirtualMachineRunCommandInstanceView'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
`appearance` 属性设置导航外观:

* 'default'(默认值) 默认导航。
* 'tabs' 标签式的导航。
* 'subtle' 弱化的导航。

<!--start-code-->

```js
const styles = {
  marginBottom: 50
};

const CustomNav = ({ active, onSelect, ...props }) => {
  return (
    <Nav {...props} activeKey={active} onSelect={onSelect} style={styles}>
      <Nav.Item eventKey="home" icon={<Icon icon="home" />}>
        Home
      </Nav.Item>
      <Nav.Item eventKey="news">News</Nav.Item>
      <Nav.Item eventKey="solutions">Solutions</Nav.Item>
      <Nav.Item eventKey="products">Products</Nav.Item>
      <Nav.Item eventKey="about">About</Nav.Item>
    </Nav>
  );
};

class Demo extends React.Component {
  constructor() {
    super();
    this.state = {
      active: 'home'
    };
    this.handleSelect = this.handleSelect.bind(this);
  }
  handleSelect(activeKey) {
    this.setState({ active: activeKey });
  }
  render() {
    const { active } = this.state;
    return (
      <div>
        <CustomNav active={active} onSelect={this.handleSelect} />
        <CustomNav appearance="tabs" active={active} onSelect={this.handleSelect} />
        <CustomNav appearance="tabs" reversed active={active} onSelect={this.handleSelect} />
        <CustomNav appearance="subtle" active={active} onSelect={this.handleSelect} />
        <CustomNav appearance="subtle" reversed active={active} onSelect={this.handleSelect} />
      </div>
    );
  }
}

ReactDOM.render(<Demo />);
```

<!--end-code-->

> 针对 subtle/tabs 导航,可以设置一个 `reversed` 属性颠倒方向,用来适配导航在上下左右都可以使用。


text:
A view to show bling bling stars when you touch it.

## Demo

![](art/sample.gif)

## Dependency

```groovy
compile('com.liangfeizc:glitterview:1.0.0@aar')
```

## Attributes

|name|format|
|---|---|
|starColor|color|
|maxStarCount|integer|

## Usage

The assumed way to use `GlifferView` is put it above the content view.

For example if you want to draw bling bling stars on an ImageView like the demo above, you xml file would be like this.

*Lay a `GlifferView` above an `ImageView`*:

```xml
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:glitter="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerInside"
        android:src="@drawable/your_image" />

    <com.liangfeizc.glitterview.GlitterView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        glitter:starColor="#ED2727"
        glitter:maxStarCount="250" />

</FrameLayout>
```

## License

    The MIT License (MIT)


text:
#ifndef DATAIO_H
#define	DATAIO_H

// Errors handlers (ON = 1|OFF = 0)
#ifndef E_MEM_EXCEPTION
#define E_MEM_EXCEPTION 0
#endif

#include <stdlib.h>
#include <stdio.h>

/* Data Structures */

// Singly Linked List
typedef struct sl_node {
    int id;
    struct sl_node *next;
} sl_node;

// Doubly linked list
typedef struct dl_node {
    int id;
    struct dl_node *next, *prev;
} dl_node;

// Binary Tree
typedef struct btree_node {
    int id;
    struct btree_node *left, *right;
} btree_node;

/*
 * Functions declarations
 * Sorted alphabetically, each start with same
 * prefix name as the respective data structure
*/

// Singly Linked List
int slIndexOf(sl_node *head, int key);
int slIsEmpty(sl_node *head);
int slSize(sl_node *head);
sl_node *slFind(sl_node *head, int key);
sl_node *slFirst(sl_node *head);
sl_node *slInsert(sl_node *head, int new_id);
sl_node *slInsertAt(sl_node *head, int index, int new_id);
sl_node *slInsertLast(sl_node *head, int new_id);
sl_node *slInsertOrder(sl_node *head, int new_id);
sl_node *slLast(sl_node *head);
sl_node *slRemove(sl_node *head, int key);
sl_node *slRemoveAt(sl_node *head, int index);
sl_node *slSort(sl_node *head);
void slPrint(sl_node *head);

// Doubly linked list

#endif /* DATAIO_H */


text: package bsoncodec


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34209
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace PowerShellTools.Common {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PowerShellTools.Common.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Invalid argument '{0}'.
        /// </summary>
        internal static string ArgumentException_1arg {
            get {
                return ResourceManager.GetString("ArgumentException_1arg", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Exactly one of parameters '{0}' and '{1}' should be specified..
        /// </summary>
        internal static string ValidateExactlyOneSpecifiedFailed_2args {
            get {
                return ResourceManager.GetString("ValidateExactlyOneSpecifiedFailed_2args", resourceCulture);
            }
        }
    }
}


text:
package com.hzp.pedometer.service.step;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;

import com.hzp.pedometer.persistance.file.StepDataStorageManager;
import com.hzp.pedometer.persistance.sp.StepConfigManager;
import com.hzp.pedometer.service.StepCountMode;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 何志鹏 on 2016/1/18.
 * @email hoholiday@hotmail.com
 */
public class StepCountModule implements OnStepCountListener, DataProcessModule.OnDataProcessListener {

    public static final String ACTION_STEP_COUNT = "step_count";
    public static final String KEY_STEP_COUNT = "STEP_COUNT";
    public static final String KEY_STEP_PER_MIN = "STEP_PER_MIN";
    public StepAlgorithm stepAlgorithm;//算法模块
    private Context context;
    private int waveletWindowSize, medianWindowSize;
    private int samplingRate;
    private long samplingInterval; //采样间隔 微秒
    private DataProcessModule dataProcessModule;

    private boolean broadcastEnable = true;//是否开启步数广播

    private int stepPerMin;//步数每分钟
    private int lastStep;//上一次记录的步数
    private int calcRate;//每分钟步数计算间隔 ms

    private long startTime;//管理器计步的开始时间 ms
    private long endTime;//计算结束的时间

    private StepCountMode stepCountMode;

    private ExecutorService executorService;

    public StepCountModule(Context context, StepCountMode stepCountMode) {
        this.context = context;
        this.stepCountMode = stepCountMode;
        setMode(stepCountMode);

        executorService = Executors.newSingleThreadExecutor();

        stepAlgorithm = new StepAlgorithm();
        stepAlgorithm.setStepCountListener(this);

        reset();
    }

    private void reset() {

        stepPerMin = 0;
        lastStep = 0;

        startTime = endTime = 0;

        stepAlgorithm.initConfig();

        waveletWindowSize = StepConfigManager.getInstance().getWaveletWindowSize();
        medianWindowSize = StepConfigManager.getInstance().getMedianWindowSize();
        samplingRate = StepConfigManager.getInstance().getSamplingRate();
        calcRate = (int) ((1000.0 / samplingRate) * waveletWindowSize);
        samplingInterval = 1000 / samplingRate;

        dataProcessModule = new DataProcessModule(medianWindowSize, waveletWindowSize);
        dataProcessModule.setOnDataProcessListener(this);
    }

    /**
     * 开始计步
     * 在inputPoint函数之前调用
     * 否则无法计算
     *
     * @param startTime 开始时间 (毫秒)
     */
    public void start(long startTime) {

        reset();

        this.startTime = startTime;
        this.endTime = this.startTime;
    }

    public long getEndTime() {
        return endTime;
    }

    public void setEndTime(long endTime) {
        this.endTime = endTime;
    }

    public void inputPoint(double x, double y, double z) {
        //直接从内存读入数据进行处理
        dataProcessModule.processData(x, y, z);
    }

    public int inputPoint(String stepDataName) {
        //从文本文件读入处理数据
        try {
            BufferedReader reader = new BufferedReader(
                    new FileReader(
                            context.getFilesDir().getPath() + File.separator + stepDataName));
            if (reader.ready()) {
                //跳过第一行的时间记录
                reader.readLine();
                String data = reader.readLine();
                while (data != null) {
                    //处理数据
                    String[] splits = data.split(" ");
                    double[] temp = {Double.valueOf(splits[0])
                            , Double.valueOf(splits[1])
                            , Double.valueOf(splits[2])};

                    dataProcessModule.processDataSync(temp[0], temp[1], temp[2]);

                    data = reader.readLine();
                }
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getStepCount();
    }

    /**
     * 计算步数每分钟
     */
    private void calcStepPerMin() {
        stepPerMin = (getStepCount() - lastStep) * 60 * 1000 / calcRate;
        lastStep = getStepCount();
    }

    /**
     * 发送包含步数数据的广播
     */
    private void sendStepBroadcast() {
        if (broadcastEnable) {
            Intent intent = new Intent();
            intent.setAction(ACTION_STEP_COUNT);
            intent.putExtra(KEY_STEP_COUNT, getStepCount());
            intent.putExtra(KEY_STEP_PER_MIN, getStepPerMin());
            context.sendBroadcast(intent);
        }
    }

    @Override
    public void onStepCounted(int count) {
        /*empty*/
    }

    /**
     * 获取当前计算的总步数
     */
    public int getStepCount() {
        return stepAlgorithm.stepCount;
    }

    /**
     * 获得每分钟的步行速率
     *
     * @return 步数每分钟
     */
    public int getStepPerMin() {
        return stepPerMin;
    }

    /**
     * 开关步数广播
     */
    public void setBroadcastEnable(boolean enable) {
        broadcastEnable = enable;
    }

    public void setMode(StepCountMode mode) {
        switch (mode) {
            case NORMAL:
                setBroadcastEnable(false);
                break;
            case REAL_TIME:
                setBroadcastEnable(true);
                break;
        }
    }

    @Override
    public void OnDataProcessed(double[] data) {
        switch (stepCountMode) {
            case REAL_TIME:
                calcStepPerMin();
                executorService.submit(new StepCountTask(data, getEndTime()));
                break;
            case NORMAL:
                try {
                    Thread temp = new Thread(new StepCountTask(data, getEndTime()));
                    temp.start();
                    temp.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
        }

    }

    class StepCountTask implements Runnable {
        double[] data;
        long startTime;

        public StepCountTask(double[] data, long startTime) {
            this.data = data;
            this.startTime = startTime;
        }

        @Override
        public void run() {

            int length = data.length;
            for (int i = 0; i < length; i++) {
                setEndTime(getEndTime() + samplingInterval);
                stepAlgorithm.inputPoint(data[i], getEndTime());
            }

            sendStepBroadcast();
        }
    }

}


text:
package com.madewithtea.bottledynamo

import com.twitter.util.{Await, Future}
import io.circe._
import io.circe.generic.auto._
import io.circe.syntax._
import org.scalatest.{FlatSpec, Matchers}

class CirceBaseSpec extends FlatSpec with Matchers {

  case class A(long: Long)

  it should "encode put to KV and get and decode" in {
    val inMemoryKVImpl = new InMemoryKVImpl()
    val tableDef = TableDef("testTable",inMemoryKVImpl)
    val table = new Table[A](tableDef)
    Await.ready(table.create)
    Await.ready(table.put("somekey")(A(1L)))
    Await.result(table.get("somekey")) shouldEqual Some(A(1L))
  }
}


text:
/*
** Revision 1.7 1997/03/17   15:26:00  pmr
** when EST is reversed, need to reverse the EST sequence positions
** also cleaned up long code lines
**
** Revision 1.6  1997/02/10  14:07:54  rmott
** fixed bug so that splice sites in REVERSE direction
** (ie ct/ac rather than gt/ag) are found correctly.
** Output modified so that splice direction is written
**
** Revision 1.4  1997/01/30  17:21:22  rmott
** fixed bug, and now computes area limit better
**
** Revision 1.3  1997/01/30  17:03:45  rmott
** debugged version with debug statements still in.
** Fixed problem of not initialising edge properly
**
** Revision 1.2  1996/08/07  10:12:05  rmott
**
** Linear-Space version
**
** Revision 1.1  1996/08/01  13:55:42  rmott
** Initial revision
**
*/

#include "emboss.h"
#include <math.h>

extern ajint lsimmat[256][256];

#define BOTH 0
#define FORWARD_ONLY 1
#define REVERSE_ONLY 2

ajint verbose;
ajint debug;

static void  est2genome_make_output(AjPFile ofile,
				    const AjPSeq genome, const AjPSeq est,
				    const EmbPEstAlign ge, ajint gap_penalty,
				    ajint intron_penalty,
				    ajint splice_penalty, ajint minscore,
				    ajint align, ajint width, ajint reverse);

/* @prog est2genome ***********************************************************
**
** Align EST and genomic DNA sequences
**
******************************************************************************/

int main(int argc, char **argv)
{
    AjPSeq genome = NULL;
    AjPSeq splice_sites = NULL;
    AjPSeq reversed_splice_sites = NULL;
    AjPSeq est = NULL;
    AjPSeq reversed_est = NULL;
    EmbPEstAlign fge = NULL;
    EmbPEstAlign rge = NULL;
    EmbPEstAlign bge = NULL;
    ajint width = 50;
    ajint match = 1;
    ajint mismatch = 1;
    ajint gap_penalty = 2;
    ajint intron_penalty = 40;
    ajint splice_penalty = 20;
    ajint splice = 1;
    ajint align = 0;
    ajint reverse = 0;
    ajint isreverse = 0;
    ajint doreverse = 0; /* zero for first inclusion, set to 1 later */
    float megabytes = 10.0;
    ajint minscore = 30;
    ajint shuffles = 0;
    ajint max_score = 0;
    ajint seed;
    ajint best=1;
    ajint search_mode;
    AjPStr modestr   = NULL;
    AjPFile outfile  = NULL;
    AjPSeqall estset = NULL;

    /* the fasta input files */

    embInit("est2genome", argc, argv);

    estset  = ajAcdGetSeqall("estsequence");
    genome  = ajAcdGetSeq("genomesequence");
    outfile = ajAcdGetOutfile("outfile");

    /* the alignment penalties */

    match          = ajAcdGetInt("match");
    mismatch       = ajAcdGetInt("mismatch");
    gap_penalty    = ajAcdGetInt("gappenalty");
    intron_penalty = ajAcdGetInt("intronpenalty");
    splice_penalty = ajAcdGetInt("splicepenalty");
    doreverse      = ajAcdGetBoolean("reverse");

    /* the min score for an alignment to be output */
    minscore = ajAcdGetInt("minscore");

    if(doreverse)
	isreverse = 1;

    splice = ajAcdGetBoolean("usesplice");

    /* Print the alignment */
    align = ajAcdGetBoolean("align");
    width = ajAcdGetInt("width");

    /* mode: This is complicated.
    **
    ** "forward"   just search forward strands of both sequences
    ** "reverse"   just search forward of genomic vs reverse of est
    ** "both"      search forward strand of genomic against forward and
    ** reverse
    ** THEN: take the best of these two, and re-align assuming
    ** a reversed gene so that the splice sites would be appear
    ** as ct/ac. Only output the best alignment unless the
    ** flag -nobest is set.
    **
    ** Thus THREE alignments are made.
    **
    ** The output cordinates are such that the genomic sequence
    ** is always in the forward direction.
    */

    modestr = ajAcdGetListSingle("mode");

    if(ajStrMatchC(modestr,"both"))
	search_mode = BOTH;
    else if(ajStrMatchC(modestr,"forward"))
	search_mode = FORWARD_ONLY;
    else if(ajStrMatchC(modestr,"reverse"))
	search_mode = REVERSE_ONLY;
    else
    {
	ajErr("search mode %S must be one of: "
	      "both, forward, reverse\n", modestr);
	exit(1);
    }

    /* just print the best alignment ? */

    best = ajAcdGetBoolean("best");

    /* max space in megabytes */

    megabytes = ajAcdGetFloat("space");

    /* print debugging info */

    verbose = ajAcdGetBoolean("verbose");
    debug = ajAcdGetBoolean("debug");

    if(verbose)
	ajDebug("debugging set to %d\n", debug);

    if(verbose)
	embEstSetVerbose();
    if(debug)
	embEstSetDebug();

    /*
    ** shuffle the sequences to test for statistical
    ** significance this many times
    */

    shuffles = ajAcdGetInt("shuffle");
    seed = ajAcdGetInt("seed");

    if(!seed)
	seed = embEstGetSeed();
    seed = -seed;

    if(mismatch < 0)
	mismatch = -mismatch;
    if(gap_penalty < 0)
	gap_penalty = -gap_penalty;
    if(intron_penalty < 0)
	intron_penalty = -intron_penalty;
    if(splice_penalty < 0)
	splice_penalty = -splice_penalty;

    embEstMatInit(match, mismatch, gap_penalty, 0, '-');

    ajSeqTrim(genome);

    /* Make sure theres enough space to hold the genomic AjPSeq */

    if(megabytes < ajSeqGetLen(genome)*1.5e-6)
    {
	ajWarn("increasing space from %.3f to %.3f Mb\n",
	       megabytes, 1.5e-6*ajSeqGetLen(genome));
	megabytes = (float)1.5e-6*ajSeqGetLen(genome);
    }

    /* find the GT/AG splice sites */

    if(splice)
	splice_sites = embEstFindSpliceSites(genome, 1);
    else
	splice_sites = NULL;

    if(search_mode == BOTH && splice)
	reversed_splice_sites = embEstFindSpliceSites( genome, 0 );
    else
	reversed_splice_sites = NULL;

    /* process each est */

    while(ajSeqallNext(estset, &est))
    {
	/*
	 ** if required, make shuffled comparisons
	 ** to get statistical significance
	 */
	ajSeqTrim(est);

	ajDebug("shuffles: %d\n", shuffles);
	if(shuffles > 0)
	{
	    AjPSeq shuffled_est;
	    ajint n;
	    ajint score;
	    double mean = 0;
	    double std  = 0;
	    EmbPEstAlign sge;

	    shuffled_est = ajSeqNewSeq(est);

	    for(n=0;n<shuffles;n++)
	    {
		embEstShuffleSeq(shuffled_est, 1, &seed);
		sge = embEstAlignNonRecursive(shuffled_est,
					      genome,
					      gap_penalty,
					      intron_penalty,
					      splice_penalty,
					      splice_sites, 0, 0,
					      DIAGONAL);
		score = sge->score;
		ajDebug("%30.30S\n", ajSeqGetSeqS(shuffled_est));
		ajDebug("%5d score %d seed %d\n", n, score, seed);
		if(score > max_score)
		    max_score = score;
		mean += score;
		std += score*score;
		embEstFreeAlign(&sge);
	    }

	    mean /= shuffles;
	    std = sqrt((std = shuffles*mean*mean)/(shuffles-1.0));
	    ajDebug("shuffles: %d max: %d mean: %.2f std dev: %.2f\n",
		    shuffles, max_score, mean, std);
	    minscore = max_score+1;
	    ajSeqDel(&shuffled_est);
	}

	if(search_mode != REVERSE_ONLY)
	{
	    /* forward strand */
	    fge = embEstAlignLinearSpace(est, genome, match,
					 mismatch, gap_penalty,
					 intron_penalty, splice_penalty,
					 splice_sites, megabytes);
	    if(!fge)
		ajFatal("forward strand alignment failed");
	}
	else
	    fge = NULL;

	if(search_mode != FORWARD_ONLY) /* reverse strand */
	{
	    reversed_est = ajSeqNewSeq(est);
	    ajSeqReverseForce(reversed_est);

	    rge = embEstAlignLinearSpace(reversed_est, genome,
					 match, mismatch, gap_penalty,
					 intron_penalty, splice_penalty,
					 splice_sites, megabytes);
	    if(!rge)
		ajFatal("reverse strand alignment failed");
	}
	else
	    rge = NULL;

	if(search_mode == BOTH)	/* search both strands */
	{
	    if(fge->score > rge->score)
	    {			/* redo forward search with
				   reversed splice sites */
		bge = embEstAlignLinearSpace(est, genome, match,
					     mismatch, gap_penalty,
					     intron_penalty,
					     splice_penalty,
					     reversed_splice_sites,
					     megabytes);

		if(bge->score > fge->score) /* probably have a
					       reversed gene */
		{
		    ajFmtPrintF(outfile,
				"Note Best alignment is between forward "
				"est and forward genome, but splice "
				"sites imply REVERSED GENE\n");
		    est2genome_make_output(outfile, genome, est, bge,
					   gap_penalty,
					   intron_penalty, splice_penalty,
					   minscore, align, width,
					   reverse);

		    if(best == 0)	/* print substandard alignment too */
			est2genome_make_output(outfile, genome, est, fge,
					       gap_penalty, intron_penalty,
					       splice_penalty, minscore,
					       align, width, reverse);
		}
		else
		{
		    ajFmtPrintF(outfile,
				"Note Best alignment is between forward "
				"est and forward genome, and splice "
				"sites imply forward gene\n");
		    est2genome_make_output(outfile, genome, est, fge,
					   gap_penalty, intron_penalty,
					   splice_penalty, minscore,
					   align, width, reverse);
		    if(best == 0)
			est2genome_make_output(outfile, genome, est, bge,
					       gap_penalty, intron_penalty,
					       splice_penalty, minscore,
					       align, width, reverse);
		}
	    }
	    else
	    {
		bge = embEstAlignLinearSpace(reversed_est,genome,
					     match, mismatch,
					     gap_penalty,
					     intron_penalty,
					     splice_penalty,
					     reversed_splice_sites,
					     megabytes);

		if(bge->score > rge->score) /* probably have a
					       reversed gene */
		{
		    ajFmtPrintF(outfile,
				"Note Best alignment is between "
				"reversed est and forward genome, but "
				"splice sites imply REVERSED GENE\n");
		    est2genome_make_output(outfile, genome, reversed_est,
					   bge, gap_penalty, intron_penalty,
					   splice_penalty, minscore,
					   align, width, isreverse);
		    if(best == 0)	/* print substandard alignment too */
			est2genome_make_output(outfile, genome,
					       reversed_est, rge, gap_penalty,
					       intron_penalty,
					       splice_penalty, minscore,
					       align, width, isreverse);
		}
		else
		{
		    ajFmtPrintF(outfile,
				"Note Best alignment is between reversed "
				"est and forward genome, and splice "
				"sites imply forward gene\n");
		    est2genome_make_output(outfile, genome, reversed_est,
					   rge, gap_penalty, intron_penalty,
					   splice_penalty, minscore,
					   align, width, isreverse);

		    if(best == 0)
			est2genome_make_output(outfile, genome,
					       reversed_est, bge,
					       gap_penalty, intron_penalty,
					       splice_penalty, minscore,
					       align, width, isreverse);
		}
	    }
	}
	else if(search_mode == FORWARD_ONLY)
	{
	    ajFmtPrintF(outfile,
			"Note requested forward est and forward genome\n");
	    est2genome_make_output(outfile, genome, est, fge,
				   gap_penalty, intron_penalty,
				   splice_penalty, minscore,
				   align, width, reverse);
		if(best == 0)
		    est2genome_make_output(outfile, genome, est, bge,
					   gap_penalty, intron_penalty,
					   splice_penalty, minscore,
					   align, width, reverse);
	    }

	else if(search_mode == REVERSE_ONLY)
	{
	    ajFmtPrintF(outfile,"Note requested reversed est and "
			"forward genome\n");
	    est2genome_make_output(outfile, genome, reversed_est,
				   rge, gap_penalty, intron_penalty,
				   splice_penalty, minscore,
				   align, width, isreverse);
	    if( best == 0 )
		est2genome_make_output(outfile, genome,
				       reversed_est, bge, gap_penalty,
				       intron_penalty,
				       splice_penalty, minscore,
				       align, width, isreverse);
	}

	embEstFreeAlign(&bge);
	embEstFreeAlign(&rge);
	embEstFreeAlign(&fge);

	/* ajSeqDel(&est); */ /* Clone from seqall: Don't delete */
	ajSeqDel(&reversed_est);
    }

    ajSeqDel(&splice_sites);

    ajSeqDel(&reversed_splice_sites);

    ajSeqDel(&genome);
    ajSeqallDel(&estset);
    ajSeqDel(&est);
    ajFileClose(&outfile);
    ajStrDel(&modestr);

    embExit();

    return 0;
}

/* @funcstatic est2genome_make_output *****************************************
**
** Undocumented.
**
** @param [u] ofile [AjPFile] Undocumented
** @param [r] genome [const AjPSeq] Undocumented
** @param [r] est [const AjPSeq] Undocumented
** @param [r] ge [const EmbPEstAlign] Undocumented
** @param [r] gap_penalty [ajint] Undocumented
** @param [r] intron_penalty [ajint] Undocumented
** @param [r] splice_penalty [ajint] Undocumented
** @param [r] minscore [ajint] Undocumented
** @param [r] align [ajint] Undocumented
** @param [r] width [ajint] Undocumented
** @param [r] reverse [ajint] Undocumented
** @@
******************************************************************************/

static void est2genome_make_output(AjPFile ofile,
				   const AjPSeq genome, const AjPSeq est,
				   const EmbPEstAlign ge, ajint gap_penalty,
				   ajint intron_penalty, ajint splice_penalty,
				   ajint minscore, ajint align, ajint width,
				   ajint reverse)
{

    if(ge->score >= minscore)
    {
	embEstOutBlastStyle(ofile, genome, est, ge,
			    gap_penalty,
			    intron_penalty, splice_penalty, 1, reverse );
	ajFmtPrintF( ofile, "\n");
	embEstOutBlastStyle(ofile, genome, est, ge,
			    gap_penalty,
			    intron_penalty, splice_penalty, 0, reverse);

	if(align)
	{
	    ajFmtPrintF(ofile, "\n\n%s vs %s:\n",
			ajSeqGetNameC(genome), ajSeqGetNameC(est));
	    embEstPrintAlign(ofile, genome, est, ge, width);
	}
    }

    return;
}


text:
extern java::lang::Class *class_(const char16_t *c, int n);

java::lang::Class* poi::ss::formula::eval::NumericValueEval::class_()
{
    static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.eval.NumericValueEval", 47);
    return c;
}


text:
using System;
using Newtonsoft.Json;

namespace Clubhouse.io.net.Entities.Stories
{
    public class ClubhouseCreateCommentParams
    {
        [JsonProperty(PropertyName = "author_id")]
        public Guid AuthorID { get; set; }

        [JsonProperty(PropertyName = "created_at")]
        public DateTime CreatedAt { get; set; }

        [JsonProperty(PropertyName = "external_id")]
        public string ExternalID { get; set; }

        [JsonProperty(PropertyName = "text", Required = Required.Always)]
        public string Text { get; set; }

        [JsonProperty(PropertyName = "updated_at")]
        public DateTime? UpdatedAt { get; set; }
    }
}


text:
"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.

Script for building docker image. This is expected to run inside container.
"""

import json
import logging
import tempfile
import signal
import docker

from atomic_reactor.build import InsideBuilder
from atomic_reactor.plugin import (
    AutoRebuildCanceledException,
    BuildCanceledException,
    BuildStepPluginsRunner,
    ExitPluginsRunner,
    InputPluginsRunner,
    PluginFailedException,
    PostBuildPluginsRunner,
    PreBuildPluginsRunner,
    PrePublishPluginsRunner,
)
from atomic_reactor.source import get_source_instance_for
from atomic_reactor.constants import INSPECT_ROOTFS, INSPECT_ROOTFS_LAYERS
from atomic_reactor.util import ImageName
from atomic_reactor.build import BuildResult
from atomic_reactor import get_logging_encoding

logger = logging.getLogger(__name__)

class BuildResults(object):
    build_logs = None
    dockerfile = None
    built_img_inspect = None
    built_img_info = None
    base_img_inspect = None
    base_img_info = None
    base_plugins_output = None
    built_img_plugins_output = None
    container_id = None
    return_code = None

class BuildResultsEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, BuildResults):
            return {
                'build_logs': obj.build_logs,
                'built_img_inspect': obj.built_img_inspect,
                'built_img_info': obj.built_img_info,
                'base_img_info': obj.base_img_info,
                'base_plugins_output': obj.base_plugins_output,
                'built_img_plugins_output': obj.built_img_plugins_output,
            }
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)

class BuildResultsJSONDecoder(json.JSONDecoder):
    def decode(self, obj):
        d = super(BuildResultsJSONDecoder, self).decode(obj)
        results = BuildResults()
        results.built_img_inspect = d.get('built_img_inspect', None)
        results.built_img_info = d.get('built_img_info', None)
        results.base_img_info = d.get('base_img_info', None)
        results.base_plugins_output = d.get('base_plugins_output', None)
        results.built_img_plugins_output = d.get('built_img_plugins_output', None)
        return results

class TagConf(object):
    """
    confguration of image names and tags to be applied
    """

    def __init__(self):
        # list of ImageNames with predictable names
        self._primary_images = []
        # list if ImageName instances with unpredictable names
        self._unique_images = []

    @property
    def primary_images(self):
        """
        primary image names are predictable and should be used for layering

        this is consumed by metadata plugin

        :return: list of ImageName
        """
        return self._primary_images

    @property
    def images(self):
        """
        list of all ImageNames

        :return: list of ImageName
        """
        return self._primary_images + self._unique_images

    @property
    def unique_images(self):
        """
        unique image names are unpredictable and should be used for tracking only

        this is consumed by metadata plugin

        :return: list of ImageName
        """
        return self._unique_images

    def add_primary_image(self, image):
        """
        add new primary image

        used by tag_by_labels plugin

        :param image: str, name of image (e.g. "namespace/httpd:2.4")
        :return: None
        """
        self._primary_images.append(ImageName.parse(image))

    def add_unique_image(self, image):
        """
        add image with unpredictable name

        used by tag_by_labels plugin

        :param image: str, name of image (e.g. "namespace/httpd:2.4")
        :return: None
        """
        self._unique_images.append(ImageName.parse(image))

    def add_primary_images(self, images):
        """
        add new primary images in bulk

        used by tag_by_labels plugin

        :param images: list of str, list of image names
        :return: None
        """
        for image in images:
            self.add_primary_image(image)

class Registry(object):
    def __init__(self, uri, insecure=False):
        """
        abstraction for all registry classes

        :param uri: str, uri for pulling (in case of docker-registry, pushing too)
        :param insecure: bool
        """
        self.uri = uri
        self.insecure = insecure

class PulpRegistry(Registry):
    """ pulp & crane """
    def __init__(self, name, crane_uri, insecure=False):
        """
        :param name: str, pulp's rest api is specified in dockpulp's config, we refer only by name
        :param crane_uri: str, read-only docker registry api access point
        :param insecure: bool
        """
        super(PulpRegistry, self).__init__(crane_uri, insecure=insecure)
        self.name = name

        # True if we've synced an image to the pulp repository using the
        # docker protocol - and thus can support retrieving manifests
        # via the v2 api.
        self.server_side_sync = False

class DockerRegistry(Registry):
    """ v1/v2 docker registry """
    def __init__(self, uri, insecure=False):
        """
        :param uri: str, uri for pushing/pulling
        :param insecure: bool
        """
        super(DockerRegistry, self).__init__(uri, insecure=insecure)
        self.digests = {}  # maps tags (str) to their digest, if available
        self.config = None  # stores image config from the registry,
        # media type of the config is application/vnd.docker.container.image.v1+json

class PushConf(object):
    """
    configuration of remote registries: docker-registry or pulp
    """

    def __init__(self):
        self._registries = {
            "docker": [],
            "pulp": {},  # name -> PulpRegistry
        }

    def add_docker_registry(self, registry_uri, insecure=False):
        if registry_uri is None:
            raise RuntimeError("registry URI cannot be None")
        r = DockerRegistry(registry_uri, insecure=insecure)
        self._registries["docker"].append(r)
        return r

    def add_docker_registries(self, registry_uris, insecure=False):
        for registry_uri in registry_uris:
            self.add_docker_registry(registry_uri, insecure=insecure)

    def remove_docker_registry(self, docker_registry):
        self._registries["docker"].remove(docker_registry)

    def add_pulp_registry(self, name, crane_uri, server_side_sync=True):
        if crane_uri is None:
            raise RuntimeError("registry URI cannot be None")

        old_registry = self._registries["pulp"].get(name)
        if old_registry is not None:
            if crane_uri != old_registry.uri:
                raise RuntimeError("Conflicting Pulp registries with name: %s" % name)
            # Merge
            if server_side_sync:
                old_registry.server_side_sync = True
            return old_registry

        r = PulpRegistry(name, crane_uri)
        r.server_side_sync = server_side_sync
        self._registries["pulp"][name] = r
        return r

    @property
    def has_some_docker_registry(self):
        return len(self.docker_registries) > 0

    @property
    def docker_registries(self):
        return self._registries["docker"]

    @property
    def pulp_registries(self):
        return [registry for registry in self._registries["pulp"].values()]

    @property
    def all_registries(self):
        return self.docker_registries + self.pulp_registries

class DockerBuildWorkflow(object):
    """
    This class defines a workflow for building images:

    1. pull image from registry
    2. tag it properly if needed
    3. obtain source
    4. build image
    5. tag it
    6. push it to registries
    """

    def __init__(self, source, image, prebuild_plugins=None, prepublish_plugins=None,
                 postbuild_plugins=None, exit_plugins=None, plugin_files=None,
                 openshift_build_selflink=None, client_version=None,
                 buildstep_plugins=None, **kwargs):
        """
        :param source: dict, where/how to get source code to put in image
        :param image: str, tag for built image ([registry/]image_name[:tag])
        :param prebuild_plugins: dict, arguments for pre-build plugins
        :param prepublish_plugins: dict, arguments for test-build plugins
        :param postbuild_plugins: dict, arguments for post-build plugins
        :param plugin_files: list of str, load plugins also from these files
        :param openshift_build_selflink: str, link to openshift build (if we're actually running
            on openshift) without the actual hostname/IP address
        :param client_version: str, osbs-client version used to render build json
        :param buildstep_plugins: dict, arguments for build-step plugins
        """
        self.source = get_source_instance_for(source, tmpdir=tempfile.mkdtemp())
        self.image = image

        self.prebuild_plugins_conf = prebuild_plugins
        self.buildstep_plugins_conf = buildstep_plugins
        self.prepublish_plugins_conf = prepublish_plugins
        self.postbuild_plugins_conf = postbuild_plugins
        self.exit_plugins_conf = exit_plugins
        self.prebuild_results = {}
        self.buildstep_result = {}
        self.postbuild_results = {}
        self.prepub_results = {}
        self.exit_results = {}
        self.build_result = BuildResult(fail_reason="not built")
        self.plugin_workspace = {}
        self.plugins_timestamps = {}
        self.plugins_durations = {}
        self.plugins_errors = {}
        self.autorebuild_canceled = False
        self.build_canceled = False
        self.plugin_failed = False
        self.plugin_files = plugin_files

        self.kwargs = kwargs

        self.builder = None
        self.built_image_inspect = None
        self.layer_sizes = []
        self._base_image_inspect = None

        self.pulled_base_images = set()

        # When an image is exported into tarball, it can then be processed by various plugins.
        #  Each plugin that transforms the image should save it as a new file and append it to
        #  the end of exported_image_sequence. Other plugins should then operate with last
        #  member of this structure. Example:
        #  [{'path': '/tmp/foo.tar', 'size': 12345678, 'md5sum': '<md5>', 'sha256sum': '<sha256>'}]
        #  You can use util.get_exported_image_metadata to create a dict to append to this list.
        self.exported_image_sequence = []

        self.tag_conf = TagConf()
        self.push_conf = PushConf()

        # mapping of downloaded files; DON'T PUT ANYTHING BIG HERE!
        # "path/to/file" -> "content"
        self.files = {}

        self.openshift_build_selflink = openshift_build_selflink

        # List of RPMs that go into the final result, as per rpm_util.parse_rpm_output
        self.image_components = None

        if client_version:
            logger.debug("build json was built by osbs-client %s", client_version)

        if kwargs:
            logger.warning("unprocessed keyword arguments: %s", kwargs)

    @property
    def build_process_failed(self):
        """
        Has any aspect of the build process failed?
        """
        return self.build_result.is_failed() or self.plugin_failed

    # inspect base image lazily just before it's needed - pre plugins may change the base image
    @property
    def base_image_inspect(self):
        if self._base_image_inspect is None:
            try:
                self._base_image_inspect = self.builder.tasker.inspect_image(
                    self.builder.base_image)
            except docker.errors.NotFound:
                # If the base image cannot be found throw KeyError - as this property should behave
                # like a dict
                raise KeyError("Unprocessed base image Dockerfile cannot be inspected")
        return self._base_image_inspect

    def throw_canceled_build_exception(self, *args, **kwargs):
        self.build_canceled = True
        raise BuildCanceledException("Build was canceled")

    def build_docker_image(self):
        """
        build docker image

        :return: BuildResult
        """
        self.builder = InsideBuilder(self.source, self.image)
        try:
            signal.signal(signal.SIGTERM, self.throw_canceled_build_exception)
            # time to run pre-build plugins, so they can access cloned repo
            logger.info("running pre-build plugins")
            prebuild_runner = PreBuildPluginsRunner(self.builder.tasker, self,
                                                    self.prebuild_plugins_conf,
                                                    plugin_files=self.plugin_files)
            try:
                prebuild_runner.run()
            except PluginFailedException as ex:
                logger.error("one or more prebuild plugins failed: %s", ex)
                raise
            except AutoRebuildCanceledException as ex:
                logger.info(str(ex))
                self.autorebuild_canceled = True
                raise

            logger.info("running buildstep plugins")
            buildstep_runner = BuildStepPluginsRunner(self.builder.tasker, self,
                                                      self.buildstep_plugins_conf,
                                                      plugin_files=self.plugin_files)
            try:
                self.build_result = buildstep_runner.run()

                if self.build_result.is_failed():
                    raise PluginFailedException(self.build_result.fail_reason)
            except PluginFailedException as ex:
                self.builder.is_built = False
                logger.error('buildstep plugin failed: %s', ex)
                raise

            self.builder.is_built = True
            if self.build_result.is_image_available():
                self.builder.image_id = self.build_result.image_id

            # run prepublish plugins
            prepublish_runner = PrePublishPluginsRunner(self.builder.tasker, self,
                                                        self.prepublish_plugins_conf,
                                                        plugin_files=self.plugin_files)
            try:
                prepublish_runner.run()
            except PluginFailedException as ex:
                logger.error("one or more prepublish plugins failed: %s", ex)
                raise

            if self.build_result.is_image_available():
                self.built_image_inspect = self.builder.inspect_built_image()
                history = self.builder.tasker.d.history(self.builder.image_id)
                diff_ids = self.built_image_inspect[INSPECT_ROOTFS][INSPECT_ROOTFS_LAYERS]

                # diff_ids is ordered oldest first
                # history is ordered newest first
                # We want layer_sizes to be ordered oldest first
                self.layer_sizes = [{"diff_id": diff_id, "size": layer['Size']}
                                    for (diff_id, layer) in zip(diff_ids, reversed(history))]

            postbuild_runner = PostBuildPluginsRunner(self.builder.tasker, self,
                                                      self.postbuild_plugins_conf,
                                                      plugin_files=self.plugin_files)
            try:
                postbuild_runner.run()
            except PluginFailedException as ex:
                logger.error("one or more postbuild plugins failed: %s", ex)
                raise

            return self.build_result
        except Exception as ex:
            logger.debug("caught exception (%r) so running exit plugins", ex)
            raise
        finally:
            # We need to make sure all exit plugins are executed
            signal.signal(signal.SIGTERM, lambda *args: None)
            exit_runner = ExitPluginsRunner(self.builder.tasker, self,
                                            self.exit_plugins_conf,
                                            plugin_files=self.plugin_files)
            try:
                exit_runner.run(keep_going=True)
            except PluginFailedException as ex:
                logger.error("one or more exit plugins failed: %s", ex)
                raise
            finally:
                self.source.remove_tmpdir()

            signal.signal(signal.SIGTERM, signal.SIG_DFL)

def build_inside(input_method, input_args=None, substitutions=None):
    """
    use requested input plugin to load configuration and then initiate build
    """
    def process_keyvals(keyvals):
        """ ["key=val", "x=y"] -> {"key": "val", "x": "y"} """
        keyvals = keyvals or []
        processed_keyvals = {}
        for arg in keyvals:
            key, value = arg.split("=", 1)
            processed_keyvals[key] = value
        return processed_keyvals

    main = __name__.split('.', 1)[0]
    log_encoding = get_logging_encoding(main)
    logger.info("log encoding: %s", log_encoding)

    if not input_method:
        raise RuntimeError("No input method specified!")
    else:
        logger.debug("getting build json from input %s", input_method)

        cleaned_input_args = process_keyvals(input_args)
        cleaned_subs = process_keyvals(substitutions)

        cleaned_input_args['substitutions'] = cleaned_subs

        input_runner = InputPluginsRunner([{'name': input_method,
                                            'args': cleaned_input_args}])
        build_json = input_runner.run()[input_method]
        logger.debug("build json: %s", build_json)
    if not build_json:
        raise RuntimeError("No valid build json!")
    # TODO: validate json
    dbw = DockerBuildWorkflow(**build_json)
    build_result = dbw.build_docker_image()
    if not build_result or build_result.is_failed():
        raise RuntimeError("no image built")
    else:
        logger.info("build has finished successfully \o/")


text:
package me.donniesky.dailypaper.common.injection.module;

import android.content.Context;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import me.donniesky.dailypaper.common.injection.qualifier.ApplicationContext;
import me.donniesky.dailypaper.data.model.TopicModel;

/**
 * Created by Mysim on 2016/6/27.
 */
@Module(includes = AppModule.class)
public class ApiModule {

    @Provides
    @Singleton
    TopicModel provideTopicModel(@ApplicationContext Context context){
        return new TopicModel(context);
    }

}


text:
[![Fruit][logo]][repo-link]

[![CI Buimd][build-image]][build-url]
[![Dependencied][dependencies-image]][dependencies-url]
[![MIT license][license-img]][license-url]
[![Gitter][gitter-img]][gitter-url]

### Introduction:

This is the global package that contains both the [fruit](http://npmjs.com/package/fruit) ORM module and all its available adapters. If you haven't take a look at its documentation yet, please make sure to do so.

### Installation:
```bash
  $ npm install fruits
```

### How does it work:

Once you require the fruits module :
```javascript
  var fruits = require('fruits');
```

You can get the fruit constructor :
```javascript
  var Fruit = fruits.fruit;
```

You can also get the available adapters :
```javascript
  var mongoAdapter    = fruits.adapters.mongodb
    , mysqlAdapter    = fruits.adapters.mysql
    , postgresAdapter = fruits.adapters.postgresql
```

### Contributing

All contributions are welcome. Let's get this project to the next level.
Significant and valuable contributions will allow you to be part of [Fruit organisation](http://github.com/nodefruit).
See the [contribution guide](http://github.com/nodefruit/fruit/blob/master/CONTRIBUTING.md) for more details

### Community

If you'd like to chat and discuss this project, you can find us here:

- Mailing list: [https://groups.google.com/forum/#!forum/nodefruit](https://groups.google.com/forum/#!forum/nodefruit)
- [![Join the chat at https://gitter.im/nodefruit/fruit](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/nodefruit/fruit?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

[logo]: https://github.com/nodefruit/fruits/raw/master/pres/logo.png
[repo-link]: https://github.com/nodefruit/fruits
[build-image]: https://api.travis-ci.org/nodefruit/fruits.svg
[build-url]: https://github.com/nodefruit/fruits
[stability-image]: https://img.shields.io/badge/stability-experimental-orange.svg
[stability-url]: https://github.com/nodefruit/fruits
[license-img]: https://img.shields.io/badge/license-MIT-green.svg
[license-url]: https://github.com/nodefruit/fruits/blob/master/LICENSE
[dependencies-image]:https://david-dm.org/nodefruit/fruits.svg
[dependencies-url]:https://npmjs.com/package/fruits
[gitter-img]: https://badges.gitter.im/Join%20Chat.svg
[gitter-url]: https://gitter.im/nodefruit/fruit?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge


text:
using namespace std;
using namespace Eigen;

#include "sim.h"

int main(int argc, char* argv[]) {

  // Default values

  int num_dims = 2;
  int num_atoms = 16;

  float box_length = 4.0;

  float vel_width = 0.1;
  float vel_max = 10 * vel_width; // if this is too high, lots of rejections

  float t_step = 0.004;
  int num_t_steps = 1000;

  char* bc_type_ptr;
  char bc_type = 't'; // Toroidal Boundary Conditions

  char* force_type_ptr;
  char force_type = 'l'; // Lennard-Jones

  float cutoff = 0.0;

  string filename = "moldy_argon.json";

  // Iterate over argv[] to get the parameters stored inside.
  for (int i = 1; i < argc; i++) {
    // Check that we haven't finished parsing already
    if (i + 1 != argc) {
      if (string(argv[i]) == "--num-dims")
        num_dims = atoi(argv[i+1]);
      else if (string(argv[i]) == "--num-atoms")
        num_atoms = atoi(argv[i+1]);
      else if (string(argv[i]) == "--box-length")
        box_length = atof(argv[i+1]);
      else if (string(argv[i]) == "--vel-width")
        vel_width = atof(argv[i+1]);
      else if (string(argv[i]) == "--t-step") // Time step
        t_step = atof(argv[i+1]);
      else if (string(argv[i]) == "--num-t-steps") // Number of time steps
        num_t_steps = atoi(argv[i+1]);
      else if (string(argv[i]) == "--bc-type") {// Boundary condition type
        bc_type_ptr = argv[i+1];
        bc_type = *bc_type_ptr;
      }
      else if (string(argv[i]) == "--force-type") { // Force type
        force_type_ptr = argv[i+1];
        force_type = *force_type_ptr;
      }
      else if (string(argv[i]) == "--cutoff")
        cutoff = atof(argv[i+1]);
      else if (string(argv[i]) == "--filename")
        filename = argv[i+1];
    }
  }

  cout << "Num dims: " << num_dims << endl;
  cout << "Num atoms: " << num_atoms << endl;
  cout << "Box length: " << box_length << endl;
  cout << "Vel width:" << vel_width << endl;
  cout << "Time step: " << t_step << endl;
  cout << "Num time steps: " << num_t_steps << endl;
  cout << "BC Type: " << bc_type << endl;
  cout << "Force Type: " << force_type << endl;
  cout << "Cutoff: " << cutoff << endl;
  cout << "Filename: " << filename << endl;

  Sim sim(box_length, num_dims, num_atoms);

  // Seed random number generator for MB dist
  srand(time(NULL));

  // Assign positions
  // sim.set_atoms_pos_random_in_box();
  // sim.get_atoms()->set_pos_random_min(box_length, 1.25);
  sim.get_atoms()->set_pos_lattice(box_length);

  // Assign velocities, Maxwell-Boltzmann distribution
  sim.set_atoms_vel_mb(vel_width, vel_max);

  sim.run(num_t_steps, t_step, bc_type, force_type, cutoff, filename);

  return 0;

}


text:
require 'tmpdir'

shared_context :uses_tmp_dir do
  around do |example|
    Dir.mktmpdir('schrank-rspec-') do |dir|
      @tmp_dir = dir
      example.run
    end
  end

  attr_reader :tmp_dir
end


text:
<!DOCTYPE html>
    <meta charset="utf-8">
    <title>のフォグ</title>
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:site" content="@threejs">
    <meta name="twitter:title" content="Three.js – のフォグ">
    <meta property="og:image" content="https://threejs.org/files/share.png">
    <link rel="shortcut icon" href="/files/favicon_white.ico" media="(prefers-color-scheme: dark)">
    <link rel="shortcut icon" href="/files/favicon.ico" media="(prefers-color-scheme: light)">

    <link rel="stylesheet" href="/manual/resources/lesson.css">
    <link rel="stylesheet" href="/manual/resources/lang.css">

のフォグ

この記事はThree.jsの連載記事の1つです。
最初の記事はThree.jsの基礎知識です。
まだ読んでいない場合、そこから始めると良いかもしれません。
カメラの記事を読んでない方は、まずはこの記事を読んでみて下さい。

一般的には3Dエンジンでのフォグ(霧)は、カメラからの距離によって特定の色にフェードアウトする方法です。
three.jsでは Fog または FogExp2 オブジェクトを作成し、シーンにfog プロパティを設定してフォグを追加します。

Fog はカメラからの距離を表す near と far があります。
near よりも近いものはフォグの影響を受けません。
far より遠いものはフォグの影響を受けます。
near と far の中間部分では、マテリアルの色からフォグの色にグラデーションします。

また、カメラからの距離で急激にグラデーションする FogExp2 もあります。

どちらのタイプのフォグも使用するにはフォグを作成してシーンに割り当てます。

const scene = new THREE.Scene();
{
  const color = 0xFFFFFF;  // white
  const near = 10;
  const far = 100;
  scene.fog = new THREE.Fog(color, near, far);
}

FogExp2 の場合は次のようなコードになります。

const scene = new THREE.Scene();
{
  const color = 0xFFFFFF;
  const density = 0.1;
  scene.fog = new THREE.FogExp2(color, density);
}

FogExp2 は現実表現に近いですが、Fog の方が一般的によく使われています。
Fogは適用する場所を選択できるので、ある距離まではクリアなシーンを表示し、その距離を過ぎるとフェードアウトした色にできます。

THREE.Fog

THREE.FogExp2

ここで注意すべき点は、フォグは レンダリングされる ものに適用される事です。
以下はオブジェクトの色の各ピクセルの計算の一部です。
つまり、シーンを特定の色にフェードさせたい場合、フォグ と 背景色を同じ色に設定します。
背景色は scene.background プロパティで設定します。
背景色は THREE.Color で指定します。例えば

scene.background = new THREE.Color('#F00');  // red

fog blue, background red

fog blue, background blue

以下はフォグを追加した例です。
シーンにフォグを追加し背景色を設定します。

const scene = new THREE.Scene();

+{
+  const near = 1;
+  const far = 2;
+  const color = 'lightblue';
+  scene.fog = new THREE.Fog(color, near, far);
+  scene.background = new THREE.Color(color);
+}

以下の例ではカメラの near は 0.1、far は 5です。
カメラは z = 2 にあります。
立方体は1の大きさで z = 0 です。
つまり、フォグを near = 1 と far = 2 と設定し、立方体の中心付近でフェードアウトしています。

  ここをクリックして別のウィンドウで開きます

フォグを調整するインターフェースを追加してみましょう。
ここでもlil-guiを使用します。
lil-guiはオブジェクトとプロパティを受け取り、インタフェースを自動生成します。
これでフォグの near と far プロパティを簡単に操作できます。
しかし、 near が far より大きい場合は無効になります。
lil-guiで near と far を操作するヘルパーを作ってみましょう。

// We use this class to pass to lil-gui
// so when it manipulates near or far
// near is never > far and far is never < near
class FogGUIHelper {
  constructor(fog) {
    this.fog = fog;
  }
  get near() {
    return this.fog.near;
  }
  set near(v) {
    this.fog.near = v;
    this.fog.far = Math.max(this.fog.far, v);
  }
  get far() {
    return this.fog.far;
  }
  set far(v) {
    this.fog.far = v;
    this.fog.near = Math.min(this.fog.near, v);
  }
}

次のコードを追加します。

{
  const near = 1;
  const far = 2;
  const color = 'lightblue';
  scene.fog = new THREE.Fog(color, near, far);
  scene.background = new THREE.Color(color);
+
+  const fogGUIHelper = new FogGUIHelper(scene.fog);
+  gui.add(fogGUIHelper, 'near', near, far).listen();
+  gui.add(fogGUIHelper, 'far', near, far).listen();
}

near と far のパラメーターは、フォグを調整する最小値と最大値を設定します。
これはカメラ設定時にセットします。

最後の2行の .listen() をlil-guiに変更し  listen するようにします。
これで near や far の変更時、lil-guiが他のプロパティのUIを更新してくれます。

フォグの色を変更できますが、上記で述べたようにフォグの色と背景色を同期させる必要があります。
lil-gui操作時に両方の色を変更する virtual プロパティをヘルパーに追加してみましょう。

lil-guiでは4つの方法で色を操作できます。

CSSの6桁の16進数(例: #112233)

色相、彩度、値、オブジェクト (例: {h: 60, s: 1, v: })

RGB (例: [255, 128, 64])

RGBA(例:[127, 200, 75, 0.3])

lil-guiが単一の値を操作するので、16進数を使うのが一番簡単です。
幸運な事に THREE.Color で getHexString を使用でき、文字列を簡単に取得できます。

// We use this class to pass to lil-gui
// so when it manipulates near or far
// near is never > far and far is never < near
+// Also when lil-gui manipulates color we'll
+// update both the fog and background colors.
class FogGUIHelper {
*  constructor(fog, backgroundColor) {
    this.fog = fog;
+    this.backgroundColor = backgroundColor;
  }
  get near() {
    return this.fog.near;
  }
  set near(v) {
    this.fog.near = v;
    this.fog.far = Math.max(this.fog.far, v);
  }
  get far() {
    return this.fog.far;
  }
  set far(v) {
    this.fog.far = v;
    this.fog.near = Math.min(this.fog.near, v);
  }
+  get color() {
+    return `#${this.fog.color.getHexString()}`;
+  }
+  set color(hexString) {
+    this.fog.color.set(hexString);
+    this.backgroundColor.set(hexString);
+  }
}

gui.addColor を呼び出し、ヘルパーのvirtualプロパティにcolorのlil-guiを追加します。

{
  const near = 1;
  const far = 2;
  const color = 'lightblue';
  scene.fog = new THREE.Fog(color, near, far);
  scene.background = new THREE.Color(color);

*  const fogGUIHelper = new FogGUIHelper(scene.fog, scene.background);
  gui.add(fogGUIHelper, 'near', near, far).listen();
  gui.add(fogGUIHelper, 'far', near, far).listen();
+  gui.addColor(fogGUIHelper, 'color');
}

  ここをクリックして別のウィンドウで開きます

near を1.9、far を2.0にすると以下のようになりました。
曇っていない状態と完全に曇っている状態との中間では、シャープなグラデーションします。
near = 1.1、far = 2.9 とすると、カメラから 2 離れて回転する立方体で最も滑らかになります。

最後に、マテリアルでレンダリングされたオブジェクトがフォグの影響を受けるか判断するために、マテリアルにはboolean型のfogプロパティがあります。
そのマテリアルを使用してる場合は、フォグの影響を受けます。
ほとんどのマテリアルのデフォルトは true です。
フォグを消去する理由は、運転席やコックピットからの視点で3Dの車のシミュレーターを作っている時を想像して下さい。
車内から見ると、車内の全てのものはフォグを外しておきたいと思うでしょう。

フォグの良い例としては、家の外に濃いフォグが出ている場合が挙げられます。
例えば、フォグが2m先(near = 2)から始まり、4m先(far = 4)でフォグがあるとします。
部屋の長さは2メートル以上、家の長さは4メートル以上で、家の中にフォグがかからないように設定が必要です。
設定しない場合に家の中に立っている時に部屋の奥の壁の外を見ると、フォグの中にいるように見えてしまいます。

fog: true, all

部屋の奥の壁と天井にフォグがかかっています。
家のマテリアルのフォグをオフにすると、この問題が解決できます。

fog: true, only outside materials

<canvas id="c"></canvas>


text:
<?php

declare(strict_types=1);

namespace Snc\RedisBundle\Client\Predis\Connection;

use Closure;
use Predis\Command\CommandInterface;
use Predis\Connection\ConnectionException;
use Predis\Connection\NodeConnectionInterface;
use Predis\Connection\ParametersInterface;
use Predis\Response\Error;
use Snc\RedisBundle\Logger\RedisLogger;
use Symfony\Component\Stopwatch\Stopwatch;

use function array_reduce;
use function assert;
use function is_string;
use function microtime;
use function preg_replace;
use function strlen;
use function substr;
use function var_export;

class ConnectionWrapper implements NodeConnectionInterface
{
    protected NodeConnectionInterface $connection;

    protected ?RedisLogger $logger = null;

    protected ?Stopwatch $stopwatch = null;

    public function __construct(NodeConnectionInterface $connection)
    {
        if ($connection instanceof ConnectionWrapper) {
            $connection = $connection->getConnection();
            assert($connection instanceof ConnectionWrapper);
        }

        $this->connection = $connection;
    }

    public function getConnection(): NodeConnectionInterface
    {
        return $this->connection;
    }

    public function setLogger(?RedisLogger $logger = null): void
    {
        $this->logger = $logger;
    }

    public function setStopwatch(Stopwatch $stopwatch): void
    {
        $this->stopwatch = $stopwatch;
    }

    /**
     * {@inheritdoc}
     */
    public function connect()
    {
        return $this->connection->connect();
    }

    public function disconnect(): void
    {
        $this->connection->disconnect();
    }

    public function isConnected(): bool
    {
        return $this->connection->isConnected();
    }

    public function writeRequest(CommandInterface $command): void
    {
        $this->execute($command, fn (CommandInterface $command) => $this->connection->writeRequest($command));
    }

    /** @return mixed */
    public function readResponse(CommandInterface $command)
    {
        return $this->connection->readResponse($command);
    }

    public function __toString(): string
    {
        return (string) $this->connection;
    }

    /** @return resource */
    public function getResource()
    {
        return $this->connection->getResource();
    }

    public function getParameters(): ParametersInterface
    {
        return $this->connection->getParameters();
    }

    public function addConnectCommand(CommandInterface $command): void
    {
        $this->connection->addConnectCommand($command);
    }

    /** @return mixed */
    public function read()
    {
        return $this->connection->read();
    }

    /** @return mixed */
    public function executeCommand(CommandInterface $command)
    {
        return $this->execute($command, fn (CommandInterface $command) => $this->connection->executeCommand($command));
    }

    private function commandToString(CommandInterface $command): string
    {
        return array_reduce(
            $command->getArguments(),
            fn (string $accumulator, $argument) => $this->toStringArgumentReducer($accumulator, $argument),
            $command->getId(),
        );
    }

    /** @param mixed $argument */
    private function toStringArgumentReducer(string $accumulator, $argument): string
    {
        if (is_string($argument) && strlen($argument) > 10240) {
            $argument = substr($argument, 0, 10240) . ' (truncated, complete string is ' . strlen($argument) . ' bytes)';
        }

        return $accumulator . ' ' . var_export($argument, true);
    }

    /**
     * @param Closure(CommandInterface): mixed $execute
     *
     * @return mixed
     */
    private function execute(CommandInterface $command, Closure $execute)
    {
        if (!$this->logger) {
            return $execute($command);
        }

        $commandName = $this->commandToString($command);

        if ($this->stopwatch) {
            $event = $this->stopwatch->start(preg_replace('/[^[:print:]]/', '', $commandName), 'redis');
        }

        $startTime = microtime(true);
        try {
            $result = $execute($command);
        } catch (ConnectionException $exception) {
            throw new ConnectionException($this, $exception->getMessage(), $exception->getCode(), $exception);
        }

        if (isset($event)) {
            $event->stop();
        }

        /** @psalm-suppress NoInterfaceProperties */
        $this->logger->logCommand(
            $this->commandToString($command),
            (microtime(true) - $startTime) * 1000,
            $this->getParameters()->alias,
            $this->isResultTrulyAnError($result) ? (string) $result : false,
        );

        return $result;
    }

    /**
     * Certain results from redis are marked as "error", but are meant to be handled by redis client.
     * Unfortunately, in some cases this evaluation happens only after executeCommand in ConnectionWrapper returns.
     * For example, RedisCluster wraps ConnectionWrapper and not opposite, hence ConnectionWrapper must make assumption
     * here about handling of certain errors based on error type and connection parameters in order of not wrongly
     * classifying responses as errors that were already taken care of by client.
     *
     * @param mixed $result
     */
    private function isResultTrulyAnError($result): bool
    {
        if (!$result instanceof Error) {
            return false;
        }

        /** @psalm-suppress NoInterfaceProperties */
        if ($this->connection->getParameters()->cluster) {
            return $result->getErrorType() !== 'MOVED';
        }

        return true;
    }
}