text:
using MatterHackers.Agg.VertexSource;
using System;

namespace MatterHackers.Agg.UI
{
	public class ProgressBar : GuiWidget
	{
		private double ratioComplete;

		public ProgressBar()
		{
			this.BorderColor = Color.Black;
		}

		public ProgressBar(double width, double height)
			: base(width, height)
		{
		}

		public event EventHandler ProgressChanged;

		public Color FillColor { get; set; }

		public int PercentComplete
		{
			get => (int)(ratioComplete * 100 + .5);

			set
			{
				if (value != (int)(ratioComplete * ratioComplete + .5))
				{
					ProgressChanged?.Invoke(this, null);
					ratioComplete = value / 100.0;
					Invalidate();
				}
			}
		}

		public double RatioComplete
		{
			get => ratioComplete;

			set
			{
				if (value != ratioComplete)
				{
					ProgressChanged?.Invoke(this, null);
					ratioComplete = value;
					Invalidate();
				}
			}
		}

		public override void OnDraw(Graphics2D graphics2D)
		{
			base.OnDraw(graphics2D);

			var bounds = this.LocalBounds;
			var rect = new RoundedRect(bounds.Left, bounds.Bottom, bounds.Right, bounds.Top);
			rect.radius(BackgroundRadius.SW, BackgroundRadius.SE, BackgroundRadius.NE, BackgroundRadius.NW);

			// fill the background
			if (BackgroundColor.Alpha0To255 > 0)
			{
				graphics2D.Render(rect, BackgroundColor);
			}

			// Restrict fill to valid values
			var fillWidth = Math.Max(0, Math.Min(Width, Width * RatioComplete));
			if (fillWidth > 0)
			{
				if (BackgroundRadius == 0)
				{
					graphics2D.FillRectangle(0, 0, fillWidth, Height, FillColor);
				}
				else
				{
					var fill = new RoundedRect(0, 0, fillWidth, Height, BackgroundRadius.NW);
					graphics2D.Render(fill, FillColor);
				}
			}

			// draw the outline if needed
			if (BorderColor.Alpha0To255 > 0)
			{
				if (BackgroundOutlineWidth > 0)
				{
					var stroke = BackgroundOutlineWidth * GuiWidget.DeviceScale;
					var expand = stroke / 2;
					rect = new RoundedRect(bounds.Left + expand, bounds.Bottom + expand, bounds.Right - expand, bounds.Top - expand);
					rect.radius(BackgroundRadius.SW, BackgroundRadius.SE, BackgroundRadius.NE, BackgroundRadius.NW);

					var rectOutline = new Stroke(rect, stroke);

					graphics2D.Render(rectOutline, BorderColor);
				}
				else
				{
					graphics2D.Rectangle(LocalBounds, BorderColor);
				}
			}
		}
	}
}


text:
import rospy
import os
import json
import numpy as np
import random
import time
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from collections import deque
from std_msgs.msg import Float32MultiArray
from environment_cnn import Env
import tensorflow as tf
from keras.models import Sequential, load_model
from keras.optimizers import RMSprop
from keras.layers import Conv1D, GlobalAveragePooling1D, MaxPooling1D
from keras.layers import Dense, Dropout, Activation, Flatten
from turtlebot2i_safety.msg import SafetyRisk

class ReinforceAgent():
    def __init__(self, env, training_mode):
        self.pub_result = rospy.Publisher('result', Float32MultiArray, queue_size=5)
        self.dirPath = os.path.dirname(os.path.realpath(__file__))
        self.dirPath = self.dirPath.replace('scott-eu/simulation-ros/src/turtlebot2i/turtlebot2i_safety/src', 'scott-eu/simulation-ros/src/turtlebot2i/turtlebot2i_safety/src/models/cnn_')
        self.result = Float32MultiArray()

        self.load_model = True
        self.load_episode = 315#571#340 #0
        self.env = env
        self.stack_len = 20
        self.state_stack = deque(maxlen=self.stack_len)
        if training_mode:
            self.single_state_len = len(self.env.reset())
        else:
            self.single_state_len = len(self.env.getEmptyState())
        self.state_size = (self.stack_len, self.single_state_len)
        self.state = np.empty((self.state_size), dtype=np.float64)
        self.action_size = self.env.action_size
        self.episode_step = 6000
        self.target_update = 2000
        self.discount_factor = 0.99
        self.learning_rate = 0.00025
        self.epsilon = 1.0
        self.epsilon_decay = 0.99
        self.epsilon_min = 0.05
        self.batch_size = 64
        self.train_start = 64
        self.memory = deque(maxlen=1000000)

        self.model = self.buildModel()
        self.target_model = self.buildModel()

        self.updateTargetModel()

        self.scores   = []
        self.episodes = []
        self.maxQval  = []
        self.step_list= []

        if self.load_model:
            self.model.set_weights(load_model(self.dirPath + str(self.load_episode) + ".h5").get_weights())

            with open(self.dirPath + str(self.load_episode) + '.json') as outfile:
                param = json.load(outfile)
                self.epsilon = param.get('epsilon')

            loaded_result = np.load(self.dirPath + str(self.load_episode) + '.npz')
            self.scores   = list(loaded_result['scores'])
            self.episodes = list(loaded_result['episodes'])
            self.maxQval  = list(loaded_result['maxQval'])
            self.step_list= list(loaded_result['step_list'])

        self.action = 6
        self.score = 0
        self.e = self.load_episode + 1
        self.t = 0
        self.global_step = 0
        self.param_dictionary = dict(zip(['epsilon'], [self.epsilon]))

        if training_mode:
            self.sub_risk = rospy.Subscriber('/turtlebot2i/safety/obstacles_risk', SafetyRisk, self.training_callback)
        else:
            self.sub_risk = rospy.Subscriber('/turtlebot2i/safety/obstacles_risk', SafetyRisk, self.prediction_callback)
            self.epsilon = 0.0

        self.start_time = time.time()
        self.graph = tf.get_default_graph()
        self.time_duration_list = []

    def buildModel(self):
        model = Sequential()
        dropout = 0.2

        model.add(Conv1D(32, 3, activation='relu', input_shape=self.state_size))
        model.add(Conv1D(32, 3, activation='relu'))
        model.add(Conv1D(32, 3, activation='relu'))
        model.add(GlobalAveragePooling1D())
        model.add(Dropout(dropout))

        model.add(Dense(self.action_size, kernel_initializer='lecun_uniform'))
        model.add(Activation('linear'))
        model.compile(loss='mse', optimizer=RMSprop(lr=self.learning_rate, rho=0.9, epsilon=1e-06))
        model.summary()

        return model

    def getQvalue(self, reward, next_target, done):
        if done:
            return reward
        else:
            return reward + self.discount_factor * np.amax(next_target)

    def updateTargetModel(self):
        self.target_model.set_weights(self.model.get_weights())

    def getAction(self, state):
        if np.random.rand() <= self.epsilon:
            self.q_value = np.zeros(self.action_size)
            return random.randrange(self.action_size)
        else:
            with self.graph.as_default():
                q_value = self.model.predict(state)
            self.q_value = q_value
            return np.argmax(q_value[0])

    def appendMemory(self, state, action, reward, next_state, done):
        self.memory.append((state, action, reward, next_state, done))

    def trainModel(self, target=False):
        mini_batch = random.sample(self.memory, self.batch_size)
        X_batch = np.empty((0, self.stack_len, self.single_state_len), dtype=np.float64)
        Y_batch = np.empty((0, self.action_size), dtype=np.float64)

        with self.graph.as_default():
            for i in range(self.batch_size):
                states = mini_batch[i][0]
                actions = mini_batch[i][1]
                rewards = mini_batch[i][2]
                next_states = mini_batch[i][3]
                dones = mini_batch[i][4]
                q_value = self.model.predict(states)
                self.q_value = q_value

                if target:
                    next_target = self.target_model.predict(next_states)

                else:
                    next_target = self.model.predict(next_states)

                next_q_value = self.getQvalue(rewards, next_target, dones)

                X_batch = np.append(X_batch, np.array(states.copy()), axis=0)
                Y_sample = q_value.copy()

                Y_sample[0][actions] = next_q_value
                Y_batch = np.append(Y_batch, np.array([Y_sample[0]]), axis=0)

                if dones:
                    X_batch = np.append(X_batch, np.array(next_states.copy()), axis=0)
                    Y_batch = np.append(Y_batch, np.array([[rewards] * self.action_size]), axis=0)

            self.model.fit(X_batch, Y_batch, batch_size=self.batch_size, epochs=1, verbose=0)

    def training_callback(self, data):
        if len(self.state_stack) < self.stack_len:
            state, done = self.env.getState(data)
            self.state_stack.append(np.asarray(state))
            self.env.execute(7) #scaling to 0.4 for both wheels
            if len(self.state_stack) == self.stack_len:
                self.state = np.asarray([self.state_stack])
            if done:
                self.state_stack.clear()
                self.env.reset(data=data)

        else:
            next_state, done = self.env.getState(data)
            reward = self.env.setReward(next_state, done, self.action)
            self.state_stack.append(np.asarray(next_state))
            next_state_stack = np.asarray([self.state_stack])
            self.appendMemory(self.state, self.action, reward, next_state_stack, done)

            self.state = next_state_stack
            self.action = agent.getAction(self.state)
            self.env.execute(self.action)
            self.score += reward
            if len(self.memory) >= self.train_start:
                if self.global_step <= self.target_update:
                    self.trainModel()
                else:
                    self.trainModel(True)

            if self.t >= 2000:
                rospy.loginfo("Time out!!")
                done = True

            if done:
                if (self.e % 5 == 0) or (self.score > -4000):
                    self.model.save(self.dirPath + str(self.e) + '.h5')
                    with open(self.dirPath + str(self.e) + '.json', 'w') as outfile:
                        json.dump(self.param_dictionary, outfile)
                    np.savez(self.dirPath + str(self.e) + '.npz', scores=self.scores, episodes=self.episodes, maxQval=self.maxQval, step_list=self.step_list)

                self.env.reset(data=data)
                self.updateTargetModel()
                self.scores.append(self.score)
                self.episodes.append(self.e)
                self.maxQval.append(np.max(self.q_value))
                self.step_list.append(self.global_step)
                m, s = divmod(int(time.time() - self.start_time), 60)
                h, m = divmod(m, 60)

                if self.e>2:
                    rospy.loginfo('Ep: %d score: %.2f average_score: %.2f memory: %d epsilon: %.2f time: %d:%02d:%02d',
                                  self.e, self.score, self.score/(self.step_list[-1]-self.step_list[-2]), len(self.memory), self.epsilon, h, m, s)
                else:
                    rospy.loginfo('Ep: %d score: %.2f average_score: %.2f memory: %d epsilon: %.2f time: %d:%02d:%02d',
                                  self.e, self.score, self.score/self.step_list[-1], len(self.memory), self.epsilon, h, m, s)
                self.param_dictionary = dict(zip(['epsilon'], [self.epsilon]))

                self.score = 0
                self.e += 1
                self.t = 0
                self.state_stack.clear()
                if agent.epsilon > agent.epsilon_min:
                    agent.epsilon *= agent.epsilon_decay
            else:
                self.t += 1
                self.global_step += 1

    def prediction_callback(self, data):
        if len(self.state_stack) < self.stack_len:
            state, done = self.env.getState(data)
            self.state_stack.append(np.asarray(state))
            self.env.execute(7) #scaling to 0.4 for both wheels
            if len(self.state_stack) == self.stack_len:
                self.state = np.asarray([self.state_stack])
            if done:
                self.state_stack.clear()
                self.env.reset(data=data)

        else:
            #time_previous = time.time()
            next_state, done = self.env.getState(data)
            self.state_stack.append(np.asarray(next_state))
            next_state_stack = np.asarray([self.state_stack])

            self.state = next_state_stack
            next_action = agent.getAction(self.state)
            if next_action != self.action:
                print("action:",next_action)
            self.action = next_action
            #time_end = time.time()
            self.env.execute(self.action)

            # self.time_duration_list.append(time_end-time_previous)
            # if len(self.time_duration_list) == 100:
            #     dirPath = os.path.dirname(os.path.realpath(__file__))
            #     savePath = self.dirPath.replace('scott-eu/simulation-ros/src/turtlebot2i/turtlebot2i_safety/src', 'time_duration/time_duration_rm_cnn.npz')
            #     np.savez(savePath, time_duration_list=self.time_duration_list)

EPISODES = 3000
if __name__ == '__main__':
    try:
        rospy.init_node('risk_mitigation_cnn_py')
        training_mode = False
        env = Env()
        agent = ReinforceAgent(env,training_mode)
        print("Program ready!")
        rospy.spin()

    except rospy.ROSInterruptException:
        env.vrep_control.shutdown()
        rospy.loginfo("Training finished.")

redpajama_set_name: RedPajamaGithub


text: google-site-verification: google51f6f955c70ab662.html


text:
package edu.tmc.uth.teo.model;

/**
 * The top TEOClass
 *
 * @author yluo
 *
 */
public abstract class TEOClass {
	private String iriStr = null;
	private String label = null; // as unique id

	public String getIRIStr() {
		return this.iriStr;
	}

	public void setIRIStr(String iriStr) {
		this.iriStr = iriStr;
	}

	public String getLabel() {
		return this.label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

}


text:
@interface PodsDummy_Pods_ParseChat : NSObject
@end
@implementation PodsDummy_Pods_ParseChat
@end


text:
using System;
using System.Collections.Generic;

using Grasshopper.Kernel;
using Rhino.Geometry;
using System.IO;

namespace ANT._01_DataSets
{
    public class _0_DigitsDataset : GH_Component
    {
        private bool processhasexit = false;

        string workingDir = "C:\\ant\\_02_datasets\\DigitsDataset\\";

        /// <summary>
        /// Initializes a new instance of the _0_DigitsDataset class.
        /// </summary>
        public _0_DigitsDataset()
            : base("_0_DigitsDataset", "Digits",
                "Loads the Ditigts DataSEt",
                "ANT", "1|Data Set")
        {
            if (!Directory.Exists(@workingDir))
            {
                Directory.CreateDirectory(@workingDir);
            }
            this.Message = "The Digits Dataset";
        }

        /// <summary>
        /// Registers all the input parameters for this component.
        /// </summary>
        protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
        {
            pManager.AddBooleanParameter("Load Digits dataset ?   |", "LoadDigits  |", "", GH_ParamAccess.item);
        }

        /// <summary>
        /// Registers all the output parameters for this component.
        /// </summary>
        protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
        {
            pManager.AddTextParameter("|    Log_ : ", "|   Log", "Result of loading DigitsDataset", GH_ParamAccess.item);
            pManager.AddTextParameter("|    Data |", "|   Data", "List of data to be trained .. ", GH_ParamAccess.item);
            pManager.AddTextParameter("|    Targets |", "|   Targets", "List of targets to be fitted .. ", GH_ParamAccess.item);
        }

        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            bool load_iris = false;
            string workingDir2 = workingDir.Replace("\\", "\\\\");

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "python.exe";
            process.StartInfo.Arguments = "working.py";
            process.StartInfo.WorkingDirectory = workingDir;
            process.EnableRaisingEvents = true;
            process.Exited += process_Exited;

            if (!DA.GetData(0, ref load_iris)) { return; }
            if (load_iris == false) { return; }

            string file = Resources.allResources.digitsDataset;
            file = file.Replace("##directory##", workingDir2);

            System.IO.File.WriteAllText(@workingDir + "working.py", file);

            process.Start();
            while (!processhasexit)
            {

            }
            try
            {
                DA.SetData(0, System.IO.File.ReadAllText(workingDir + "digitslog.txt") + "\n " + System.IO.File.ReadAllText(workingDir + "digitsdata_r.txt") + "\n " + System.IO.File.ReadAllText(workingDir + "digitstarget_r.txt"));
                DA.SetData(1, workingDir + "data.txt");
                DA.SetData(2, workingDir + "targets.txt");

            }
            catch (Exception e)
            {
                DA.SetData(0, e.Message);
            }
            processhasexit = false;

        }

        private void process_Exited(object sender, EventArgs e)
        {
            processhasexit = true;
        }

        /// <summary>
        /// Provides an Icon for every component that will be visible in the User Interface.
        /// Icons need to be 24x24 pixels.
        /// </summary>
        protected override System.Drawing.Bitmap Icon
        {
            get
            {
                // You can add image files to your project resources and access them like this:
                //return Resources.IconForThisComponent;
                //return (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile("C:\\ant\\iris_icon.png");
                return ANT.Resources.allResources.digits;
            }
        }

        /// <summary>
        /// Gets the unique ID for this component. Do not change this ID after release.
        /// </summary>
        public override Guid ComponentGuid
        {
            get { return new Guid("{3ab3d8f5-f524-46a7-84d9-018bba39e1ff}"); }
        }
    }
}


text:
#include "python.hpp"
#include "../include/librealsense2/hpp/rs_processing.hpp"

void init_processing(py::module &m) {
    /** rs_processing.hpp **/
    py::class_<rs2::frame_source> frame_source(m, "frame_source", "The source used to generate frames, which is usually done by the low level driver for each sensor. "
                                               "frame_source is one of the parameters of processing_block's callback function, which can be used to re-generate the "
                                               "frame and via frame_ready invoke another callback function to notify application frame is ready.");
    frame_source.def("allocate_video_frame", &rs2::frame_source::allocate_video_frame, "Allocate a new video frame with given params",
                     "profile"_a, "original"_a, "new_bpp"_a = 0, "new_width"_a = 0,
                     "new_height"_a = 0, "new_stride"_a = 0, "frame_type"_a = RS2_EXTENSION_VIDEO_FRAME)
        .def("allocate_motion_frame", &rs2::frame_source::allocate_motion_frame, "Allocate a new motion frame with given params",
            "profile"_a, "original"_a, "frame_type"_a = RS2_EXTENSION_MOTION_FRAME)
        .def("allocate_points", &rs2::frame_source::allocate_points, "profile"_a,
             "original"_a) // No docstring in C++
        .def("allocate_composite_frame", &rs2::frame_source::allocate_composite_frame,
             "Allocate composite frame with given params", "frames"_a)
        .def("frame_ready", &rs2::frame_source::frame_ready, "Invoke the "
             "callback funtion informing the frame is ready.", "result"_a);

    // Not binding frame_processor_callback, templated

    py::class_<rs2::frame_queue> frame_queue(m, "frame_queue", "Frame queues are the simplest cross-platform "
                                             "synchronization primitive provided by librealsense to help "
                                             "developers who are not using async APIs.");
    frame_queue.def(py::init<>())
        .def(py::init<unsigned int, bool>(), "capacity"_a, "keep_frames"_a = false)
        .def("enqueue", &rs2::frame_queue::enqueue, "Enqueue a new frame into the queue.", "f"_a)
        .def("wait_for_frame", &rs2::frame_queue::wait_for_frame, "Wait until a new frame "
             "becomes available in the queue and dequeue it.", "timeout_ms"_a = 5000, py::call_guard<py::gil_scoped_release>())
        .def("poll_for_frame", [](const rs2::frame_queue &self) {
            rs2::frame frame;
            self.poll_for_frame(&frame);
            return frame;
        }, "Poll if a new frame is available and dequeue it if it is")
        .def("try_wait_for_frame", [](const rs2::frame_queue &self, unsigned int timeout_ms) {
            rs2::frame frame;
            auto success = self.try_wait_for_frame(&frame, timeout_ms);
            return std::make_tuple(success, frame);
        }, "timeout_ms"_a = 5000, py::call_guard<py::gil_scoped_release>()) // No docstring in C++
        .def("__call__", &rs2::frame_queue::operator(), "Identical to calling enqueue.", "f"_a)
        .def("capacity", &rs2::frame_queue::capacity, "Return the capacity of the queue.")
        .def("size", &rs2::frame_queue::size, "Number of enqueued frames.")
        .def("keep_frames", &rs2::frame_queue::keep_frames, "Return whether or not the queue calls keep on enqueued frames.");

    py::class_<rs2::processing_block, rs2::options> processing_block(m, "processing_block", "Define the processing block workflow, inherit this class to "
                                                                     "generate your own processing_block.");
    processing_block.def(py::init([](std::function<void(rs2::frame, rs2::frame_source&)> processing_function) {
            return new rs2::processing_block(processing_function);
        }), "processing_function"_a)
        .def("start", [](rs2::processing_block& self, std::function<void(rs2::frame)> f) {
            self.start(f);
        }, "Start the processing block with callback function to inform the application the frame is processed.", "callback"_a)
        .def("invoke", &rs2::processing_block::invoke, "Ask processing block to process the frame", "f"_a)
        .def("supports", (bool (rs2::processing_block::*)(rs2_camera_info) const) &rs2::processing_block::supports, "Check if a specific camera info field is supported.")
        .def("get_info", &rs2::processing_block::get_info, "Retrieve camera specific information, like versions of various internal components.");
        /*.def("__call__", &rs2::processing_block::operator(), "f"_a)*/
        // supports(camera_info) / get_info(camera_info)?

    py::class_<rs2::filter, rs2::processing_block, rs2::filter_interface> filter(m, "filter", "Define the filter workflow, inherit this class to generate your own filter.");
    filter.def(py::init([](std::function<void(rs2::frame, rs2::frame_source&)> filter_function, int queue_size) {
            return new rs2::filter(filter_function, queue_size);
        }), "filter_function"_a, "queue_size"_a = 1)
        .def(BIND_DOWNCAST(filter, decimation_filter))
        .def(BIND_DOWNCAST(filter, disparity_transform))
        .def(BIND_DOWNCAST(filter, hole_filling_filter))
        .def(BIND_DOWNCAST(filter, spatial_filter))
        .def(BIND_DOWNCAST(filter, temporal_filter))
        .def(BIND_DOWNCAST(filter, threshold_filter))
        .def(BIND_DOWNCAST(filter, zero_order_invalidation))
        .def(BIND_DOWNCAST(filter, depth_huffman_decoder))
        .def(BIND_DOWNCAST(filter, hdr_merge))
        .def(BIND_DOWNCAST(filter, sequence_id_filter))
        .def("__nonzero__", &rs2::filter::operator bool) // Called to implement truth value testing in Python 2
        .def("__bool__", &rs2::filter::operator bool);   // Called to implement truth value testing in Python 3
        // get_queue?
        // is/as?

    py::class_<rs2::pointcloud, rs2::filter> pointcloud(m, "pointcloud", "Generates 3D point clouds based on a depth frame. Can also map textures from a color frame.");
    pointcloud.def(py::init<>())
        .def(py::init<rs2_stream, int>(), "stream"_a, "index"_a = 0)
        .def("calculate", &rs2::pointcloud::calculate, "Generate the pointcloud and texture mappings of depth map.", "depth"_a)
        .def("map_to", &rs2::pointcloud::map_to, "Map the point cloud to the given color frame.", "mapped"_a);

    py::class_<rs2::yuy_decoder, rs2::filter> yuy_decoder(m, "yuy_decoder", "Converts frames in raw YUY format to RGB. This conversion is somewhat costly, "
                                                          "but the SDK will automatically try to use SSE2, AVX, or CUDA instructions where available to "
                                                          "get better performance. Othere implementations (GLSL, OpenCL, Neon, NCS) should follow.");
    yuy_decoder.def(py::init<>());

    py::class_<rs2::threshold_filter, rs2::filter> threshold(m, "threshold_filter", "Depth thresholding filter. By controlling min and "
                                                             "max options on the block, one could filter out depth values that are either too large "
                                                             "or too small, as a software post-processing step");
    threshold.def(py::init<float, float>(), "min_dist"_a = 0.15f, "max_dist"_a = 4.f);

    py::class_<rs2::units_transform, rs2::filter> units_transform(m, "units_transform");
    units_transform.def(py::init<>());

    // rs2::asynchronous_syncer

    py::class_<rs2::syncer> syncer(m, "syncer", "Sync instance to align frames from different streams");
    auto poll_for_frame = []( const rs2::syncer & self ) {
        rs2::frameset frames;
        self.poll_for_frames( &frames );
        return frames;
    };
    auto wait_for_frame = []( const rs2::syncer& self, unsigned int timeout_ms ) {
        rs2::frameset fs;
        auto success = self.try_wait_for_frames( &fs, timeout_ms );
        return std::make_tuple( success, fs );
    };
    syncer.def( py::init< int >(), "queue_size"_a = 1 )
        .def( "wait_for_frames",
              &rs2::syncer::wait_for_frames,
              "Wait until a coherent set of frames becomes available",
              "timeout_ms"_a = 5000,
              py::call_guard< py::gil_scoped_release >() )
        .def( "wait_for_frame",  // same, but with a name that matches frame_queue!
              &rs2::syncer::wait_for_frames,
              "Wait until a coherent set of frames becomes available",
              "timeout_ms"_a = 5000,
              py::call_guard< py::gil_scoped_release >() )
        .def( "poll_for_frames", poll_for_frame, "Check if a coherent set of frames is available" )
        .def( "poll_for_frame",  poll_for_frame, "Check if a coherent set of frames is available" )  // same, but with a name that matches frame_queue!
        .def( "try_wait_for_frames",
              wait_for_frame,
              "timeout_ms"_a = 5000,
              py::call_guard< py::gil_scoped_release >() )
        .def( "try_wait_for_frame",  // same, but with a name that matches frame_queue!
              wait_for_frame,
              "timeout_ms"_a = 5000,
              py::call_guard< py::gil_scoped_release >() );
      /*.def("__call__", &rs2::syncer::operator(), "frame"_a)*/

    py::class_<rs2::align, rs2::filter> align(m, "align", "Performs alignment between depth image and another image.");
    align.def(py::init<rs2_stream>(), "To perform alignment of a depth image to the other, set the align_to parameter with the other stream type.\n"
              "To perform alignment of a non depth image to a depth image, set the align_to parameter to RS2_STREAM_DEPTH.\n"
              "Camera calibration and frame's stream type are determined on the fly, according to the first valid frameset passed to process().", "align_to"_a)
        .def("process", (rs2::frameset(rs2::align::*)(rs2::frameset)) &rs2::align::process, "Run thealignment process on the given frames to get an aligned set of frames", "frames"_a);

    py::class_<rs2::colorizer, rs2::filter> colorizer(m, "colorizer", "Colorizer filter generates color images based on input depth frame");
    colorizer.def(py::init<>())
        .def(py::init<float>(), "Possible values for color_scheme:\n"
             "0 - Jet\n"
             "1 - Classic\n"
             "2 - WhiteToBlack\n"
             "3 - BlackToWhite\n"
             "4 - Bio\n"
             "5 - Cold\n"
             "6 - Warm\n"
             "7 - Quantized\n"
             "8 - Pattern", "color_scheme"_a)
        .def("colorize", &rs2::colorizer::colorize, "Start to generate color image base on depth frame", "depth"_a)
        /*.def("__call__", &rs2::colorizer::operator())*/;

    py::class_<rs2::decimation_filter, rs2::filter> decimation_filter(m, "decimation_filter", "Performs downsampling by using the median with specific kernel size.");
    decimation_filter.def(py::init<>())
        .def(py::init<float>(), "magnitude"_a);

    py::class_<rs2::temporal_filter, rs2::filter> temporal_filter(m, "temporal_filter", "Temporal filter smooths the image by calculating multiple frames "
                                                                  "with alpha and delta settings. Alpha defines the weight of current frame, and delta defines the"
                                                                  "threshold for edge classification and preserving.");
    temporal_filter.def(py::init<>())
        .def(py::init<float, float, int>(), "Possible values for persistence_control:\n"
             "1 - Valid in 8/8 - Persistency activated if the pixel was valid in 8 out of the last 8 frames\n"
             "2 - Valid in 2 / last 3 - Activated if the pixel was valid in two out of the last 3 frames\n"
             "3 - Valid in 2 / last 4 - Activated if the pixel was valid in two out of the last 4 frames\n"
             "4 - Valid in 2 / 8 - Activated if the pixel was valid in two out of the last 8 frames\n"
             "5 - Valid in 1 / last 2 - Activated if the pixel was valid in one of the last two frames\n"
             "6 - Valid in 1 / last 5 - Activated if the pixel was valid in one out of the last 5 frames\n"
             "7 - Valid in 1 / last 8 - Activated if the pixel was valid in one out of the last 8 frames\n"
             "8 - Persist Indefinitely - Persistency will be imposed regardless of the stored history(most aggressive filtering)",
             "smooth_alpha"_a, "smooth_delta"_a, "persistence_control"_a);

    py::class_<rs2::spatial_filter, rs2::filter> spatial_filter(m, "spatial_filter", "Spatial filter smooths the image by calculating frame with alpha and delta settings. "
                                                                "Alpha defines the weight of the current pixel for smoothing, and is bounded within [25..100]%. Delta "
                                                                "defines the depth gradient below which the smoothing will occur as number of depth levels.");
    spatial_filter.def(py::init<>())
        .def(py::init<float, float, float, float>(), "smooth_alpha"_a, "smooth_delta"_a, "magnitude"_a, "hole_fill"_a);;

    py::class_<rs2::disparity_transform, rs2::filter> disparity_transform(m, "disparity_transform", "Converts from depth representation "
                                                                          "to disparity representation and vice - versa in depth frames");
    disparity_transform.def(py::init<bool>(), "transform_to_disparity"_a = true);

    py::class_<rs2::zero_order_invalidation, rs2::filter> zero_order_invalidation(m, "zero_order_invalidation", "Fixes the zero order artifact");
    zero_order_invalidation.def(py::init<>());

    py::class_<rs2::hole_filling_filter, rs2::filter> hole_filling_filter(m, "hole_filling_filter", "The processing performed depends on the selected hole filling mode.");
    hole_filling_filter.def(py::init<>())
        .def(py::init<int>(), "Possible values for mode:\n"
             "0 - fill_from_left - Use the value from the left neighbor pixel to fill the hole\n"
             "1 - farest_from_around - Use the value from the neighboring pixel which is furthest away from the sensor\n"
             "2 - nearest_from_around - -Use the value from the neighboring pixel closest to the sensor", "mode"_a);

    py::class_<rs2::depth_huffman_decoder, rs2::filter> depth_huffman_decoder(m, "depth_huffman_decoder", "Decompresses Huffman-encoded Depth frame to standartized Z16 format");
    depth_huffman_decoder.def(py::init<>());

    py::class_<rs2::hdr_merge, rs2::filter> hdr_merge(m, "hdr_merge", "Merges depth frames with different sequence ID");
    hdr_merge.def(py::init<>());

    py::class_<rs2::sequence_id_filter, rs2::filter> sequence_id_filter(m, "sequence_id_filter", "Splits depth frames with different sequence ID");
    sequence_id_filter.def(py::init<>())
        .def(py::init<float>(), "sequence_id"_a);
    // rs2::rates_printer
    /** end rs_processing.hpp **/
}


text:
// Copyright 2015 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Directive for the background banner.
 */

oppia.directive('backgroundBanner', [function() {
  return {
    restrict: 'E',
    scope: {},
    templateUrl: 'background/banner',
    controller: [
      '$scope', 'UrlInterpolationService',
      function($scope, UrlInterpolationService) {
        var possibleBannerFilenames = [
          'bannerA.svg', 'bannerB.svg', 'bannerC.svg', 'bannerD.svg'];
        var bannerImageFilename = possibleBannerFilenames[
          Math.floor(Math.random() * possibleBannerFilenames.length)];
        $scope.bannerImageFileUrl = UrlInterpolationService.getStaticImageUrl(
          '/background/' + bannerImageFilename);
      }
    ]
  };
}]);


text:
cd $TFB_REPOPARENT
git clone -b $TFB_REPOBRANCH $TFB_REPOURI
cd $TFB_REPOPARENT/$TFB_REPONAME

#
# Make the results directory if it doesn't exist.
#
# save the current git commit to results/.commit
#
echo "Saving current git commit to results directory..."
GIT_COMMIT=$(git rev-parse HEAD)
mkdir -p results
echo $GIT_COMMIT > results/.commit
echo "Using commit: " $GIT_COMMIT


text:
package main

import  "fmt"
import "io/ioutil"
import "log"
import "strings"
import "strconv"

type Tree struct {
    Left *Tree
    Value int
    Right *Tree
}

func maxTotal(tree *Tree) int {
    if tree.Left == nil {
        return tree.Value
    }

    leftTotal := maxTotal(tree.Left)
    rightTotal := maxTotal(tree.Right)
    if leftTotal > rightTotal {
        return leftTotal + tree.Value
    }
    return rightTotal + tree.Value
}

func main() {
    content, err := ioutil.ReadFile("18.txt")
    if err!=nil {
        log.Fatal("couldn't read file", err)
    }

    tree := new(Tree)
    prevLevel := make([]*Tree, 0)
    lines := strings.Split(string(content), "\n")
    for i,line := range lines {
        if line == "" { continue }
        numbers := make([]int,0)
        for _, num := range strings.Split(line, " ") {
            n, _ := strconv.Atoi(num)
            numbers = append(numbers,n)
        }
        if i == 0 {
            tree.Value = numbers[0]
            prevLevel = append(prevLevel, tree)
            continue
        }

        newLevel := make([]*Tree, 0)
        for _, n := range numbers {
            newLevel = append(newLevel, &Tree{Value: n})
        }

        for j, node := range prevLevel {
            node.Left = newLevel[j]
            node.Right = newLevel[j+1]
        }
        prevLevel = newLevel
    }
    fmt.Println(maxTotal(tree))
}


text:
<?php
namespace hav\V1\Rest\OnlineUsers;

class OnlineUsersEntity
{
}


text:
using System;
using NServiceBus;

namespace Grinding
{
    public class CocoaButterProducer : IHandleMessages<ProduceCocoaButter>
    {
        public void Handle(ProduceCocoaButter message)
        {
            Console.WriteLine($"['{message.LotNumber}' - Handler] Produced cocoa butter");
        }
    }
}


text:
package endpoint

import "message"

type SystemAdmin interface {
	// Work returns proof-of-work for a given magic number.
	Work(magic int64) []*message.SingleWorkMessage

	// ChangeNetwork changes the system's network.
	ChangeNetwork(network Network)

	Network() Network
}

type Network interface {
	Neighbours(u int) []int
	HasEdge(u, v int) bool
	Size() int
}


text:
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.

using System;

namespace DotSpatial.Controls
{
    /// <summary>
    /// Describe different behaviors that map functions can have when working with
    /// respect to other map-functions.
    /// </summary>
    [Flags]
    public enum YieldStyles
    {
        /// <summary>
        /// This is a null state for testing, and should not be used directly.
        /// </summary>
        None = 0x0,

        /// <summary>
        /// This function will deactivate if another LeftButton function activates.
        /// </summary>
        LeftButton = 0x1,

        /// <summary>
        /// This function will deactivate if another RightButton function activates.
        /// </summary>
        RightButton = 0x2,

        /// <summary>
        /// This function will deactivate if another scroll function activates.
        /// </summary>
        Scroll = 0x4,

        /// <summary>
        /// This function will deactivate if another keyboard function activates.
        /// </summary>
        Keyboard = 0x8,

        /// <summary>
        /// This function is like a glyph and never yields to other functions.
        /// </summary>
        AlwaysOn = 16,
    }
}


text:
package integration_test

import (
	. "github.com/iotaledger/iota.go/api"
	_ "github.com/iotaledger/iota.go/api/integration/gocks"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"strings"
)

var _ = Describe("GetNodeInfo()", func() {
	api, err := ComposeAPI(HTTPClientSettings{}, nil)
	if err != nil {
		panic(err)
	}

	It("resolves to correct response", func() {
		info, err := api.GetNodeInfo()
		Expect(err).ToNot(HaveOccurred())
		Expect(*info).To(Equal(GetNodeInfoResponse{
			AppName:                            "IRI",
			AppVersion:                         "",
			Duration:                           100,
			JREAvailableProcessors:             4,
			JREFreeMemory:                      13020403,
			JREMaxMemory:                       1241331231,
			JRETotalMemory:                     4245234332,
			LatestMilestone:                    strings.Repeat("M", 81),
			LatestMilestoneIndex:               1,
			LatestSolidSubtangleMilestone:      strings.Repeat("M", 81),
			LatestSolidSubtangleMilestoneIndex: 1,
			Neighbors:                          5,
			PacketsQueueSize:                   23,
			Time:                               213213214,
			Tips:                               123,
			TransactionsToRequest:              10,
		}))
	})

})


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="fill_parent">

    <FrameLayout
        android:id="@+id/content_settings_checkin_reminder"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

    <FrameLayout
        android:id="@+id/content_settings_general"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

    <FrameLayout
        android:id="@+id/content_settings_data_sync"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

    <FrameLayout
        android:id="@+id/content_settings_notification"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

</LinearLayout>


text:
include("methods.jl")
include("const.jl")
include("helpers.jl")


text:
/**
 * @file
 * movie video source
 *
 * @todo use direct rendering (no allocation of a new frame)
 * @todo support a PTS correction mechanism
 */

/* #define DEBUG */

#include <float.h>
#include "libavutil/avstring.h"
#include "libavutil/avassert.h"
#include "libavutil/opt.h"
#include "libavutil/imgutils.h"
#include "libavutil/timestamp.h"
#include "libavformat/avformat.h"
#include "audio.h"
#include "avcodec.h"
#include "avfilter.h"
#include "formats.h"
#include "internal.h"
#include "video.h"

typedef struct {
    AVStream *st;
    int done;
} MovieStream;

typedef struct {
    /* common A/V fields */
    const AVClass *class;
    int64_t seek_point;   ///< seekpoint in microseconds
    double seek_point_d;
    char *format_name;
    char *file_name;
    char *stream_specs; /**< user-provided list of streams, separated by + */
    int stream_index; /**< for compatibility */
    int loop_count;

    AVFormatContext *format_ctx;
    int eof;
    AVPacket pkt, pkt0;
    AVFrame *frame;   ///< video frame to store the decoded images in

    int max_stream_index; /**< max stream # actually used for output */
    MovieStream *st; /**< array of all streams, one per output */
    int *out_index; /**< stream number -> output number map, or -1 */
} MovieContext;

#define OFFSET(x) offsetof(MovieContext, x)
#define F AV_OPT_FLAG_FILTERING_PARAM

static const AVOption movie_options[]= {
{"format_name",  "set format name",         OFFSET(format_name),  AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MIN, CHAR_MAX, F },
{"f",            "set format name",         OFFSET(format_name),  AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MIN, CHAR_MAX, F },
{"streams",      "set streams",             OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MAX, CHAR_MAX, F },
{"s",            "set streams",             OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MAX, CHAR_MAX, F },
{"si",           "set stream index",        OFFSET(stream_index), AV_OPT_TYPE_INT,    {.i64 = -1},  -1,       INT_MAX, F },
{"stream_index", "set stream index",        OFFSET(stream_index), AV_OPT_TYPE_INT,    {.i64 = -1},  -1,       INT_MAX, F },
{"seek_point",   "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl =  0},  0,        (INT64_MAX-1) / 1000000, F },
{"sp",           "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl =  0},  0,        (INT64_MAX-1) / 1000000, F },
{"loop",         "set loop count",          OFFSET(loop_count),   AV_OPT_TYPE_INT,    {.i64 =  1},  0,        INT_MAX, F },
{NULL},
};

static int movie_config_output_props(AVFilterLink *outlink);
static int movie_request_frame(AVFilterLink *outlink);

static AVStream *find_stream(void *log, AVFormatContext *avf, const char *spec)
{
    int i, ret, already = 0, stream_id = -1;
    char type_char, dummy;
    AVStream *found = NULL;
    enum AVMediaType type;

    ret = sscanf(spec, "d%[av]%d%c", &type_char, &stream_id, &dummy);
    if (ret >= 1 && ret <= 2) {
        type = type_char == 'v' ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
        ret = av_find_best_stream(avf, type, stream_id, -1, NULL, 0);
        if (ret < 0) {
            av_log(log, AV_LOG_ERROR, "No %s stream with index '%d' found\n",
                   av_get_media_type_string(type), stream_id);
            return NULL;
        }
        return avf->streams[ret];
    }
    for (i = 0; i < avf->nb_streams; i++) {
        ret = avformat_match_stream_specifier(avf, avf->streams[i], spec);
        if (ret < 0) {
            av_log(log, AV_LOG_ERROR,
                   "Invalid stream specifier \"%s\"\n", spec);
            return NULL;
        }
        if (!ret)
            continue;
        if (avf->streams[i]->discard != AVDISCARD_ALL) {
            already++;
            continue;
        }
        if (found) {
            av_log(log, AV_LOG_WARNING,
                   "Ambiguous stream specifier \"%s\", using #%d\n", spec, i);
            break;
        }
        found = avf->streams[i];
    }
    if (!found) {
        av_log(log, AV_LOG_WARNING, "Stream specifier \"%s\" %s\n", spec,
               already ? "matched only already used streams" :
                         "did not match any stream");
        return NULL;
    }
    if (found->codec->codec_type != AVMEDIA_TYPE_VIDEO &&
        found->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
        av_log(log, AV_LOG_ERROR, "Stream specifier \"%s\" matched a %s stream,"
               "currently unsupported by libavfilter\n", spec,
               av_get_media_type_string(found->codec->codec_type));
        return NULL;
    }
    return found;
}

static int open_stream(void *log, MovieStream *st)
{
    AVCodec *codec;
    int ret;

    codec = avcodec_find_decoder(st->st->codec->codec_id);
    if (!codec) {
        av_log(log, AV_LOG_ERROR, "Failed to find any codec\n");
        return AVERROR(EINVAL);
    }

    if ((ret = avcodec_open2(st->st->codec, codec, NULL)) < 0) {
        av_log(log, AV_LOG_ERROR, "Failed to open codec\n");
        return ret;
    }

    return 0;
}

static int guess_channel_layout(MovieStream *st, int st_index, void *log_ctx)
{
    AVCodecContext *dec_ctx = st->st->codec;
    char buf[256];
    int64_t chl = av_get_default_channel_layout(dec_ctx->channels);

    if (!chl) {
        av_log(log_ctx, AV_LOG_ERROR,
               "Channel layout is not set in stream %d, and could not "
               "be guessed from the number of channels (%d)\n",
               st_index, dec_ctx->channels);
        return AVERROR(EINVAL);
    }

    av_get_channel_layout_string(buf, sizeof(buf), dec_ctx->channels, chl);
    av_log(log_ctx, AV_LOG_WARNING,
           "Channel layout is not set in output stream %d, "
           "guessed channel layout is '%s'\n",
           st_index, buf);
    dec_ctx->channel_layout = chl;
    return 0;
}

static av_cold int movie_common_init(AVFilterContext *ctx, const char *args, const AVClass *class)
{
    MovieContext *movie = ctx->priv;
    AVInputFormat *iformat = NULL;
    int64_t timestamp;
    int nb_streams, ret, i;
    char default_streams[16], *stream_specs, *spec, *cursor;
    char name[16];
    AVStream *st;

    movie->class = class;
    av_opt_set_defaults(movie);

    if (args)
        movie->file_name = av_get_token(&args, ":");
    if (!movie->file_name || !*movie->file_name) {
        av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
        return AVERROR(EINVAL);
    }

    if (*args++ == ':' && (ret = av_set_options_string(movie, args, "=", ":")) < 0)
        return ret;

    movie->seek_point = movie->seek_point_d * 1000000 + 0.5;

    stream_specs = movie->stream_specs;
    if (!stream_specs) {
        snprintf(default_streams, sizeof(default_streams), "d%c%d",
                 !strcmp(ctx->filter->name, "amovie") ? 'a' : 'v',
                 movie->stream_index);
        stream_specs = default_streams;
    }
    for (cursor = stream_specs, nb_streams = 1; *cursor; cursor++)
        if (*cursor == '+')
            nb_streams++;

    if (movie->loop_count != 1 && nb_streams != 1) {
        av_log(ctx, AV_LOG_ERROR,
               "Loop with several streams is currently unsupported\n");
        return AVERROR_PATCHWELCOME;
    }

    av_register_all();

    // Try to find the movie format (container)
    iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;

    movie->format_ctx = NULL;
    if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
        av_log(ctx, AV_LOG_ERROR,
               "Failed to avformat_open_input '%s'\n", movie->file_name);
        return ret;
    }
    if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
        av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");

    // if seeking requested, we execute it
    if (movie->seek_point > 0) {
        timestamp = movie->seek_point;
        // add the stream start time, should it exist
        if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
            if (timestamp > INT64_MAX - movie->format_ctx->start_time) {
                av_log(ctx, AV_LOG_ERROR,
                       "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
                       movie->file_name, movie->format_ctx->start_time, movie->seek_point);
                return AVERROR(EINVAL);
            }
            timestamp += movie->format_ctx->start_time;
        }
        if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
            av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
                   movie->file_name, timestamp);
            return ret;
        }
    }

    for (i = 0; i < movie->format_ctx->nb_streams; i++)
        movie->format_ctx->streams[i]->discard = AVDISCARD_ALL;

    movie->st = av_calloc(nb_streams, sizeof(*movie->st));
    if (!movie->st)
        return AVERROR(ENOMEM);

    for (i = 0; i < nb_streams; i++) {
        spec = av_strtok(stream_specs, "+", &cursor);
        if (!spec)
            return AVERROR_BUG;
        stream_specs = NULL; /* for next strtok */
        st = find_stream(ctx, movie->format_ctx, spec);
        if (!st)
            return AVERROR(EINVAL);
        st->discard = AVDISCARD_DEFAULT;
        movie->st[i].st = st;
        movie->max_stream_index = FFMAX(movie->max_stream_index, st->index);
    }
    if (av_strtok(NULL, "+", &cursor))
        return AVERROR_BUG;

    movie->out_index = av_calloc(movie->max_stream_index + 1,
                                 sizeof(*movie->out_index));
    if (!movie->out_index)
        return AVERROR(ENOMEM);
    for (i = 0; i <= movie->max_stream_index; i++)
        movie->out_index[i] = -1;
    for (i = 0; i < nb_streams; i++)
        movie->out_index[movie->st[i].st->index] = i;

    for (i = 0; i < nb_streams; i++) {
        AVFilterPad pad = { 0 };
        snprintf(name, sizeof(name), "out%d", i);
        pad.type          = movie->st[i].st->codec->codec_type;
        pad.name          = av_strdup(name);
        pad.config_props  = movie_config_output_props;
        pad.request_frame = movie_request_frame;
        ff_insert_outpad(ctx, i, &pad);
        ret = open_stream(ctx, &movie->st[i]);
        if (ret < 0)
            return ret;
        if ( movie->st[i].st->codec->codec->type == AVMEDIA_TYPE_AUDIO &&
            !movie->st[i].st->codec->channel_layout) {
            ret = guess_channel_layout(&movie->st[i], i, ctx);
            if (ret < 0)
                return ret;
        }
    }

    if (!(movie->frame = avcodec_alloc_frame()) ) {
        av_log(log, AV_LOG_ERROR, "Failed to alloc frame\n");
        return AVERROR(ENOMEM);
    }

    av_log(ctx, AV_LOG_VERBOSE, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",
           movie->seek_point, movie->format_name, movie->file_name,
           movie->stream_index);

    return 0;
}

static av_cold void movie_uninit(AVFilterContext *ctx)
{
    MovieContext *movie = ctx->priv;
    int i;

    for (i = 0; i < ctx->nb_outputs; i++) {
        av_freep(&ctx->output_pads[i].name);
        if (movie->st[i].st)
            avcodec_close(movie->st[i].st->codec);
    }
    av_opt_free(movie);
    av_freep(&movie->file_name);
    av_freep(&movie->st);
    av_freep(&movie->out_index);
    avcodec_free_frame(&movie->frame);
    if (movie->format_ctx)
        avformat_close_input(&movie->format_ctx);
}

static int movie_query_formats(AVFilterContext *ctx)
{
    MovieContext *movie = ctx->priv;
    int list[] = { 0, -1 };
    int64_t list64[] = { 0, -1 };
    int i;

    for (i = 0; i < ctx->nb_outputs; i++) {
        MovieStream *st = &movie->st[i];
        AVCodecContext *c = st->st->codec;
        AVFilterLink *outlink = ctx->outputs[i];

        switch (c->codec_type) {
        case AVMEDIA_TYPE_VIDEO:
            list[0] = c->pix_fmt;
            ff_formats_ref(ff_make_format_list(list), &outlink->in_formats);
            break;
        case AVMEDIA_TYPE_AUDIO:
            list[0] = c->sample_fmt;
            ff_formats_ref(ff_make_format_list(list), &outlink->in_formats);
            list[0] = c->sample_rate;
            ff_formats_ref(ff_make_format_list(list), &outlink->in_samplerates);
            list64[0] = c->channel_layout;
            ff_channel_layouts_ref(avfilter_make_format64_list(list64),
                                   &outlink->in_channel_layouts);
            break;
        }
    }

    return 0;
}

static int movie_config_output_props(AVFilterLink *outlink)
{
    AVFilterContext *ctx = outlink->src;
    MovieContext *movie  = ctx->priv;
    unsigned out_id = FF_OUTLINK_IDX(outlink);
    MovieStream *st = &movie->st[out_id];
    AVCodecContext *c = st->st->codec;

    outlink->time_base = st->st->time_base;

    switch (c->codec_type) {
    case AVMEDIA_TYPE_VIDEO:
        outlink->w          = c->width;
        outlink->h          = c->height;
        outlink->frame_rate = st->st->r_frame_rate;
        break;
    case AVMEDIA_TYPE_AUDIO:
        break;
    }

    return 0;
}

static AVFilterBufferRef *frame_to_buf(enum AVMediaType type, AVFrame *frame,
                                       AVFilterLink *outlink)
{
    AVFilterBufferRef *buf, *copy;

    buf = avfilter_get_buffer_ref_from_frame(type, frame,
                                             AV_PERM_WRITE |
                                             AV_PERM_PRESERVE |
                                             AV_PERM_REUSE2);
    if (!buf)
        return NULL;
    buf->pts = av_frame_get_best_effort_timestamp(frame);
    copy = ff_copy_buffer_ref(outlink, buf);
    if (!copy)
        return NULL;
    buf->buf->data[0] = NULL; /* it belongs to the frame */
    avfilter_unref_buffer(buf);
    return copy;
}

static char *describe_bufref_to_str(char *dst, size_t dst_size,
                                    AVFilterBufferRef *buf,
                                    AVFilterLink *link)
{
    switch (buf->type) {
    case AVMEDIA_TYPE_VIDEO:
        snprintf(dst, dst_size,
                 "video pts:%s time:%s pos:%"PRId64" size:%dx%d aspect:%d/%d",
                 av_ts2str(buf->pts), av_ts2timestr(buf->pts, &link->time_base),
                 buf->pos, buf->video->w, buf->video->h,
                 buf->video->sample_aspect_ratio.num,
                 buf->video->sample_aspect_ratio.den);
                 break;
    case AVMEDIA_TYPE_AUDIO:
        snprintf(dst, dst_size,
                 "audio pts:%s time:%s pos:%"PRId64" samples:%d",
                 av_ts2str(buf->pts), av_ts2timestr(buf->pts, &link->time_base),
                 buf->pos, buf->audio->nb_samples);
                 break;
    default:
        snprintf(dst, dst_size, "%s BUG", av_get_media_type_string(buf->type));
        break;
    }
    return dst;
}

#define describe_bufref(buf, link) \
    describe_bufref_to_str((char[1024]){0}, 1024, buf, link)

static int rewind_file(AVFilterContext *ctx)
{
    MovieContext *movie = ctx->priv;
    int64_t timestamp = movie->seek_point;
    int ret, i;

    if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
        timestamp += movie->format_ctx->start_time;
    ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD);
    if (ret < 0) {
        av_log(ctx, AV_LOG_ERROR, "Unable to loop: %s\n", av_err2str(ret));
        movie->loop_count = 1; /* do not try again */
        return ret;
    }

    for (i = 0; i < ctx->nb_outputs; i++) {
        avcodec_flush_buffers(movie->st[i].st->codec);
        movie->st[i].done = 0;
    }
    movie->eof = 0;
    return 0;
}

/**
 * Try to push a frame to the requested output.
 *
 * @param ctx     filter context
 * @param out_id  number of output where a frame is wanted;
 *                if the frame is read from file, used to set the return value;
 *                if the codec is being flushed, flush the corresponding stream
 * @return  1 if a frame was pushed on the requested output,
 *          0 if another attempt is possible,
 *          <0 AVERROR code
 */
static int movie_push_frame(AVFilterContext *ctx, unsigned out_id)
{
    MovieContext *movie = ctx->priv;
    AVPacket *pkt = &movie->pkt;
    MovieStream *st;
    int ret, got_frame = 0, pkt_out_id;
    AVFilterLink *outlink;
    AVFilterBufferRef *buf;

    if (!pkt->size) {
        if (movie->eof) {
            if (movie->st[out_id].done) {
                if (movie->loop_count != 1) {
                    ret = rewind_file(ctx);
                    if (ret < 0)
                        return ret;
                    movie->loop_count -= movie->loop_count > 1;
                    av_log(ctx, AV_LOG_VERBOSE, "Stream finished, looping.\n");
                    return 0; /* retry */
                }
                return AVERROR_EOF;
            }
            pkt->stream_index = movie->st[out_id].st->index;
            /* packet is already ready for flushing */
        } else {
            ret = av_read_frame(movie->format_ctx, &movie->pkt0);
            if (ret < 0) {
                av_init_packet(&movie->pkt0); /* ready for flushing */
                *pkt = movie->pkt0;
                if (ret == AVERROR_EOF) {
                    movie->eof = 1;
                    return 0; /* start flushing */
                }
                return ret;
            }
            *pkt = movie->pkt0;
        }
    }

    pkt_out_id = pkt->stream_index > movie->max_stream_index ? -1 :
                 movie->out_index[pkt->stream_index];
    if (pkt_out_id < 0) {
        av_free_packet(&movie->pkt0);
        pkt->size = 0; /* ready for next run */
        pkt->data = NULL;
        return 0;
    }
    st = &movie->st[pkt_out_id];
    outlink = ctx->outputs[pkt_out_id];

    switch (st->st->codec->codec_type) {
    case AVMEDIA_TYPE_VIDEO:
        ret = avcodec_decode_video2(st->st->codec, movie->frame, &got_frame, pkt);
        break;
    case AVMEDIA_TYPE_AUDIO:
        ret = avcodec_decode_audio4(st->st->codec, movie->frame, &got_frame, pkt);
        break;
    default:
        ret = AVERROR(ENOSYS);
        break;
    }
    if (ret < 0) {
        av_log(ctx, AV_LOG_WARNING, "Decode error: %s\n", av_err2str(ret));
        return 0;
    }
    if (!ret)
        ret = pkt->size;

    pkt->data += ret;
    pkt->size -= ret;
    if (pkt->size <= 0) {
        av_free_packet(&movie->pkt0);
        pkt->size = 0; /* ready for next run */
        pkt->data = NULL;
    }
    if (!got_frame) {
        if (!ret)
            st->done = 1;
        return 0;
    }

    buf = frame_to_buf(st->st->codec->codec_type, movie->frame, outlink);
    if (!buf)
        return AVERROR(ENOMEM);
    av_dlog(ctx, "movie_push_frame(): file:'%s' %s\n", movie->file_name,
            describe_bufref(buf, outlink));
    switch (st->st->codec->codec_type) {
    case AVMEDIA_TYPE_VIDEO:
        if (!movie->frame->sample_aspect_ratio.num)
            buf->video->sample_aspect_ratio = st->st->sample_aspect_ratio;
        ff_start_frame(outlink, buf);
        ff_draw_slice(outlink, 0, outlink->h, 1);
        ff_end_frame(outlink);
        break;
    case AVMEDIA_TYPE_AUDIO:
        ff_filter_samples(outlink, buf);
        break;
    }

    return pkt_out_id == out_id;
}

static int movie_request_frame(AVFilterLink *outlink)
{
    AVFilterContext *ctx = outlink->src;
    unsigned out_id = FF_OUTLINK_IDX(outlink);
    int ret;

    while (1) {
        ret = movie_push_frame(ctx, out_id);
        if (ret)
            return FFMIN(ret, 0);
    }
}

#if CONFIG_MOVIE_FILTER

AVFILTER_DEFINE_CLASS(movie);

static av_cold int movie_init(AVFilterContext *ctx, const char *args)
{
    return movie_common_init(ctx, args, &movie_class);
}

AVFilter avfilter_avsrc_movie = {
    .name          = "movie",
    .description   = NULL_IF_CONFIG_SMALL("Read from a movie source."),
    .priv_size     = sizeof(MovieContext),
    .init          = movie_init,
    .uninit        = movie_uninit,
    .query_formats = movie_query_formats,

    .inputs    = NULL,
    .outputs   = (const AVFilterPad[]) {{ .name = NULL }},
    .priv_class = &movie_class,
};

#endif  /* CONFIG_MOVIE_FILTER */

#if CONFIG_AMOVIE_FILTER

#define amovie_options movie_options
AVFILTER_DEFINE_CLASS(amovie);

static av_cold int amovie_init(AVFilterContext *ctx, const char *args)
{
    return movie_common_init(ctx, args, &amovie_class);
}

AVFilter avfilter_avsrc_amovie = {
    .name          = "amovie",
    .description   = NULL_IF_CONFIG_SMALL("Read audio from a movie source."),
    .priv_size     = sizeof(MovieContext),
    .init          = amovie_init,
    .uninit        = movie_uninit,
    .query_formats = movie_query_formats,

    .inputs    = (const AVFilterPad[]) {{ .name = NULL }},
    .outputs   = (const AVFilterPad[]) {{ .name = NULL }},
    .priv_class = &amovie_class,
};

#endif /* CONFIG_AMOVIE_FILTER */


text:
require "spec_helper"
require "active_attr/serialization"
require "active_model/serializers/xml"
require "active_support/core_ext/hash/conversions"
require "active_support/json/decoding"

module ActiveAttr
  describe Serialization do
    let :model_class do
      Class.new do
        include Serialization
        include ActiveModel::Serializers::Xml
        attribute :first_name

        def self.name
          "Person"
        end
      end
    end

    subject(:model) { model_class.new }

    it "serializes to/from JSON" do
      model.first_name = "Chris"
      model_class.new.from_json(model.to_json).first_name.should == "Chris"
    end

    it "serializes to/from XML" do
      model.first_name = "Chris"
      model_class.new.from_xml(model.to_xml).first_name.should == "Chris"
    end
  end
end


text:
<?php
/**
 * Test for net::stubbles::streams::stubPrefixedStreamFactory.
 *
 * @package     stubbles
 * @subpackage  streams_test
 * @version     $Id: stubPrefixedStreamFactoryTestCase.php 2299 2009-08-24 14:09:44Z mikey $
 */
stubClassLoader::load('net::stubbles::streams::stubPrefixedStreamFactory');
/**
 * Test for net::stubbles::streams::stubPrefixedStreamFactory.
 *
 * @package     stubbles
 * @subpackage  streams_test
 * @group       streams
 */
class stubPrefixedStreamFactoryTestCase extends PHPUnit_Framework_TestCase
{
    /**
     * instance to test
     *
     * @var  stubPrefixedStreamFactory
     */
    protected $prefixedStreamFactory;
    /**
     * mocked stream factory
     *
     * @var  PHPUnit_Framework_MockObject_MockObject
     */
    protected $mockStreamFactory;

    /**
     * set up test environment
     */
    public function setUp()
    {
        $this->mockStreamFactory     = $this->getMock('stubStreamFactory');
        $this->prefixedStreamFactory = new stubPrefixedStreamFactory($this->mockStreamFactory, 'prefix/');
    }

    /**
     * @test
     */
    public function inputStreamGetsPrefix()
    {
        $mockInputStream = $this->getMock('stubInputStream');
        $this->mockStreamFactory->expects($this->once())
                                ->method('createInputStream')
                                ->with($this->equalTo('prefix/foo'), $this->equalTo(array('bar' => 'baz')))
                                ->will($this->returnValue($mockInputStream));
        $this->assertSame($mockInputStream, $this->prefixedStreamFactory->createInputStream('foo', array('bar' => 'baz')));
    }

    /**
     * @test
     */
    public function outputStreamGetsPrefix()
    {
        $mockOutputStream = $this->getMock('stubOutputStream');
        $this->mockStreamFactory->expects($this->once())
                                ->method('createOutputStream')
                                ->with($this->equalTo('prefix/foo'), $this->equalTo(array('bar' => 'baz')))
                                ->will($this->returnValue($mockOutputStream));
        $this->assertSame($mockOutputStream, $this->prefixedStreamFactory->createOutputStream('foo', array('bar' => 'baz')));
    }
}
?>


text:
<?php

namespace McCool\Tests;

use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use McCool\LaravelAutoPresenter\AutoPresenter;
use McCool\LaravelAutoPresenter\Decorators\DecoratorInterface;
use McCool\LaravelAutoPresenter\Exceptions\PresenterNotFoundException;
use McCool\Tests\Stubs\DecoratedAtom;
use McCool\Tests\Stubs\DecoratedAtomPresenter;
use McCool\Tests\Stubs\DependencyDecoratedAtom;
use McCool\Tests\Stubs\DependencyDecoratedAtomPresenter;
use McCool\Tests\Stubs\UndecoratedAtom;
use McCool\Tests\Stubs\WronglyDecoratedAtom;
use Mockery;

class AutoPresenterTest extends AbstractTestCase
{
    private $autoPresenter;

    /**
     * @before
     */
    public function setUpProperties()
    {
        $this->autoPresenter = $this->app->make(AutoPresenter::class);
    }

    public function testRegistration()
    {
        $autoPresenter = new AutoPresenter();

        $decorator = Mockery::mock(DecoratorInterface::class);

        $autoPresenter->register($decorator);

        $this->assertSame([$decorator], $autoPresenter->getDecorators());
    }

    public function testWontDecorateOtherObjects()
    {
        $atom = new UndecoratedAtom();
        $decoratedAtom = $this->autoPresenter->decorate($atom);

        $this->assertInstanceOf(UndecoratedAtom::class, $decoratedAtom);
    }

    public function testDecoratesAtom()
    {
        $atom = $this->getDecoratedAtom();
        $decoratedAtom = $this->autoPresenter->decorate($atom);

        $this->assertInstanceOf(DecoratedAtomPresenter::class, $decoratedAtom);
    }

    public function testDecoratesAtomWithDependencies()
    {
        $atom = $this->getDependencyDecoratedAtom();
        $decoratedAtom = $this->autoPresenter->decorate($atom);

        $this->assertInstanceOf(DependencyDecoratedAtomPresenter::class, $decoratedAtom);
    }

    public function testDecoratesPaginator()
    {
        $paginator = $this->getFilledPaginator();
        $decoratedPaginator = $this->autoPresenter->decorate($paginator);

        $this->assertCount(5, $decoratedPaginator);

        foreach ($decoratedPaginator as $decoratedAtom) {
            $this->assertInstanceOf(DecoratedAtomPresenter::class, $decoratedAtom);
        }
    }

    public function testDecorateCollection()
    {
        $collection = $this->getFilledCollection();
        $decoratedCollection = $this->autoPresenter->decorate($collection);

        $this->assertCount(5, $decoratedCollection);

        foreach ($decoratedCollection as $decoratedAtom) {
            $this->assertInstanceOf(DecoratedAtomPresenter::class, $decoratedAtom);
        }
    }

    /**
     * @expectedException \McCool\LaravelAutoPresenter\Exceptions\PresenterNotFoundException
     */
    public function testWronglyDecoratedClassThrowsException()
    {
        try {
            $atom = new WronglyDecoratedAtom();
            $this->autoPresenter->decorate($atom);
        } catch (PresenterNotFoundException $e) {
            $class = 'ThisClassDoesntExistAnywhereInTheKnownUniverse';
            $this->assertSame("The presenter class '$class' was not found.", $e->getMessage());
            $this->assertSame($class, $e->getClass());
            throw $e;
        }
    }

    private function getDecoratedAtom()
    {
        return new DecoratedAtom();
    }

    private function getDependencyDecoratedAtom()
    {
        return new DependencyDecoratedAtom();
    }

    private function getFilledPaginator()
    {
        $items = [];

        foreach (range(1, 5) as $i) {
            $items[] = $this->getDecoratedAtom();
        }

        return new Paginator($items, 5);
    }

    private function getFilledCollection()
    {
        $items = [];

        foreach (range(1, 5) as $i) {
            $items[] = $this->getDecoratedAtom();
        }

        return new Collection($items);
    }
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition (jackson-databind 2.0.0 API)
</TITLE>

<META NAME="date" CONTENT="2012-03-26">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition

Packages that use BeanPropertyDefinition

com.fasterxml.jackson.databind
Contains basic mapper (conversion) functionality that
allows for converting between regular streaming json content and
Java objects (beans or Tree Model: support for both is via
ObjectMapper class, as well
as convenience methods included in
JsonParser

com.fasterxml.jackson.databind.deser
Contains implementation classes of deserialization part of
 data binding.

com.fasterxml.jackson.databind.deser.impl
Contains those implementation classes of deserialization part of
 data binding that are not considered part of public or semi-public
 interfaces.

com.fasterxml.jackson.databind.introspect
Functionality needed for Bean introspection, required for detecting
 accessors and mutators for Beans, as well as locating and handling
 method annotations.

com.fasterxml.jackson.databind.ser
Contains implementation classes of serialization part of
 data binding.

com.fasterxml.jackson.databind.util
Utility classes for Mapper package.

Uses of BeanPropertyDefinition in com.fasterxml.jackson.databind

Methods in com.fasterxml.jackson.databind that return types with arguments of type BeanPropertyDefinition

abstract  List<BeanPropertyDefinition>
BeanDescription.findProperties()

Uses of BeanPropertyDefinition in com.fasterxml.jackson.databind.deser

Methods in com.fasterxml.jackson.databind.deser that return types with arguments of type BeanPropertyDefinition

protected  List<BeanPropertyDefinition>
BeanDeserializerFactory.filterBeanProps(DeserializationContext ctxt,
                BeanDescription beanDesc,
                BeanDeserializerBuilder builder,
                List<BeanPropertyDefinition> propDefsIn,
                Set<String> ignored)

          Helper method called to filter out explicit ignored properties,
 as well as properties that have "ignorable types".

 List<BeanPropertyDefinition>
BeanDeserializerModifier.updateProperties(DeserializationConfig config,
                 BeanDescription beanDesc,
                 List<BeanPropertyDefinition> propDefs)

          Method called by BeanDeserializerFactory when it has collected
 initial list of BeanPropertyDefinitions, and done basic by-name
 and by-type filtering, but before constructing builder or actual
 property handlers; or arranging order.

Methods in com.fasterxml.jackson.databind.deser with parameters of type BeanPropertyDefinition

 void
BeanDeserializerBuilder.addCreatorProperty(BeanPropertyDefinition propDef)

          Method called by deserializer factory, when a "creator property"
 (something that is passed via constructor- or factory method argument;
 instead of setter or field).

protected  SettableBeanProperty
BeanDeserializerFactory.constructSettableProperty(DeserializationContext ctxt,
                          BeanDescription beanDesc,
                          BeanPropertyDefinition propDef,
                          Type jdkType)

          Method that will construct a regular bean property setter using
 the given setter method.

protected  SettableBeanProperty
BeanDeserializerFactory.constructSetterlessProperty(DeserializationContext ctxt,
                            BeanDescription beanDesc,
                            BeanPropertyDefinition propDef)

          Method that will construct a regular bean property setter using
 the given setter method.

Method parameters in com.fasterxml.jackson.databind.deser with type arguments of type BeanPropertyDefinition

protected  List<BeanPropertyDefinition>
BeanDeserializerFactory.filterBeanProps(DeserializationContext ctxt,
                BeanDescription beanDesc,
                BeanDeserializerBuilder builder,
                List<BeanPropertyDefinition> propDefsIn,
                Set<String> ignored)

          Helper method called to filter out explicit ignored properties,
 as well as properties that have "ignorable types".

 List<BeanPropertyDefinition>
BeanDeserializerModifier.updateProperties(DeserializationConfig config,
                 BeanDescription beanDesc,
                 List<BeanPropertyDefinition> propDefs)

          Method called by BeanDeserializerFactory when it has collected
 initial list of BeanPropertyDefinitions, and done basic by-name
 and by-type filtering, but before constructing builder or actual
 property handlers; or arranging order.

Constructors in com.fasterxml.jackson.databind.deser with parameters of type BeanPropertyDefinition

SettableBeanProperty(BeanPropertyDefinition propDef,
                     JavaType type,
                     TypeDeserializer typeDeser,
                     Annotations contextAnnotations)

Uses of BeanPropertyDefinition in com.fasterxml.jackson.databind.deser.impl

Constructors in com.fasterxml.jackson.databind.deser.impl with parameters of type BeanPropertyDefinition

FieldProperty(BeanPropertyDefinition propDef,
              JavaType type,
              TypeDeserializer typeDeser,
              Annotations contextAnnotations,
              AnnotatedField field)

MethodProperty(BeanPropertyDefinition propDef,
               JavaType type,
               TypeDeserializer typeDeser,
               Annotations contextAnnotations,
               AnnotatedMethod method)

SetterlessProperty(BeanPropertyDefinition propDef,
                   JavaType type,
                   TypeDeserializer typeDeser,
                   Annotations contextAnnotations,
                   AnnotatedMethod method)

Uses of BeanPropertyDefinition in com.fasterxml.jackson.databind.introspect

Subclasses of BeanPropertyDefinition in com.fasterxml.jackson.databind.introspect

 class
POJOPropertyBuilder

          Helper class used for aggregating information about a single
 potential POJO property.

Fields in com.fasterxml.jackson.databind.introspect with type parameters of type BeanPropertyDefinition

protected  List<BeanPropertyDefinition>
BasicBeanDescription._properties

          Properties collected for the POJO.

Methods in com.fasterxml.jackson.databind.introspect that return BeanPropertyDefinition

abstract  BeanPropertyDefinition
BeanPropertyDefinition.withName(String newName)

          Method that can be used to create a definition with
 same settings as this one, but with different
 (external) name; that is, one for which
 getName() would return newName.

Methods in com.fasterxml.jackson.databind.introspect that return types with arguments of type BeanPropertyDefinition

 List<BeanPropertyDefinition>
BasicBeanDescription.findProperties()

 List<BeanPropertyDefinition>
POJOPropertiesCollector.getProperties()

Constructor parameters in com.fasterxml.jackson.databind.introspect with type arguments of type BeanPropertyDefinition

BasicBeanDescription(MapperConfig<?> config,
                     JavaType type,
                     AnnotatedClass classDef,
                     List<BeanPropertyDefinition> props)

Uses of BeanPropertyDefinition in com.fasterxml.jackson.databind.ser

Methods in com.fasterxml.jackson.databind.ser with parameters of type BeanPropertyDefinition

protected  BeanPropertyWriter
BeanSerializerFactory._constructWriter(SerializerProvider prov,
                 BeanPropertyDefinition propDef,
                 TypeBindings typeContext,
                 PropertyBuilder pb,
                 boolean staticTyping,
                 AnnotatedMember accessor)

          Secondary helper method for constructing BeanPropertyWriter for
 given member (field or method).

protected  BeanPropertyWriter
PropertyBuilder.buildWriter(BeanPropertyDefinition propDef,
            JavaType declaredType,
            JsonSerializer<?> ser,
            TypeSerializer typeSer,
            TypeSerializer contentTypeSer,
            AnnotatedMember am,
            boolean defaultUseStaticTyping)

Method parameters in com.fasterxml.jackson.databind.ser with type arguments of type BeanPropertyDefinition

protected  void
BeanSerializerFactory.removeIgnorableTypes(SerializationConfig config,
                     BeanDescription beanDesc,
                     List<BeanPropertyDefinition> properties)

          Method that will apply by-type limitations (as per [JACKSON-429]);
 by default this is based on JsonIgnoreType annotation but
 can be supplied by module-provided introspectors too.

protected  void
BeanSerializerFactory.removeSetterlessGetters(SerializationConfig config,
                        BeanDescription beanDesc,
                        List<BeanPropertyDefinition> properties)

          Helper method that will remove all properties that do not have a mutator.

Constructors in com.fasterxml.jackson.databind.ser with parameters of type BeanPropertyDefinition

BeanPropertyWriter(BeanPropertyDefinition propDef,
                   AnnotatedMember member,
                   Annotations contextAnnotations,
                   JavaType declaredType,
                   JsonSerializer<?> ser,
                   TypeSerializer typeSer,
                   JavaType serType,
                   boolean suppressNulls,
                   Object suppressableValue)

Uses of BeanPropertyDefinition in com.fasterxml.jackson.databind.util

Subclasses of BeanPropertyDefinition in com.fasterxml.jackson.databind.util

 class
SimpleBeanPropertyDefinition

          Simple immutable BeanPropertyDefinition implementation that can
 be wrapped around a AnnotatedMember that is a simple
 accessor (getter) or mutator (setter, constructor parameter)
 (or both, for fields).

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2012 fasterxml.com. All Rights Reserved.


text:
export const PACKAGE_JSON = 'package.json';
export const JEST_CONFIG = 'jest.config.js';


text:
package net.akmorrow13.endive.processing

import net.akmorrow13.endive.utils.DeepbindRecord
import org.apache.spark.rdd.RDD
import org.apache.spark.util.random

import scala.collection.mutable.ListBuffer
import scala.util.Random

object DinucleotideShuffle {

  def doublet_shuffle(seq: String): String = {
    val last_nt = seq.toCharArray.last
    val graph = Graph.form_seq_graph(seq)
    // sample a random last edge graph
    var is_ok = false
    var le_graph: Map[Char, List[Char]] = Map()
    while (!is_ok) {
      le_graph = Graph.sample_le_graph(graph, last_nt)
      // check the last edge graph
      is_ok = Graph.check_le_graph(le_graph, last_nt)
    }
    val new_graph = Graph.form_new_graph(graph, le_graph, last_nt)
    val shuf_seq  = Graph.form_shuffled_seq(new_graph.mapValues(_.toList), seq(0), seq.length)
    return shuf_seq

  }

  def getShuffledDinucletides(rdd: RDD[DeepbindRecord]): RDD[DeepbindRecord] = {

    rdd.map(_.sequence).map(r => doublet_shuffle(r))
      .zip(rdd)
      .map(r => DeepbindRecord(r._2.tf, r._2.cellType, r._2.id +"shuff", r._1, 0))

  }

}

object Graph {

   def form_shuffled_seq(new_graph: Map[Char, List[Char]], init_nt: Char, len_seq: Int): String = {
     var tmp_graph = new_graph
     var is_done = false
     var new_seq: ListBuffer[Char] = ListBuffer(init_nt)
     while (!is_done) {
       val last_nt = new_seq.last
       try {
         new_seq += tmp_graph(last_nt)(0)
       } catch {
         // TODO: this is not quite right
         case e: Exception => new_seq ++= tmp_graph.values.flatten.toList
       }

       // pop off last element
       tmp_graph = tmp_graph + (last_nt -> tmp_graph(last_nt).drop(1))
       if(new_seq.length >= len_seq)
         is_done = true
     }
     return new_seq.mkString
   }

  // sample a random last edge
  def sample_le_graph(graph: Map[Char, List[Char]], last_nt: Char): Map[Char, List[Char]] = {
    var newGraph: Map[Char, List[Char]] = Map()

    graph.map(r => {
      val newList =
        if (r._1 != last_nt) {
          val x = Random.nextInt(graph(r._1).size)
          newGraph += (r._1 -> List(graph(r._1)(x)))
        } else List()
      (r._1, r._2.toList)
    })
  }

  def check_le_graph(le_graph: Map[Char, List[Char]], last_nt: Char): Boolean = {
    for (k <- le_graph.keys) {
      if (k != last_nt) {
        if (!find_path(le_graph, k, last_nt).isDefined)
          return false
      }
    }
    true
  }

  // check whether there is a path between two nodes in a graph
  def find_path(graph: Map[Char, List[Char]], start: Char, end: Char, path: ListBuffer[Char] = ListBuffer.empty): Option[ListBuffer[Char]] = {
    path += start
    if (start == end) {
      return Some(path)
    }
    if (!graph.keySet.contains(start)) {
      return None
    }
    for (node <- graph(start)) {
      if (!path.contains(node)) {
        val newPath = find_path(graph, node, end, path)
        if (newPath.isDefined) return newPath
      }
      return None
    }
    None
  }

  def form_new_graph(graph: Map[Char, List[Char]], le_graph: Map[Char, List[Char]], last_nt: Char): Map[Char, ListBuffer[Char]] = {
    var new_graph: Map[Char, ListBuffer[Char]] = Map[Char, ListBuffer[Char]]()
    for (vx <- graph.keys) {
      new_graph += (vx -> ListBuffer[Char]())
      var temp_edges = graph(vx)
      if (vx != last_nt)
        temp_edges = Random.shuffle(temp_edges.drop(1))
      for (ux <- temp_edges)
        new_graph(vx).append(ux)
      if (vx != last_nt)
        new_graph(vx).append(le_graph(vx)(0))
    }
    new_graph
  }

  // for each base, keep track of the bases you see after that base
  def form_seq_graph(seq: String): Map[Char, List[Char]] = {

    var graph: Map[Char, ListBuffer[Char]] = Map[Char, ListBuffer[Char]]()

    val arr = seq.toCharArray

    for (i <- 0 until arr.length-1) {
      if (!graph.get(arr(i)).isDefined) {
        graph += (arr(i) -> ListBuffer())
      }
      val charList: ListBuffer[Char] = graph.get(arr(i)).get // get base in graph
      // update map
      val char =arr(i+1)
      charList += char

      graph = graph + (arr(i) -> charList)
    }
    graph.mapValues(_.toList)
  }
//
//  def empty: Map[Char, ListBuffer[Char]] = {
//    Map()
////    Map('A'-> ListBuffer(), 'C'->ListBuffer(),'G'->ListBuffer(),'T'->ListBuffer())
//  }

}


text:
require 'open-uri'
require 'resolv-replace'

module Voice::Downloadable
  extend ActiveSupport::Concern

  attr_accessor :cached_page

  included do
    field :url, type: String
    field :path, type: String
    field :page_identity, type: String
  end

  def download
    return @cached_page if @cached_page

    credential = basic_auth.present? ? decrypt(basic_auth) : nil
    @cached_page = with_retry(max_attempts) do
      # class must provide a method 'url'
      options = {}
      options[:read_timeout] = timeout_sec
      options[:http_basic_authentication] = credential if credential.present?
      open(url, options) do |f|
        status_code = f.status[0]

        html = f.read if status_code == '200'
        html.force_encoding("utf-8") if html
        page_identity = make_page_identity(html, f.meta['etag'], f.last_modified)

        page = {
          html: html,
          page_identity: page_identity
        }
        OpenStruct.new(page)
      end
    end
    @cached_page
  rescue
    Rails.logger.info("error was raised while downloading from #{url}")
    raise
  end

  def same_identity?
    download
    page_identity == @cached_page.page_identity
  end

  private

  def max_attempts
    @max_attempts ||= SS.config.voice.download['max_attempts']
  end

  def initial_wait
    @initial_wait ||= SS.config.voice.download['initial_wait']
  end

  def timeout_sec
    @timeout_sec ||= SS.config.voice.download['timeout_sec']
  end

  def basic_auth
    @basic_auth ||= SS.config.voice.download['basic_auth']
  end

  def with_retry(max_attempts)
    num_attempts = 0
    wait = initial_wait

    begin
      yield
    rescue Timeout::Error, StandardError => e
      Rails.logger.warn("#{e.class} (#{e.message}):\n  #{e.backtrace.join('\n  ')}")
      num_attempts += 1
      raise if num_attempts >= max_attempts

      sleep wait
      wait *= 2
      retry
    end
  end

  def make_page_identity(html, _, _)
    Digest::MD5.hexdigest(purge_csrf_token(html))
  end

  def purge_csrf_token(html)
    html.gsub!(/<\s*meta\s+content\s*=\s*["']authenticity_token["']\s+name\s*=\s*["']csrf-param["']\s*\/>/, '')
    html.gsub!(/<\s*meta\s+content\s*=\s*["'].+?["']\s+name\s*=\s*["']csrf-token["']\s*\/>/, '')
    html
  end

  def decrypt(auth)
    secrets = Rails.application.secrets[:secret_key_base]
    encryptor = ::ActiveSupport::MessageEncryptor.new(secrets, cipher: 'aes-256-cbc')
    user, pass = auth
    begin
      user = encryptor.decrypt_and_verify(user)
    rescue ActiveSupport::MessageVerifier::InvalidSignature
      # ignore
    end

    begin
      pass = encryptor.decrypt_and_verify(pass)
    rescue ActiveSupport::MessageVerifier::InvalidSignature
      # ignore
    end
    [ user, pass ]
  end

  module ClassMethods
    def find_or_create_by_url(url)
      url = ::URI.parse(url.to_s) unless url.respond_to?(:host)
      if url.host.blank? || url.path.blank?
        # path must not be either nil, empty.
        return nil
      end
      url.normalize!

      site = find_site url
      unless site
        Rails.logger.debug("site is not found: #{url}")
        return nil
      end

      voice_file = self.find_or_create_by site_id: site.id, path: url.path
      if voice_file.url.blank?
        # remove query string and fragments.
        voice_file.url = url.to_s.gsub(/\?.+$/, '').gsub(/#.+$/, '')
        voice_file.save!
      end
      voice_file
    end

    private

    def find_site(url)
      host = url.host
      port = url.port
      path = url.path

      SS::Site.find_by_domain("#{host}:#{port}", path) || SS::Site.find_by_domain(host.to_s, path)
    end
  end
end


text:
import pytest

from thefuck.rules.aws_cli import match, get_new_command
from thefuck.types import Command

no_suggestions = '''\
usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help
aws: error: argument command: Invalid choice, valid choices are:

dynamodb                                 | dynamodbstreams
ec2                                      | ecr
'''

misspelled_command = '''\
usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help
aws: error: argument command: Invalid choice, valid choices are:

dynamodb                                 | dynamodbstreams
ec2                                      | ecr

Invalid choice: 'dynamdb', maybe you meant:

  * dynamodb
'''

misspelled_subcommand = '''\
usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help
aws: error: argument operation: Invalid choice, valid choices are:

query                                    | scan
update-item                              | update-table

Invalid choice: 'scn', maybe you meant:

  * scan
'''

misspelled_subcommand_with_multiple_options = '''\
usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help
aws: error: argument operation: Invalid choice, valid choices are:

describe-table                           | get-item
list-tables                              | put-item

Invalid choice: 't-item', maybe you meant:

  * put-item
  * get-item
'''

@pytest.mark.parametrize('command', [
    Command('aws dynamdb scan', misspelled_command),
    Command('aws dynamodb scn', misspelled_subcommand),
    Command('aws dynamodb t-item',
            misspelled_subcommand_with_multiple_options)])
def test_match(command):
    assert match(command)

def test_not_match():
    assert not match(Command('aws dynamodb invalid', no_suggestions))

@pytest.mark.parametrize('command, result', [
    (Command('aws dynamdb scan', misspelled_command),
     ['aws dynamodb scan']),
    (Command('aws dynamodb scn', misspelled_subcommand),
     ['aws dynamodb scan']),
    (Command('aws dynamodb t-item',
             misspelled_subcommand_with_multiple_options),
     ['aws dynamodb put-item', 'aws dynamodb get-item'])])
def test_get_new_command(command, result):
    assert get_new_command(command) == result


text:
namespace
{
struct PartitionPoint {
  Eigen::VectorXf pos;
  size_t originalIndex;
  int32_t color;
};

void recursivePartitioningByAxisHelper(PartitionPoint * begin, PartitionPoint * end, int & nextFreeColor, int maxBlockSize, int axisToSplit)
{
  size_t numPoints = end - begin;
  if (numPoints <= maxBlockSize)
  {
    while (begin < end)
    {
      begin->color = nextFreeColor;
      ++begin;
    }
    ++nextFreeColor;
    return;
  }
  else
  {
    auto mid = begin + numPoints / 2;
    std::nth_element(begin, mid, end, [&](const PartitionPoint & a, const PartitionPoint & b) {
      return a.pos[axisToSplit] < b.pos[axisToSplit];
    });
    axisToSplit = (axisToSplit + 1) % begin->pos.size();
    recursivePartitioningByAxisHelper(begin, mid, nextFreeColor, maxBlockSize, axisToSplit);
    recursivePartitioningByAxisHelper(mid, end, nextFreeColor, maxBlockSize, axisToSplit);
  }
}

} // namespace anon

namespace drew
{

std::vector<int32_t> recursivePartitionByAxis(const Eigen::MatrixXf & positions, int maxBlockSize)
{
  //using ::PartitionPoint;

  const size_t numPoints = positions.cols();
  std::vector<PartitionPoint> points(numPoints);
  for (size_t p = 0; p < numPoints; ++p)
    points[p] = PartitionPoint{ positions.col(p),p };

  int32_t nextFreeColor = 0;
  recursivePartitioningByAxisHelper(points.data(), points.data() + numPoints, nextFreeColor, maxBlockSize, 0);

  std::vector<int32_t> colors(numPoints);
  for (const auto & p : points)
    colors[p.originalIndex] = p.color;

  return colors;
}

std::vector<std::vector<int64_t>> nodesOfEachColor(const std::vector<int32_t> & colors)
{
  // Count the total number of colors and the number of nodes of each color
  int64_t numColors = 0;
  std::vector<int64_t> numPerColor;
  numPerColor.reserve(100);
  for (auto & c : colors)
  {
    if (c >= numColors)
    {
      numColors = c + 1;
      numPerColor.resize(numColors, 0);
      ++numPerColor[c];
    }
  }

  std::vector<std::vector<int64_t>> indexSets(numColors);
  for (int32_t c = 0; c < numColors; ++c)
  {
    indexSets[c].reserve(numPerColor[c]);
  }

  const int64_t numVertices = colors.size();
  for(int64_t i=0; i<numVertices; ++i)
  {
    const auto c = colors[i];
    indexSets[c].push_back(i);
  }

  return indexSets;
}

std::vector<int64_t> expandSubdomain(const Eigen::SparseMatrix<double> & mat, std::vector<int64_t> nodes, int32_t depth, std::vector<bool> & visited)
{
  assert(depth >= 0);
  assert(mat.rows() == mat.cols());
  assert(visited == std::vector<bool>(mat.rows(), false));
  //assert(isSymmetricTopology(mat));

  if (depth == 0)
    return nodes;

  // Repeatedly (up to depth times) walk out from the existing nodes,
  // collecting additional nodes. Use visited to keep track of which
  // nodes are already in the result and should not be collected again.
  // A node is 'visited' if it's in the nodes array.

  size_t beginFront = 0; // nodes before beginFront have all been visisted.
  for (int32_t d = 0; d < depth; ++d)
  {
    // invariant: nodes[i] has been visited for all i <= beginFront
    // invariant: nodes[i] has not been visited for all i >= beginFront
    // invariant: visited[i] iff node i has been visited already

    size_t endFront = nodes.size();
    for (size_t i = beginFront; i < endFront; ++i)
    {
      int64_t node = nodes[i];
      for (Eigen::SparseMatrix<double>::InnerIterator it(mat, node); it; ++it)
      {
        int64_t otherNode = it.index();
        if (!visited[otherNode])
        {
          visited[otherNode] = true;
          nodes.push_back(otherNode);
        }
      }
    }
    beginFront = endFront;
  }

  // set nodes back to false
  for (auto & i : nodes)
    visited[i] = false;

  return nodes;
}

std::vector<int64_t> expandSubdomain(const Eigen::SparseMatrix<double> & mat, std::vector<int64_t> nodes, int32_t depth)
{
  std::vector<bool> visited(mat.rows(), false);
  return expandSubdomain(mat, nodes, depth, visited);
}

std::vector<std::vector<int64_t>> expandSubdomains(
  const Eigen::SparseMatrix<double> & mat, std::vector<std::vector<int64_t>> subdomains, int32_t depth)
{
  std::vector<bool> visited(mat.rows(), false);
  for (auto & a : subdomains)
    a = expandSubdomain(mat, std::move(a), depth);
  return subdomains;
}

} // namespace drew


text: Current Value


text:
import configparser
import os
import re
import textwrap
import smtplib
from email.message import EmailMessage

import requests
from lxml import html
from jinja2 import Environment, PackageLoader

BASE_URL = 'https://runningstatus.in/status/{}-today'

# Requests' default user agent might get blocked, so use a more
# appropriate one
USER_AGENT= ('Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36'
           '(KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36')
HEADERS = {'User-Agent' : USER_AGENT}

TEMPLATE_FILE='table_tmpl.j2'

# wimt configuration file
CONF_FILE = os.path.expanduser('~/.config/wimt.conf')

def get_train_data(train_no, boarding_station):
    response = requests.get(BASE_URL.format(train_no), headers=HEADERS)
    tree = html.fromstring(response.content)

    train_data = {}

    train_title = tree.xpath('//div[@class="runningstatus-widget-title"]/span/h1/text()')
    train_name = re.match(r'(^.*\))', train_title[0]).group(1)
    train_data['name'] = train_name

    train_current_status = re.match(
            r'^.*\d\.\s*(.*)$',
            tree.xpath('//div[@class="runningstatus-widget-content"]/p')[0].text_content()
        ).group(1)
    train_data['status'] = train_current_status

    train_timings = tree.xpath('//tbody/tr')
    rows = []

    for r in train_timings:
        raw_station_val = next(iter(r.xpath('td[1]/text()')), '-')
        station_code = re.match(r'^.*\((\w+)\)', raw_station_val).group(1)
        station_name = re.sub(r'\s*\(.*$', '', next(iter(r.xpath('td[1]/text()')), '-'))

        departure = re.sub(r'^.*\/\s', '', next(iter(r.xpath('td[5]/text()')), '-'))
        delay = r.xpath('td[7]/font')

        if not delay:
            delay = '-'
        else:
            delay = delay[1].text

        rows.append((station_name, departure, delay))

        if station_code == boarding_station:
            break

    train_data['rows'] = rows
    return train_data

def create_text_timetable(data):
    wrapped_status = '\n '.join(textwrap.wrap(data['status'], width=90))
    train_status = ''.join(('\n','Train : ', data['name'], '\n',
                            '\n ', wrapped_status, '\n'))

    header = '{:30}{:30}{:30}'.format(
        'Station Name',
        'Departure Time',
        'Delay Status')
    divider = '-' * 90

    rows = [train_status, header, divider]
    for station,departure,delay in data['rows']:
        rows.append('{:30}{:30}{:30}'.format(
            station, departure, delay))

    return '\n'.join(rows)

def send_email_report(data, email):
    config = configparser.ConfigParser()
    config.read(CONF_FILE)
    username = config['SMTP']['From']
    password = config['SMTP']['Password']
    smtp_host = config['SMTP']['Host']
    smtp_port = config['SMTP']['Port'] or 25
    tls_needed = config['SMTP']['TLS']

    msg = EmailMessage()
    msg['Subject'] = 'Check your train timings!'
    msg['From'] = username
    msg['To'] = email

    env = Environment(
        loader=PackageLoader('wimt', ''),
        trim_blocks=True,
        lstrip_blocks=True
    )
    template = env.get_template(TEMPLATE_FILE)

    text = create_text_timetable(data)
    html = template.render(name=data['name'], status=data['status'], rows=data['rows'])

    msg.set_content(text)
    msg.add_alternative(html, subtype='html')

    with smtplib.SMTP(host=smtp_host, port=smtp_port) as s:
        if tls_needed:
            s.starttls()
            s.ehlo()
        if password:
            s.login(username, password)
        s.send_message(msg)


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0015_auto_20150828_0654'),
    ]

    operations = [
        migrations.AlterField(
            model_name='object',
            name='text_align',
            field=models.CharField(default=b'left', max_length=64, choices=[(b'left', b'Left'), (b'right', b'Right'), (b'center', b'Center')]),
            preserve_default=True,
        ),
    ]